blob: 44f870c81795e5831590511378127d1c732bbaa7 [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"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000024#include "llvm/Analysis/InstructionSimplify.h"
Nick Lewyckyf7087ea2012-02-26 02:09:49 +000025#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000026#include "llvm/Analysis/ConstantFolding.h"
Duncan Sands18450092010-11-16 12:16:38 +000027#include "llvm/Analysis/Dominators.h"
Duncan Sandsd70d1a52011-01-25 09:38:29 +000028#include "llvm/Analysis/ValueTracking.h"
Nick Lewycky3a73e342011-03-04 07:00:57 +000029#include "llvm/Support/ConstantRange.h"
Chandler Carruthfc72ae62012-03-12 11:19:31 +000030#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerd06094f2009-11-10 00:55:12 +000031#include "llvm/Support/PatternMatch.h"
Duncan Sands18450092010-11-16 12:16:38 +000032#include "llvm/Support/ValueHandle.h"
Duncan Sandse60d79f2010-11-21 13:53:09 +000033#include "llvm/Target/TargetData.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000034using namespace llvm;
Chris Lattnerd06094f2009-11-10 00:55:12 +000035using namespace llvm::PatternMatch;
Chris Lattner9f3c25a2009-11-09 22:57:59 +000036
Chris Lattner81a0dc92011-02-09 17:15:04 +000037enum { RecursionLimit = 3 };
Duncan Sandsa74a58c2010-11-10 18:23:01 +000038
Duncan Sandsa3c44a52010-12-22 09:40:51 +000039STATISTIC(NumExpand, "Number of expansions");
40STATISTIC(NumFactor , "Number of factorizations");
41STATISTIC(NumReassoc, "Number of reassociations");
42
Duncan Sands82fdab32010-12-21 14:00:22 +000043static Value *SimplifyAndInst(Value *, Value *, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +000044 const TargetLibraryInfo *, const DominatorTree *,
45 unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000046static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +000047 const TargetLibraryInfo *, const DominatorTree *,
48 unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000049static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +000050 const TargetLibraryInfo *, const DominatorTree *,
51 unsigned);
Duncan Sands82fdab32010-12-21 14:00:22 +000052static Value *SimplifyOrInst(Value *, Value *, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +000053 const TargetLibraryInfo *, const DominatorTree *,
54 unsigned);
Duncan Sands82fdab32010-12-21 14:00:22 +000055static Value *SimplifyXorInst(Value *, Value *, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +000056 const TargetLibraryInfo *, const DominatorTree *,
57 unsigned);
Duncan Sands18450092010-11-16 12:16:38 +000058
Duncan Sandsf56138d2011-07-26 15:03:53 +000059/// getFalse - For a boolean type, or a vector of boolean type, return false, or
60/// a vector with every element false, as appropriate for the type.
61static Constant *getFalse(Type *Ty) {
Nick Lewycky66d004e2011-12-01 02:39:36 +000062 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsf56138d2011-07-26 15:03:53 +000063 "Expected i1 type or a vector of i1!");
64 return Constant::getNullValue(Ty);
65}
66
67/// getTrue - For a boolean type, or a vector of boolean type, return true, or
68/// a vector with every element true, as appropriate for the type.
69static Constant *getTrue(Type *Ty) {
Nick Lewycky66d004e2011-12-01 02:39:36 +000070 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsf56138d2011-07-26 15:03:53 +000071 "Expected i1 type or a vector of i1!");
72 return Constant::getAllOnesValue(Ty);
73}
74
Duncan Sands6dc9e2b2011-10-30 19:56:36 +000075/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
76static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
77 Value *RHS) {
78 CmpInst *Cmp = dyn_cast<CmpInst>(V);
79 if (!Cmp)
80 return false;
81 CmpInst::Predicate CPred = Cmp->getPredicate();
82 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
83 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
84 return true;
85 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
86 CRHS == LHS;
87}
88
Duncan Sands18450092010-11-16 12:16:38 +000089/// ValueDominatesPHI - Does the given value dominate the specified phi node?
90static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
91 Instruction *I = dyn_cast<Instruction>(V);
92 if (!I)
93 // Arguments and constants dominate all instructions.
94 return true;
95
96 // If we have a DominatorTree then do a precise test.
Eli Friedman5b8f0dd2012-03-13 01:06:07 +000097 if (DT) {
98 if (!DT->isReachableFromEntry(P->getParent()))
99 return true;
100 if (!DT->isReachableFromEntry(I->getParent()))
101 return false;
102 return DT->dominates(I, P);
103 }
Duncan Sands18450092010-11-16 12:16:38 +0000104
105 // Otherwise, if the instruction is in the entry block, and is not an invoke,
106 // then it obviously dominates all phi nodes.
107 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
108 !isa<InvokeInst>(I))
109 return true;
110
111 return false;
112}
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000113
Duncan Sands3421d902010-12-21 13:32:22 +0000114/// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
115/// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
116/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
117/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
118/// Returns the simplified value, or null if no simplification was performed.
119static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Benjamin Kramere21083a2010-12-28 13:52:52 +0000120 unsigned OpcToExpand, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000121 const TargetLibraryInfo *TLI, const DominatorTree *DT,
122 unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000123 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000124 // Recursion is always used, so bail out at once if we already hit the limit.
125 if (!MaxRecurse--)
126 return 0;
127
128 // Check whether the expression has the form "(A op' B) op C".
129 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
130 if (Op0->getOpcode() == OpcodeToExpand) {
131 // It does! Try turning it into "(A op C) op' (B op C)".
132 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
133 // Do "A op C" and "B op C" both simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000134 if (Value *L = SimplifyBinOp(Opcode, A, C, TD, TLI, DT, MaxRecurse))
135 if (Value *R = SimplifyBinOp(Opcode, B, C, TD, TLI, DT, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000136 // They do! Return "L op' R" if it simplifies or is already available.
137 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000138 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
139 && L == B && R == A)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000140 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000141 return LHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000142 }
Duncan Sands3421d902010-12-21 13:32:22 +0000143 // Otherwise return "L op' R" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000144 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, TLI, DT,
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000145 MaxRecurse)) {
146 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000147 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000148 }
Duncan Sands3421d902010-12-21 13:32:22 +0000149 }
150 }
151
152 // Check whether the expression has the form "A op (B op' C)".
153 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
154 if (Op1->getOpcode() == OpcodeToExpand) {
155 // It does! Try turning it into "(A op B) op' (A op C)".
156 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
157 // Do "A op B" and "A op C" both simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000158 if (Value *L = SimplifyBinOp(Opcode, A, B, TD, TLI, DT, MaxRecurse))
159 if (Value *R = SimplifyBinOp(Opcode, A, C, TD, TLI, DT, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000160 // They do! Return "L op' R" if it simplifies or is already available.
161 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000162 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
163 && L == C && R == B)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000164 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000165 return RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000166 }
Duncan Sands3421d902010-12-21 13:32:22 +0000167 // Otherwise return "L op' R" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000168 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, TLI, DT,
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000169 MaxRecurse)) {
170 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000171 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000172 }
Duncan Sands3421d902010-12-21 13:32:22 +0000173 }
174 }
175
176 return 0;
177}
178
179/// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
180/// using the operation OpCodeToExtract. For example, when Opcode is Add and
181/// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
182/// Returns the simplified value, or null if no simplification was performed.
183static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +0000184 unsigned OpcToExtract, const TargetData *TD,
185 const TargetLibraryInfo *TLI,
186 const DominatorTree *DT,
187 unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000188 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
Duncan Sands3421d902010-12-21 13:32:22 +0000189 // Recursion is always used, so bail out at once if we already hit the limit.
190 if (!MaxRecurse--)
191 return 0;
192
193 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
194 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
195
196 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
197 !Op1 || Op1->getOpcode() != OpcodeToExtract)
198 return 0;
199
200 // The expression has the form "(A op' B) op (C op' D)".
Duncan Sands82fdab32010-12-21 14:00:22 +0000201 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
202 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
Duncan Sands3421d902010-12-21 13:32:22 +0000203
204 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
205 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
206 // commutative case, "(A op' B) op (C op' A)"?
Duncan Sands124708d2011-01-01 20:08:02 +0000207 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
208 Value *DD = A == C ? D : C;
Duncan Sands3421d902010-12-21 13:32:22 +0000209 // Form "A op' (B op DD)" if it simplifies completely.
210 // Does "B op DD" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000211 if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, TLI, DT, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000212 // It does! Return "A op' V" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000213 // If V equals B then "A op' V" is just the LHS. If V equals DD then
214 // "A op' V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000215 if (V == B || V == DD) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000216 ++NumFactor;
Duncan Sands124708d2011-01-01 20:08:02 +0000217 return V == B ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000218 }
Duncan Sands3421d902010-12-21 13:32:22 +0000219 // Otherwise return "A op' V" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000220 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, TLI, DT,
221 MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000222 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000223 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000224 }
Duncan Sands3421d902010-12-21 13:32:22 +0000225 }
226 }
227
228 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
229 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
230 // commutative case, "(A op' B) op (B op' D)"?
Duncan Sands124708d2011-01-01 20:08:02 +0000231 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
232 Value *CC = B == D ? C : D;
Duncan Sands3421d902010-12-21 13:32:22 +0000233 // Form "(A op CC) op' B" if it simplifies completely..
234 // Does "A op CC" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000235 if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, TLI, DT, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000236 // It does! Return "V op' B" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000237 // If V equals A then "V op' B" is just the LHS. If V equals CC then
238 // "V op' B" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000239 if (V == A || V == CC) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000240 ++NumFactor;
Duncan Sands124708d2011-01-01 20:08:02 +0000241 return V == A ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000242 }
Duncan Sands3421d902010-12-21 13:32:22 +0000243 // Otherwise return "V op' B" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000244 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, TLI, DT,
245 MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000246 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000247 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000248 }
Duncan Sands3421d902010-12-21 13:32:22 +0000249 }
250 }
251
252 return 0;
253}
254
255/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
256/// operations. Returns the simpler value, or null if none was found.
Benjamin Kramere21083a2010-12-28 13:52:52 +0000257static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sands566edb02010-12-21 08:49:00 +0000258 const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000259 const TargetLibraryInfo *TLI,
Duncan Sands566edb02010-12-21 08:49:00 +0000260 const DominatorTree *DT,
261 unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000262 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands566edb02010-12-21 08:49:00 +0000263 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
264
265 // Recursion is always used, so bail out at once if we already hit the limit.
266 if (!MaxRecurse--)
267 return 0;
268
269 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
270 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
271
272 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
273 if (Op0 && Op0->getOpcode() == Opcode) {
274 Value *A = Op0->getOperand(0);
275 Value *B = Op0->getOperand(1);
276 Value *C = RHS;
277
278 // Does "B op C" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000279 if (Value *V = SimplifyBinOp(Opcode, B, C, TD, TLI, DT, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000280 // It does! Return "A op V" if it simplifies or is already available.
281 // If V equals B then "A op V" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000282 if (V == B) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000283 // Otherwise return "A op V" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000284 if (Value *W = SimplifyBinOp(Opcode, A, V, TD, TLI, DT, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000285 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000286 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000287 }
Duncan Sands566edb02010-12-21 08:49:00 +0000288 }
289 }
290
291 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
292 if (Op1 && Op1->getOpcode() == Opcode) {
293 Value *A = LHS;
294 Value *B = Op1->getOperand(0);
295 Value *C = Op1->getOperand(1);
296
297 // Does "A op B" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000298 if (Value *V = SimplifyBinOp(Opcode, A, B, TD, TLI, DT, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000299 // It does! Return "V op C" if it simplifies or is already available.
300 // If V equals B then "V op C" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000301 if (V == B) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000302 // Otherwise return "V op C" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000303 if (Value *W = SimplifyBinOp(Opcode, V, C, TD, TLI, DT, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000304 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000305 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000306 }
Duncan Sands566edb02010-12-21 08:49:00 +0000307 }
308 }
309
310 // The remaining transforms require commutativity as well as associativity.
311 if (!Instruction::isCommutative(Opcode))
312 return 0;
313
314 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
315 if (Op0 && Op0->getOpcode() == Opcode) {
316 Value *A = Op0->getOperand(0);
317 Value *B = Op0->getOperand(1);
318 Value *C = RHS;
319
320 // Does "C op A" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000321 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, TLI, DT, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000322 // It does! Return "V op B" if it simplifies or is already available.
323 // If V equals A then "V op B" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000324 if (V == A) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000325 // Otherwise return "V op B" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000326 if (Value *W = SimplifyBinOp(Opcode, V, B, TD, TLI, DT, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000327 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000328 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000329 }
Duncan Sands566edb02010-12-21 08:49:00 +0000330 }
331 }
332
333 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
334 if (Op1 && Op1->getOpcode() == Opcode) {
335 Value *A = LHS;
336 Value *B = Op1->getOperand(0);
337 Value *C = Op1->getOperand(1);
338
339 // Does "C op A" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000340 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, TLI, DT, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000341 // It does! Return "B op V" if it simplifies or is already available.
342 // If V equals C then "B op V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000343 if (V == C) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000344 // Otherwise return "B op V" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000345 if (Value *W = SimplifyBinOp(Opcode, B, V, TD, TLI, DT, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000346 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000347 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000348 }
Duncan Sands566edb02010-12-21 08:49:00 +0000349 }
350 }
351
352 return 0;
353}
354
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000355/// ThreadBinOpOverSelect - In the case of a binary operation with a select
356/// instruction as an operand, try to simplify the binop by seeing whether
357/// evaluating it on both branches of the select results in the same value.
358/// Returns the common value if so, otherwise returns null.
359static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000360 const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000361 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +0000362 const DominatorTree *DT,
363 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000364 // Recursion is always used, so bail out at once if we already hit the limit.
365 if (!MaxRecurse--)
366 return 0;
367
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000368 SelectInst *SI;
369 if (isa<SelectInst>(LHS)) {
370 SI = cast<SelectInst>(LHS);
371 } else {
372 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
373 SI = cast<SelectInst>(RHS);
374 }
375
376 // Evaluate the BinOp on the true and false branches of the select.
377 Value *TV;
378 Value *FV;
379 if (SI == LHS) {
Chad Rosier618c1db2011-12-01 03:08:23 +0000380 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, TLI, DT, MaxRecurse);
381 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, TLI, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000382 } else {
Chad Rosier618c1db2011-12-01 03:08:23 +0000383 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, TLI, DT, MaxRecurse);
384 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, TLI, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000385 }
386
Duncan Sands7cf85e72011-01-01 16:12:09 +0000387 // If they simplified to the same value, then return the common value.
Duncan Sands124708d2011-01-01 20:08:02 +0000388 // If they both failed to simplify then return null.
389 if (TV == FV)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000390 return TV;
391
392 // If one branch simplified to undef, return the other one.
393 if (TV && isa<UndefValue>(TV))
394 return FV;
395 if (FV && isa<UndefValue>(FV))
396 return TV;
397
398 // If applying the operation did not change the true and false select values,
399 // then the result of the binop is the select itself.
Duncan Sands124708d2011-01-01 20:08:02 +0000400 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000401 return SI;
402
403 // If one branch simplified and the other did not, and the simplified
404 // value is equal to the unsimplified one, return the simplified value.
405 // For example, select (cond, X, X & Z) & Z -> X & Z.
406 if ((FV && !TV) || (TV && !FV)) {
407 // Check that the simplified value has the form "X op Y" where "op" is the
408 // same as the original operation.
409 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
410 if (Simplified && Simplified->getOpcode() == Opcode) {
411 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
412 // We already know that "op" is the same as for the simplified value. See
413 // if the operands match too. If so, return the simplified value.
414 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
415 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
416 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands124708d2011-01-01 20:08:02 +0000417 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
418 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000419 return Simplified;
420 if (Simplified->isCommutative() &&
Duncan Sands124708d2011-01-01 20:08:02 +0000421 Simplified->getOperand(1) == UnsimplifiedLHS &&
422 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000423 return Simplified;
424 }
425 }
426
427 return 0;
428}
429
430/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
431/// try to simplify the comparison by seeing whether both branches of the select
432/// result in the same value. Returns the common value if so, otherwise returns
433/// null.
434static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000435 Value *RHS, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000436 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +0000437 const DominatorTree *DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000438 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000439 // Recursion is always used, so bail out at once if we already hit the limit.
440 if (!MaxRecurse--)
441 return 0;
442
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000443 // Make sure the select is on the LHS.
444 if (!isa<SelectInst>(LHS)) {
445 std::swap(LHS, RHS);
446 Pred = CmpInst::getSwappedPredicate(Pred);
447 }
448 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
449 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000450 Value *Cond = SI->getCondition();
451 Value *TV = SI->getTrueValue();
452 Value *FV = SI->getFalseValue();
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000453
Duncan Sands50ca4d32011-02-03 09:37:39 +0000454 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000455 // Does "cmp TV, RHS" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000456 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, TD, TLI, DT, MaxRecurse);
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000457 if (TCmp == Cond) {
458 // It not only simplified, it simplified to the select condition. Replace
459 // it with 'true'.
460 TCmp = getTrue(Cond->getType());
461 } else if (!TCmp) {
462 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
463 // condition then we can replace it with 'true'. Otherwise give up.
464 if (!isSameCompare(Cond, Pred, TV, RHS))
465 return 0;
466 TCmp = getTrue(Cond->getType());
Duncan Sands50ca4d32011-02-03 09:37:39 +0000467 }
468
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000469 // Does "cmp FV, RHS" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000470 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, TD, TLI, DT, MaxRecurse);
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000471 if (FCmp == Cond) {
472 // It not only simplified, it simplified to the select condition. Replace
473 // it with 'false'.
474 FCmp = getFalse(Cond->getType());
475 } else if (!FCmp) {
476 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
477 // condition then we can replace it with 'false'. Otherwise give up.
478 if (!isSameCompare(Cond, Pred, FV, RHS))
479 return 0;
480 FCmp = getFalse(Cond->getType());
481 }
482
483 // If both sides simplified to the same value, then use it as the result of
484 // the original comparison.
485 if (TCmp == FCmp)
486 return TCmp;
Duncan Sandsaa97bb52012-02-10 14:31:24 +0000487
488 // The remaining cases only make sense if the select condition has the same
489 // type as the result of the comparison, so bail out if this is not so.
490 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
491 return 0;
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000492 // If the false value simplified to false, then the result of the compare
493 // is equal to "Cond && TCmp". This also catches the case when the false
494 // value simplified to false and the true value to true, returning "Cond".
495 if (match(FCmp, m_Zero()))
Chad Rosier618c1db2011-12-01 03:08:23 +0000496 if (Value *V = SimplifyAndInst(Cond, TCmp, TD, TLI, DT, MaxRecurse))
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000497 return V;
498 // If the true value simplified to true, then the result of the compare
499 // is equal to "Cond || FCmp".
500 if (match(TCmp, m_One()))
Chad Rosier618c1db2011-12-01 03:08:23 +0000501 if (Value *V = SimplifyOrInst(Cond, FCmp, TD, TLI, DT, MaxRecurse))
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000502 return V;
503 // Finally, if the false value simplified to true and the true value to
504 // false, then the result of the compare is equal to "!Cond".
505 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
506 if (Value *V =
507 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Chad Rosier618c1db2011-12-01 03:08:23 +0000508 TD, TLI, DT, MaxRecurse))
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000509 return V;
510
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000511 return 0;
512}
513
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000514/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
515/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
516/// it on the incoming phi values yields the same result for every value. If so
517/// returns the common value, otherwise returns null.
518static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +0000519 const TargetData *TD,
520 const TargetLibraryInfo *TLI,
521 const DominatorTree *DT,
Duncan Sands18450092010-11-16 12:16:38 +0000522 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000523 // Recursion is always used, so bail out at once if we already hit the limit.
524 if (!MaxRecurse--)
525 return 0;
526
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000527 PHINode *PI;
528 if (isa<PHINode>(LHS)) {
529 PI = cast<PHINode>(LHS);
Duncan Sands18450092010-11-16 12:16:38 +0000530 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
531 if (!ValueDominatesPHI(RHS, PI, DT))
532 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000533 } else {
534 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
535 PI = cast<PHINode>(RHS);
Duncan Sands18450092010-11-16 12:16:38 +0000536 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
537 if (!ValueDominatesPHI(LHS, PI, DT))
538 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000539 }
540
541 // Evaluate the BinOp on the incoming phi values.
542 Value *CommonValue = 0;
543 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000544 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000545 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000546 if (Incoming == PI) continue;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000547 Value *V = PI == LHS ?
Chad Rosier618c1db2011-12-01 03:08:23 +0000548 SimplifyBinOp(Opcode, Incoming, RHS, TD, TLI, DT, MaxRecurse) :
549 SimplifyBinOp(Opcode, LHS, Incoming, TD, TLI, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000550 // If the operation failed to simplify, or simplified to a different value
551 // to previously, then give up.
552 if (!V || (CommonValue && V != CommonValue))
553 return 0;
554 CommonValue = V;
555 }
556
557 return CommonValue;
558}
559
560/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
561/// try to simplify the comparison by seeing whether comparing with all of the
562/// incoming phi values yields the same result every time. If so returns the
563/// common result, otherwise returns null.
564static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +0000565 const TargetData *TD,
566 const TargetLibraryInfo *TLI,
567 const DominatorTree *DT,
Duncan Sands18450092010-11-16 12:16:38 +0000568 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000569 // Recursion is always used, so bail out at once if we already hit the limit.
570 if (!MaxRecurse--)
571 return 0;
572
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000573 // Make sure the phi is on the LHS.
574 if (!isa<PHINode>(LHS)) {
575 std::swap(LHS, RHS);
576 Pred = CmpInst::getSwappedPredicate(Pred);
577 }
578 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
579 PHINode *PI = cast<PHINode>(LHS);
580
Duncan Sands18450092010-11-16 12:16:38 +0000581 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
582 if (!ValueDominatesPHI(RHS, PI, DT))
583 return 0;
584
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000585 // Evaluate the BinOp on the incoming phi values.
586 Value *CommonValue = 0;
587 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000588 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000589 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000590 if (Incoming == PI) continue;
Chad Rosier618c1db2011-12-01 03:08:23 +0000591 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, TLI, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000592 // If the operation failed to simplify, or simplified to a different value
593 // to previously, then give up.
594 if (!V || (CommonValue && V != CommonValue))
595 return 0;
596 CommonValue = V;
597 }
598
599 return CommonValue;
600}
601
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000602/// SimplifyAddInst - Given operands for an Add, see if we can
603/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000604static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +0000605 const TargetData *TD,
606 const TargetLibraryInfo *TLI,
607 const DominatorTree *DT,
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000608 unsigned MaxRecurse) {
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000609 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
610 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
611 Constant *Ops[] = { CLHS, CRHS };
612 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
Chad Rosier618c1db2011-12-01 03:08:23 +0000613 Ops, TD, TLI);
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000614 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000615
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000616 // Canonicalize the constant to the RHS.
617 std::swap(Op0, Op1);
618 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000619
Duncan Sandsfea3b212010-12-15 14:07:39 +0000620 // X + undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000621 if (match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000622 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000623
Duncan Sandsfea3b212010-12-15 14:07:39 +0000624 // X + 0 -> X
625 if (match(Op1, m_Zero()))
626 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000627
Duncan Sandsfea3b212010-12-15 14:07:39 +0000628 // X + (Y - X) -> Y
629 // (Y - X) + X -> Y
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000630 // Eg: X + -X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000631 Value *Y = 0;
632 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
633 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000634 return Y;
635
636 // X + ~X -> -1 since ~X = -X-1
Duncan Sands124708d2011-01-01 20:08:02 +0000637 if (match(Op0, m_Not(m_Specific(Op1))) ||
638 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000639 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands87689cf2010-11-19 09:20:39 +0000640
Duncan Sands82fdab32010-12-21 14:00:22 +0000641 /// i1 add -> xor.
Duncan Sands75d289e2010-12-21 14:48:48 +0000642 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Chad Rosier618c1db2011-12-01 03:08:23 +0000643 if (Value *V = SimplifyXorInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000644 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000645
Duncan Sands566edb02010-12-21 08:49:00 +0000646 // Try some generic simplifications for associative operations.
Chad Rosier618c1db2011-12-01 03:08:23 +0000647 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, TLI, DT,
Duncan Sands566edb02010-12-21 08:49:00 +0000648 MaxRecurse))
649 return V;
650
Duncan Sands3421d902010-12-21 13:32:22 +0000651 // Mul distributes over Add. Try some generic simplifications based on this.
652 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
Chad Rosier618c1db2011-12-01 03:08:23 +0000653 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +0000654 return V;
655
Duncan Sands87689cf2010-11-19 09:20:39 +0000656 // Threading Add over selects and phi nodes is pointless, so don't bother.
657 // Threading over the select in "A + select(cond, B, C)" means evaluating
658 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
659 // only if B and C are equal. If B and C are equal then (since we assume
660 // that operands have already been simplified) "select(cond, B, C)" should
661 // have been simplified to the common value of B and C already. Analysing
662 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
663 // for threading over phi nodes.
664
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000665 return 0;
666}
667
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000668Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +0000669 const TargetData *TD, const TargetLibraryInfo *TLI,
670 const DominatorTree *DT) {
671 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000672}
673
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000674/// \brief Accumulate the constant integer offset a GEP represents.
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000675///
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000676/// Given a getelementptr instruction/constantexpr, accumulate the constant
677/// offset from the base pointer into the provided APInt 'Offset'. Returns true
678/// if the GEP has all-constant indices. Returns false if any non-constant
679/// index is encountered leaving the 'Offset' in an undefined state. The
680/// 'Offset' APInt must be the bitwidth of the target's pointer size.
681static bool accumulateGEPOffset(const TargetData &TD, GEPOperator *GEP,
682 APInt &Offset) {
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000683 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000684 assert(IntPtrWidth == Offset.getBitWidth());
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000685
686 gep_type_iterator GTI = gep_type_begin(GEP);
687 for (User::op_iterator I = GEP->op_begin() + 1, E = GEP->op_end(); I != E;
688 ++I, ++GTI) {
689 ConstantInt *OpC = dyn_cast<ConstantInt>(*I);
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000690 if (!OpC) return false;
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000691 if (OpC->isZero()) continue;
692
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000693 // Handle a struct index, which adds its field offset to the pointer.
694 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000695 unsigned ElementIdx = OpC->getZExtValue();
696 const StructLayout *SL = TD.getStructLayout(STy);
697 Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx),
698 /*isSigned=*/true);
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000699 continue;
700 }
701
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000702 APInt TypeSize(IntPtrWidth, TD.getTypeAllocSize(GTI.getIndexedType()),
703 /*isSigned=*/true);
704 Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000705 }
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000706 return true;
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000707}
708
709/// \brief Compute the base pointer and cumulative constant offsets for V.
710///
711/// This strips all constant offsets off of V, leaving it the base pointer, and
712/// accumulates the total constant offset applied in the returned constant. It
713/// returns 0 if V is not a pointer, and returns the constant '0' if there are
714/// no constant offsets applied.
715static Constant *stripAndComputeConstantOffsets(const TargetData &TD,
716 Value *&V) {
717 if (!V->getType()->isPointerTy())
718 return 0;
719
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000720 unsigned IntPtrWidth = TD.getPointerSizeInBits();
721 APInt Offset = APInt::getNullValue(IntPtrWidth);
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000722
723 // Even though we don't look through PHI nodes, we could be called on an
724 // instruction in an unreachable block, which may be on a cycle.
725 SmallPtrSet<Value *, 4> Visited;
726 Visited.insert(V);
727 do {
728 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000729 if (!accumulateGEPOffset(TD, GEP, Offset))
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000730 break;
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000731 V = GEP->getPointerOperand();
732 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
733 V = cast<Operator>(V)->getOperand(0);
734 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
735 if (GA->mayBeOverridden())
736 break;
737 V = GA->getAliasee();
738 } else {
739 break;
740 }
741 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
742 } while (Visited.insert(V));
743
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000744 Type *IntPtrTy = TD.getIntPtrType(V->getContext());
745 return ConstantInt::get(IntPtrTy, Offset);
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000746}
747
748/// \brief Compute the constant difference between two pointer values.
749/// If the difference is not a constant, returns zero.
750static Constant *computePointerDifference(const TargetData &TD,
751 Value *LHS, Value *RHS) {
752 Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
753 if (!LHSOffset)
754 return 0;
755 Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
756 if (!RHSOffset)
757 return 0;
758
759 // If LHS and RHS are not related via constant offsets to the same base
760 // value, there is nothing we can do here.
761 if (LHS != RHS)
762 return 0;
763
764 // Otherwise, the difference of LHS - RHS can be computed as:
765 // LHS - RHS
766 // = (LHSOffset + Base) - (RHSOffset + Base)
767 // = LHSOffset - RHSOffset
768 return ConstantExpr::getSub(LHSOffset, RHSOffset);
769}
770
Duncan Sandsfea3b212010-12-15 14:07:39 +0000771/// SimplifySubInst - Given operands for a Sub, see if we can
772/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000773static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +0000774 const TargetData *TD,
775 const TargetLibraryInfo *TLI,
776 const DominatorTree *DT,
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000777 unsigned MaxRecurse) {
Duncan Sandsfea3b212010-12-15 14:07:39 +0000778 if (Constant *CLHS = dyn_cast<Constant>(Op0))
779 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
780 Constant *Ops[] = { CLHS, CRHS };
781 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
Chad Rosier618c1db2011-12-01 03:08:23 +0000782 Ops, TD, TLI);
Duncan Sandsfea3b212010-12-15 14:07:39 +0000783 }
784
785 // X - undef -> undef
786 // undef - X -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000787 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000788 return UndefValue::get(Op0->getType());
789
790 // X - 0 -> X
791 if (match(Op1, m_Zero()))
792 return Op0;
793
794 // X - X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000795 if (Op0 == Op1)
Duncan Sandsfea3b212010-12-15 14:07:39 +0000796 return Constant::getNullValue(Op0->getType());
797
Duncan Sandsfe02c692011-01-18 09:24:58 +0000798 // (X*2) - X -> X
799 // (X<<1) - X -> X
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000800 Value *X = 0;
Duncan Sandsfe02c692011-01-18 09:24:58 +0000801 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
802 match(Op0, m_Shl(m_Specific(Op1), m_One())))
803 return Op1;
804
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000805 if (TD) {
806 Value *LHSOp, *RHSOp;
807 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
808 match(Op1, m_PtrToInt(m_Value(RHSOp))))
809 if (Constant *Result = computePointerDifference(*TD, LHSOp, RHSOp))
810 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
811
812 // trunc(p)-trunc(q) -> trunc(p-q)
813 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
814 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
815 if (Constant *Result = computePointerDifference(*TD, LHSOp, RHSOp))
816 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
817 }
818
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000819 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
820 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
821 Value *Y = 0, *Z = Op1;
822 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
823 // See if "V === Y - Z" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000824 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000825 // It does! Now see if "X + V" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000826 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, TD, TLI, DT,
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000827 MaxRecurse-1)) {
828 // It does, we successfully reassociated!
829 ++NumReassoc;
830 return W;
831 }
832 // See if "V === X - Z" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000833 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000834 // It does! Now see if "Y + V" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000835 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, TD, TLI, DT,
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000836 MaxRecurse-1)) {
837 // It does, we successfully reassociated!
838 ++NumReassoc;
839 return W;
840 }
841 }
Duncan Sands82fdab32010-12-21 14:00:22 +0000842
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000843 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
844 // For example, X - (X + 1) -> -1
845 X = Op0;
846 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
847 // See if "V === X - Y" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000848 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000849 // It does! Now see if "V - Z" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000850 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, TD, TLI, DT,
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000851 MaxRecurse-1)) {
852 // It does, we successfully reassociated!
853 ++NumReassoc;
854 return W;
855 }
856 // See if "V === X - Z" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000857 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000858 // It does! Now see if "V - Y" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000859 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, TD, TLI, DT,
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000860 MaxRecurse-1)) {
861 // It does, we successfully reassociated!
862 ++NumReassoc;
863 return W;
864 }
865 }
866
867 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
868 // For example, X - (X - Y) -> Y.
869 Z = Op0;
Duncan Sandsc087e202011-01-14 15:26:10 +0000870 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
871 // See if "V === Z - X" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000872 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000873 // It does! Now see if "V + Y" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000874 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, TD, TLI, DT,
Duncan Sandsc087e202011-01-14 15:26:10 +0000875 MaxRecurse-1)) {
876 // It does, we successfully reassociated!
877 ++NumReassoc;
878 return W;
879 }
880
Duncan Sands3421d902010-12-21 13:32:22 +0000881 // Mul distributes over Sub. Try some generic simplifications based on this.
882 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
Chad Rosier618c1db2011-12-01 03:08:23 +0000883 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +0000884 return V;
885
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000886 // i1 sub -> xor.
887 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Chad Rosier618c1db2011-12-01 03:08:23 +0000888 if (Value *V = SimplifyXorInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000889 return V;
890
Duncan Sandsfea3b212010-12-15 14:07:39 +0000891 // Threading Sub over selects and phi nodes is pointless, so don't bother.
892 // Threading over the select in "A - select(cond, B, C)" means evaluating
893 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
894 // only if B and C are equal. If B and C are equal then (since we assume
895 // that operands have already been simplified) "select(cond, B, C)" should
896 // have been simplified to the common value of B and C already. Analysing
897 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
898 // for threading over phi nodes.
899
900 return 0;
901}
902
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000903Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +0000904 const TargetData *TD,
905 const TargetLibraryInfo *TLI,
906 const DominatorTree *DT) {
907 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000908}
909
Duncan Sands82fdab32010-12-21 14:00:22 +0000910/// SimplifyMulInst - Given operands for a Mul, see if we can
911/// fold the result. If not, this returns null.
912static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000913 const TargetLibraryInfo *TLI,
Duncan Sands82fdab32010-12-21 14:00:22 +0000914 const DominatorTree *DT, unsigned MaxRecurse) {
915 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
916 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
917 Constant *Ops[] = { CLHS, CRHS };
918 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
Chad Rosier618c1db2011-12-01 03:08:23 +0000919 Ops, TD, TLI);
Duncan Sands82fdab32010-12-21 14:00:22 +0000920 }
921
922 // Canonicalize the constant to the RHS.
923 std::swap(Op0, Op1);
924 }
925
926 // X * undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000927 if (match(Op1, m_Undef()))
Duncan Sands82fdab32010-12-21 14:00:22 +0000928 return Constant::getNullValue(Op0->getType());
929
930 // X * 0 -> 0
931 if (match(Op1, m_Zero()))
932 return Op1;
933
934 // X * 1 -> X
935 if (match(Op1, m_One()))
936 return Op0;
937
Duncan Sands1895e982011-01-30 18:03:50 +0000938 // (X / Y) * Y -> X if the division is exact.
Benjamin Kramer55c6d572012-01-01 17:55:30 +0000939 Value *X = 0;
940 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
941 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
942 return X;
Duncan Sands1895e982011-01-30 18:03:50 +0000943
Nick Lewycky54138802011-01-29 19:55:23 +0000944 // i1 mul -> and.
Duncan Sands75d289e2010-12-21 14:48:48 +0000945 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Chad Rosier618c1db2011-12-01 03:08:23 +0000946 if (Value *V = SimplifyAndInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000947 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000948
949 // Try some generic simplifications for associative operations.
Chad Rosier618c1db2011-12-01 03:08:23 +0000950 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, TLI, DT,
Duncan Sands82fdab32010-12-21 14:00:22 +0000951 MaxRecurse))
952 return V;
953
954 // Mul distributes over Add. Try some generic simplifications based on this.
955 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Chad Rosier618c1db2011-12-01 03:08:23 +0000956 TD, TLI, DT, MaxRecurse))
Duncan Sands82fdab32010-12-21 14:00:22 +0000957 return V;
958
959 // If the operation is with the result of a select instruction, check whether
960 // operating on either branch of the select always yields the same value.
961 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +0000962 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, TLI, DT,
Duncan Sands82fdab32010-12-21 14:00:22 +0000963 MaxRecurse))
964 return V;
965
966 // If the operation is with the result of a phi instruction, check whether
967 // operating on all incoming values of the phi always yields the same value.
968 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +0000969 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, TLI, DT,
Duncan Sands82fdab32010-12-21 14:00:22 +0000970 MaxRecurse))
971 return V;
972
973 return 0;
974}
975
976Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000977 const TargetLibraryInfo *TLI,
Duncan Sands82fdab32010-12-21 14:00:22 +0000978 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +0000979 return ::SimplifyMulInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sands82fdab32010-12-21 14:00:22 +0000980}
981
Duncan Sands593faa52011-01-28 16:51:11 +0000982/// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
983/// fold the result. If not, this returns null.
Anders Carlsson479b4b92011-02-05 18:33:43 +0000984static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Chad Rosier618c1db2011-12-01 03:08:23 +0000985 const TargetData *TD, const TargetLibraryInfo *TLI,
986 const DominatorTree *DT, unsigned MaxRecurse) {
Duncan Sands593faa52011-01-28 16:51:11 +0000987 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
988 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
989 Constant *Ops[] = { C0, C1 };
Chad Rosier618c1db2011-12-01 03:08:23 +0000990 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
Duncan Sands593faa52011-01-28 16:51:11 +0000991 }
992 }
993
Duncan Sandsa3e292c2011-01-28 18:50:50 +0000994 bool isSigned = Opcode == Instruction::SDiv;
995
Duncan Sands593faa52011-01-28 16:51:11 +0000996 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000997 if (match(Op1, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +0000998 return Op1;
999
1000 // undef / X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001001 if (match(Op0, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +00001002 return Constant::getNullValue(Op0->getType());
1003
1004 // 0 / X -> 0, we don't need to preserve faults!
1005 if (match(Op0, m_Zero()))
1006 return Op0;
1007
1008 // X / 1 -> X
1009 if (match(Op1, m_One()))
1010 return Op0;
Duncan Sands593faa52011-01-28 16:51:11 +00001011
1012 if (Op0->getType()->isIntegerTy(1))
1013 // It can't be division by zero, hence it must be division by one.
1014 return Op0;
1015
1016 // X / X -> 1
1017 if (Op0 == Op1)
1018 return ConstantInt::get(Op0->getType(), 1);
1019
1020 // (X * Y) / Y -> X if the multiplication does not overflow.
1021 Value *X = 0, *Y = 0;
1022 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1023 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands32a43cc2011-10-27 19:16:21 +00001024 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands4b720712011-02-02 20:52:00 +00001025 // If the Mul knows it does not overflow, then we are good to go.
1026 if ((isSigned && Mul->hasNoSignedWrap()) ||
1027 (!isSigned && Mul->hasNoUnsignedWrap()))
1028 return X;
Duncan Sands593faa52011-01-28 16:51:11 +00001029 // If X has the form X = A / Y then X * Y cannot overflow.
1030 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1031 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1032 return X;
1033 }
1034
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001035 // (X rem Y) / Y -> 0
1036 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1037 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1038 return Constant::getNullValue(Op0->getType());
1039
1040 // If the operation is with the result of a select instruction, check whether
1041 // operating on either branch of the select always yields the same value.
1042 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001043 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT,
1044 MaxRecurse))
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001045 return V;
1046
1047 // If the operation is with the result of a phi instruction, check whether
1048 // operating on all incoming values of the phi always yields the same value.
1049 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001050 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT,
1051 MaxRecurse))
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001052 return V;
1053
Duncan Sands593faa52011-01-28 16:51:11 +00001054 return 0;
1055}
1056
1057/// SimplifySDivInst - Given operands for an SDiv, see if we can
1058/// fold the result. If not, this returns null.
1059static Value *SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001060 const TargetLibraryInfo *TLI,
Duncan Sands593faa52011-01-28 16:51:11 +00001061 const DominatorTree *DT, unsigned MaxRecurse) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001062 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, TD, TLI, DT,
1063 MaxRecurse))
Duncan Sands593faa52011-01-28 16:51:11 +00001064 return V;
1065
Duncan Sands593faa52011-01-28 16:51:11 +00001066 return 0;
1067}
1068
1069Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001070 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001071 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001072 return ::SimplifySDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sands593faa52011-01-28 16:51:11 +00001073}
1074
1075/// SimplifyUDivInst - Given operands for a UDiv, see if we can
1076/// fold the result. If not, this returns null.
1077static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001078 const TargetLibraryInfo *TLI,
Duncan Sands593faa52011-01-28 16:51:11 +00001079 const DominatorTree *DT, unsigned MaxRecurse) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001080 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, TD, TLI, DT,
1081 MaxRecurse))
Duncan Sands593faa52011-01-28 16:51:11 +00001082 return V;
1083
Duncan Sands593faa52011-01-28 16:51:11 +00001084 return 0;
1085}
1086
1087Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001088 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001089 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001090 return ::SimplifyUDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sands593faa52011-01-28 16:51:11 +00001091}
1092
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001093static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +00001094 const TargetLibraryInfo *,
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001095 const DominatorTree *, unsigned) {
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001096 // undef / X -> undef (the undef could be a snan).
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001097 if (match(Op0, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001098 return Op0;
1099
1100 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001101 if (match(Op1, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001102 return Op1;
1103
1104 return 0;
1105}
1106
1107Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001108 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001109 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001110 return ::SimplifyFDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001111}
1112
Duncan Sandsf24ed772011-05-02 16:27:02 +00001113/// SimplifyRem - Given operands for an SRem or URem, see if we can
1114/// fold the result. If not, this returns null.
1115static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Chad Rosier618c1db2011-12-01 03:08:23 +00001116 const TargetData *TD, const TargetLibraryInfo *TLI,
1117 const DominatorTree *DT, unsigned MaxRecurse) {
Duncan Sandsf24ed772011-05-02 16:27:02 +00001118 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1119 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1120 Constant *Ops[] = { C0, C1 };
Chad Rosier618c1db2011-12-01 03:08:23 +00001121 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001122 }
1123 }
1124
Duncan Sandsf24ed772011-05-02 16:27:02 +00001125 // X % undef -> undef
1126 if (match(Op1, m_Undef()))
1127 return Op1;
1128
1129 // undef % X -> 0
1130 if (match(Op0, m_Undef()))
1131 return Constant::getNullValue(Op0->getType());
1132
1133 // 0 % X -> 0, we don't need to preserve faults!
1134 if (match(Op0, m_Zero()))
1135 return Op0;
1136
1137 // X % 0 -> undef, we don't need to preserve faults!
1138 if (match(Op1, m_Zero()))
1139 return UndefValue::get(Op0->getType());
1140
1141 // X % 1 -> 0
1142 if (match(Op1, m_One()))
1143 return Constant::getNullValue(Op0->getType());
1144
1145 if (Op0->getType()->isIntegerTy(1))
1146 // It can't be remainder by zero, hence it must be remainder by one.
1147 return Constant::getNullValue(Op0->getType());
1148
1149 // X % X -> 0
1150 if (Op0 == Op1)
1151 return Constant::getNullValue(Op0->getType());
1152
1153 // If the operation is with the result of a select instruction, check whether
1154 // operating on either branch of the select always yields the same value.
1155 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001156 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001157 return V;
1158
1159 // If the operation is with the result of a phi instruction, check whether
1160 // operating on all incoming values of the phi always yields the same value.
1161 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001162 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001163 return V;
1164
1165 return 0;
1166}
1167
1168/// SimplifySRemInst - Given operands for an SRem, see if we can
1169/// fold the result. If not, this returns null.
1170static Value *SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001171 const TargetLibraryInfo *TLI,
1172 const DominatorTree *DT,
1173 unsigned MaxRecurse) {
1174 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001175 return V;
1176
1177 return 0;
1178}
1179
1180Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001181 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001182 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001183 return ::SimplifySRemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001184}
1185
1186/// SimplifyURemInst - Given operands for a URem, see if we can
1187/// fold the result. If not, this returns null.
1188static Value *SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001189 const TargetLibraryInfo *TLI,
1190 const DominatorTree *DT,
1191 unsigned MaxRecurse) {
1192 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001193 return V;
1194
1195 return 0;
1196}
1197
1198Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001199 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001200 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001201 return ::SimplifyURemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001202}
1203
1204static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +00001205 const TargetLibraryInfo *,
1206 const DominatorTree *,
1207 unsigned) {
Duncan Sandsf24ed772011-05-02 16:27:02 +00001208 // undef % X -> undef (the undef could be a snan).
1209 if (match(Op0, m_Undef()))
1210 return Op0;
1211
1212 // X % undef -> undef
1213 if (match(Op1, m_Undef()))
1214 return Op1;
1215
1216 return 0;
1217}
1218
1219Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001220 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001221 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001222 return ::SimplifyFRemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001223}
1224
Duncan Sandscf80bc12011-01-14 14:44:12 +00001225/// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
Duncan Sandsc43cee32011-01-14 00:37:45 +00001226/// fold the result. If not, this returns null.
Duncan Sandscf80bc12011-01-14 14:44:12 +00001227static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Chad Rosier618c1db2011-12-01 03:08:23 +00001228 const TargetData *TD, const TargetLibraryInfo *TLI,
1229 const DominatorTree *DT, unsigned MaxRecurse) {
Duncan Sandsc43cee32011-01-14 00:37:45 +00001230 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1231 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1232 Constant *Ops[] = { C0, C1 };
Chad Rosier618c1db2011-12-01 03:08:23 +00001233 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001234 }
1235 }
1236
Duncan Sandscf80bc12011-01-14 14:44:12 +00001237 // 0 shift by X -> 0
Duncan Sandsc43cee32011-01-14 00:37:45 +00001238 if (match(Op0, m_Zero()))
1239 return Op0;
1240
Duncan Sandscf80bc12011-01-14 14:44:12 +00001241 // X shift by 0 -> X
Duncan Sandsc43cee32011-01-14 00:37:45 +00001242 if (match(Op1, m_Zero()))
1243 return Op0;
1244
Duncan Sandscf80bc12011-01-14 14:44:12 +00001245 // X shift by undef -> undef because it may shift by the bitwidth.
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001246 if (match(Op1, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001247 return Op1;
1248
1249 // Shifting by the bitwidth or more is undefined.
1250 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1251 if (CI->getValue().getLimitedValue() >=
1252 Op0->getType()->getScalarSizeInBits())
1253 return UndefValue::get(Op0->getType());
1254
Duncan Sandscf80bc12011-01-14 14:44:12 +00001255 // If the operation is with the result of a select instruction, check whether
1256 // operating on either branch of the select always yields the same value.
1257 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001258 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001259 return V;
1260
1261 // If the operation is with the result of a phi instruction, check whether
1262 // operating on all incoming values of the phi always yields the same value.
1263 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001264 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001265 return V;
1266
1267 return 0;
1268}
1269
1270/// SimplifyShlInst - Given operands for an Shl, see if we can
1271/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001272static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +00001273 const TargetData *TD,
1274 const TargetLibraryInfo *TLI,
1275 const DominatorTree *DT, unsigned MaxRecurse) {
1276 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001277 return V;
1278
1279 // undef << X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001280 if (match(Op0, m_Undef()))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001281 return Constant::getNullValue(Op0->getType());
1282
Chris Lattner81a0dc92011-02-09 17:15:04 +00001283 // (X >> A) << A -> X
1284 Value *X;
Benjamin Kramer55c6d572012-01-01 17:55:30 +00001285 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner81a0dc92011-02-09 17:15:04 +00001286 return X;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001287 return 0;
1288}
1289
Chris Lattner81a0dc92011-02-09 17:15:04 +00001290Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +00001291 const TargetData *TD, const TargetLibraryInfo *TLI,
1292 const DominatorTree *DT) {
1293 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001294}
1295
1296/// SimplifyLShrInst - Given operands for an LShr, see if we can
1297/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001298static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Chad Rosier618c1db2011-12-01 03:08:23 +00001299 const TargetData *TD,
1300 const TargetLibraryInfo *TLI,
1301 const DominatorTree *DT,
Chris Lattner81a0dc92011-02-09 17:15:04 +00001302 unsigned MaxRecurse) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001303 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001304 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001305
1306 // undef >>l X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001307 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001308 return Constant::getNullValue(Op0->getType());
1309
Chris Lattner81a0dc92011-02-09 17:15:04 +00001310 // (X << A) >> A -> X
1311 Value *X;
1312 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1313 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1314 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001315
Duncan Sandsc43cee32011-01-14 00:37:45 +00001316 return 0;
1317}
1318
Chris Lattner81a0dc92011-02-09 17:15:04 +00001319Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Chad Rosier618c1db2011-12-01 03:08:23 +00001320 const TargetData *TD,
1321 const TargetLibraryInfo *TLI,
1322 const DominatorTree *DT) {
1323 return ::SimplifyLShrInst(Op0, Op1, isExact, TD, TLI, DT, RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001324}
1325
1326/// SimplifyAShrInst - Given operands for an AShr, see if we can
1327/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001328static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Chad Rosier618c1db2011-12-01 03:08:23 +00001329 const TargetData *TD,
1330 const TargetLibraryInfo *TLI,
1331 const DominatorTree *DT,
Chris Lattner81a0dc92011-02-09 17:15:04 +00001332 unsigned MaxRecurse) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001333 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001334 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001335
1336 // all ones >>a X -> all ones
1337 if (match(Op0, m_AllOnes()))
1338 return Op0;
1339
1340 // undef >>a X -> all ones
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001341 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001342 return Constant::getAllOnesValue(Op0->getType());
1343
Chris Lattner81a0dc92011-02-09 17:15:04 +00001344 // (X << A) >> A -> X
1345 Value *X;
1346 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1347 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1348 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001349
Duncan Sandsc43cee32011-01-14 00:37:45 +00001350 return 0;
1351}
1352
Chris Lattner81a0dc92011-02-09 17:15:04 +00001353Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Chad Rosier618c1db2011-12-01 03:08:23 +00001354 const TargetData *TD,
1355 const TargetLibraryInfo *TLI,
1356 const DominatorTree *DT) {
1357 return ::SimplifyAShrInst(Op0, Op1, isExact, TD, TLI, DT, RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001358}
1359
Chris Lattnerd06094f2009-11-10 00:55:12 +00001360/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001361/// fold the result. If not, this returns null.
Chad Rosier618c1db2011-12-01 03:08:23 +00001362static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1363 const TargetLibraryInfo *TLI,
1364 const DominatorTree *DT,
1365 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001366 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1367 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1368 Constant *Ops[] = { CLHS, CRHS };
1369 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
Chad Rosier618c1db2011-12-01 03:08:23 +00001370 Ops, TD, TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001371 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001372
Chris Lattnerd06094f2009-11-10 00:55:12 +00001373 // Canonicalize the constant to the RHS.
1374 std::swap(Op0, Op1);
1375 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001376
Chris Lattnerd06094f2009-11-10 00:55:12 +00001377 // X & undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001378 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001379 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001380
Chris Lattnerd06094f2009-11-10 00:55:12 +00001381 // X & X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001382 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001383 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001384
Duncan Sands2b749872010-11-17 18:52:15 +00001385 // X & 0 = 0
1386 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001387 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001388
Duncan Sands2b749872010-11-17 18:52:15 +00001389 // X & -1 = X
1390 if (match(Op1, m_AllOnes()))
1391 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001392
Chris Lattnerd06094f2009-11-10 00:55:12 +00001393 // A & ~A = ~A & A = 0
Chris Lattner81a0dc92011-02-09 17:15:04 +00001394 if (match(Op0, m_Not(m_Specific(Op1))) ||
1395 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001396 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001397
Chris Lattnerd06094f2009-11-10 00:55:12 +00001398 // (A | ?) & A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001399 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001400 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001401 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001402 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001403
Chris Lattnerd06094f2009-11-10 00:55:12 +00001404 // A & (A | ?) = A
1405 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001406 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001407 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001408
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001409 // A & (-A) = A if A is a power of two or zero.
1410 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1411 match(Op1, m_Neg(m_Specific(Op0)))) {
1412 if (isPowerOfTwo(Op0, TD, /*OrZero*/true))
1413 return Op0;
1414 if (isPowerOfTwo(Op1, TD, /*OrZero*/true))
1415 return Op1;
1416 }
1417
Duncan Sands566edb02010-12-21 08:49:00 +00001418 // Try some generic simplifications for associative operations.
Chad Rosier618c1db2011-12-01 03:08:23 +00001419 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, TLI,
1420 DT, MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001421 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001422
Duncan Sands3421d902010-12-21 13:32:22 +00001423 // And distributes over Or. Try some generic simplifications based on this.
1424 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Chad Rosier618c1db2011-12-01 03:08:23 +00001425 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001426 return V;
1427
1428 // And distributes over Xor. Try some generic simplifications based on this.
1429 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Chad Rosier618c1db2011-12-01 03:08:23 +00001430 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001431 return V;
1432
1433 // Or distributes over And. Try some generic simplifications based on this.
1434 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Chad Rosier618c1db2011-12-01 03:08:23 +00001435 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001436 return V;
1437
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001438 // If the operation is with the result of a select instruction, check whether
1439 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001440 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001441 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, TLI,
1442 DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001443 return V;
1444
1445 // If the operation is with the result of a phi instruction, check whether
1446 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001447 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001448 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, TLI, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001449 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001450 return V;
1451
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001452 return 0;
1453}
1454
Duncan Sands18450092010-11-16 12:16:38 +00001455Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001456 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +00001457 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001458 return ::SimplifyAndInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001459}
1460
Chris Lattnerd06094f2009-11-10 00:55:12 +00001461/// SimplifyOrInst - Given operands for an Or, see if we can
1462/// fold the result. If not, this returns null.
Chad Rosier618c1db2011-12-01 03:08:23 +00001463static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1464 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +00001465 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001466 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1467 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1468 Constant *Ops[] = { CLHS, CRHS };
1469 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
Chad Rosier618c1db2011-12-01 03:08:23 +00001470 Ops, TD, TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001471 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001472
Chris Lattnerd06094f2009-11-10 00:55:12 +00001473 // Canonicalize the constant to the RHS.
1474 std::swap(Op0, Op1);
1475 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001476
Chris Lattnerd06094f2009-11-10 00:55:12 +00001477 // X | undef -> -1
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001478 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001479 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001480
Chris Lattnerd06094f2009-11-10 00:55:12 +00001481 // X | X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001482 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001483 return Op0;
1484
Duncan Sands2b749872010-11-17 18:52:15 +00001485 // X | 0 = X
1486 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001487 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001488
Duncan Sands2b749872010-11-17 18:52:15 +00001489 // X | -1 = -1
1490 if (match(Op1, m_AllOnes()))
1491 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001492
Chris Lattnerd06094f2009-11-10 00:55:12 +00001493 // A | ~A = ~A | A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001494 if (match(Op0, m_Not(m_Specific(Op1))) ||
1495 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001496 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001497
Chris Lattnerd06094f2009-11-10 00:55:12 +00001498 // (A & ?) | A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001499 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001500 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001501 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001502 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001503
Chris Lattnerd06094f2009-11-10 00:55:12 +00001504 // A | (A & ?) = A
1505 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001506 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001507 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001508
Benjamin Kramer38f7f662011-02-20 15:20:01 +00001509 // ~(A & ?) | A = -1
1510 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1511 (A == Op1 || B == Op1))
1512 return Constant::getAllOnesValue(Op1->getType());
1513
1514 // A | ~(A & ?) = -1
1515 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1516 (A == Op0 || B == Op0))
1517 return Constant::getAllOnesValue(Op0->getType());
1518
Duncan Sands566edb02010-12-21 08:49:00 +00001519 // Try some generic simplifications for associative operations.
Chad Rosier618c1db2011-12-01 03:08:23 +00001520 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, TLI,
1521 DT, MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001522 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001523
Duncan Sands3421d902010-12-21 13:32:22 +00001524 // Or distributes over And. Try some generic simplifications based on this.
Chad Rosier618c1db2011-12-01 03:08:23 +00001525 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, TD,
1526 TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001527 return V;
1528
1529 // And distributes over Or. Try some generic simplifications based on this.
1530 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
Chad Rosier618c1db2011-12-01 03:08:23 +00001531 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001532 return V;
1533
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001534 // If the operation is with the result of a select instruction, check whether
1535 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001536 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001537 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, TLI, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001538 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001539 return V;
1540
1541 // If the operation is with the result of a phi instruction, check whether
1542 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001543 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001544 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, TLI, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001545 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001546 return V;
1547
Chris Lattnerd06094f2009-11-10 00:55:12 +00001548 return 0;
1549}
1550
Duncan Sands18450092010-11-16 12:16:38 +00001551Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001552 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +00001553 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001554 return ::SimplifyOrInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001555}
Chris Lattnerd06094f2009-11-10 00:55:12 +00001556
Duncan Sands2b749872010-11-17 18:52:15 +00001557/// SimplifyXorInst - Given operands for a Xor, see if we can
1558/// fold the result. If not, this returns null.
1559static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001560 const TargetLibraryInfo *TLI,
Duncan Sands2b749872010-11-17 18:52:15 +00001561 const DominatorTree *DT, unsigned MaxRecurse) {
1562 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1563 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1564 Constant *Ops[] = { CLHS, CRHS };
1565 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
Chad Rosier618c1db2011-12-01 03:08:23 +00001566 Ops, TD, TLI);
Duncan Sands2b749872010-11-17 18:52:15 +00001567 }
1568
1569 // Canonicalize the constant to the RHS.
1570 std::swap(Op0, Op1);
1571 }
1572
1573 // A ^ undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001574 if (match(Op1, m_Undef()))
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00001575 return Op1;
Duncan Sands2b749872010-11-17 18:52:15 +00001576
1577 // A ^ 0 = A
1578 if (match(Op1, m_Zero()))
1579 return Op0;
1580
Eli Friedmanf23d4ad2011-08-17 19:31:49 +00001581 // A ^ A = 0
1582 if (Op0 == Op1)
1583 return Constant::getNullValue(Op0->getType());
1584
Duncan Sands2b749872010-11-17 18:52:15 +00001585 // A ^ ~A = ~A ^ A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001586 if (match(Op0, m_Not(m_Specific(Op1))) ||
1587 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands2b749872010-11-17 18:52:15 +00001588 return Constant::getAllOnesValue(Op0->getType());
1589
Duncan Sands566edb02010-12-21 08:49:00 +00001590 // Try some generic simplifications for associative operations.
Chad Rosier618c1db2011-12-01 03:08:23 +00001591 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, TLI,
1592 DT, MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001593 return V;
Duncan Sands2b749872010-11-17 18:52:15 +00001594
Duncan Sands3421d902010-12-21 13:32:22 +00001595 // And distributes over Xor. Try some generic simplifications based on this.
1596 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
Chad Rosier618c1db2011-12-01 03:08:23 +00001597 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001598 return V;
1599
Duncan Sands87689cf2010-11-19 09:20:39 +00001600 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1601 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1602 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1603 // only if B and C are equal. If B and C are equal then (since we assume
1604 // that operands have already been simplified) "select(cond, B, C)" should
1605 // have been simplified to the common value of B and C already. Analysing
1606 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1607 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +00001608
1609 return 0;
1610}
1611
1612Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001613 const TargetLibraryInfo *TLI,
Duncan Sands2b749872010-11-17 18:52:15 +00001614 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001615 return ::SimplifyXorInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sands2b749872010-11-17 18:52:15 +00001616}
1617
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001618static Type *GetCompareTy(Value *Op) {
Chris Lattner210c5d42009-11-09 23:55:12 +00001619 return CmpInst::makeCmpResultType(Op->getType());
1620}
1621
Duncan Sandse864b5b2011-05-07 16:56:49 +00001622/// ExtractEquivalentCondition - Rummage around inside V looking for something
1623/// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1624/// otherwise return null. Helper function for analyzing max/min idioms.
1625static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1626 Value *LHS, Value *RHS) {
1627 SelectInst *SI = dyn_cast<SelectInst>(V);
1628 if (!SI)
1629 return 0;
1630 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1631 if (!Cmp)
1632 return 0;
1633 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1634 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1635 return Cmp;
1636 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1637 LHS == CmpRHS && RHS == CmpLHS)
1638 return Cmp;
1639 return 0;
1640}
1641
Chris Lattner009e2652012-02-24 19:01:58 +00001642
Chris Lattner9dbb4292009-11-09 23:28:39 +00001643/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1644/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001645static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00001646 const TargetData *TD,
1647 const TargetLibraryInfo *TLI,
1648 const DominatorTree *DT,
Duncan Sands18450092010-11-16 12:16:38 +00001649 unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001650 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +00001651 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +00001652
Chris Lattnerd06094f2009-11-10 00:55:12 +00001653 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +00001654 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00001655 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD, TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001656
1657 // If we have a constant, make sure it is on the RHS.
1658 std::swap(LHS, RHS);
1659 Pred = CmpInst::getSwappedPredicate(Pred);
1660 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001661
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001662 Type *ITy = GetCompareTy(LHS); // The return type.
1663 Type *OpTy = LHS->getType(); // The operand type.
Duncan Sands12a86f52010-11-14 11:23:23 +00001664
Chris Lattner210c5d42009-11-09 23:55:12 +00001665 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +00001666 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1667 // because X could be 0.
Duncan Sands124708d2011-01-01 20:08:02 +00001668 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +00001669 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +00001670
Duncan Sands6dc91252011-01-13 08:56:29 +00001671 // Special case logic when the operands have i1 type.
Nick Lewycky66d004e2011-12-01 02:39:36 +00001672 if (OpTy->getScalarType()->isIntegerTy(1)) {
Duncan Sands6dc91252011-01-13 08:56:29 +00001673 switch (Pred) {
1674 default: break;
1675 case ICmpInst::ICMP_EQ:
1676 // X == 1 -> X
1677 if (match(RHS, m_One()))
1678 return LHS;
1679 break;
1680 case ICmpInst::ICMP_NE:
1681 // X != 0 -> X
1682 if (match(RHS, m_Zero()))
1683 return LHS;
1684 break;
1685 case ICmpInst::ICMP_UGT:
1686 // X >u 0 -> X
1687 if (match(RHS, m_Zero()))
1688 return LHS;
1689 break;
1690 case ICmpInst::ICMP_UGE:
1691 // X >=u 1 -> X
1692 if (match(RHS, m_One()))
1693 return LHS;
1694 break;
1695 case ICmpInst::ICMP_SLT:
1696 // X <s 0 -> X
1697 if (match(RHS, m_Zero()))
1698 return LHS;
1699 break;
1700 case ICmpInst::ICMP_SLE:
1701 // X <=s -1 -> X
1702 if (match(RHS, m_One()))
1703 return LHS;
1704 break;
1705 }
1706 }
1707
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001708 // icmp <object*>, <object*/null> - Different identified objects have
1709 // different addresses (unless null), and what's more the address of an
1710 // identified local is never equal to another argument (again, barring null).
1711 // Note that generalizing to the case where LHS is a global variable address
1712 // or null is pointless, since if both LHS and RHS are constants then we
1713 // already constant folded the compare, and if only one of them is then we
1714 // moved it to RHS already.
Benjamin Kramerea79b8e2012-02-16 15:19:59 +00001715 Value *LHSPtr = LHS->stripPointerCasts();
1716 Value *RHSPtr = RHS->stripPointerCasts();
Eli Friedman2c3acb02012-02-18 03:29:25 +00001717 if (LHSPtr == RHSPtr)
1718 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001719
Chris Lattnerb053fc12012-02-20 00:42:49 +00001720 // Be more aggressive about stripping pointer adjustments when checking a
1721 // comparison of an alloca address to another object. We can rip off all
1722 // inbounds GEP operations, even if they are variable.
Chandler Carruth84dfc322012-03-10 08:39:09 +00001723 LHSPtr = LHSPtr->stripInBoundsOffsets();
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001724 if (llvm::isIdentifiedObject(LHSPtr)) {
Chandler Carruth84dfc322012-03-10 08:39:09 +00001725 RHSPtr = RHSPtr->stripInBoundsOffsets();
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001726 if (llvm::isKnownNonNull(LHSPtr) || llvm::isKnownNonNull(RHSPtr)) {
1727 // If both sides are different identified objects, they aren't equal
1728 // unless they're null.
Bill Wendlingc17731d652012-03-10 17:56:03 +00001729 if (LHSPtr != RHSPtr && llvm::isIdentifiedObject(RHSPtr) &&
Bill Wendling798d0132012-03-10 18:20:55 +00001730 Pred == CmpInst::ICMP_EQ)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001731 return ConstantInt::get(ITy, false);
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001732
1733 // A local identified object (alloca or noalias call) can't equal any
1734 // incoming argument, unless they're both null.
Bill Wendlingc17731d652012-03-10 17:56:03 +00001735 if (isa<Instruction>(LHSPtr) && isa<Argument>(RHSPtr) &&
Bill Wendling798d0132012-03-10 18:20:55 +00001736 Pred == CmpInst::ICMP_EQ)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001737 return ConstantInt::get(ITy, false);
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001738 }
1739
1740 // Assume that the constant null is on the right.
Bill Wendlingc17731d652012-03-10 17:56:03 +00001741 if (llvm::isKnownNonNull(LHSPtr) && isa<ConstantPointerNull>(RHSPtr)) {
Bill Wendling798d0132012-03-10 18:20:55 +00001742 if (Pred == CmpInst::ICMP_EQ)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001743 return ConstantInt::get(ITy, false);
Bill Wendling798d0132012-03-10 18:20:55 +00001744 else if (Pred == CmpInst::ICMP_NE)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001745 return ConstantInt::get(ITy, true);
1746 }
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001747 } else if (isa<Argument>(LHSPtr)) {
Chandler Carruth84dfc322012-03-10 08:39:09 +00001748 RHSPtr = RHSPtr->stripInBoundsOffsets();
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001749 // An alloca can't be equal to an argument.
Bill Wendlingc17731d652012-03-10 17:56:03 +00001750 if (isa<AllocaInst>(RHSPtr)) {
Bill Wendling798d0132012-03-10 18:20:55 +00001751 if (Pred == CmpInst::ICMP_EQ)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001752 return ConstantInt::get(ITy, false);
Bill Wendling798d0132012-03-10 18:20:55 +00001753 else if (Pred == CmpInst::ICMP_NE)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001754 return ConstantInt::get(ITy, true);
1755 }
Chris Lattnerb053fc12012-02-20 00:42:49 +00001756 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001757
1758 // If we are comparing with zero then try hard since this is a common case.
1759 if (match(RHS, m_Zero())) {
1760 bool LHSKnownNonNegative, LHSKnownNegative;
1761 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00001762 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001763 case ICmpInst::ICMP_ULT:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001764 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001765 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001766 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001767 case ICmpInst::ICMP_EQ:
1768 case ICmpInst::ICMP_ULE:
1769 if (isKnownNonZero(LHS, TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001770 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001771 break;
1772 case ICmpInst::ICMP_NE:
1773 case ICmpInst::ICMP_UGT:
1774 if (isKnownNonZero(LHS, TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001775 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001776 break;
1777 case ICmpInst::ICMP_SLT:
1778 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1779 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001780 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001781 if (LHSKnownNonNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001782 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001783 break;
1784 case ICmpInst::ICMP_SLE:
1785 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1786 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001787 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001788 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001789 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001790 break;
1791 case ICmpInst::ICMP_SGE:
1792 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1793 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001794 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001795 if (LHSKnownNonNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001796 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001797 break;
1798 case ICmpInst::ICMP_SGT:
1799 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1800 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001801 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001802 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001803 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001804 break;
1805 }
1806 }
1807
1808 // See if we are doing a comparison with a constant integer.
Duncan Sands6dc91252011-01-13 08:56:29 +00001809 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Nick Lewycky3a73e342011-03-04 07:00:57 +00001810 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1811 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1812 if (RHS_CR.isEmptySet())
1813 return ConstantInt::getFalse(CI->getContext());
1814 if (RHS_CR.isFullSet())
1815 return ConstantInt::getTrue(CI->getContext());
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001816
Nick Lewycky3a73e342011-03-04 07:00:57 +00001817 // Many binary operators with constant RHS have easy to compute constant
1818 // range. Use them to check whether the comparison is a tautology.
1819 uint32_t Width = CI->getBitWidth();
1820 APInt Lower = APInt(Width, 0);
1821 APInt Upper = APInt(Width, 0);
1822 ConstantInt *CI2;
1823 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1824 // 'urem x, CI2' produces [0, CI2).
1825 Upper = CI2->getValue();
1826 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1827 // 'srem x, CI2' produces (-|CI2|, |CI2|).
1828 Upper = CI2->getValue().abs();
1829 Lower = (-Upper) + 1;
Duncan Sandsc65c7472011-10-28 18:17:44 +00001830 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
1831 // 'udiv CI2, x' produces [0, CI2].
Eli Friedman7781ae52011-11-08 21:08:02 +00001832 Upper = CI2->getValue() + 1;
Nick Lewycky3a73e342011-03-04 07:00:57 +00001833 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1834 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1835 APInt NegOne = APInt::getAllOnesValue(Width);
1836 if (!CI2->isZero())
1837 Upper = NegOne.udiv(CI2->getValue()) + 1;
1838 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1839 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1840 APInt IntMin = APInt::getSignedMinValue(Width);
1841 APInt IntMax = APInt::getSignedMaxValue(Width);
1842 APInt Val = CI2->getValue().abs();
1843 if (!Val.isMinValue()) {
1844 Lower = IntMin.sdiv(Val);
1845 Upper = IntMax.sdiv(Val) + 1;
1846 }
1847 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1848 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1849 APInt NegOne = APInt::getAllOnesValue(Width);
1850 if (CI2->getValue().ult(Width))
1851 Upper = NegOne.lshr(CI2->getValue()) + 1;
1852 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1853 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1854 APInt IntMin = APInt::getSignedMinValue(Width);
1855 APInt IntMax = APInt::getSignedMaxValue(Width);
1856 if (CI2->getValue().ult(Width)) {
1857 Lower = IntMin.ashr(CI2->getValue());
1858 Upper = IntMax.ashr(CI2->getValue()) + 1;
1859 }
1860 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1861 // 'or x, CI2' produces [CI2, UINT_MAX].
1862 Lower = CI2->getValue();
1863 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1864 // 'and x, CI2' produces [0, CI2].
1865 Upper = CI2->getValue() + 1;
1866 }
1867 if (Lower != Upper) {
1868 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1869 if (RHS_CR.contains(LHS_CR))
1870 return ConstantInt::getTrue(RHS->getContext());
1871 if (RHS_CR.inverse().contains(LHS_CR))
1872 return ConstantInt::getFalse(RHS->getContext());
1873 }
Duncan Sands6dc91252011-01-13 08:56:29 +00001874 }
1875
Duncan Sands9d32f602011-01-20 13:21:55 +00001876 // Compare of cast, for example (zext X) != 0 -> X != 0
1877 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1878 Instruction *LI = cast<CastInst>(LHS);
1879 Value *SrcOp = LI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001880 Type *SrcTy = SrcOp->getType();
1881 Type *DstTy = LI->getType();
Duncan Sands9d32f602011-01-20 13:21:55 +00001882
1883 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1884 // if the integer type is the same size as the pointer type.
1885 if (MaxRecurse && TD && isa<PtrToIntInst>(LI) &&
1886 TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
1887 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1888 // Transfer the cast to the constant.
1889 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1890 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Chad Rosier618c1db2011-12-01 03:08:23 +00001891 TD, TLI, DT, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001892 return V;
1893 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1894 if (RI->getOperand(0)->getType() == SrcTy)
1895 // Compare without the cast.
1896 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Chad Rosier618c1db2011-12-01 03:08:23 +00001897 TD, TLI, DT, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001898 return V;
1899 }
1900 }
1901
1902 if (isa<ZExtInst>(LHS)) {
1903 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1904 // same type.
1905 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1906 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1907 // Compare X and Y. Note that signed predicates become unsigned.
1908 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Chad Rosier618c1db2011-12-01 03:08:23 +00001909 SrcOp, RI->getOperand(0), TD, TLI, DT,
Duncan Sands9d32f602011-01-20 13:21:55 +00001910 MaxRecurse-1))
1911 return V;
1912 }
1913 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1914 // too. If not, then try to deduce the result of the comparison.
1915 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1916 // Compute the constant that would happen if we truncated to SrcTy then
1917 // reextended to DstTy.
1918 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1919 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1920
1921 // If the re-extended constant didn't change then this is effectively
1922 // also a case of comparing two zero-extended values.
1923 if (RExt == CI && MaxRecurse)
1924 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Nadav Rotem16087692011-12-05 06:29:09 +00001925 SrcOp, Trunc, TD, TLI, DT, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001926 return V;
1927
1928 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1929 // there. Use this to work out the result of the comparison.
1930 if (RExt != CI) {
1931 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00001932 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands9d32f602011-01-20 13:21:55 +00001933 // LHS <u RHS.
1934 case ICmpInst::ICMP_EQ:
1935 case ICmpInst::ICMP_UGT:
1936 case ICmpInst::ICMP_UGE:
1937 return ConstantInt::getFalse(CI->getContext());
1938
1939 case ICmpInst::ICMP_NE:
1940 case ICmpInst::ICMP_ULT:
1941 case ICmpInst::ICMP_ULE:
1942 return ConstantInt::getTrue(CI->getContext());
1943
1944 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
1945 // is non-negative then LHS <s RHS.
1946 case ICmpInst::ICMP_SGT:
1947 case ICmpInst::ICMP_SGE:
1948 return CI->getValue().isNegative() ?
1949 ConstantInt::getTrue(CI->getContext()) :
1950 ConstantInt::getFalse(CI->getContext());
1951
1952 case ICmpInst::ICMP_SLT:
1953 case ICmpInst::ICMP_SLE:
1954 return CI->getValue().isNegative() ?
1955 ConstantInt::getFalse(CI->getContext()) :
1956 ConstantInt::getTrue(CI->getContext());
1957 }
1958 }
1959 }
1960 }
1961
1962 if (isa<SExtInst>(LHS)) {
1963 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1964 // same type.
1965 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1966 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1967 // Compare X and Y. Note that the predicate does not change.
1968 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Chad Rosier618c1db2011-12-01 03:08:23 +00001969 TD, TLI, DT, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001970 return V;
1971 }
1972 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1973 // too. If not, then try to deduce the result of the comparison.
1974 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1975 // Compute the constant that would happen if we truncated to SrcTy then
1976 // reextended to DstTy.
1977 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1978 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1979
1980 // If the re-extended constant didn't change then this is effectively
1981 // also a case of comparing two sign-extended values.
1982 if (RExt == CI && MaxRecurse)
Chad Rosier618c1db2011-12-01 03:08:23 +00001983 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, TD, TLI, DT,
Duncan Sands9d32f602011-01-20 13:21:55 +00001984 MaxRecurse-1))
1985 return V;
1986
1987 // Otherwise the upper bits of LHS are all equal, while RHS has varying
1988 // bits there. Use this to work out the result of the comparison.
1989 if (RExt != CI) {
1990 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00001991 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands9d32f602011-01-20 13:21:55 +00001992 case ICmpInst::ICMP_EQ:
1993 return ConstantInt::getFalse(CI->getContext());
1994 case ICmpInst::ICMP_NE:
1995 return ConstantInt::getTrue(CI->getContext());
1996
1997 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
1998 // LHS >s RHS.
1999 case ICmpInst::ICMP_SGT:
2000 case ICmpInst::ICMP_SGE:
2001 return CI->getValue().isNegative() ?
2002 ConstantInt::getTrue(CI->getContext()) :
2003 ConstantInt::getFalse(CI->getContext());
2004 case ICmpInst::ICMP_SLT:
2005 case ICmpInst::ICMP_SLE:
2006 return CI->getValue().isNegative() ?
2007 ConstantInt::getFalse(CI->getContext()) :
2008 ConstantInt::getTrue(CI->getContext());
2009
2010 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
2011 // LHS >u RHS.
2012 case ICmpInst::ICMP_UGT:
2013 case ICmpInst::ICMP_UGE:
2014 // Comparison is true iff the LHS <s 0.
2015 if (MaxRecurse)
2016 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2017 Constant::getNullValue(SrcTy),
Chad Rosier618c1db2011-12-01 03:08:23 +00002018 TD, TLI, DT, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00002019 return V;
2020 break;
2021 case ICmpInst::ICMP_ULT:
2022 case ICmpInst::ICMP_ULE:
2023 // Comparison is true iff the LHS >=s 0.
2024 if (MaxRecurse)
2025 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2026 Constant::getNullValue(SrcTy),
Chad Rosier618c1db2011-12-01 03:08:23 +00002027 TD, TLI, DT, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00002028 return V;
2029 break;
2030 }
2031 }
2032 }
2033 }
2034 }
2035
Duncan Sands52fb8462011-02-13 17:15:40 +00002036 // Special logic for binary operators.
2037 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2038 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2039 if (MaxRecurse && (LBO || RBO)) {
Duncan Sands52fb8462011-02-13 17:15:40 +00002040 // Analyze the case when either LHS or RHS is an add instruction.
2041 Value *A = 0, *B = 0, *C = 0, *D = 0;
2042 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2043 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2044 if (LBO && LBO->getOpcode() == Instruction::Add) {
2045 A = LBO->getOperand(0); B = LBO->getOperand(1);
2046 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2047 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2048 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2049 }
2050 if (RBO && RBO->getOpcode() == Instruction::Add) {
2051 C = RBO->getOperand(0); D = RBO->getOperand(1);
2052 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2053 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2054 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2055 }
2056
2057 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2058 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2059 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2060 Constant::getNullValue(RHS->getType()),
Chad Rosier618c1db2011-12-01 03:08:23 +00002061 TD, TLI, DT, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00002062 return V;
2063
2064 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2065 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2066 if (Value *V = SimplifyICmpInst(Pred,
2067 Constant::getNullValue(LHS->getType()),
Chad Rosier618c1db2011-12-01 03:08:23 +00002068 C == LHS ? D : C, TD, TLI, DT, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00002069 return V;
2070
2071 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2072 if (A && C && (A == C || A == D || B == C || B == D) &&
2073 NoLHSWrapProblem && NoRHSWrapProblem) {
2074 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2075 Value *Y = (A == C || A == D) ? B : A;
2076 Value *Z = (C == A || C == B) ? D : C;
Chad Rosier618c1db2011-12-01 03:08:23 +00002077 if (Value *V = SimplifyICmpInst(Pred, Y, Z, TD, TLI, DT, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00002078 return V;
2079 }
2080 }
2081
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002082 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Nick Lewycky78679272011-03-04 10:06:52 +00002083 bool KnownNonNegative, KnownNegative;
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002084 switch (Pred) {
2085 default:
2086 break;
Nick Lewycky78679272011-03-04 10:06:52 +00002087 case ICmpInst::ICMP_SGT:
2088 case ICmpInst::ICMP_SGE:
2089 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
2090 if (!KnownNonNegative)
2091 break;
2092 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002093 case ICmpInst::ICMP_EQ:
2094 case ICmpInst::ICMP_UGT:
2095 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002096 return getFalse(ITy);
Nick Lewycky78679272011-03-04 10:06:52 +00002097 case ICmpInst::ICMP_SLT:
2098 case ICmpInst::ICMP_SLE:
2099 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
2100 if (!KnownNonNegative)
2101 break;
2102 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002103 case ICmpInst::ICMP_NE:
2104 case ICmpInst::ICMP_ULT:
2105 case ICmpInst::ICMP_ULE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002106 return getTrue(ITy);
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002107 }
2108 }
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002109 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2110 bool KnownNonNegative, KnownNegative;
2111 switch (Pred) {
2112 default:
2113 break;
2114 case ICmpInst::ICMP_SGT:
2115 case ICmpInst::ICMP_SGE:
2116 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
2117 if (!KnownNonNegative)
2118 break;
2119 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00002120 case ICmpInst::ICMP_NE:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002121 case ICmpInst::ICMP_UGT:
2122 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002123 return getTrue(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002124 case ICmpInst::ICMP_SLT:
2125 case ICmpInst::ICMP_SLE:
2126 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
2127 if (!KnownNonNegative)
2128 break;
2129 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00002130 case ICmpInst::ICMP_EQ:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002131 case ICmpInst::ICMP_ULT:
2132 case ICmpInst::ICMP_ULE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002133 return getFalse(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002134 }
2135 }
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002136
Duncan Sandsc65c7472011-10-28 18:17:44 +00002137 // x udiv y <=u x.
2138 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2139 // icmp pred (X /u Y), X
2140 if (Pred == ICmpInst::ICMP_UGT)
2141 return getFalse(ITy);
2142 if (Pred == ICmpInst::ICMP_ULE)
2143 return getTrue(ITy);
2144 }
2145
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002146 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2147 LBO->getOperand(1) == RBO->getOperand(1)) {
2148 switch (LBO->getOpcode()) {
2149 default: break;
2150 case Instruction::UDiv:
2151 case Instruction::LShr:
2152 if (ICmpInst::isSigned(Pred))
2153 break;
2154 // fall-through
2155 case Instruction::SDiv:
2156 case Instruction::AShr:
Eli Friedmanb6e7cd62011-05-05 21:59:18 +00002157 if (!LBO->isExact() || !RBO->isExact())
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002158 break;
2159 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Chad Rosier618c1db2011-12-01 03:08:23 +00002160 RBO->getOperand(0), TD, TLI, DT, MaxRecurse-1))
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002161 return V;
2162 break;
2163 case Instruction::Shl: {
Duncan Sandsc9d904e2011-08-04 10:02:21 +00002164 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002165 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2166 if (!NUW && !NSW)
2167 break;
2168 if (!NSW && ICmpInst::isSigned(Pred))
2169 break;
2170 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Chad Rosier618c1db2011-12-01 03:08:23 +00002171 RBO->getOperand(0), TD, TLI, DT, MaxRecurse-1))
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002172 return V;
2173 break;
2174 }
2175 }
2176 }
2177
Duncan Sandsad206812011-05-03 19:53:10 +00002178 // Simplify comparisons involving max/min.
2179 Value *A, *B;
2180 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2181 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2182
Duncan Sands8140ad32011-05-04 16:05:05 +00002183 // Signed variants on "max(a,b)>=a -> true".
Duncan Sandsad206812011-05-03 19:53:10 +00002184 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2185 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2186 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2187 // We analyze this as smax(A, B) pred A.
2188 P = Pred;
2189 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2190 (A == LHS || B == LHS)) {
2191 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2192 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2193 // We analyze this as smax(A, B) swapped-pred A.
2194 P = CmpInst::getSwappedPredicate(Pred);
2195 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2196 (A == RHS || B == RHS)) {
2197 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2198 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2199 // We analyze this as smax(-A, -B) swapped-pred -A.
2200 // Note that we do not need to actually form -A or -B thanks to EqP.
2201 P = CmpInst::getSwappedPredicate(Pred);
2202 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2203 (A == LHS || B == LHS)) {
2204 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2205 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2206 // We analyze this as smax(-A, -B) pred -A.
2207 // Note that we do not need to actually form -A or -B thanks to EqP.
2208 P = Pred;
2209 }
2210 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2211 // Cases correspond to "max(A, B) p A".
2212 switch (P) {
2213 default:
2214 break;
2215 case CmpInst::ICMP_EQ:
2216 case CmpInst::ICMP_SLE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002217 // Equivalent to "A EqP B". This may be the same as the condition tested
2218 // in the max/min; if so, we can just return that.
2219 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2220 return V;
2221 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2222 return V;
2223 // Otherwise, see if "A EqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002224 if (MaxRecurse)
Chad Rosier618c1db2011-12-01 03:08:23 +00002225 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002226 return V;
2227 break;
2228 case CmpInst::ICMP_NE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002229 case CmpInst::ICMP_SGT: {
2230 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2231 // Equivalent to "A InvEqP B". This may be the same as the condition
2232 // tested in the max/min; if so, we can just return that.
2233 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2234 return V;
2235 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2236 return V;
2237 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002238 if (MaxRecurse)
Chad Rosier618c1db2011-12-01 03:08:23 +00002239 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002240 return V;
2241 break;
Duncan Sandse864b5b2011-05-07 16:56:49 +00002242 }
Duncan Sandsad206812011-05-03 19:53:10 +00002243 case CmpInst::ICMP_SGE:
2244 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002245 return getTrue(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002246 case CmpInst::ICMP_SLT:
2247 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002248 return getFalse(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002249 }
2250 }
2251
Duncan Sands8140ad32011-05-04 16:05:05 +00002252 // Unsigned variants on "max(a,b)>=a -> true".
Duncan Sandsad206812011-05-03 19:53:10 +00002253 P = CmpInst::BAD_ICMP_PREDICATE;
2254 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2255 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2256 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2257 // We analyze this as umax(A, B) pred A.
2258 P = Pred;
2259 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2260 (A == LHS || B == LHS)) {
2261 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2262 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2263 // We analyze this as umax(A, B) swapped-pred A.
2264 P = CmpInst::getSwappedPredicate(Pred);
2265 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2266 (A == RHS || B == RHS)) {
2267 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2268 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2269 // We analyze this as umax(-A, -B) swapped-pred -A.
2270 // Note that we do not need to actually form -A or -B thanks to EqP.
2271 P = CmpInst::getSwappedPredicate(Pred);
2272 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2273 (A == LHS || B == LHS)) {
2274 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2275 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2276 // We analyze this as umax(-A, -B) pred -A.
2277 // Note that we do not need to actually form -A or -B thanks to EqP.
2278 P = Pred;
2279 }
2280 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2281 // Cases correspond to "max(A, B) p A".
2282 switch (P) {
2283 default:
2284 break;
2285 case CmpInst::ICMP_EQ:
2286 case CmpInst::ICMP_ULE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002287 // Equivalent to "A EqP B". This may be the same as the condition tested
2288 // in the max/min; if so, we can just return that.
2289 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2290 return V;
2291 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2292 return V;
2293 // Otherwise, see if "A EqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002294 if (MaxRecurse)
Chad Rosier618c1db2011-12-01 03:08:23 +00002295 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002296 return V;
2297 break;
2298 case CmpInst::ICMP_NE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002299 case CmpInst::ICMP_UGT: {
2300 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2301 // Equivalent to "A InvEqP B". This may be the same as the condition
2302 // tested in the max/min; if so, we can just return that.
2303 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2304 return V;
2305 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2306 return V;
2307 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002308 if (MaxRecurse)
Chad Rosier618c1db2011-12-01 03:08:23 +00002309 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002310 return V;
2311 break;
Duncan Sandse864b5b2011-05-07 16:56:49 +00002312 }
Duncan Sandsad206812011-05-03 19:53:10 +00002313 case CmpInst::ICMP_UGE:
2314 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002315 return getTrue(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002316 case CmpInst::ICMP_ULT:
2317 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002318 return getFalse(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002319 }
2320 }
2321
Duncan Sands8140ad32011-05-04 16:05:05 +00002322 // Variants on "max(x,y) >= min(x,z)".
2323 Value *C, *D;
2324 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2325 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2326 (A == C || A == D || B == C || B == D)) {
2327 // max(x, ?) pred min(x, ?).
2328 if (Pred == CmpInst::ICMP_SGE)
2329 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002330 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002331 if (Pred == CmpInst::ICMP_SLT)
2332 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002333 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002334 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2335 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2336 (A == C || A == D || B == C || B == D)) {
2337 // min(x, ?) pred max(x, ?).
2338 if (Pred == CmpInst::ICMP_SLE)
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_SGT)
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_UMax(m_Value(A), m_Value(B))) &&
2345 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2346 (A == C || A == D || B == C || B == D)) {
2347 // max(x, ?) pred min(x, ?).
2348 if (Pred == CmpInst::ICMP_UGE)
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_ULT)
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_UMin(m_Value(A), m_Value(B))) &&
2355 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2356 (A == C || A == D || B == C || B == D)) {
2357 // min(x, ?) pred max(x, ?).
2358 if (Pred == CmpInst::ICMP_ULE)
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_UGT)
2362 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002363 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002364 }
2365
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00002366 // Simplify comparisons of GEPs.
2367 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2368 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2369 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2370 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2371 (ICmpInst::isEquality(Pred) ||
2372 (GLHS->isInBounds() && GRHS->isInBounds() &&
2373 Pred == ICmpInst::getSignedPredicate(Pred)))) {
2374 // The bases are equal and the indices are constant. Build a constant
2375 // expression GEP with the same indices and a null base pointer to see
2376 // what constant folding can make out of it.
2377 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2378 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2379 Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2380
2381 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2382 Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2383 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2384 }
2385 }
2386 }
2387
Duncan Sands1ac7c992010-11-07 16:12:23 +00002388 // If the comparison is with the result of a select instruction, check whether
2389 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002390 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002391 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002392 return V;
2393
2394 // If the comparison is with the result of a phi instruction, check whether
2395 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00002396 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002397 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00002398 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +00002399
Chris Lattner9f3c25a2009-11-09 22:57:59 +00002400 return 0;
2401}
2402
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002403Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002404 const TargetData *TD,
2405 const TargetLibraryInfo *TLI,
2406 const DominatorTree *DT) {
2407 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002408}
2409
Chris Lattner9dbb4292009-11-09 23:28:39 +00002410/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2411/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002412static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002413 const TargetData *TD,
2414 const TargetLibraryInfo *TLI,
2415 const DominatorTree *DT,
Duncan Sands18450092010-11-16 12:16:38 +00002416 unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00002417 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2418 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2419
Chris Lattnerd06094f2009-11-10 00:55:12 +00002420 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00002421 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002422 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD, TLI);
Duncan Sands12a86f52010-11-14 11:23:23 +00002423
Chris Lattnerd06094f2009-11-10 00:55:12 +00002424 // If we have a constant, make sure it is on the RHS.
2425 std::swap(LHS, RHS);
2426 Pred = CmpInst::getSwappedPredicate(Pred);
2427 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002428
Chris Lattner210c5d42009-11-09 23:55:12 +00002429 // Fold trivial predicates.
2430 if (Pred == FCmpInst::FCMP_FALSE)
2431 return ConstantInt::get(GetCompareTy(LHS), 0);
2432 if (Pred == FCmpInst::FCMP_TRUE)
2433 return ConstantInt::get(GetCompareTy(LHS), 1);
2434
Chris Lattner210c5d42009-11-09 23:55:12 +00002435 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2436 return UndefValue::get(GetCompareTy(LHS));
2437
2438 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands124708d2011-01-01 20:08:02 +00002439 if (LHS == RHS) {
Chris Lattner210c5d42009-11-09 23:55:12 +00002440 if (CmpInst::isTrueWhenEqual(Pred))
2441 return ConstantInt::get(GetCompareTy(LHS), 1);
2442 if (CmpInst::isFalseWhenEqual(Pred))
2443 return ConstantInt::get(GetCompareTy(LHS), 0);
2444 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002445
Chris Lattner210c5d42009-11-09 23:55:12 +00002446 // Handle fcmp with constant RHS
2447 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2448 // If the constant is a nan, see if we can fold the comparison based on it.
2449 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2450 if (CFP->getValueAPF().isNaN()) {
2451 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2452 return ConstantInt::getFalse(CFP->getContext());
2453 assert(FCmpInst::isUnordered(Pred) &&
2454 "Comparison must be either ordered or unordered!");
2455 // True if unordered.
2456 return ConstantInt::getTrue(CFP->getContext());
2457 }
Dan Gohman6b617a72010-02-22 04:06:03 +00002458 // Check whether the constant is an infinity.
2459 if (CFP->getValueAPF().isInfinity()) {
2460 if (CFP->getValueAPF().isNegative()) {
2461 switch (Pred) {
2462 case FCmpInst::FCMP_OLT:
2463 // No value is ordered and less than negative infinity.
2464 return ConstantInt::getFalse(CFP->getContext());
2465 case FCmpInst::FCMP_UGE:
2466 // All values are unordered with or at least negative infinity.
2467 return ConstantInt::getTrue(CFP->getContext());
2468 default:
2469 break;
2470 }
2471 } else {
2472 switch (Pred) {
2473 case FCmpInst::FCMP_OGT:
2474 // No value is ordered and greater than infinity.
2475 return ConstantInt::getFalse(CFP->getContext());
2476 case FCmpInst::FCMP_ULE:
2477 // All values are unordered with and at most infinity.
2478 return ConstantInt::getTrue(CFP->getContext());
2479 default:
2480 break;
2481 }
2482 }
2483 }
Chris Lattner210c5d42009-11-09 23:55:12 +00002484 }
2485 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002486
Duncan Sands92826de2010-11-07 16:46:25 +00002487 // If the comparison is with the result of a select instruction, check whether
2488 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002489 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002490 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002491 return V;
2492
2493 // If the comparison is with the result of a phi instruction, check whether
2494 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00002495 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002496 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00002497 return V;
Duncan Sands92826de2010-11-07 16:46:25 +00002498
Chris Lattner9dbb4292009-11-09 23:28:39 +00002499 return 0;
2500}
2501
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002502Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002503 const TargetData *TD,
2504 const TargetLibraryInfo *TLI,
2505 const DominatorTree *DT) {
2506 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002507}
2508
Chris Lattner04754262010-04-20 05:32:14 +00002509/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2510/// the result. If not, this returns null.
Duncan Sands124708d2011-01-01 20:08:02 +00002511Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
2512 const TargetData *TD, const DominatorTree *) {
Chris Lattner04754262010-04-20 05:32:14 +00002513 // select true, X, Y -> X
2514 // select false, X, Y -> Y
2515 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2516 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002517
Chris Lattner04754262010-04-20 05:32:14 +00002518 // select C, X, X -> X
Duncan Sands124708d2011-01-01 20:08:02 +00002519 if (TrueVal == FalseVal)
Chris Lattner04754262010-04-20 05:32:14 +00002520 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002521
Chris Lattner04754262010-04-20 05:32:14 +00002522 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2523 if (isa<Constant>(TrueVal))
2524 return TrueVal;
2525 return FalseVal;
2526 }
Dan Gohman68c0dbc2011-07-01 01:03:43 +00002527 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2528 return FalseVal;
2529 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2530 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002531
Chris Lattner04754262010-04-20 05:32:14 +00002532 return 0;
2533}
2534
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002535/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2536/// fold the result. If not, this returns null.
Chad Rosier618c1db2011-12-01 03:08:23 +00002537Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const TargetData *TD,
2538 const DominatorTree *) {
Duncan Sands85bbff62010-11-22 13:42:49 +00002539 // The type of the GEP pointer operand.
Nadav Rotem16087692011-12-05 06:29:09 +00002540 PointerType *PtrTy = dyn_cast<PointerType>(Ops[0]->getType());
2541 // The GEP pointer operand is not a pointer, it's a vector of pointers.
2542 if (!PtrTy)
2543 return 0;
Duncan Sands85bbff62010-11-22 13:42:49 +00002544
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002545 // getelementptr P -> P.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002546 if (Ops.size() == 1)
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002547 return Ops[0];
2548
Duncan Sands85bbff62010-11-22 13:42:49 +00002549 if (isa<UndefValue>(Ops[0])) {
2550 // Compute the (pointer) type returned by the GEP instruction.
Jay Foada9203102011-07-25 09:48:08 +00002551 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002552 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
Duncan Sands85bbff62010-11-22 13:42:49 +00002553 return UndefValue::get(GEPTy);
2554 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002555
Jay Foadb9b54eb2011-07-19 15:07:52 +00002556 if (Ops.size() == 2) {
Duncan Sandse60d79f2010-11-21 13:53:09 +00002557 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002558 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2559 if (C->isZero())
2560 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +00002561 // getelementptr P, N -> P if P points to a type of zero size.
2562 if (TD) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002563 Type *Ty = PtrTy->getElementType();
Duncan Sandsa63395a2010-11-22 16:32:50 +00002564 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +00002565 return Ops[0];
2566 }
2567 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002568
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002569 // Check to see if this is constant foldable.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002570 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002571 if (!isa<Constant>(Ops[i]))
2572 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +00002573
Jay Foaddab3d292011-07-21 14:31:17 +00002574 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002575}
2576
Duncan Sandsdabc2802011-09-05 06:52:48 +00002577/// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2578/// can fold the result. If not, this returns null.
2579Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2580 ArrayRef<unsigned> Idxs,
2581 const TargetData *,
2582 const DominatorTree *) {
2583 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2584 if (Constant *CVal = dyn_cast<Constant>(Val))
2585 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2586
2587 // insertvalue x, undef, n -> x
2588 if (match(Val, m_Undef()))
2589 return Agg;
2590
2591 // insertvalue x, (extractvalue y, n), n
2592 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramerae707bd2011-09-05 18:16:19 +00002593 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2594 EV->getIndices() == Idxs) {
Duncan Sandsdabc2802011-09-05 06:52:48 +00002595 // insertvalue undef, (extractvalue y, n), n -> y
2596 if (match(Agg, m_Undef()))
2597 return EV->getAggregateOperand();
2598
2599 // insertvalue y, (extractvalue y, n), n -> y
2600 if (Agg == EV->getAggregateOperand())
2601 return Agg;
2602 }
2603
2604 return 0;
2605}
2606
Duncan Sandsff103412010-11-17 04:30:22 +00002607/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
2608static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
2609 // If all of the PHI's incoming values are the same then replace the PHI node
2610 // with the common value.
2611 Value *CommonValue = 0;
2612 bool HasUndefInput = false;
2613 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2614 Value *Incoming = PN->getIncomingValue(i);
2615 // If the incoming value is the phi node itself, it can safely be skipped.
2616 if (Incoming == PN) continue;
2617 if (isa<UndefValue>(Incoming)) {
2618 // Remember that we saw an undef value, but otherwise ignore them.
2619 HasUndefInput = true;
2620 continue;
2621 }
2622 if (CommonValue && Incoming != CommonValue)
2623 return 0; // Not the same, bail out.
2624 CommonValue = Incoming;
2625 }
2626
2627 // If CommonValue is null then all of the incoming values were either undef or
2628 // equal to the phi node itself.
2629 if (!CommonValue)
2630 return UndefValue::get(PN->getType());
2631
2632 // If we have a PHI node like phi(X, undef, X), where X is defined by some
2633 // instruction, we cannot return X as the result of the PHI node unless it
2634 // dominates the PHI block.
2635 if (HasUndefInput)
2636 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
2637
2638 return CommonValue;
2639}
2640
Chris Lattnerd06094f2009-11-10 00:55:12 +00002641//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +00002642
Chris Lattnerd06094f2009-11-10 00:55:12 +00002643/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2644/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002645static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002646 const TargetData *TD,
2647 const TargetLibraryInfo *TLI,
2648 const DominatorTree *DT,
Duncan Sands18450092010-11-16 12:16:38 +00002649 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00002650 switch (Opcode) {
Chris Lattner81a0dc92011-02-09 17:15:04 +00002651 case Instruction::Add:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002652 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Chad Rosier618c1db2011-12-01 03:08:23 +00002653 TD, TLI, DT, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002654 case Instruction::Sub:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002655 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Chad Rosier618c1db2011-12-01 03:08:23 +00002656 TD, TLI, DT, MaxRecurse);
2657 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, TD, TLI, DT,
2658 MaxRecurse);
2659 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, TD, TLI, DT,
2660 MaxRecurse);
2661 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, TD, TLI, DT,
2662 MaxRecurse);
2663 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, TD, TLI, DT,
2664 MaxRecurse);
2665 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, TD, TLI, DT,
2666 MaxRecurse);
2667 case Instruction::URem: return SimplifyURemInst(LHS, RHS, TD, TLI, DT,
2668 MaxRecurse);
2669 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, TD, TLI, DT,
2670 MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002671 case Instruction::Shl:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002672 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Chad Rosier618c1db2011-12-01 03:08:23 +00002673 TD, TLI, DT, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002674 case Instruction::LShr:
Chad Rosier618c1db2011-12-01 03:08:23 +00002675 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, TD, TLI, DT,
2676 MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002677 case Instruction::AShr:
Chad Rosier618c1db2011-12-01 03:08:23 +00002678 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, TD, TLI, DT,
2679 MaxRecurse);
2680 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, TLI, DT,
2681 MaxRecurse);
2682 case Instruction::Or: return SimplifyOrInst (LHS, RHS, TD, TLI, DT,
2683 MaxRecurse);
2684 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, TLI, DT,
2685 MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002686 default:
2687 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2688 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2689 Constant *COps[] = {CLHS, CRHS};
Chad Rosier618c1db2011-12-01 03:08:23 +00002690 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, TD, TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002691 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002692
Duncan Sands566edb02010-12-21 08:49:00 +00002693 // If the operation is associative, try some generic simplifications.
2694 if (Instruction::isAssociative(Opcode))
Chad Rosier618c1db2011-12-01 03:08:23 +00002695 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, TLI, DT,
Duncan Sands566edb02010-12-21 08:49:00 +00002696 MaxRecurse))
2697 return V;
2698
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002699 // If the operation is with the result of a select instruction, check whether
2700 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002701 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002702 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, TLI, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00002703 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002704 return V;
2705
2706 // If the operation is with the result of a phi instruction, check whether
2707 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002708 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002709 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, TLI, DT,
2710 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002711 return V;
2712
Chris Lattnerd06094f2009-11-10 00:55:12 +00002713 return 0;
2714 }
2715}
Chris Lattner9dbb4292009-11-09 23:28:39 +00002716
Duncan Sands12a86f52010-11-14 11:23:23 +00002717Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002718 const TargetData *TD, const TargetLibraryInfo *TLI,
2719 const DominatorTree *DT) {
2720 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, TLI, DT, RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +00002721}
2722
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002723/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2724/// fold the result.
2725static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002726 const TargetData *TD,
2727 const TargetLibraryInfo *TLI,
2728 const DominatorTree *DT,
Duncan Sands18450092010-11-16 12:16:38 +00002729 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002730 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Chad Rosier618c1db2011-12-01 03:08:23 +00002731 return SimplifyICmpInst(Predicate, LHS, RHS, TD, TLI, DT, MaxRecurse);
2732 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, TLI, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002733}
2734
2735Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002736 const TargetData *TD, const TargetLibraryInfo *TLI,
2737 const DominatorTree *DT) {
2738 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002739}
Chris Lattnere3453782009-11-10 01:08:51 +00002740
Dan Gohman71d05032011-11-04 18:32:42 +00002741static Value *SimplifyCallInst(CallInst *CI) {
2742 // call undef -> undef
2743 if (isa<UndefValue>(CI->getCalledValue()))
2744 return UndefValue::get(CI->getType());
2745
2746 return 0;
2747}
2748
Chris Lattnere3453782009-11-10 01:08:51 +00002749/// SimplifyInstruction - See if we can compute a simplified version of this
2750/// instruction. If not, this returns null.
Duncan Sandseff05812010-11-14 18:36:10 +00002751Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00002752 const TargetLibraryInfo *TLI,
Duncan Sandseff05812010-11-14 18:36:10 +00002753 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +00002754 Value *Result;
2755
Chris Lattnere3453782009-11-10 01:08:51 +00002756 switch (I->getOpcode()) {
2757 default:
Chad Rosier618c1db2011-12-01 03:08:23 +00002758 Result = ConstantFoldInstruction(I, TD, TLI);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002759 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002760 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002761 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2762 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2763 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002764 TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002765 break;
Duncan Sandsfea3b212010-12-15 14:07:39 +00002766 case Instruction::Sub:
2767 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2768 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2769 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002770 TD, TLI, DT);
Duncan Sandsfea3b212010-12-15 14:07:39 +00002771 break;
Duncan Sands82fdab32010-12-21 14:00:22 +00002772 case Instruction::Mul:
Chad Rosier618c1db2011-12-01 03:08:23 +00002773 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands82fdab32010-12-21 14:00:22 +00002774 break;
Duncan Sands593faa52011-01-28 16:51:11 +00002775 case Instruction::SDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002776 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands593faa52011-01-28 16:51:11 +00002777 break;
2778 case Instruction::UDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002779 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands593faa52011-01-28 16:51:11 +00002780 break;
Frits van Bommel1fca2c32011-01-29 15:26:31 +00002781 case Instruction::FDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002782 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Frits van Bommel1fca2c32011-01-29 15:26:31 +00002783 break;
Duncan Sandsf24ed772011-05-02 16:27:02 +00002784 case Instruction::SRem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002785 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002786 break;
2787 case Instruction::URem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002788 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002789 break;
2790 case Instruction::FRem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002791 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002792 break;
Duncan Sandsc43cee32011-01-14 00:37:45 +00002793 case Instruction::Shl:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002794 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2795 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2796 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002797 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002798 break;
2799 case Instruction::LShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002800 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2801 cast<BinaryOperator>(I)->isExact(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002802 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002803 break;
2804 case Instruction::AShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002805 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2806 cast<BinaryOperator>(I)->isExact(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002807 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002808 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002809 case Instruction::And:
Chad Rosier618c1db2011-12-01 03:08:23 +00002810 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002811 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002812 case Instruction::Or:
Chad Rosier618c1db2011-12-01 03:08:23 +00002813 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002814 break;
Duncan Sands2b749872010-11-17 18:52:15 +00002815 case Instruction::Xor:
Chad Rosier618c1db2011-12-01 03:08:23 +00002816 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands2b749872010-11-17 18:52:15 +00002817 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002818 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002819 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002820 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002821 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002822 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002823 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002824 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002825 break;
Chris Lattner04754262010-04-20 05:32:14 +00002826 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002827 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
2828 I->getOperand(2), TD, DT);
2829 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002830 case Instruction::GetElementPtr: {
2831 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Jay Foadb9b54eb2011-07-19 15:07:52 +00002832 Result = SimplifyGEPInst(Ops, TD, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002833 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002834 }
Duncan Sandsdabc2802011-09-05 06:52:48 +00002835 case Instruction::InsertValue: {
2836 InsertValueInst *IV = cast<InsertValueInst>(I);
2837 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
2838 IV->getInsertedValueOperand(),
2839 IV->getIndices(), TD, DT);
2840 break;
2841 }
Duncan Sandscd6636c2010-11-14 13:30:18 +00002842 case Instruction::PHI:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002843 Result = SimplifyPHINode(cast<PHINode>(I), DT);
2844 break;
Dan Gohman71d05032011-11-04 18:32:42 +00002845 case Instruction::Call:
2846 Result = SimplifyCallInst(cast<CallInst>(I));
2847 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002848 }
Duncan Sandsd261dc62010-11-17 08:35:29 +00002849
2850 /// If called on unreachable code, the above logic may report that the
2851 /// instruction simplified to itself. Make life easier for users by
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00002852 /// detecting that case here, returning a safe value instead.
2853 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnere3453782009-11-10 01:08:51 +00002854}
2855
Chris Lattner40d8c282009-11-10 22:26:15 +00002856/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
2857/// delete the From instruction. In addition to a basic RAUW, this does a
2858/// recursive simplification of the newly formed instructions. This catches
2859/// things where one simplification exposes other opportunities. This only
2860/// simplifies and deletes scalar operations, it does not change the CFG.
2861///
2862void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
Duncan Sandseff05812010-11-14 18:36:10 +00002863 const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00002864 const TargetLibraryInfo *TLI,
Duncan Sandseff05812010-11-14 18:36:10 +00002865 const DominatorTree *DT) {
Chris Lattner40d8c282009-11-10 22:26:15 +00002866 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
Duncan Sands12a86f52010-11-14 11:23:23 +00002867
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002868 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
2869 // we can know if it gets deleted out from under us or replaced in a
2870 // recursive simplification.
Chris Lattner40d8c282009-11-10 22:26:15 +00002871 WeakVH FromHandle(From);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002872 WeakVH ToHandle(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00002873
Chris Lattner40d8c282009-11-10 22:26:15 +00002874 while (!From->use_empty()) {
2875 // Update the instruction to use the new value.
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002876 Use &TheUse = From->use_begin().getUse();
2877 Instruction *User = cast<Instruction>(TheUse.getUser());
2878 TheUse = To;
2879
2880 // Check to see if the instruction can be folded due to the operand
2881 // replacement. For example changing (or X, Y) into (or X, -1) can replace
2882 // the 'or' with -1.
2883 Value *SimplifiedVal;
2884 {
2885 // Sanity check to make sure 'User' doesn't dangle across
2886 // SimplifyInstruction.
2887 AssertingVH<> UserHandle(User);
Duncan Sands12a86f52010-11-14 11:23:23 +00002888
Chad Rosier618c1db2011-12-01 03:08:23 +00002889 SimplifiedVal = SimplifyInstruction(User, TD, TLI, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002890 if (SimplifiedVal == 0) continue;
Chris Lattner40d8c282009-11-10 22:26:15 +00002891 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002892
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002893 // Recursively simplify this user to the new value.
Chad Rosier618c1db2011-12-01 03:08:23 +00002894 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, TLI, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002895 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
2896 To = ToHandle;
Duncan Sands12a86f52010-11-14 11:23:23 +00002897
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002898 assert(ToHandle && "To value deleted by recursive simplification?");
Duncan Sands12a86f52010-11-14 11:23:23 +00002899
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002900 // If the recursive simplification ended up revisiting and deleting
2901 // 'From' then we're done.
2902 if (From == 0)
2903 return;
Chris Lattner40d8c282009-11-10 22:26:15 +00002904 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002905
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002906 // If 'From' has value handles referring to it, do a real RAUW to update them.
2907 From->replaceAllUsesWith(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00002908
Chris Lattner40d8c282009-11-10 22:26:15 +00002909 From->eraseFromParent();
2910}