blob: 370ab962888a134b96679462e30d3444126708a0 [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"
Jay Foad562b84b2011-04-11 09:35:34 +000021#include "llvm/Operator.h"
Duncan Sandsa3c44a52010-12-22 09:40:51 +000022#include "llvm/ADT/Statistic.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000023#include "llvm/Analysis/InstructionSimplify.h"
Nick Lewyckyf7087ea2012-02-26 02:09:49 +000024#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000025#include "llvm/Analysis/ConstantFolding.h"
Duncan Sands18450092010-11-16 12:16:38 +000026#include "llvm/Analysis/Dominators.h"
Duncan Sandsd70d1a52011-01-25 09:38:29 +000027#include "llvm/Analysis/ValueTracking.h"
Nick Lewycky3a73e342011-03-04 07:00:57 +000028#include "llvm/Support/ConstantRange.h"
Chris Lattnerd06094f2009-11-10 00:55:12 +000029#include "llvm/Support/PatternMatch.h"
Duncan Sands18450092010-11-16 12:16:38 +000030#include "llvm/Support/ValueHandle.h"
Duncan Sandse60d79f2010-11-21 13:53:09 +000031#include "llvm/Target/TargetData.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000032using namespace llvm;
Chris Lattnerd06094f2009-11-10 00:55:12 +000033using namespace llvm::PatternMatch;
Chris Lattner9f3c25a2009-11-09 22:57:59 +000034
Chris Lattner81a0dc92011-02-09 17:15:04 +000035enum { RecursionLimit = 3 };
Duncan Sandsa74a58c2010-11-10 18:23:01 +000036
Duncan Sandsa3c44a52010-12-22 09:40:51 +000037STATISTIC(NumExpand, "Number of expansions");
38STATISTIC(NumFactor , "Number of factorizations");
39STATISTIC(NumReassoc, "Number of reassociations");
40
Duncan Sands82fdab32010-12-21 14:00:22 +000041static Value *SimplifyAndInst(Value *, Value *, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +000042 const TargetLibraryInfo *, const DominatorTree *,
43 unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000044static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +000045 const TargetLibraryInfo *, const DominatorTree *,
46 unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000047static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +000048 const TargetLibraryInfo *, const DominatorTree *,
49 unsigned);
Duncan Sands82fdab32010-12-21 14:00:22 +000050static Value *SimplifyOrInst(Value *, Value *, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +000051 const TargetLibraryInfo *, const DominatorTree *,
52 unsigned);
Duncan Sands82fdab32010-12-21 14:00:22 +000053static Value *SimplifyXorInst(Value *, Value *, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +000054 const TargetLibraryInfo *, const DominatorTree *,
55 unsigned);
Duncan Sands18450092010-11-16 12:16:38 +000056
Duncan Sandsf56138d2011-07-26 15:03:53 +000057/// getFalse - For a boolean type, or a vector of boolean type, return false, or
58/// a vector with every element false, as appropriate for the type.
59static Constant *getFalse(Type *Ty) {
Nick Lewycky66d004e2011-12-01 02:39:36 +000060 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsf56138d2011-07-26 15:03:53 +000061 "Expected i1 type or a vector of i1!");
62 return Constant::getNullValue(Ty);
63}
64
65/// getTrue - For a boolean type, or a vector of boolean type, return true, or
66/// a vector with every element true, as appropriate for the type.
67static Constant *getTrue(Type *Ty) {
Nick Lewycky66d004e2011-12-01 02:39:36 +000068 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsf56138d2011-07-26 15:03:53 +000069 "Expected i1 type or a vector of i1!");
70 return Constant::getAllOnesValue(Ty);
71}
72
Duncan Sands6dc9e2b2011-10-30 19:56:36 +000073/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
74static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
75 Value *RHS) {
76 CmpInst *Cmp = dyn_cast<CmpInst>(V);
77 if (!Cmp)
78 return false;
79 CmpInst::Predicate CPred = Cmp->getPredicate();
80 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
81 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
82 return true;
83 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
84 CRHS == LHS;
85}
86
Duncan Sands18450092010-11-16 12:16:38 +000087/// ValueDominatesPHI - Does the given value dominate the specified phi node?
88static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
89 Instruction *I = dyn_cast<Instruction>(V);
90 if (!I)
91 // Arguments and constants dominate all instructions.
92 return true;
93
94 // If we have a DominatorTree then do a precise test.
95 if (DT)
Rafael Espindola8c727f92012-02-26 01:50:14 +000096 return !DT->isReachableFromEntry(P->getParent()) ||
97 !DT->isReachableFromEntry(I->getParent()) || DT->dominates(I, P);
Duncan Sands18450092010-11-16 12:16:38 +000098
99 // Otherwise, if the instruction is in the entry block, and is not an invoke,
100 // then it obviously dominates all phi nodes.
101 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
102 !isa<InvokeInst>(I))
103 return true;
104
105 return false;
106}
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000107
Duncan Sands3421d902010-12-21 13:32:22 +0000108/// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
109/// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
110/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
111/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
112/// Returns the simplified value, or null if no simplification was performed.
113static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Benjamin Kramere21083a2010-12-28 13:52:52 +0000114 unsigned OpcToExpand, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000115 const TargetLibraryInfo *TLI, const DominatorTree *DT,
116 unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000117 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000118 // Recursion is always used, so bail out at once if we already hit the limit.
119 if (!MaxRecurse--)
120 return 0;
121
122 // Check whether the expression has the form "(A op' B) op C".
123 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
124 if (Op0->getOpcode() == OpcodeToExpand) {
125 // It does! Try turning it into "(A op C) op' (B op C)".
126 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
127 // Do "A op C" and "B op C" both simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000128 if (Value *L = SimplifyBinOp(Opcode, A, C, TD, TLI, DT, MaxRecurse))
129 if (Value *R = SimplifyBinOp(Opcode, B, C, TD, TLI, DT, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000130 // They do! Return "L op' R" if it simplifies or is already available.
131 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000132 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
133 && L == B && R == A)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000134 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000135 return LHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000136 }
Duncan Sands3421d902010-12-21 13:32:22 +0000137 // Otherwise return "L op' R" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000138 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, TLI, DT,
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000139 MaxRecurse)) {
140 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000141 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000142 }
Duncan Sands3421d902010-12-21 13:32:22 +0000143 }
144 }
145
146 // Check whether the expression has the form "A op (B op' C)".
147 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
148 if (Op1->getOpcode() == OpcodeToExpand) {
149 // It does! Try turning it into "(A op B) op' (A op C)".
150 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
151 // Do "A op B" and "A op C" both simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000152 if (Value *L = SimplifyBinOp(Opcode, A, B, TD, TLI, DT, MaxRecurse))
153 if (Value *R = SimplifyBinOp(Opcode, A, C, TD, TLI, DT, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000154 // They do! Return "L op' R" if it simplifies or is already available.
155 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000156 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
157 && L == C && R == B)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000158 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000159 return RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000160 }
Duncan Sands3421d902010-12-21 13:32:22 +0000161 // Otherwise return "L op' R" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000162 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, TLI, DT,
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000163 MaxRecurse)) {
164 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000165 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000166 }
Duncan Sands3421d902010-12-21 13:32:22 +0000167 }
168 }
169
170 return 0;
171}
172
173/// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
174/// using the operation OpCodeToExtract. For example, when Opcode is Add and
175/// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
176/// Returns the simplified value, or null if no simplification was performed.
177static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +0000178 unsigned OpcToExtract, const TargetData *TD,
179 const TargetLibraryInfo *TLI,
180 const DominatorTree *DT,
181 unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000182 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
Duncan Sands3421d902010-12-21 13:32:22 +0000183 // Recursion is always used, so bail out at once if we already hit the limit.
184 if (!MaxRecurse--)
185 return 0;
186
187 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
188 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
189
190 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
191 !Op1 || Op1->getOpcode() != OpcodeToExtract)
192 return 0;
193
194 // The expression has the form "(A op' B) op (C op' D)".
Duncan Sands82fdab32010-12-21 14:00:22 +0000195 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
196 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
Duncan Sands3421d902010-12-21 13:32:22 +0000197
198 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
199 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
200 // commutative case, "(A op' B) op (C op' A)"?
Duncan Sands124708d2011-01-01 20:08:02 +0000201 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
202 Value *DD = A == C ? D : C;
Duncan Sands3421d902010-12-21 13:32:22 +0000203 // Form "A op' (B op DD)" if it simplifies completely.
204 // Does "B op DD" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000205 if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, TLI, DT, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000206 // It does! Return "A op' V" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000207 // If V equals B then "A op' V" is just the LHS. If V equals DD then
208 // "A op' V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000209 if (V == B || V == DD) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000210 ++NumFactor;
Duncan Sands124708d2011-01-01 20:08:02 +0000211 return V == B ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000212 }
Duncan Sands3421d902010-12-21 13:32:22 +0000213 // Otherwise return "A op' V" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000214 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, TLI, DT,
215 MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000216 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000217 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000218 }
Duncan Sands3421d902010-12-21 13:32:22 +0000219 }
220 }
221
222 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
223 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
224 // commutative case, "(A op' B) op (B op' D)"?
Duncan Sands124708d2011-01-01 20:08:02 +0000225 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
226 Value *CC = B == D ? C : D;
Duncan Sands3421d902010-12-21 13:32:22 +0000227 // Form "(A op CC) op' B" if it simplifies completely..
228 // Does "A op CC" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000229 if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, TLI, DT, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000230 // It does! Return "V op' B" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000231 // If V equals A then "V op' B" is just the LHS. If V equals CC then
232 // "V op' B" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000233 if (V == A || V == CC) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000234 ++NumFactor;
Duncan Sands124708d2011-01-01 20:08:02 +0000235 return V == A ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000236 }
Duncan Sands3421d902010-12-21 13:32:22 +0000237 // Otherwise return "V op' B" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000238 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, TLI, DT,
239 MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000240 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000241 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000242 }
Duncan Sands3421d902010-12-21 13:32:22 +0000243 }
244 }
245
246 return 0;
247}
248
249/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
250/// operations. Returns the simpler value, or null if none was found.
Benjamin Kramere21083a2010-12-28 13:52:52 +0000251static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sands566edb02010-12-21 08:49:00 +0000252 const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000253 const TargetLibraryInfo *TLI,
Duncan Sands566edb02010-12-21 08:49:00 +0000254 const DominatorTree *DT,
255 unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000256 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands566edb02010-12-21 08:49:00 +0000257 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
258
259 // Recursion is always used, so bail out at once if we already hit the limit.
260 if (!MaxRecurse--)
261 return 0;
262
263 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
264 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
265
266 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
267 if (Op0 && Op0->getOpcode() == Opcode) {
268 Value *A = Op0->getOperand(0);
269 Value *B = Op0->getOperand(1);
270 Value *C = RHS;
271
272 // Does "B op C" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000273 if (Value *V = SimplifyBinOp(Opcode, B, C, TD, TLI, DT, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000274 // It does! Return "A op V" if it simplifies or is already available.
275 // If V equals B then "A op V" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000276 if (V == B) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000277 // Otherwise return "A op V" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000278 if (Value *W = SimplifyBinOp(Opcode, A, V, TD, TLI, DT, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000279 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000280 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000281 }
Duncan Sands566edb02010-12-21 08:49:00 +0000282 }
283 }
284
285 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
286 if (Op1 && Op1->getOpcode() == Opcode) {
287 Value *A = LHS;
288 Value *B = Op1->getOperand(0);
289 Value *C = Op1->getOperand(1);
290
291 // Does "A op B" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000292 if (Value *V = SimplifyBinOp(Opcode, A, B, TD, TLI, DT, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000293 // It does! Return "V op C" if it simplifies or is already available.
294 // If V equals B then "V op C" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000295 if (V == B) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000296 // Otherwise return "V op C" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000297 if (Value *W = SimplifyBinOp(Opcode, V, C, TD, TLI, DT, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000298 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000299 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000300 }
Duncan Sands566edb02010-12-21 08:49:00 +0000301 }
302 }
303
304 // The remaining transforms require commutativity as well as associativity.
305 if (!Instruction::isCommutative(Opcode))
306 return 0;
307
308 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
309 if (Op0 && Op0->getOpcode() == Opcode) {
310 Value *A = Op0->getOperand(0);
311 Value *B = Op0->getOperand(1);
312 Value *C = RHS;
313
314 // Does "C op A" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000315 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, TLI, DT, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000316 // It does! Return "V op B" if it simplifies or is already available.
317 // If V equals A then "V op B" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000318 if (V == A) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000319 // Otherwise return "V op B" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000320 if (Value *W = SimplifyBinOp(Opcode, V, B, TD, TLI, DT, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000321 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000322 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000323 }
Duncan Sands566edb02010-12-21 08:49:00 +0000324 }
325 }
326
327 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
328 if (Op1 && Op1->getOpcode() == Opcode) {
329 Value *A = LHS;
330 Value *B = Op1->getOperand(0);
331 Value *C = Op1->getOperand(1);
332
333 // Does "C op A" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000334 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, TLI, DT, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000335 // It does! Return "B op V" if it simplifies or is already available.
336 // If V equals C then "B op V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000337 if (V == C) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000338 // Otherwise return "B op V" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000339 if (Value *W = SimplifyBinOp(Opcode, B, V, TD, TLI, DT, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000340 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000341 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000342 }
Duncan Sands566edb02010-12-21 08:49:00 +0000343 }
344 }
345
346 return 0;
347}
348
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000349/// ThreadBinOpOverSelect - In the case of a binary operation with a select
350/// instruction as an operand, try to simplify the binop by seeing whether
351/// evaluating it on both branches of the select results in the same value.
352/// Returns the common value if so, otherwise returns null.
353static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000354 const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000355 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +0000356 const DominatorTree *DT,
357 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000358 // Recursion is always used, so bail out at once if we already hit the limit.
359 if (!MaxRecurse--)
360 return 0;
361
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000362 SelectInst *SI;
363 if (isa<SelectInst>(LHS)) {
364 SI = cast<SelectInst>(LHS);
365 } else {
366 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
367 SI = cast<SelectInst>(RHS);
368 }
369
370 // Evaluate the BinOp on the true and false branches of the select.
371 Value *TV;
372 Value *FV;
373 if (SI == LHS) {
Chad Rosier618c1db2011-12-01 03:08:23 +0000374 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, TLI, DT, MaxRecurse);
375 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, TLI, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000376 } else {
Chad Rosier618c1db2011-12-01 03:08:23 +0000377 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, TLI, DT, MaxRecurse);
378 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, TLI, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000379 }
380
Duncan Sands7cf85e72011-01-01 16:12:09 +0000381 // If they simplified to the same value, then return the common value.
Duncan Sands124708d2011-01-01 20:08:02 +0000382 // If they both failed to simplify then return null.
383 if (TV == FV)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000384 return TV;
385
386 // If one branch simplified to undef, return the other one.
387 if (TV && isa<UndefValue>(TV))
388 return FV;
389 if (FV && isa<UndefValue>(FV))
390 return TV;
391
392 // If applying the operation did not change the true and false select values,
393 // then the result of the binop is the select itself.
Duncan Sands124708d2011-01-01 20:08:02 +0000394 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000395 return SI;
396
397 // If one branch simplified and the other did not, and the simplified
398 // value is equal to the unsimplified one, return the simplified value.
399 // For example, select (cond, X, X & Z) & Z -> X & Z.
400 if ((FV && !TV) || (TV && !FV)) {
401 // Check that the simplified value has the form "X op Y" where "op" is the
402 // same as the original operation.
403 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
404 if (Simplified && Simplified->getOpcode() == Opcode) {
405 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
406 // We already know that "op" is the same as for the simplified value. See
407 // if the operands match too. If so, return the simplified value.
408 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
409 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
410 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands124708d2011-01-01 20:08:02 +0000411 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
412 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000413 return Simplified;
414 if (Simplified->isCommutative() &&
Duncan Sands124708d2011-01-01 20:08:02 +0000415 Simplified->getOperand(1) == UnsimplifiedLHS &&
416 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000417 return Simplified;
418 }
419 }
420
421 return 0;
422}
423
424/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
425/// try to simplify the comparison by seeing whether both branches of the select
426/// result in the same value. Returns the common value if so, otherwise returns
427/// null.
428static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000429 Value *RHS, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000430 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +0000431 const DominatorTree *DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000432 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000433 // Recursion is always used, so bail out at once if we already hit the limit.
434 if (!MaxRecurse--)
435 return 0;
436
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000437 // Make sure the select is on the LHS.
438 if (!isa<SelectInst>(LHS)) {
439 std::swap(LHS, RHS);
440 Pred = CmpInst::getSwappedPredicate(Pred);
441 }
442 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
443 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000444 Value *Cond = SI->getCondition();
445 Value *TV = SI->getTrueValue();
446 Value *FV = SI->getFalseValue();
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000447
Duncan Sands50ca4d32011-02-03 09:37:39 +0000448 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000449 // Does "cmp TV, RHS" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000450 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, TD, TLI, DT, MaxRecurse);
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000451 if (TCmp == Cond) {
452 // It not only simplified, it simplified to the select condition. Replace
453 // it with 'true'.
454 TCmp = getTrue(Cond->getType());
455 } else if (!TCmp) {
456 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
457 // condition then we can replace it with 'true'. Otherwise give up.
458 if (!isSameCompare(Cond, Pred, TV, RHS))
459 return 0;
460 TCmp = getTrue(Cond->getType());
Duncan Sands50ca4d32011-02-03 09:37:39 +0000461 }
462
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000463 // Does "cmp FV, RHS" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000464 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, TD, TLI, DT, MaxRecurse);
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000465 if (FCmp == Cond) {
466 // It not only simplified, it simplified to the select condition. Replace
467 // it with 'false'.
468 FCmp = getFalse(Cond->getType());
469 } else if (!FCmp) {
470 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
471 // condition then we can replace it with 'false'. Otherwise give up.
472 if (!isSameCompare(Cond, Pred, FV, RHS))
473 return 0;
474 FCmp = getFalse(Cond->getType());
475 }
476
477 // If both sides simplified to the same value, then use it as the result of
478 // the original comparison.
479 if (TCmp == FCmp)
480 return TCmp;
Duncan Sandsaa97bb52012-02-10 14:31:24 +0000481
482 // The remaining cases only make sense if the select condition has the same
483 // type as the result of the comparison, so bail out if this is not so.
484 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
485 return 0;
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000486 // If the false value simplified to false, then the result of the compare
487 // is equal to "Cond && TCmp". This also catches the case when the false
488 // value simplified to false and the true value to true, returning "Cond".
489 if (match(FCmp, m_Zero()))
Chad Rosier618c1db2011-12-01 03:08:23 +0000490 if (Value *V = SimplifyAndInst(Cond, TCmp, TD, TLI, DT, MaxRecurse))
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000491 return V;
492 // If the true value simplified to true, then the result of the compare
493 // is equal to "Cond || FCmp".
494 if (match(TCmp, m_One()))
Chad Rosier618c1db2011-12-01 03:08:23 +0000495 if (Value *V = SimplifyOrInst(Cond, FCmp, TD, TLI, DT, MaxRecurse))
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000496 return V;
497 // Finally, if the false value simplified to true and the true value to
498 // false, then the result of the compare is equal to "!Cond".
499 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
500 if (Value *V =
501 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Chad Rosier618c1db2011-12-01 03:08:23 +0000502 TD, TLI, DT, MaxRecurse))
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000503 return V;
504
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000505 return 0;
506}
507
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000508/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
509/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
510/// it on the incoming phi values yields the same result for every value. If so
511/// returns the common value, otherwise returns null.
512static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +0000513 const TargetData *TD,
514 const TargetLibraryInfo *TLI,
515 const DominatorTree *DT,
Duncan Sands18450092010-11-16 12:16:38 +0000516 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000517 // Recursion is always used, so bail out at once if we already hit the limit.
518 if (!MaxRecurse--)
519 return 0;
520
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000521 PHINode *PI;
522 if (isa<PHINode>(LHS)) {
523 PI = cast<PHINode>(LHS);
Duncan Sands18450092010-11-16 12:16:38 +0000524 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
525 if (!ValueDominatesPHI(RHS, PI, DT))
526 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000527 } else {
528 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
529 PI = cast<PHINode>(RHS);
Duncan Sands18450092010-11-16 12:16:38 +0000530 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
531 if (!ValueDominatesPHI(LHS, PI, DT))
532 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000533 }
534
535 // Evaluate the BinOp on the incoming phi values.
536 Value *CommonValue = 0;
537 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000538 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000539 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000540 if (Incoming == PI) continue;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000541 Value *V = PI == LHS ?
Chad Rosier618c1db2011-12-01 03:08:23 +0000542 SimplifyBinOp(Opcode, Incoming, RHS, TD, TLI, DT, MaxRecurse) :
543 SimplifyBinOp(Opcode, LHS, Incoming, TD, TLI, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000544 // If the operation failed to simplify, or simplified to a different value
545 // to previously, then give up.
546 if (!V || (CommonValue && V != CommonValue))
547 return 0;
548 CommonValue = V;
549 }
550
551 return CommonValue;
552}
553
554/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
555/// try to simplify the comparison by seeing whether comparing with all of the
556/// incoming phi values yields the same result every time. If so returns the
557/// common result, otherwise returns null.
558static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +0000559 const TargetData *TD,
560 const TargetLibraryInfo *TLI,
561 const DominatorTree *DT,
Duncan Sands18450092010-11-16 12:16:38 +0000562 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000563 // Recursion is always used, so bail out at once if we already hit the limit.
564 if (!MaxRecurse--)
565 return 0;
566
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000567 // Make sure the phi is on the LHS.
568 if (!isa<PHINode>(LHS)) {
569 std::swap(LHS, RHS);
570 Pred = CmpInst::getSwappedPredicate(Pred);
571 }
572 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
573 PHINode *PI = cast<PHINode>(LHS);
574
Duncan Sands18450092010-11-16 12:16:38 +0000575 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
576 if (!ValueDominatesPHI(RHS, PI, DT))
577 return 0;
578
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000579 // Evaluate the BinOp on the incoming phi values.
580 Value *CommonValue = 0;
581 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000582 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000583 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000584 if (Incoming == PI) continue;
Chad Rosier618c1db2011-12-01 03:08:23 +0000585 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, TLI, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000586 // If the operation failed to simplify, or simplified to a different value
587 // to previously, then give up.
588 if (!V || (CommonValue && V != CommonValue))
589 return 0;
590 CommonValue = V;
591 }
592
593 return CommonValue;
594}
595
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000596/// SimplifyAddInst - Given operands for an Add, see if we can
597/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000598static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +0000599 const TargetData *TD,
600 const TargetLibraryInfo *TLI,
601 const DominatorTree *DT,
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000602 unsigned MaxRecurse) {
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000603 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
604 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
605 Constant *Ops[] = { CLHS, CRHS };
606 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
Chad Rosier618c1db2011-12-01 03:08:23 +0000607 Ops, TD, TLI);
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000608 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000609
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000610 // Canonicalize the constant to the RHS.
611 std::swap(Op0, Op1);
612 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000613
Duncan Sandsfea3b212010-12-15 14:07:39 +0000614 // X + undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000615 if (match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000616 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000617
Duncan Sandsfea3b212010-12-15 14:07:39 +0000618 // X + 0 -> X
619 if (match(Op1, m_Zero()))
620 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000621
Duncan Sandsfea3b212010-12-15 14:07:39 +0000622 // X + (Y - X) -> Y
623 // (Y - X) + X -> Y
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000624 // Eg: X + -X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000625 Value *Y = 0;
626 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
627 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000628 return Y;
629
630 // X + ~X -> -1 since ~X = -X-1
Duncan Sands124708d2011-01-01 20:08:02 +0000631 if (match(Op0, m_Not(m_Specific(Op1))) ||
632 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000633 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands87689cf2010-11-19 09:20:39 +0000634
Duncan Sands82fdab32010-12-21 14:00:22 +0000635 /// i1 add -> xor.
Duncan Sands75d289e2010-12-21 14:48:48 +0000636 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Chad Rosier618c1db2011-12-01 03:08:23 +0000637 if (Value *V = SimplifyXorInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000638 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000639
Duncan Sands566edb02010-12-21 08:49:00 +0000640 // Try some generic simplifications for associative operations.
Chad Rosier618c1db2011-12-01 03:08:23 +0000641 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, TLI, DT,
Duncan Sands566edb02010-12-21 08:49:00 +0000642 MaxRecurse))
643 return V;
644
Duncan Sands3421d902010-12-21 13:32:22 +0000645 // Mul distributes over Add. Try some generic simplifications based on this.
646 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
Chad Rosier618c1db2011-12-01 03:08:23 +0000647 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +0000648 return V;
649
Duncan Sands87689cf2010-11-19 09:20:39 +0000650 // Threading Add over selects and phi nodes is pointless, so don't bother.
651 // Threading over the select in "A + select(cond, B, C)" means evaluating
652 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
653 // only if B and C are equal. If B and C are equal then (since we assume
654 // that operands have already been simplified) "select(cond, B, C)" should
655 // have been simplified to the common value of B and C already. Analysing
656 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
657 // for threading over phi nodes.
658
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000659 return 0;
660}
661
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000662Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +0000663 const TargetData *TD, const TargetLibraryInfo *TLI,
664 const DominatorTree *DT) {
665 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000666}
667
Duncan Sandsfea3b212010-12-15 14:07:39 +0000668/// SimplifySubInst - Given operands for a Sub, see if we can
669/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000670static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +0000671 const TargetData *TD,
672 const TargetLibraryInfo *TLI,
673 const DominatorTree *DT,
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000674 unsigned MaxRecurse) {
Duncan Sandsfea3b212010-12-15 14:07:39 +0000675 if (Constant *CLHS = dyn_cast<Constant>(Op0))
676 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
677 Constant *Ops[] = { CLHS, CRHS };
678 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
Chad Rosier618c1db2011-12-01 03:08:23 +0000679 Ops, TD, TLI);
Duncan Sandsfea3b212010-12-15 14:07:39 +0000680 }
681
682 // X - undef -> undef
683 // undef - X -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000684 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000685 return UndefValue::get(Op0->getType());
686
687 // X - 0 -> X
688 if (match(Op1, m_Zero()))
689 return Op0;
690
691 // X - X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000692 if (Op0 == Op1)
Duncan Sandsfea3b212010-12-15 14:07:39 +0000693 return Constant::getNullValue(Op0->getType());
694
Duncan Sandsfe02c692011-01-18 09:24:58 +0000695 // (X*2) - X -> X
696 // (X<<1) - X -> X
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000697 Value *X = 0;
Duncan Sandsfe02c692011-01-18 09:24:58 +0000698 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
699 match(Op0, m_Shl(m_Specific(Op1), m_One())))
700 return Op1;
701
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000702 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
703 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
704 Value *Y = 0, *Z = Op1;
705 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
706 // See if "V === Y - Z" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000707 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000708 // It does! Now see if "X + V" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000709 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, TD, TLI, DT,
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000710 MaxRecurse-1)) {
711 // It does, we successfully reassociated!
712 ++NumReassoc;
713 return W;
714 }
715 // See if "V === X - Z" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000716 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000717 // It does! Now see if "Y + V" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000718 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, TD, TLI, DT,
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000719 MaxRecurse-1)) {
720 // It does, we successfully reassociated!
721 ++NumReassoc;
722 return W;
723 }
724 }
Duncan Sands82fdab32010-12-21 14:00:22 +0000725
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000726 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
727 // For example, X - (X + 1) -> -1
728 X = Op0;
729 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
730 // See if "V === X - Y" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000731 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000732 // It does! Now see if "V - Z" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000733 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, TD, TLI, DT,
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000734 MaxRecurse-1)) {
735 // It does, we successfully reassociated!
736 ++NumReassoc;
737 return W;
738 }
739 // See if "V === X - Z" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000740 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000741 // It does! Now see if "V - Y" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000742 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, TD, TLI, DT,
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000743 MaxRecurse-1)) {
744 // It does, we successfully reassociated!
745 ++NumReassoc;
746 return W;
747 }
748 }
749
750 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
751 // For example, X - (X - Y) -> Y.
752 Z = Op0;
Duncan Sandsc087e202011-01-14 15:26:10 +0000753 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
754 // See if "V === Z - X" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000755 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000756 // It does! Now see if "V + Y" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000757 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, TD, TLI, DT,
Duncan Sandsc087e202011-01-14 15:26:10 +0000758 MaxRecurse-1)) {
759 // It does, we successfully reassociated!
760 ++NumReassoc;
761 return W;
762 }
763
Duncan Sands3421d902010-12-21 13:32:22 +0000764 // Mul distributes over Sub. Try some generic simplifications based on this.
765 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
Chad Rosier618c1db2011-12-01 03:08:23 +0000766 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +0000767 return V;
768
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000769 // i1 sub -> xor.
770 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Chad Rosier618c1db2011-12-01 03:08:23 +0000771 if (Value *V = SimplifyXorInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000772 return V;
773
Duncan Sandsfea3b212010-12-15 14:07:39 +0000774 // Threading Sub over selects and phi nodes is pointless, so don't bother.
775 // Threading over the select in "A - select(cond, B, C)" means evaluating
776 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
777 // only if B and C are equal. If B and C are equal then (since we assume
778 // that operands have already been simplified) "select(cond, B, C)" should
779 // have been simplified to the common value of B and C already. Analysing
780 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
781 // for threading over phi nodes.
782
783 return 0;
784}
785
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000786Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +0000787 const TargetData *TD,
788 const TargetLibraryInfo *TLI,
789 const DominatorTree *DT) {
790 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000791}
792
Duncan Sands82fdab32010-12-21 14:00:22 +0000793/// SimplifyMulInst - Given operands for a Mul, see if we can
794/// fold the result. If not, this returns null.
795static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000796 const TargetLibraryInfo *TLI,
Duncan Sands82fdab32010-12-21 14:00:22 +0000797 const DominatorTree *DT, unsigned MaxRecurse) {
798 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
799 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
800 Constant *Ops[] = { CLHS, CRHS };
801 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
Chad Rosier618c1db2011-12-01 03:08:23 +0000802 Ops, TD, TLI);
Duncan Sands82fdab32010-12-21 14:00:22 +0000803 }
804
805 // Canonicalize the constant to the RHS.
806 std::swap(Op0, Op1);
807 }
808
809 // X * undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000810 if (match(Op1, m_Undef()))
Duncan Sands82fdab32010-12-21 14:00:22 +0000811 return Constant::getNullValue(Op0->getType());
812
813 // X * 0 -> 0
814 if (match(Op1, m_Zero()))
815 return Op1;
816
817 // X * 1 -> X
818 if (match(Op1, m_One()))
819 return Op0;
820
Duncan Sands1895e982011-01-30 18:03:50 +0000821 // (X / Y) * Y -> X if the division is exact.
Benjamin Kramer55c6d572012-01-01 17:55:30 +0000822 Value *X = 0;
823 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
824 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
825 return X;
Duncan Sands1895e982011-01-30 18:03:50 +0000826
Nick Lewycky54138802011-01-29 19:55:23 +0000827 // i1 mul -> and.
Duncan Sands75d289e2010-12-21 14:48:48 +0000828 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Chad Rosier618c1db2011-12-01 03:08:23 +0000829 if (Value *V = SimplifyAndInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000830 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000831
832 // Try some generic simplifications for associative operations.
Chad Rosier618c1db2011-12-01 03:08:23 +0000833 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, TLI, DT,
Duncan Sands82fdab32010-12-21 14:00:22 +0000834 MaxRecurse))
835 return V;
836
837 // Mul distributes over Add. Try some generic simplifications based on this.
838 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Chad Rosier618c1db2011-12-01 03:08:23 +0000839 TD, TLI, DT, MaxRecurse))
Duncan Sands82fdab32010-12-21 14:00:22 +0000840 return V;
841
842 // If the operation is with the result of a select instruction, check whether
843 // operating on either branch of the select always yields the same value.
844 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +0000845 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, TLI, DT,
Duncan Sands82fdab32010-12-21 14:00:22 +0000846 MaxRecurse))
847 return V;
848
849 // If the operation is with the result of a phi instruction, check whether
850 // operating on all incoming values of the phi always yields the same value.
851 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +0000852 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, TLI, DT,
Duncan Sands82fdab32010-12-21 14:00:22 +0000853 MaxRecurse))
854 return V;
855
856 return 0;
857}
858
859Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000860 const TargetLibraryInfo *TLI,
Duncan Sands82fdab32010-12-21 14:00:22 +0000861 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +0000862 return ::SimplifyMulInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sands82fdab32010-12-21 14:00:22 +0000863}
864
Duncan Sands593faa52011-01-28 16:51:11 +0000865/// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
866/// fold the result. If not, this returns null.
Anders Carlsson479b4b92011-02-05 18:33:43 +0000867static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Chad Rosier618c1db2011-12-01 03:08:23 +0000868 const TargetData *TD, const TargetLibraryInfo *TLI,
869 const DominatorTree *DT, unsigned MaxRecurse) {
Duncan Sands593faa52011-01-28 16:51:11 +0000870 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
871 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
872 Constant *Ops[] = { C0, C1 };
Chad Rosier618c1db2011-12-01 03:08:23 +0000873 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
Duncan Sands593faa52011-01-28 16:51:11 +0000874 }
875 }
876
Duncan Sandsa3e292c2011-01-28 18:50:50 +0000877 bool isSigned = Opcode == Instruction::SDiv;
878
Duncan Sands593faa52011-01-28 16:51:11 +0000879 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000880 if (match(Op1, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +0000881 return Op1;
882
883 // undef / X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000884 if (match(Op0, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +0000885 return Constant::getNullValue(Op0->getType());
886
887 // 0 / X -> 0, we don't need to preserve faults!
888 if (match(Op0, m_Zero()))
889 return Op0;
890
891 // X / 1 -> X
892 if (match(Op1, m_One()))
893 return Op0;
Duncan Sands593faa52011-01-28 16:51:11 +0000894
895 if (Op0->getType()->isIntegerTy(1))
896 // It can't be division by zero, hence it must be division by one.
897 return Op0;
898
899 // X / X -> 1
900 if (Op0 == Op1)
901 return ConstantInt::get(Op0->getType(), 1);
902
903 // (X * Y) / Y -> X if the multiplication does not overflow.
904 Value *X = 0, *Y = 0;
905 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
906 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands32a43cc2011-10-27 19:16:21 +0000907 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands4b720712011-02-02 20:52:00 +0000908 // If the Mul knows it does not overflow, then we are good to go.
909 if ((isSigned && Mul->hasNoSignedWrap()) ||
910 (!isSigned && Mul->hasNoUnsignedWrap()))
911 return X;
Duncan Sands593faa52011-01-28 16:51:11 +0000912 // If X has the form X = A / Y then X * Y cannot overflow.
913 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
914 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
915 return X;
916 }
917
Duncan Sandsa3e292c2011-01-28 18:50:50 +0000918 // (X rem Y) / Y -> 0
919 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
920 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
921 return Constant::getNullValue(Op0->getType());
922
923 // If the operation is with the result of a select instruction, check whether
924 // operating on either branch of the select always yields the same value.
925 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +0000926 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT,
927 MaxRecurse))
Duncan Sandsa3e292c2011-01-28 18:50:50 +0000928 return V;
929
930 // If the operation is with the result of a phi instruction, check whether
931 // operating on all incoming values of the phi always yields the same value.
932 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +0000933 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT,
934 MaxRecurse))
Duncan Sandsa3e292c2011-01-28 18:50:50 +0000935 return V;
936
Duncan Sands593faa52011-01-28 16:51:11 +0000937 return 0;
938}
939
940/// SimplifySDivInst - Given operands for an SDiv, see if we can
941/// fold the result. If not, this returns null.
942static Value *SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000943 const TargetLibraryInfo *TLI,
Duncan Sands593faa52011-01-28 16:51:11 +0000944 const DominatorTree *DT, unsigned MaxRecurse) {
Chad Rosier618c1db2011-12-01 03:08:23 +0000945 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, TD, TLI, DT,
946 MaxRecurse))
Duncan Sands593faa52011-01-28 16:51:11 +0000947 return V;
948
Duncan Sands593faa52011-01-28 16:51:11 +0000949 return 0;
950}
951
952Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000953 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000954 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +0000955 return ::SimplifySDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sands593faa52011-01-28 16:51:11 +0000956}
957
958/// SimplifyUDivInst - Given operands for a UDiv, see if we can
959/// fold the result. If not, this returns null.
960static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000961 const TargetLibraryInfo *TLI,
Duncan Sands593faa52011-01-28 16:51:11 +0000962 const DominatorTree *DT, unsigned MaxRecurse) {
Chad Rosier618c1db2011-12-01 03:08:23 +0000963 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, TD, TLI, DT,
964 MaxRecurse))
Duncan Sands593faa52011-01-28 16:51:11 +0000965 return V;
966
Duncan Sands593faa52011-01-28 16:51:11 +0000967 return 0;
968}
969
970Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000971 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000972 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +0000973 return ::SimplifyUDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sands593faa52011-01-28 16:51:11 +0000974}
975
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000976static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +0000977 const TargetLibraryInfo *,
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000978 const DominatorTree *, unsigned) {
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000979 // undef / X -> undef (the undef could be a snan).
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000980 if (match(Op0, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000981 return Op0;
982
983 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000984 if (match(Op1, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000985 return Op1;
986
987 return 0;
988}
989
990Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000991 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000992 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +0000993 return ::SimplifyFDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000994}
995
Duncan Sandsf24ed772011-05-02 16:27:02 +0000996/// SimplifyRem - Given operands for an SRem or URem, see if we can
997/// fold the result. If not, this returns null.
998static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Chad Rosier618c1db2011-12-01 03:08:23 +0000999 const TargetData *TD, const TargetLibraryInfo *TLI,
1000 const DominatorTree *DT, unsigned MaxRecurse) {
Duncan Sandsf24ed772011-05-02 16:27:02 +00001001 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1002 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1003 Constant *Ops[] = { C0, C1 };
Chad Rosier618c1db2011-12-01 03:08:23 +00001004 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001005 }
1006 }
1007
Duncan Sandsf24ed772011-05-02 16:27:02 +00001008 // X % undef -> undef
1009 if (match(Op1, m_Undef()))
1010 return Op1;
1011
1012 // undef % X -> 0
1013 if (match(Op0, m_Undef()))
1014 return Constant::getNullValue(Op0->getType());
1015
1016 // 0 % X -> 0, we don't need to preserve faults!
1017 if (match(Op0, m_Zero()))
1018 return Op0;
1019
1020 // X % 0 -> undef, we don't need to preserve faults!
1021 if (match(Op1, m_Zero()))
1022 return UndefValue::get(Op0->getType());
1023
1024 // X % 1 -> 0
1025 if (match(Op1, m_One()))
1026 return Constant::getNullValue(Op0->getType());
1027
1028 if (Op0->getType()->isIntegerTy(1))
1029 // It can't be remainder by zero, hence it must be remainder by one.
1030 return Constant::getNullValue(Op0->getType());
1031
1032 // X % X -> 0
1033 if (Op0 == Op1)
1034 return Constant::getNullValue(Op0->getType());
1035
1036 // If the operation is with the result of a select instruction, check whether
1037 // operating on either branch of the select always yields the same value.
1038 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001039 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001040 return V;
1041
1042 // If the operation is with the result of a phi instruction, check whether
1043 // operating on all incoming values of the phi always yields the same value.
1044 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001045 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001046 return V;
1047
1048 return 0;
1049}
1050
1051/// SimplifySRemInst - Given operands for an SRem, see if we can
1052/// fold the result. If not, this returns null.
1053static Value *SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001054 const TargetLibraryInfo *TLI,
1055 const DominatorTree *DT,
1056 unsigned MaxRecurse) {
1057 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001058 return V;
1059
1060 return 0;
1061}
1062
1063Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001064 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001065 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001066 return ::SimplifySRemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001067}
1068
1069/// SimplifyURemInst - Given operands for a URem, see if we can
1070/// fold the result. If not, this returns null.
1071static Value *SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001072 const TargetLibraryInfo *TLI,
1073 const DominatorTree *DT,
1074 unsigned MaxRecurse) {
1075 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001076 return V;
1077
1078 return 0;
1079}
1080
1081Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001082 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001083 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001084 return ::SimplifyURemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001085}
1086
1087static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +00001088 const TargetLibraryInfo *,
1089 const DominatorTree *,
1090 unsigned) {
Duncan Sandsf24ed772011-05-02 16:27:02 +00001091 // undef % X -> undef (the undef could be a snan).
1092 if (match(Op0, m_Undef()))
1093 return Op0;
1094
1095 // X % undef -> undef
1096 if (match(Op1, m_Undef()))
1097 return Op1;
1098
1099 return 0;
1100}
1101
1102Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001103 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001104 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001105 return ::SimplifyFRemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001106}
1107
Duncan Sandscf80bc12011-01-14 14:44:12 +00001108/// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
Duncan Sandsc43cee32011-01-14 00:37:45 +00001109/// fold the result. If not, this returns null.
Duncan Sandscf80bc12011-01-14 14:44:12 +00001110static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Chad Rosier618c1db2011-12-01 03:08:23 +00001111 const TargetData *TD, const TargetLibraryInfo *TLI,
1112 const DominatorTree *DT, unsigned MaxRecurse) {
Duncan Sandsc43cee32011-01-14 00:37:45 +00001113 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1114 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1115 Constant *Ops[] = { C0, C1 };
Chad Rosier618c1db2011-12-01 03:08:23 +00001116 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001117 }
1118 }
1119
Duncan Sandscf80bc12011-01-14 14:44:12 +00001120 // 0 shift by X -> 0
Duncan Sandsc43cee32011-01-14 00:37:45 +00001121 if (match(Op0, m_Zero()))
1122 return Op0;
1123
Duncan Sandscf80bc12011-01-14 14:44:12 +00001124 // X shift by 0 -> X
Duncan Sandsc43cee32011-01-14 00:37:45 +00001125 if (match(Op1, m_Zero()))
1126 return Op0;
1127
Duncan Sandscf80bc12011-01-14 14:44:12 +00001128 // X shift by undef -> undef because it may shift by the bitwidth.
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001129 if (match(Op1, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001130 return Op1;
1131
1132 // Shifting by the bitwidth or more is undefined.
1133 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1134 if (CI->getValue().getLimitedValue() >=
1135 Op0->getType()->getScalarSizeInBits())
1136 return UndefValue::get(Op0->getType());
1137
Duncan Sandscf80bc12011-01-14 14:44:12 +00001138 // If the operation is with the result of a select instruction, check whether
1139 // operating on either branch of the select always yields the same value.
1140 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001141 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001142 return V;
1143
1144 // If the operation is with the result of a phi instruction, check whether
1145 // operating on all incoming values of the phi always yields the same value.
1146 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001147 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001148 return V;
1149
1150 return 0;
1151}
1152
1153/// SimplifyShlInst - Given operands for an Shl, see if we can
1154/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001155static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +00001156 const TargetData *TD,
1157 const TargetLibraryInfo *TLI,
1158 const DominatorTree *DT, unsigned MaxRecurse) {
1159 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001160 return V;
1161
1162 // undef << X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001163 if (match(Op0, m_Undef()))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001164 return Constant::getNullValue(Op0->getType());
1165
Chris Lattner81a0dc92011-02-09 17:15:04 +00001166 // (X >> A) << A -> X
1167 Value *X;
Benjamin Kramer55c6d572012-01-01 17:55:30 +00001168 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner81a0dc92011-02-09 17:15:04 +00001169 return X;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001170 return 0;
1171}
1172
Chris Lattner81a0dc92011-02-09 17:15:04 +00001173Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +00001174 const TargetData *TD, const TargetLibraryInfo *TLI,
1175 const DominatorTree *DT) {
1176 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001177}
1178
1179/// SimplifyLShrInst - Given operands for an LShr, see if we can
1180/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001181static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Chad Rosier618c1db2011-12-01 03:08:23 +00001182 const TargetData *TD,
1183 const TargetLibraryInfo *TLI,
1184 const DominatorTree *DT,
Chris Lattner81a0dc92011-02-09 17:15:04 +00001185 unsigned MaxRecurse) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001186 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001187 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001188
1189 // undef >>l X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001190 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001191 return Constant::getNullValue(Op0->getType());
1192
Chris Lattner81a0dc92011-02-09 17:15:04 +00001193 // (X << A) >> A -> X
1194 Value *X;
1195 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1196 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1197 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001198
Duncan Sandsc43cee32011-01-14 00:37:45 +00001199 return 0;
1200}
1201
Chris Lattner81a0dc92011-02-09 17:15:04 +00001202Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Chad Rosier618c1db2011-12-01 03:08:23 +00001203 const TargetData *TD,
1204 const TargetLibraryInfo *TLI,
1205 const DominatorTree *DT) {
1206 return ::SimplifyLShrInst(Op0, Op1, isExact, TD, TLI, DT, RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001207}
1208
1209/// SimplifyAShrInst - Given operands for an AShr, see if we can
1210/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001211static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Chad Rosier618c1db2011-12-01 03:08:23 +00001212 const TargetData *TD,
1213 const TargetLibraryInfo *TLI,
1214 const DominatorTree *DT,
Chris Lattner81a0dc92011-02-09 17:15:04 +00001215 unsigned MaxRecurse) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001216 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001217 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001218
1219 // all ones >>a X -> all ones
1220 if (match(Op0, m_AllOnes()))
1221 return Op0;
1222
1223 // undef >>a X -> all ones
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001224 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001225 return Constant::getAllOnesValue(Op0->getType());
1226
Chris Lattner81a0dc92011-02-09 17:15:04 +00001227 // (X << A) >> A -> X
1228 Value *X;
1229 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1230 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1231 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001232
Duncan Sandsc43cee32011-01-14 00:37:45 +00001233 return 0;
1234}
1235
Chris Lattner81a0dc92011-02-09 17:15:04 +00001236Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Chad Rosier618c1db2011-12-01 03:08:23 +00001237 const TargetData *TD,
1238 const TargetLibraryInfo *TLI,
1239 const DominatorTree *DT) {
1240 return ::SimplifyAShrInst(Op0, Op1, isExact, TD, TLI, DT, RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001241}
1242
Chris Lattnerd06094f2009-11-10 00:55:12 +00001243/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001244/// fold the result. If not, this returns null.
Chad Rosier618c1db2011-12-01 03:08:23 +00001245static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1246 const TargetLibraryInfo *TLI,
1247 const DominatorTree *DT,
1248 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001249 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1250 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1251 Constant *Ops[] = { CLHS, CRHS };
1252 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
Chad Rosier618c1db2011-12-01 03:08:23 +00001253 Ops, TD, TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001254 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001255
Chris Lattnerd06094f2009-11-10 00:55:12 +00001256 // Canonicalize the constant to the RHS.
1257 std::swap(Op0, Op1);
1258 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001259
Chris Lattnerd06094f2009-11-10 00:55:12 +00001260 // X & undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001261 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001262 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001263
Chris Lattnerd06094f2009-11-10 00:55:12 +00001264 // X & X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001265 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001266 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001267
Duncan Sands2b749872010-11-17 18:52:15 +00001268 // X & 0 = 0
1269 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001270 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001271
Duncan Sands2b749872010-11-17 18:52:15 +00001272 // X & -1 = X
1273 if (match(Op1, m_AllOnes()))
1274 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001275
Chris Lattnerd06094f2009-11-10 00:55:12 +00001276 // A & ~A = ~A & A = 0
Chris Lattner81a0dc92011-02-09 17:15:04 +00001277 if (match(Op0, m_Not(m_Specific(Op1))) ||
1278 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001279 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001280
Chris Lattnerd06094f2009-11-10 00:55:12 +00001281 // (A | ?) & A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001282 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001283 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001284 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001285 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001286
Chris Lattnerd06094f2009-11-10 00:55:12 +00001287 // A & (A | ?) = A
1288 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001289 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001290 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001291
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001292 // A & (-A) = A if A is a power of two or zero.
1293 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1294 match(Op1, m_Neg(m_Specific(Op0)))) {
1295 if (isPowerOfTwo(Op0, TD, /*OrZero*/true))
1296 return Op0;
1297 if (isPowerOfTwo(Op1, TD, /*OrZero*/true))
1298 return Op1;
1299 }
1300
Duncan Sands566edb02010-12-21 08:49:00 +00001301 // Try some generic simplifications for associative operations.
Chad Rosier618c1db2011-12-01 03:08:23 +00001302 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, TLI,
1303 DT, MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001304 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001305
Duncan Sands3421d902010-12-21 13:32:22 +00001306 // And distributes over Or. Try some generic simplifications based on this.
1307 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Chad Rosier618c1db2011-12-01 03:08:23 +00001308 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001309 return V;
1310
1311 // And distributes over Xor. Try some generic simplifications based on this.
1312 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Chad Rosier618c1db2011-12-01 03:08:23 +00001313 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001314 return V;
1315
1316 // Or distributes over And. Try some generic simplifications based on this.
1317 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Chad Rosier618c1db2011-12-01 03:08:23 +00001318 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001319 return V;
1320
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001321 // If the operation is with the result of a select instruction, check whether
1322 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001323 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001324 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, TLI,
1325 DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001326 return V;
1327
1328 // If the operation is with the result of a phi instruction, check whether
1329 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001330 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001331 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, TLI, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001332 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001333 return V;
1334
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001335 return 0;
1336}
1337
Duncan Sands18450092010-11-16 12:16:38 +00001338Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001339 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +00001340 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001341 return ::SimplifyAndInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001342}
1343
Chris Lattnerd06094f2009-11-10 00:55:12 +00001344/// SimplifyOrInst - Given operands for an Or, see if we can
1345/// fold the result. If not, this returns null.
Chad Rosier618c1db2011-12-01 03:08:23 +00001346static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1347 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +00001348 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001349 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1350 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1351 Constant *Ops[] = { CLHS, CRHS };
1352 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
Chad Rosier618c1db2011-12-01 03:08:23 +00001353 Ops, TD, TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001354 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001355
Chris Lattnerd06094f2009-11-10 00:55:12 +00001356 // Canonicalize the constant to the RHS.
1357 std::swap(Op0, Op1);
1358 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001359
Chris Lattnerd06094f2009-11-10 00:55:12 +00001360 // X | undef -> -1
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001361 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001362 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001363
Chris Lattnerd06094f2009-11-10 00:55:12 +00001364 // X | X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001365 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001366 return Op0;
1367
Duncan Sands2b749872010-11-17 18:52:15 +00001368 // X | 0 = X
1369 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001370 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001371
Duncan Sands2b749872010-11-17 18:52:15 +00001372 // X | -1 = -1
1373 if (match(Op1, m_AllOnes()))
1374 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001375
Chris Lattnerd06094f2009-11-10 00:55:12 +00001376 // A | ~A = ~A | A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001377 if (match(Op0, m_Not(m_Specific(Op1))) ||
1378 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001379 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001380
Chris Lattnerd06094f2009-11-10 00:55:12 +00001381 // (A & ?) | A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001382 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001383 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001384 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001385 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001386
Chris Lattnerd06094f2009-11-10 00:55:12 +00001387 // A | (A & ?) = A
1388 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001389 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001390 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001391
Benjamin Kramer38f7f662011-02-20 15:20:01 +00001392 // ~(A & ?) | A = -1
1393 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1394 (A == Op1 || B == Op1))
1395 return Constant::getAllOnesValue(Op1->getType());
1396
1397 // A | ~(A & ?) = -1
1398 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1399 (A == Op0 || B == Op0))
1400 return Constant::getAllOnesValue(Op0->getType());
1401
Duncan Sands566edb02010-12-21 08:49:00 +00001402 // Try some generic simplifications for associative operations.
Chad Rosier618c1db2011-12-01 03:08:23 +00001403 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, TLI,
1404 DT, MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001405 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001406
Duncan Sands3421d902010-12-21 13:32:22 +00001407 // Or distributes over And. Try some generic simplifications based on this.
Chad Rosier618c1db2011-12-01 03:08:23 +00001408 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, TD,
1409 TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001410 return V;
1411
1412 // And distributes over Or. Try some generic simplifications based on this.
1413 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
Chad Rosier618c1db2011-12-01 03:08:23 +00001414 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001415 return V;
1416
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001417 // If the operation is with the result of a select instruction, check whether
1418 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001419 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001420 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, TLI, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001421 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001422 return V;
1423
1424 // If the operation is with the result of a phi instruction, check whether
1425 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001426 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001427 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, TLI, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001428 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001429 return V;
1430
Chris Lattnerd06094f2009-11-10 00:55:12 +00001431 return 0;
1432}
1433
Duncan Sands18450092010-11-16 12:16:38 +00001434Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001435 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +00001436 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001437 return ::SimplifyOrInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001438}
Chris Lattnerd06094f2009-11-10 00:55:12 +00001439
Duncan Sands2b749872010-11-17 18:52:15 +00001440/// SimplifyXorInst - Given operands for a Xor, see if we can
1441/// fold the result. If not, this returns null.
1442static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001443 const TargetLibraryInfo *TLI,
Duncan Sands2b749872010-11-17 18:52:15 +00001444 const DominatorTree *DT, unsigned MaxRecurse) {
1445 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1446 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1447 Constant *Ops[] = { CLHS, CRHS };
1448 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
Chad Rosier618c1db2011-12-01 03:08:23 +00001449 Ops, TD, TLI);
Duncan Sands2b749872010-11-17 18:52:15 +00001450 }
1451
1452 // Canonicalize the constant to the RHS.
1453 std::swap(Op0, Op1);
1454 }
1455
1456 // A ^ undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001457 if (match(Op1, m_Undef()))
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00001458 return Op1;
Duncan Sands2b749872010-11-17 18:52:15 +00001459
1460 // A ^ 0 = A
1461 if (match(Op1, m_Zero()))
1462 return Op0;
1463
Eli Friedmanf23d4ad2011-08-17 19:31:49 +00001464 // A ^ A = 0
1465 if (Op0 == Op1)
1466 return Constant::getNullValue(Op0->getType());
1467
Duncan Sands2b749872010-11-17 18:52:15 +00001468 // A ^ ~A = ~A ^ A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001469 if (match(Op0, m_Not(m_Specific(Op1))) ||
1470 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands2b749872010-11-17 18:52:15 +00001471 return Constant::getAllOnesValue(Op0->getType());
1472
Duncan Sands566edb02010-12-21 08:49:00 +00001473 // Try some generic simplifications for associative operations.
Chad Rosier618c1db2011-12-01 03:08:23 +00001474 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, TLI,
1475 DT, MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001476 return V;
Duncan Sands2b749872010-11-17 18:52:15 +00001477
Duncan Sands3421d902010-12-21 13:32:22 +00001478 // And distributes over Xor. Try some generic simplifications based on this.
1479 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
Chad Rosier618c1db2011-12-01 03:08:23 +00001480 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001481 return V;
1482
Duncan Sands87689cf2010-11-19 09:20:39 +00001483 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1484 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1485 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1486 // only if B and C are equal. If B and C are equal then (since we assume
1487 // that operands have already been simplified) "select(cond, B, C)" should
1488 // have been simplified to the common value of B and C already. Analysing
1489 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1490 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +00001491
1492 return 0;
1493}
1494
1495Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001496 const TargetLibraryInfo *TLI,
Duncan Sands2b749872010-11-17 18:52:15 +00001497 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001498 return ::SimplifyXorInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sands2b749872010-11-17 18:52:15 +00001499}
1500
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001501static Type *GetCompareTy(Value *Op) {
Chris Lattner210c5d42009-11-09 23:55:12 +00001502 return CmpInst::makeCmpResultType(Op->getType());
1503}
1504
Duncan Sandse864b5b2011-05-07 16:56:49 +00001505/// ExtractEquivalentCondition - Rummage around inside V looking for something
1506/// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1507/// otherwise return null. Helper function for analyzing max/min idioms.
1508static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1509 Value *LHS, Value *RHS) {
1510 SelectInst *SI = dyn_cast<SelectInst>(V);
1511 if (!SI)
1512 return 0;
1513 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1514 if (!Cmp)
1515 return 0;
1516 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1517 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1518 return Cmp;
1519 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1520 LHS == CmpRHS && RHS == CmpLHS)
1521 return Cmp;
1522 return 0;
1523}
1524
Chris Lattnerb053fc12012-02-20 00:42:49 +00001525/// stripPointerAdjustments - This is like Value::stripPointerCasts, but also
1526/// removes inbounds gep operations, regardless of their indices.
Chris Lattner009e2652012-02-24 19:01:58 +00001527static Value *stripPointerAdjustmentsImpl(Value *V,
1528 SmallPtrSet<GEPOperator*, 8> &VisitedGEPs) {
1529 GEPOperator *GEP = dyn_cast<GEPOperator>(V);
1530 if (GEP == 0 || !GEP->isInBounds())
1531 return V;
1532
1533 // If we've already seen this GEP, we will end up infinitely looping. This
1534 // can happen in unreachable code.
1535 if (!VisitedGEPs.insert(GEP))
1536 return V;
1537
1538 return stripPointerAdjustmentsImpl(GEP->getOperand(0)->stripPointerCasts(),
1539 VisitedGEPs);
Chris Lattnerb053fc12012-02-20 00:42:49 +00001540}
1541
Chris Lattner009e2652012-02-24 19:01:58 +00001542static Value *stripPointerAdjustments(Value *V) {
1543 SmallPtrSet<GEPOperator*, 8> VisitedGEPs;
1544 return stripPointerAdjustmentsImpl(V, VisitedGEPs);
1545}
1546
1547
Chris Lattner9dbb4292009-11-09 23:28:39 +00001548/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1549/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001550static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00001551 const TargetData *TD,
1552 const TargetLibraryInfo *TLI,
1553 const DominatorTree *DT,
Duncan Sands18450092010-11-16 12:16:38 +00001554 unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001555 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +00001556 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +00001557
Chris Lattnerd06094f2009-11-10 00:55:12 +00001558 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +00001559 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00001560 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD, TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001561
1562 // If we have a constant, make sure it is on the RHS.
1563 std::swap(LHS, RHS);
1564 Pred = CmpInst::getSwappedPredicate(Pred);
1565 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001566
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001567 Type *ITy = GetCompareTy(LHS); // The return type.
1568 Type *OpTy = LHS->getType(); // The operand type.
Duncan Sands12a86f52010-11-14 11:23:23 +00001569
Chris Lattner210c5d42009-11-09 23:55:12 +00001570 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +00001571 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1572 // because X could be 0.
Duncan Sands124708d2011-01-01 20:08:02 +00001573 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +00001574 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +00001575
Duncan Sands6dc91252011-01-13 08:56:29 +00001576 // Special case logic when the operands have i1 type.
Nick Lewycky66d004e2011-12-01 02:39:36 +00001577 if (OpTy->getScalarType()->isIntegerTy(1)) {
Duncan Sands6dc91252011-01-13 08:56:29 +00001578 switch (Pred) {
1579 default: break;
1580 case ICmpInst::ICMP_EQ:
1581 // X == 1 -> X
1582 if (match(RHS, m_One()))
1583 return LHS;
1584 break;
1585 case ICmpInst::ICMP_NE:
1586 // X != 0 -> X
1587 if (match(RHS, m_Zero()))
1588 return LHS;
1589 break;
1590 case ICmpInst::ICMP_UGT:
1591 // X >u 0 -> X
1592 if (match(RHS, m_Zero()))
1593 return LHS;
1594 break;
1595 case ICmpInst::ICMP_UGE:
1596 // X >=u 1 -> X
1597 if (match(RHS, m_One()))
1598 return LHS;
1599 break;
1600 case ICmpInst::ICMP_SLT:
1601 // X <s 0 -> X
1602 if (match(RHS, m_Zero()))
1603 return LHS;
1604 break;
1605 case ICmpInst::ICMP_SLE:
1606 // X <=s -1 -> X
1607 if (match(RHS, m_One()))
1608 return LHS;
1609 break;
1610 }
1611 }
1612
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001613 // icmp <object*>, <object*/null> - Different identified objects have
1614 // different addresses (unless null), and what's more the address of an
1615 // identified local is never equal to another argument (again, barring null).
1616 // Note that generalizing to the case where LHS is a global variable address
1617 // or null is pointless, since if both LHS and RHS are constants then we
1618 // already constant folded the compare, and if only one of them is then we
1619 // moved it to RHS already.
Benjamin Kramerea79b8e2012-02-16 15:19:59 +00001620 Value *LHSPtr = LHS->stripPointerCasts();
1621 Value *RHSPtr = RHS->stripPointerCasts();
Eli Friedman2c3acb02012-02-18 03:29:25 +00001622 if (LHSPtr == RHSPtr)
1623 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001624
Chris Lattnerb053fc12012-02-20 00:42:49 +00001625 // Be more aggressive about stripping pointer adjustments when checking a
1626 // comparison of an alloca address to another object. We can rip off all
1627 // inbounds GEP operations, even if they are variable.
1628 LHSPtr = stripPointerAdjustments(LHSPtr);
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001629 if (llvm::isIdentifiedObject(LHSPtr)) {
Chris Lattnerb053fc12012-02-20 00:42:49 +00001630 RHSPtr = stripPointerAdjustments(RHSPtr);
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001631 if (llvm::isKnownNonNull(LHSPtr) || llvm::isKnownNonNull(RHSPtr)) {
1632 // If both sides are different identified objects, they aren't equal
1633 // unless they're null.
1634 if (LHSPtr != RHSPtr && llvm::isIdentifiedObject(RHSPtr))
1635 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1636
1637 // A local identified object (alloca or noalias call) can't equal any
1638 // incoming argument, unless they're both null.
1639 if (isa<Instruction>(LHSPtr) && isa<Argument>(RHSPtr))
1640 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1641 }
1642
1643 // Assume that the constant null is on the right.
1644 if (llvm::isKnownNonNull(LHSPtr) && isa<ConstantPointerNull>(RHSPtr))
1645 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1646 } else if (isa<Argument>(LHSPtr)) {
1647 RHSPtr = stripPointerAdjustments(RHSPtr);
1648 // An alloca can't be equal to an argument.
1649 if (isa<AllocaInst>(RHSPtr))
Nick Lewycky1e4e1c72012-02-25 19:07:42 +00001650 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
Chris Lattnerb053fc12012-02-20 00:42:49 +00001651 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001652
1653 // If we are comparing with zero then try hard since this is a common case.
1654 if (match(RHS, m_Zero())) {
1655 bool LHSKnownNonNegative, LHSKnownNegative;
1656 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00001657 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001658 case ICmpInst::ICMP_ULT:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001659 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001660 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001661 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001662 case ICmpInst::ICMP_EQ:
1663 case ICmpInst::ICMP_ULE:
1664 if (isKnownNonZero(LHS, TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001665 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001666 break;
1667 case ICmpInst::ICMP_NE:
1668 case ICmpInst::ICMP_UGT:
1669 if (isKnownNonZero(LHS, TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001670 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001671 break;
1672 case ICmpInst::ICMP_SLT:
1673 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1674 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001675 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001676 if (LHSKnownNonNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001677 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001678 break;
1679 case ICmpInst::ICMP_SLE:
1680 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1681 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001682 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001683 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001684 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001685 break;
1686 case ICmpInst::ICMP_SGE:
1687 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1688 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001689 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001690 if (LHSKnownNonNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001691 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001692 break;
1693 case ICmpInst::ICMP_SGT:
1694 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1695 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001696 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001697 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001698 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001699 break;
1700 }
1701 }
1702
1703 // See if we are doing a comparison with a constant integer.
Duncan Sands6dc91252011-01-13 08:56:29 +00001704 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Nick Lewycky3a73e342011-03-04 07:00:57 +00001705 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1706 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1707 if (RHS_CR.isEmptySet())
1708 return ConstantInt::getFalse(CI->getContext());
1709 if (RHS_CR.isFullSet())
1710 return ConstantInt::getTrue(CI->getContext());
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001711
Nick Lewycky3a73e342011-03-04 07:00:57 +00001712 // Many binary operators with constant RHS have easy to compute constant
1713 // range. Use them to check whether the comparison is a tautology.
1714 uint32_t Width = CI->getBitWidth();
1715 APInt Lower = APInt(Width, 0);
1716 APInt Upper = APInt(Width, 0);
1717 ConstantInt *CI2;
1718 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1719 // 'urem x, CI2' produces [0, CI2).
1720 Upper = CI2->getValue();
1721 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1722 // 'srem x, CI2' produces (-|CI2|, |CI2|).
1723 Upper = CI2->getValue().abs();
1724 Lower = (-Upper) + 1;
Duncan Sandsc65c7472011-10-28 18:17:44 +00001725 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
1726 // 'udiv CI2, x' produces [0, CI2].
Eli Friedman7781ae52011-11-08 21:08:02 +00001727 Upper = CI2->getValue() + 1;
Nick Lewycky3a73e342011-03-04 07:00:57 +00001728 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1729 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1730 APInt NegOne = APInt::getAllOnesValue(Width);
1731 if (!CI2->isZero())
1732 Upper = NegOne.udiv(CI2->getValue()) + 1;
1733 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1734 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1735 APInt IntMin = APInt::getSignedMinValue(Width);
1736 APInt IntMax = APInt::getSignedMaxValue(Width);
1737 APInt Val = CI2->getValue().abs();
1738 if (!Val.isMinValue()) {
1739 Lower = IntMin.sdiv(Val);
1740 Upper = IntMax.sdiv(Val) + 1;
1741 }
1742 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1743 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1744 APInt NegOne = APInt::getAllOnesValue(Width);
1745 if (CI2->getValue().ult(Width))
1746 Upper = NegOne.lshr(CI2->getValue()) + 1;
1747 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1748 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1749 APInt IntMin = APInt::getSignedMinValue(Width);
1750 APInt IntMax = APInt::getSignedMaxValue(Width);
1751 if (CI2->getValue().ult(Width)) {
1752 Lower = IntMin.ashr(CI2->getValue());
1753 Upper = IntMax.ashr(CI2->getValue()) + 1;
1754 }
1755 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1756 // 'or x, CI2' produces [CI2, UINT_MAX].
1757 Lower = CI2->getValue();
1758 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1759 // 'and x, CI2' produces [0, CI2].
1760 Upper = CI2->getValue() + 1;
1761 }
1762 if (Lower != Upper) {
1763 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1764 if (RHS_CR.contains(LHS_CR))
1765 return ConstantInt::getTrue(RHS->getContext());
1766 if (RHS_CR.inverse().contains(LHS_CR))
1767 return ConstantInt::getFalse(RHS->getContext());
1768 }
Duncan Sands6dc91252011-01-13 08:56:29 +00001769 }
1770
Duncan Sands9d32f602011-01-20 13:21:55 +00001771 // Compare of cast, for example (zext X) != 0 -> X != 0
1772 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1773 Instruction *LI = cast<CastInst>(LHS);
1774 Value *SrcOp = LI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001775 Type *SrcTy = SrcOp->getType();
1776 Type *DstTy = LI->getType();
Duncan Sands9d32f602011-01-20 13:21:55 +00001777
1778 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1779 // if the integer type is the same size as the pointer type.
1780 if (MaxRecurse && TD && isa<PtrToIntInst>(LI) &&
1781 TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
1782 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1783 // Transfer the cast to the constant.
1784 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1785 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Chad Rosier618c1db2011-12-01 03:08:23 +00001786 TD, TLI, DT, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001787 return V;
1788 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1789 if (RI->getOperand(0)->getType() == SrcTy)
1790 // Compare without the cast.
1791 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Chad Rosier618c1db2011-12-01 03:08:23 +00001792 TD, TLI, DT, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001793 return V;
1794 }
1795 }
1796
1797 if (isa<ZExtInst>(LHS)) {
1798 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1799 // same type.
1800 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1801 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1802 // Compare X and Y. Note that signed predicates become unsigned.
1803 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Chad Rosier618c1db2011-12-01 03:08:23 +00001804 SrcOp, RI->getOperand(0), TD, TLI, DT,
Duncan Sands9d32f602011-01-20 13:21:55 +00001805 MaxRecurse-1))
1806 return V;
1807 }
1808 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1809 // too. If not, then try to deduce the result of the comparison.
1810 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1811 // Compute the constant that would happen if we truncated to SrcTy then
1812 // reextended to DstTy.
1813 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1814 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1815
1816 // If the re-extended constant didn't change then this is effectively
1817 // also a case of comparing two zero-extended values.
1818 if (RExt == CI && MaxRecurse)
1819 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Nadav Rotem16087692011-12-05 06:29:09 +00001820 SrcOp, Trunc, TD, TLI, DT, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001821 return V;
1822
1823 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1824 // there. Use this to work out the result of the comparison.
1825 if (RExt != CI) {
1826 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00001827 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands9d32f602011-01-20 13:21:55 +00001828 // LHS <u RHS.
1829 case ICmpInst::ICMP_EQ:
1830 case ICmpInst::ICMP_UGT:
1831 case ICmpInst::ICMP_UGE:
1832 return ConstantInt::getFalse(CI->getContext());
1833
1834 case ICmpInst::ICMP_NE:
1835 case ICmpInst::ICMP_ULT:
1836 case ICmpInst::ICMP_ULE:
1837 return ConstantInt::getTrue(CI->getContext());
1838
1839 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
1840 // is non-negative then LHS <s RHS.
1841 case ICmpInst::ICMP_SGT:
1842 case ICmpInst::ICMP_SGE:
1843 return CI->getValue().isNegative() ?
1844 ConstantInt::getTrue(CI->getContext()) :
1845 ConstantInt::getFalse(CI->getContext());
1846
1847 case ICmpInst::ICMP_SLT:
1848 case ICmpInst::ICMP_SLE:
1849 return CI->getValue().isNegative() ?
1850 ConstantInt::getFalse(CI->getContext()) :
1851 ConstantInt::getTrue(CI->getContext());
1852 }
1853 }
1854 }
1855 }
1856
1857 if (isa<SExtInst>(LHS)) {
1858 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1859 // same type.
1860 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1861 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1862 // Compare X and Y. Note that the predicate does not change.
1863 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Chad Rosier618c1db2011-12-01 03:08:23 +00001864 TD, TLI, DT, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001865 return V;
1866 }
1867 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1868 // too. If not, then try to deduce the result of the comparison.
1869 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1870 // Compute the constant that would happen if we truncated to SrcTy then
1871 // reextended to DstTy.
1872 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1873 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1874
1875 // If the re-extended constant didn't change then this is effectively
1876 // also a case of comparing two sign-extended values.
1877 if (RExt == CI && MaxRecurse)
Chad Rosier618c1db2011-12-01 03:08:23 +00001878 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, TD, TLI, DT,
Duncan Sands9d32f602011-01-20 13:21:55 +00001879 MaxRecurse-1))
1880 return V;
1881
1882 // Otherwise the upper bits of LHS are all equal, while RHS has varying
1883 // bits there. Use this to work out the result of the comparison.
1884 if (RExt != CI) {
1885 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00001886 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands9d32f602011-01-20 13:21:55 +00001887 case ICmpInst::ICMP_EQ:
1888 return ConstantInt::getFalse(CI->getContext());
1889 case ICmpInst::ICMP_NE:
1890 return ConstantInt::getTrue(CI->getContext());
1891
1892 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
1893 // LHS >s RHS.
1894 case ICmpInst::ICMP_SGT:
1895 case ICmpInst::ICMP_SGE:
1896 return CI->getValue().isNegative() ?
1897 ConstantInt::getTrue(CI->getContext()) :
1898 ConstantInt::getFalse(CI->getContext());
1899 case ICmpInst::ICMP_SLT:
1900 case ICmpInst::ICMP_SLE:
1901 return CI->getValue().isNegative() ?
1902 ConstantInt::getFalse(CI->getContext()) :
1903 ConstantInt::getTrue(CI->getContext());
1904
1905 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
1906 // LHS >u RHS.
1907 case ICmpInst::ICMP_UGT:
1908 case ICmpInst::ICMP_UGE:
1909 // Comparison is true iff the LHS <s 0.
1910 if (MaxRecurse)
1911 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
1912 Constant::getNullValue(SrcTy),
Chad Rosier618c1db2011-12-01 03:08:23 +00001913 TD, TLI, DT, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001914 return V;
1915 break;
1916 case ICmpInst::ICMP_ULT:
1917 case ICmpInst::ICMP_ULE:
1918 // Comparison is true iff the LHS >=s 0.
1919 if (MaxRecurse)
1920 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
1921 Constant::getNullValue(SrcTy),
Chad Rosier618c1db2011-12-01 03:08:23 +00001922 TD, TLI, DT, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001923 return V;
1924 break;
1925 }
1926 }
1927 }
1928 }
1929 }
1930
Duncan Sands52fb8462011-02-13 17:15:40 +00001931 // Special logic for binary operators.
1932 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
1933 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
1934 if (MaxRecurse && (LBO || RBO)) {
Duncan Sands52fb8462011-02-13 17:15:40 +00001935 // Analyze the case when either LHS or RHS is an add instruction.
1936 Value *A = 0, *B = 0, *C = 0, *D = 0;
1937 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
1938 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
1939 if (LBO && LBO->getOpcode() == Instruction::Add) {
1940 A = LBO->getOperand(0); B = LBO->getOperand(1);
1941 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
1942 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
1943 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
1944 }
1945 if (RBO && RBO->getOpcode() == Instruction::Add) {
1946 C = RBO->getOperand(0); D = RBO->getOperand(1);
1947 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
1948 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
1949 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
1950 }
1951
1952 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
1953 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
1954 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
1955 Constant::getNullValue(RHS->getType()),
Chad Rosier618c1db2011-12-01 03:08:23 +00001956 TD, TLI, DT, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00001957 return V;
1958
1959 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
1960 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
1961 if (Value *V = SimplifyICmpInst(Pred,
1962 Constant::getNullValue(LHS->getType()),
Chad Rosier618c1db2011-12-01 03:08:23 +00001963 C == LHS ? D : C, TD, TLI, DT, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00001964 return V;
1965
1966 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
1967 if (A && C && (A == C || A == D || B == C || B == D) &&
1968 NoLHSWrapProblem && NoRHSWrapProblem) {
1969 // Determine Y and Z in the form icmp (X+Y), (X+Z).
1970 Value *Y = (A == C || A == D) ? B : A;
1971 Value *Z = (C == A || C == B) ? D : C;
Chad Rosier618c1db2011-12-01 03:08:23 +00001972 if (Value *V = SimplifyICmpInst(Pred, Y, Z, TD, TLI, DT, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00001973 return V;
1974 }
1975 }
1976
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001977 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Nick Lewycky78679272011-03-04 10:06:52 +00001978 bool KnownNonNegative, KnownNegative;
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001979 switch (Pred) {
1980 default:
1981 break;
Nick Lewycky78679272011-03-04 10:06:52 +00001982 case ICmpInst::ICMP_SGT:
1983 case ICmpInst::ICMP_SGE:
1984 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1985 if (!KnownNonNegative)
1986 break;
1987 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001988 case ICmpInst::ICMP_EQ:
1989 case ICmpInst::ICMP_UGT:
1990 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001991 return getFalse(ITy);
Nick Lewycky78679272011-03-04 10:06:52 +00001992 case ICmpInst::ICMP_SLT:
1993 case ICmpInst::ICMP_SLE:
1994 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1995 if (!KnownNonNegative)
1996 break;
1997 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001998 case ICmpInst::ICMP_NE:
1999 case ICmpInst::ICMP_ULT:
2000 case ICmpInst::ICMP_ULE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002001 return getTrue(ITy);
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002002 }
2003 }
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002004 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2005 bool KnownNonNegative, KnownNegative;
2006 switch (Pred) {
2007 default:
2008 break;
2009 case ICmpInst::ICMP_SGT:
2010 case ICmpInst::ICMP_SGE:
2011 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
2012 if (!KnownNonNegative)
2013 break;
2014 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00002015 case ICmpInst::ICMP_NE:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002016 case ICmpInst::ICMP_UGT:
2017 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002018 return getTrue(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002019 case ICmpInst::ICMP_SLT:
2020 case ICmpInst::ICMP_SLE:
2021 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
2022 if (!KnownNonNegative)
2023 break;
2024 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00002025 case ICmpInst::ICMP_EQ:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002026 case ICmpInst::ICMP_ULT:
2027 case ICmpInst::ICMP_ULE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002028 return getFalse(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002029 }
2030 }
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002031
Duncan Sandsc65c7472011-10-28 18:17:44 +00002032 // x udiv y <=u x.
2033 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2034 // icmp pred (X /u Y), X
2035 if (Pred == ICmpInst::ICMP_UGT)
2036 return getFalse(ITy);
2037 if (Pred == ICmpInst::ICMP_ULE)
2038 return getTrue(ITy);
2039 }
2040
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002041 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2042 LBO->getOperand(1) == RBO->getOperand(1)) {
2043 switch (LBO->getOpcode()) {
2044 default: break;
2045 case Instruction::UDiv:
2046 case Instruction::LShr:
2047 if (ICmpInst::isSigned(Pred))
2048 break;
2049 // fall-through
2050 case Instruction::SDiv:
2051 case Instruction::AShr:
Eli Friedmanb6e7cd62011-05-05 21:59:18 +00002052 if (!LBO->isExact() || !RBO->isExact())
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002053 break;
2054 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Chad Rosier618c1db2011-12-01 03:08:23 +00002055 RBO->getOperand(0), TD, TLI, DT, MaxRecurse-1))
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002056 return V;
2057 break;
2058 case Instruction::Shl: {
Duncan Sandsc9d904e2011-08-04 10:02:21 +00002059 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002060 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2061 if (!NUW && !NSW)
2062 break;
2063 if (!NSW && ICmpInst::isSigned(Pred))
2064 break;
2065 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Chad Rosier618c1db2011-12-01 03:08:23 +00002066 RBO->getOperand(0), TD, TLI, DT, MaxRecurse-1))
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002067 return V;
2068 break;
2069 }
2070 }
2071 }
2072
Duncan Sandsad206812011-05-03 19:53:10 +00002073 // Simplify comparisons involving max/min.
2074 Value *A, *B;
2075 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2076 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2077
Duncan Sands8140ad32011-05-04 16:05:05 +00002078 // Signed variants on "max(a,b)>=a -> true".
Duncan Sandsad206812011-05-03 19:53:10 +00002079 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2080 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2081 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2082 // We analyze this as smax(A, B) pred A.
2083 P = Pred;
2084 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2085 (A == LHS || B == LHS)) {
2086 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2087 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2088 // We analyze this as smax(A, B) swapped-pred A.
2089 P = CmpInst::getSwappedPredicate(Pred);
2090 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2091 (A == RHS || B == RHS)) {
2092 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2093 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2094 // We analyze this as smax(-A, -B) swapped-pred -A.
2095 // Note that we do not need to actually form -A or -B thanks to EqP.
2096 P = CmpInst::getSwappedPredicate(Pred);
2097 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2098 (A == LHS || B == LHS)) {
2099 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2100 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2101 // We analyze this as smax(-A, -B) pred -A.
2102 // Note that we do not need to actually form -A or -B thanks to EqP.
2103 P = Pred;
2104 }
2105 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2106 // Cases correspond to "max(A, B) p A".
2107 switch (P) {
2108 default:
2109 break;
2110 case CmpInst::ICMP_EQ:
2111 case CmpInst::ICMP_SLE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002112 // Equivalent to "A EqP B". This may be the same as the condition tested
2113 // in the max/min; if so, we can just return that.
2114 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2115 return V;
2116 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2117 return V;
2118 // Otherwise, see if "A EqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002119 if (MaxRecurse)
Chad Rosier618c1db2011-12-01 03:08:23 +00002120 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002121 return V;
2122 break;
2123 case CmpInst::ICMP_NE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002124 case CmpInst::ICMP_SGT: {
2125 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2126 // Equivalent to "A InvEqP B". This may be the same as the condition
2127 // tested in the max/min; if so, we can just return that.
2128 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2129 return V;
2130 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2131 return V;
2132 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002133 if (MaxRecurse)
Chad Rosier618c1db2011-12-01 03:08:23 +00002134 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002135 return V;
2136 break;
Duncan Sandse864b5b2011-05-07 16:56:49 +00002137 }
Duncan Sandsad206812011-05-03 19:53:10 +00002138 case CmpInst::ICMP_SGE:
2139 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002140 return getTrue(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002141 case CmpInst::ICMP_SLT:
2142 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002143 return getFalse(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002144 }
2145 }
2146
Duncan Sands8140ad32011-05-04 16:05:05 +00002147 // Unsigned variants on "max(a,b)>=a -> true".
Duncan Sandsad206812011-05-03 19:53:10 +00002148 P = CmpInst::BAD_ICMP_PREDICATE;
2149 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2150 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2151 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2152 // We analyze this as umax(A, B) pred A.
2153 P = Pred;
2154 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2155 (A == LHS || B == LHS)) {
2156 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2157 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2158 // We analyze this as umax(A, B) swapped-pred A.
2159 P = CmpInst::getSwappedPredicate(Pred);
2160 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2161 (A == RHS || B == RHS)) {
2162 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2163 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2164 // We analyze this as umax(-A, -B) swapped-pred -A.
2165 // Note that we do not need to actually form -A or -B thanks to EqP.
2166 P = CmpInst::getSwappedPredicate(Pred);
2167 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2168 (A == LHS || B == LHS)) {
2169 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2170 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2171 // We analyze this as umax(-A, -B) pred -A.
2172 // Note that we do not need to actually form -A or -B thanks to EqP.
2173 P = Pred;
2174 }
2175 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2176 // Cases correspond to "max(A, B) p A".
2177 switch (P) {
2178 default:
2179 break;
2180 case CmpInst::ICMP_EQ:
2181 case CmpInst::ICMP_ULE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002182 // Equivalent to "A EqP B". This may be the same as the condition tested
2183 // in the max/min; if so, we can just return that.
2184 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2185 return V;
2186 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2187 return V;
2188 // Otherwise, see if "A EqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002189 if (MaxRecurse)
Chad Rosier618c1db2011-12-01 03:08:23 +00002190 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002191 return V;
2192 break;
2193 case CmpInst::ICMP_NE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002194 case CmpInst::ICMP_UGT: {
2195 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2196 // Equivalent to "A InvEqP B". This may be the same as the condition
2197 // tested in the max/min; if so, we can just return that.
2198 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2199 return V;
2200 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2201 return V;
2202 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002203 if (MaxRecurse)
Chad Rosier618c1db2011-12-01 03:08:23 +00002204 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002205 return V;
2206 break;
Duncan Sandse864b5b2011-05-07 16:56:49 +00002207 }
Duncan Sandsad206812011-05-03 19:53:10 +00002208 case CmpInst::ICMP_UGE:
2209 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002210 return getTrue(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002211 case CmpInst::ICMP_ULT:
2212 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002213 return getFalse(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002214 }
2215 }
2216
Duncan Sands8140ad32011-05-04 16:05:05 +00002217 // Variants on "max(x,y) >= min(x,z)".
2218 Value *C, *D;
2219 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2220 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2221 (A == C || A == D || B == C || B == D)) {
2222 // max(x, ?) pred min(x, ?).
2223 if (Pred == CmpInst::ICMP_SGE)
2224 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002225 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002226 if (Pred == CmpInst::ICMP_SLT)
2227 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002228 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002229 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2230 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2231 (A == C || A == D || B == C || B == D)) {
2232 // min(x, ?) pred max(x, ?).
2233 if (Pred == CmpInst::ICMP_SLE)
2234 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002235 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002236 if (Pred == CmpInst::ICMP_SGT)
2237 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002238 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002239 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2240 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2241 (A == C || A == D || B == C || B == D)) {
2242 // max(x, ?) pred min(x, ?).
2243 if (Pred == CmpInst::ICMP_UGE)
2244 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002245 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002246 if (Pred == CmpInst::ICMP_ULT)
2247 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002248 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002249 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2250 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2251 (A == C || A == D || B == C || B == D)) {
2252 // min(x, ?) pred max(x, ?).
2253 if (Pred == CmpInst::ICMP_ULE)
2254 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002255 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002256 if (Pred == CmpInst::ICMP_UGT)
2257 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002258 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002259 }
2260
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00002261 // Simplify comparisons of GEPs.
2262 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2263 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2264 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2265 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2266 (ICmpInst::isEquality(Pred) ||
2267 (GLHS->isInBounds() && GRHS->isInBounds() &&
2268 Pred == ICmpInst::getSignedPredicate(Pred)))) {
2269 // The bases are equal and the indices are constant. Build a constant
2270 // expression GEP with the same indices and a null base pointer to see
2271 // what constant folding can make out of it.
2272 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2273 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2274 Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2275
2276 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2277 Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2278 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2279 }
2280 }
2281 }
2282
Duncan Sands1ac7c992010-11-07 16:12:23 +00002283 // If the comparison is with the result of a select instruction, check whether
2284 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002285 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002286 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002287 return V;
2288
2289 // If the comparison is with the result of a phi instruction, check whether
2290 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00002291 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002292 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00002293 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +00002294
Chris Lattner9f3c25a2009-11-09 22:57:59 +00002295 return 0;
2296}
2297
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002298Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002299 const TargetData *TD,
2300 const TargetLibraryInfo *TLI,
2301 const DominatorTree *DT) {
2302 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002303}
2304
Chris Lattner9dbb4292009-11-09 23:28:39 +00002305/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2306/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002307static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002308 const TargetData *TD,
2309 const TargetLibraryInfo *TLI,
2310 const DominatorTree *DT,
Duncan Sands18450092010-11-16 12:16:38 +00002311 unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00002312 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2313 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2314
Chris Lattnerd06094f2009-11-10 00:55:12 +00002315 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00002316 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002317 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD, TLI);
Duncan Sands12a86f52010-11-14 11:23:23 +00002318
Chris Lattnerd06094f2009-11-10 00:55:12 +00002319 // If we have a constant, make sure it is on the RHS.
2320 std::swap(LHS, RHS);
2321 Pred = CmpInst::getSwappedPredicate(Pred);
2322 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002323
Chris Lattner210c5d42009-11-09 23:55:12 +00002324 // Fold trivial predicates.
2325 if (Pred == FCmpInst::FCMP_FALSE)
2326 return ConstantInt::get(GetCompareTy(LHS), 0);
2327 if (Pred == FCmpInst::FCMP_TRUE)
2328 return ConstantInt::get(GetCompareTy(LHS), 1);
2329
Chris Lattner210c5d42009-11-09 23:55:12 +00002330 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2331 return UndefValue::get(GetCompareTy(LHS));
2332
2333 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands124708d2011-01-01 20:08:02 +00002334 if (LHS == RHS) {
Chris Lattner210c5d42009-11-09 23:55:12 +00002335 if (CmpInst::isTrueWhenEqual(Pred))
2336 return ConstantInt::get(GetCompareTy(LHS), 1);
2337 if (CmpInst::isFalseWhenEqual(Pred))
2338 return ConstantInt::get(GetCompareTy(LHS), 0);
2339 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002340
Chris Lattner210c5d42009-11-09 23:55:12 +00002341 // Handle fcmp with constant RHS
2342 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2343 // If the constant is a nan, see if we can fold the comparison based on it.
2344 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2345 if (CFP->getValueAPF().isNaN()) {
2346 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2347 return ConstantInt::getFalse(CFP->getContext());
2348 assert(FCmpInst::isUnordered(Pred) &&
2349 "Comparison must be either ordered or unordered!");
2350 // True if unordered.
2351 return ConstantInt::getTrue(CFP->getContext());
2352 }
Dan Gohman6b617a72010-02-22 04:06:03 +00002353 // Check whether the constant is an infinity.
2354 if (CFP->getValueAPF().isInfinity()) {
2355 if (CFP->getValueAPF().isNegative()) {
2356 switch (Pred) {
2357 case FCmpInst::FCMP_OLT:
2358 // No value is ordered and less than negative infinity.
2359 return ConstantInt::getFalse(CFP->getContext());
2360 case FCmpInst::FCMP_UGE:
2361 // All values are unordered with or at least negative infinity.
2362 return ConstantInt::getTrue(CFP->getContext());
2363 default:
2364 break;
2365 }
2366 } else {
2367 switch (Pred) {
2368 case FCmpInst::FCMP_OGT:
2369 // No value is ordered and greater than infinity.
2370 return ConstantInt::getFalse(CFP->getContext());
2371 case FCmpInst::FCMP_ULE:
2372 // All values are unordered with and at most infinity.
2373 return ConstantInt::getTrue(CFP->getContext());
2374 default:
2375 break;
2376 }
2377 }
2378 }
Chris Lattner210c5d42009-11-09 23:55:12 +00002379 }
2380 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002381
Duncan Sands92826de2010-11-07 16:46:25 +00002382 // If the comparison is with the result of a select instruction, check whether
2383 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002384 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002385 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002386 return V;
2387
2388 // If the comparison is with the result of a phi instruction, check whether
2389 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00002390 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002391 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00002392 return V;
Duncan Sands92826de2010-11-07 16:46:25 +00002393
Chris Lattner9dbb4292009-11-09 23:28:39 +00002394 return 0;
2395}
2396
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002397Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002398 const TargetData *TD,
2399 const TargetLibraryInfo *TLI,
2400 const DominatorTree *DT) {
2401 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002402}
2403
Chris Lattner04754262010-04-20 05:32:14 +00002404/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2405/// the result. If not, this returns null.
Duncan Sands124708d2011-01-01 20:08:02 +00002406Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
2407 const TargetData *TD, const DominatorTree *) {
Chris Lattner04754262010-04-20 05:32:14 +00002408 // select true, X, Y -> X
2409 // select false, X, Y -> Y
2410 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2411 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002412
Chris Lattner04754262010-04-20 05:32:14 +00002413 // select C, X, X -> X
Duncan Sands124708d2011-01-01 20:08:02 +00002414 if (TrueVal == FalseVal)
Chris Lattner04754262010-04-20 05:32:14 +00002415 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002416
Chris Lattner04754262010-04-20 05:32:14 +00002417 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2418 if (isa<Constant>(TrueVal))
2419 return TrueVal;
2420 return FalseVal;
2421 }
Dan Gohman68c0dbc2011-07-01 01:03:43 +00002422 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2423 return FalseVal;
2424 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2425 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002426
Chris Lattner04754262010-04-20 05:32:14 +00002427 return 0;
2428}
2429
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002430/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2431/// fold the result. If not, this returns null.
Chad Rosier618c1db2011-12-01 03:08:23 +00002432Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const TargetData *TD,
2433 const DominatorTree *) {
Duncan Sands85bbff62010-11-22 13:42:49 +00002434 // The type of the GEP pointer operand.
Nadav Rotem16087692011-12-05 06:29:09 +00002435 PointerType *PtrTy = dyn_cast<PointerType>(Ops[0]->getType());
2436 // The GEP pointer operand is not a pointer, it's a vector of pointers.
2437 if (!PtrTy)
2438 return 0;
Duncan Sands85bbff62010-11-22 13:42:49 +00002439
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002440 // getelementptr P -> P.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002441 if (Ops.size() == 1)
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002442 return Ops[0];
2443
Duncan Sands85bbff62010-11-22 13:42:49 +00002444 if (isa<UndefValue>(Ops[0])) {
2445 // Compute the (pointer) type returned by the GEP instruction.
Jay Foada9203102011-07-25 09:48:08 +00002446 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002447 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
Duncan Sands85bbff62010-11-22 13:42:49 +00002448 return UndefValue::get(GEPTy);
2449 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002450
Jay Foadb9b54eb2011-07-19 15:07:52 +00002451 if (Ops.size() == 2) {
Duncan Sandse60d79f2010-11-21 13:53:09 +00002452 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002453 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2454 if (C->isZero())
2455 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +00002456 // getelementptr P, N -> P if P points to a type of zero size.
2457 if (TD) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002458 Type *Ty = PtrTy->getElementType();
Duncan Sandsa63395a2010-11-22 16:32:50 +00002459 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +00002460 return Ops[0];
2461 }
2462 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002463
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002464 // Check to see if this is constant foldable.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002465 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002466 if (!isa<Constant>(Ops[i]))
2467 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +00002468
Jay Foaddab3d292011-07-21 14:31:17 +00002469 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002470}
2471
Duncan Sandsdabc2802011-09-05 06:52:48 +00002472/// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2473/// can fold the result. If not, this returns null.
2474Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2475 ArrayRef<unsigned> Idxs,
2476 const TargetData *,
2477 const DominatorTree *) {
2478 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2479 if (Constant *CVal = dyn_cast<Constant>(Val))
2480 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2481
2482 // insertvalue x, undef, n -> x
2483 if (match(Val, m_Undef()))
2484 return Agg;
2485
2486 // insertvalue x, (extractvalue y, n), n
2487 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramerae707bd2011-09-05 18:16:19 +00002488 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2489 EV->getIndices() == Idxs) {
Duncan Sandsdabc2802011-09-05 06:52:48 +00002490 // insertvalue undef, (extractvalue y, n), n -> y
2491 if (match(Agg, m_Undef()))
2492 return EV->getAggregateOperand();
2493
2494 // insertvalue y, (extractvalue y, n), n -> y
2495 if (Agg == EV->getAggregateOperand())
2496 return Agg;
2497 }
2498
2499 return 0;
2500}
2501
Duncan Sandsff103412010-11-17 04:30:22 +00002502/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
2503static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
2504 // If all of the PHI's incoming values are the same then replace the PHI node
2505 // with the common value.
2506 Value *CommonValue = 0;
2507 bool HasUndefInput = false;
2508 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2509 Value *Incoming = PN->getIncomingValue(i);
2510 // If the incoming value is the phi node itself, it can safely be skipped.
2511 if (Incoming == PN) continue;
2512 if (isa<UndefValue>(Incoming)) {
2513 // Remember that we saw an undef value, but otherwise ignore them.
2514 HasUndefInput = true;
2515 continue;
2516 }
2517 if (CommonValue && Incoming != CommonValue)
2518 return 0; // Not the same, bail out.
2519 CommonValue = Incoming;
2520 }
2521
2522 // If CommonValue is null then all of the incoming values were either undef or
2523 // equal to the phi node itself.
2524 if (!CommonValue)
2525 return UndefValue::get(PN->getType());
2526
2527 // If we have a PHI node like phi(X, undef, X), where X is defined by some
2528 // instruction, we cannot return X as the result of the PHI node unless it
2529 // dominates the PHI block.
2530 if (HasUndefInput)
2531 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
2532
2533 return CommonValue;
2534}
2535
Chris Lattnerd06094f2009-11-10 00:55:12 +00002536//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +00002537
Chris Lattnerd06094f2009-11-10 00:55:12 +00002538/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2539/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002540static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002541 const TargetData *TD,
2542 const TargetLibraryInfo *TLI,
2543 const DominatorTree *DT,
Duncan Sands18450092010-11-16 12:16:38 +00002544 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00002545 switch (Opcode) {
Chris Lattner81a0dc92011-02-09 17:15:04 +00002546 case Instruction::Add:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002547 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Chad Rosier618c1db2011-12-01 03:08:23 +00002548 TD, TLI, DT, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002549 case Instruction::Sub:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002550 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Chad Rosier618c1db2011-12-01 03:08:23 +00002551 TD, TLI, DT, MaxRecurse);
2552 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, TD, TLI, DT,
2553 MaxRecurse);
2554 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, TD, TLI, DT,
2555 MaxRecurse);
2556 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, TD, TLI, DT,
2557 MaxRecurse);
2558 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, TD, TLI, DT,
2559 MaxRecurse);
2560 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, TD, TLI, DT,
2561 MaxRecurse);
2562 case Instruction::URem: return SimplifyURemInst(LHS, RHS, TD, TLI, DT,
2563 MaxRecurse);
2564 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, TD, TLI, DT,
2565 MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002566 case Instruction::Shl:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002567 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Chad Rosier618c1db2011-12-01 03:08:23 +00002568 TD, TLI, DT, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002569 case Instruction::LShr:
Chad Rosier618c1db2011-12-01 03:08:23 +00002570 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, TD, TLI, DT,
2571 MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002572 case Instruction::AShr:
Chad Rosier618c1db2011-12-01 03:08:23 +00002573 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, TD, TLI, DT,
2574 MaxRecurse);
2575 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, TLI, DT,
2576 MaxRecurse);
2577 case Instruction::Or: return SimplifyOrInst (LHS, RHS, TD, TLI, DT,
2578 MaxRecurse);
2579 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, TLI, DT,
2580 MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002581 default:
2582 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2583 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2584 Constant *COps[] = {CLHS, CRHS};
Chad Rosier618c1db2011-12-01 03:08:23 +00002585 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, TD, TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002586 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002587
Duncan Sands566edb02010-12-21 08:49:00 +00002588 // If the operation is associative, try some generic simplifications.
2589 if (Instruction::isAssociative(Opcode))
Chad Rosier618c1db2011-12-01 03:08:23 +00002590 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, TLI, DT,
Duncan Sands566edb02010-12-21 08:49:00 +00002591 MaxRecurse))
2592 return V;
2593
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002594 // If the operation is with the result of a select instruction, check whether
2595 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002596 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002597 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, TLI, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00002598 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002599 return V;
2600
2601 // If the operation is with the result of a phi instruction, check whether
2602 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002603 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002604 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, TLI, DT,
2605 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002606 return V;
2607
Chris Lattnerd06094f2009-11-10 00:55:12 +00002608 return 0;
2609 }
2610}
Chris Lattner9dbb4292009-11-09 23:28:39 +00002611
Duncan Sands12a86f52010-11-14 11:23:23 +00002612Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002613 const TargetData *TD, const TargetLibraryInfo *TLI,
2614 const DominatorTree *DT) {
2615 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, TLI, DT, RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +00002616}
2617
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002618/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2619/// fold the result.
2620static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002621 const TargetData *TD,
2622 const TargetLibraryInfo *TLI,
2623 const DominatorTree *DT,
Duncan Sands18450092010-11-16 12:16:38 +00002624 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002625 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Chad Rosier618c1db2011-12-01 03:08:23 +00002626 return SimplifyICmpInst(Predicate, LHS, RHS, TD, TLI, DT, MaxRecurse);
2627 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, TLI, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002628}
2629
2630Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002631 const TargetData *TD, const TargetLibraryInfo *TLI,
2632 const DominatorTree *DT) {
2633 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002634}
Chris Lattnere3453782009-11-10 01:08:51 +00002635
Dan Gohman71d05032011-11-04 18:32:42 +00002636static Value *SimplifyCallInst(CallInst *CI) {
2637 // call undef -> undef
2638 if (isa<UndefValue>(CI->getCalledValue()))
2639 return UndefValue::get(CI->getType());
2640
2641 return 0;
2642}
2643
Chris Lattnere3453782009-11-10 01:08:51 +00002644/// SimplifyInstruction - See if we can compute a simplified version of this
2645/// instruction. If not, this returns null.
Duncan Sandseff05812010-11-14 18:36:10 +00002646Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00002647 const TargetLibraryInfo *TLI,
Duncan Sandseff05812010-11-14 18:36:10 +00002648 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +00002649 Value *Result;
2650
Chris Lattnere3453782009-11-10 01:08:51 +00002651 switch (I->getOpcode()) {
2652 default:
Chad Rosier618c1db2011-12-01 03:08:23 +00002653 Result = ConstantFoldInstruction(I, TD, TLI);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002654 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002655 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002656 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2657 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2658 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002659 TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002660 break;
Duncan Sandsfea3b212010-12-15 14:07:39 +00002661 case Instruction::Sub:
2662 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2663 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2664 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002665 TD, TLI, DT);
Duncan Sandsfea3b212010-12-15 14:07:39 +00002666 break;
Duncan Sands82fdab32010-12-21 14:00:22 +00002667 case Instruction::Mul:
Chad Rosier618c1db2011-12-01 03:08:23 +00002668 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands82fdab32010-12-21 14:00:22 +00002669 break;
Duncan Sands593faa52011-01-28 16:51:11 +00002670 case Instruction::SDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002671 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands593faa52011-01-28 16:51:11 +00002672 break;
2673 case Instruction::UDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002674 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands593faa52011-01-28 16:51:11 +00002675 break;
Frits van Bommel1fca2c32011-01-29 15:26:31 +00002676 case Instruction::FDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002677 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Frits van Bommel1fca2c32011-01-29 15:26:31 +00002678 break;
Duncan Sandsf24ed772011-05-02 16:27:02 +00002679 case Instruction::SRem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002680 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002681 break;
2682 case Instruction::URem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002683 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002684 break;
2685 case Instruction::FRem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002686 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002687 break;
Duncan Sandsc43cee32011-01-14 00:37:45 +00002688 case Instruction::Shl:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002689 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2690 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2691 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002692 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002693 break;
2694 case Instruction::LShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002695 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2696 cast<BinaryOperator>(I)->isExact(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002697 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002698 break;
2699 case Instruction::AShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002700 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2701 cast<BinaryOperator>(I)->isExact(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002702 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002703 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002704 case Instruction::And:
Chad Rosier618c1db2011-12-01 03:08:23 +00002705 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002706 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002707 case Instruction::Or:
Chad Rosier618c1db2011-12-01 03:08:23 +00002708 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002709 break;
Duncan Sands2b749872010-11-17 18:52:15 +00002710 case Instruction::Xor:
Chad Rosier618c1db2011-12-01 03:08:23 +00002711 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands2b749872010-11-17 18:52:15 +00002712 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002713 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002714 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002715 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002716 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002717 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002718 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002719 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002720 break;
Chris Lattner04754262010-04-20 05:32:14 +00002721 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002722 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
2723 I->getOperand(2), TD, DT);
2724 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002725 case Instruction::GetElementPtr: {
2726 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Jay Foadb9b54eb2011-07-19 15:07:52 +00002727 Result = SimplifyGEPInst(Ops, TD, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002728 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002729 }
Duncan Sandsdabc2802011-09-05 06:52:48 +00002730 case Instruction::InsertValue: {
2731 InsertValueInst *IV = cast<InsertValueInst>(I);
2732 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
2733 IV->getInsertedValueOperand(),
2734 IV->getIndices(), TD, DT);
2735 break;
2736 }
Duncan Sandscd6636c2010-11-14 13:30:18 +00002737 case Instruction::PHI:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002738 Result = SimplifyPHINode(cast<PHINode>(I), DT);
2739 break;
Dan Gohman71d05032011-11-04 18:32:42 +00002740 case Instruction::Call:
2741 Result = SimplifyCallInst(cast<CallInst>(I));
2742 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002743 }
Duncan Sandsd261dc62010-11-17 08:35:29 +00002744
2745 /// If called on unreachable code, the above logic may report that the
2746 /// instruction simplified to itself. Make life easier for users by
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00002747 /// detecting that case here, returning a safe value instead.
2748 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnere3453782009-11-10 01:08:51 +00002749}
2750
Chris Lattner40d8c282009-11-10 22:26:15 +00002751/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
2752/// delete the From instruction. In addition to a basic RAUW, this does a
2753/// recursive simplification of the newly formed instructions. This catches
2754/// things where one simplification exposes other opportunities. This only
2755/// simplifies and deletes scalar operations, it does not change the CFG.
2756///
2757void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
Duncan Sandseff05812010-11-14 18:36:10 +00002758 const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00002759 const TargetLibraryInfo *TLI,
Duncan Sandseff05812010-11-14 18:36:10 +00002760 const DominatorTree *DT) {
Chris Lattner40d8c282009-11-10 22:26:15 +00002761 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
Duncan Sands12a86f52010-11-14 11:23:23 +00002762
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002763 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
2764 // we can know if it gets deleted out from under us or replaced in a
2765 // recursive simplification.
Chris Lattner40d8c282009-11-10 22:26:15 +00002766 WeakVH FromHandle(From);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002767 WeakVH ToHandle(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00002768
Chris Lattner40d8c282009-11-10 22:26:15 +00002769 while (!From->use_empty()) {
2770 // Update the instruction to use the new value.
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002771 Use &TheUse = From->use_begin().getUse();
2772 Instruction *User = cast<Instruction>(TheUse.getUser());
2773 TheUse = To;
2774
2775 // Check to see if the instruction can be folded due to the operand
2776 // replacement. For example changing (or X, Y) into (or X, -1) can replace
2777 // the 'or' with -1.
2778 Value *SimplifiedVal;
2779 {
2780 // Sanity check to make sure 'User' doesn't dangle across
2781 // SimplifyInstruction.
2782 AssertingVH<> UserHandle(User);
Duncan Sands12a86f52010-11-14 11:23:23 +00002783
Chad Rosier618c1db2011-12-01 03:08:23 +00002784 SimplifiedVal = SimplifyInstruction(User, TD, TLI, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002785 if (SimplifiedVal == 0) continue;
Chris Lattner40d8c282009-11-10 22:26:15 +00002786 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002787
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002788 // Recursively simplify this user to the new value.
Chad Rosier618c1db2011-12-01 03:08:23 +00002789 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, TLI, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002790 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
2791 To = ToHandle;
Duncan Sands12a86f52010-11-14 11:23:23 +00002792
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002793 assert(ToHandle && "To value deleted by recursive simplification?");
Duncan Sands12a86f52010-11-14 11:23:23 +00002794
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002795 // If the recursive simplification ended up revisiting and deleting
2796 // 'From' then we're done.
2797 if (From == 0)
2798 return;
Chris Lattner40d8c282009-11-10 22:26:15 +00002799 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002800
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002801 // If 'From' has value handles referring to it, do a real RAUW to update them.
2802 From->replaceAllUsesWith(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00002803
Chris Lattner40d8c282009-11-10 22:26:15 +00002804 From->eraseFromParent();
2805}