blob: f8d159dc43847a2a514182cb5b94638df4f0e3f8 [file] [log] [blame]
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001//===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements routines for folding instructions into simpler forms
Duncan Sands4cd2ad12010-11-23 10:50:08 +000011// that do not require creating new instructions. This does constant folding
12// ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
13// returning a constant ("and i32 %x, 0" -> "0") or an already existing value
Duncan Sandsee9a2e32010-12-20 14:47:04 +000014// ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been
15// simplified: This is usually true and assuming it simplifies the logic (if
16// they have not been simplified then results are correct but maybe suboptimal).
Chris Lattner9f3c25a2009-11-09 22:57:59 +000017//
18//===----------------------------------------------------------------------===//
19
Duncan Sandsa3c44a52010-12-22 09:40:51 +000020#define DEBUG_TYPE "instsimplify"
Chandler Carruthfc72ae62012-03-12 11:19:31 +000021#include "llvm/GlobalAlias.h"
Jay Foad562b84b2011-04-11 09:35:34 +000022#include "llvm/Operator.h"
Duncan Sandsa3c44a52010-12-22 09:40:51 +000023#include "llvm/ADT/Statistic.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000024#include "llvm/Analysis/InstructionSimplify.h"
Nick Lewyckyf7087ea2012-02-26 02:09:49 +000025#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000026#include "llvm/Analysis/ConstantFolding.h"
Duncan Sands18450092010-11-16 12:16:38 +000027#include "llvm/Analysis/Dominators.h"
Duncan Sandsd70d1a52011-01-25 09:38:29 +000028#include "llvm/Analysis/ValueTracking.h"
Nick Lewycky3a73e342011-03-04 07:00:57 +000029#include "llvm/Support/ConstantRange.h"
Chandler Carruthfc72ae62012-03-12 11:19:31 +000030#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerd06094f2009-11-10 00:55:12 +000031#include "llvm/Support/PatternMatch.h"
Duncan Sands18450092010-11-16 12:16:38 +000032#include "llvm/Support/ValueHandle.h"
Duncan Sandse60d79f2010-11-21 13:53:09 +000033#include "llvm/Target/TargetData.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000034using namespace llvm;
Chris Lattnerd06094f2009-11-10 00:55:12 +000035using namespace llvm::PatternMatch;
Chris Lattner9f3c25a2009-11-09 22:57:59 +000036
Chris Lattner81a0dc92011-02-09 17:15:04 +000037enum { RecursionLimit = 3 };
Duncan Sandsa74a58c2010-11-10 18:23:01 +000038
Duncan Sandsa3c44a52010-12-22 09:40:51 +000039STATISTIC(NumExpand, "Number of expansions");
40STATISTIC(NumFactor , "Number of factorizations");
41STATISTIC(NumReassoc, "Number of reassociations");
42
Duncan Sands0aa85eb2012-03-13 11:42:19 +000043struct Query {
44 const TargetData *TD;
45 const TargetLibraryInfo *TLI;
46 const DominatorTree *DT;
47
48 Query(const TargetData *td, const TargetLibraryInfo *tli,
49 const DominatorTree *dt) : TD(td), TLI(tli), DT(dt) {};
50};
51
52static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
53static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
Chad Rosier618c1db2011-12-01 03:08:23 +000054 unsigned);
Duncan Sands0aa85eb2012-03-13 11:42:19 +000055static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
Chad Rosier618c1db2011-12-01 03:08:23 +000056 unsigned);
Duncan Sands0aa85eb2012-03-13 11:42:19 +000057static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
58static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
Duncan Sandsbd0fe562012-03-13 14:07:05 +000059static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
Duncan Sands18450092010-11-16 12:16:38 +000060
Duncan Sandsf56138d2011-07-26 15:03:53 +000061/// getFalse - For a boolean type, or a vector of boolean type, return false, or
62/// a vector with every element false, as appropriate for the type.
63static Constant *getFalse(Type *Ty) {
Nick Lewycky66d004e2011-12-01 02:39:36 +000064 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsf56138d2011-07-26 15:03:53 +000065 "Expected i1 type or a vector of i1!");
66 return Constant::getNullValue(Ty);
67}
68
69/// getTrue - For a boolean type, or a vector of boolean type, return true, or
70/// a vector with every element true, as appropriate for the type.
71static Constant *getTrue(Type *Ty) {
Nick Lewycky66d004e2011-12-01 02:39:36 +000072 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsf56138d2011-07-26 15:03:53 +000073 "Expected i1 type or a vector of i1!");
74 return Constant::getAllOnesValue(Ty);
75}
76
Duncan Sands6dc9e2b2011-10-30 19:56:36 +000077/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
78static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
79 Value *RHS) {
80 CmpInst *Cmp = dyn_cast<CmpInst>(V);
81 if (!Cmp)
82 return false;
83 CmpInst::Predicate CPred = Cmp->getPredicate();
84 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
85 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
86 return true;
87 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
88 CRHS == LHS;
89}
90
Duncan Sands18450092010-11-16 12:16:38 +000091/// ValueDominatesPHI - Does the given value dominate the specified phi node?
92static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
93 Instruction *I = dyn_cast<Instruction>(V);
94 if (!I)
95 // Arguments and constants dominate all instructions.
96 return true;
97
98 // If we have a DominatorTree then do a precise test.
Eli Friedman5b8f0dd2012-03-13 01:06:07 +000099 if (DT) {
100 if (!DT->isReachableFromEntry(P->getParent()))
101 return true;
102 if (!DT->isReachableFromEntry(I->getParent()))
103 return false;
104 return DT->dominates(I, P);
105 }
Duncan Sands18450092010-11-16 12:16:38 +0000106
107 // Otherwise, if the instruction is in the entry block, and is not an invoke,
108 // then it obviously dominates all phi nodes.
109 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
110 !isa<InvokeInst>(I))
111 return true;
112
113 return false;
114}
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000115
Duncan Sands3421d902010-12-21 13:32:22 +0000116/// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
117/// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
118/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
119/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
120/// Returns the simplified value, or null if no simplification was performed.
121static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000122 unsigned OpcToExpand, const Query &Q,
Chad Rosier618c1db2011-12-01 03:08:23 +0000123 unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000124 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000125 // Recursion is always used, so bail out at once if we already hit the limit.
126 if (!MaxRecurse--)
127 return 0;
128
129 // Check whether the expression has the form "(A op' B) op C".
130 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
131 if (Op0->getOpcode() == OpcodeToExpand) {
132 // It does! Try turning it into "(A op C) op' (B op C)".
133 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
134 // Do "A op C" and "B op C" both simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000135 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
136 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000137 // They do! Return "L op' R" if it simplifies or is already available.
138 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000139 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
140 && L == B && R == A)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000141 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000142 return LHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000143 }
Duncan Sands3421d902010-12-21 13:32:22 +0000144 // Otherwise return "L op' R" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000145 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000146 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000147 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000148 }
Duncan Sands3421d902010-12-21 13:32:22 +0000149 }
150 }
151
152 // Check whether the expression has the form "A op (B op' C)".
153 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
154 if (Op1->getOpcode() == OpcodeToExpand) {
155 // It does! Try turning it into "(A op B) op' (A op C)".
156 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
157 // Do "A op B" and "A op C" both simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000158 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
159 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000160 // They do! Return "L op' R" if it simplifies or is already available.
161 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000162 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
163 && L == C && R == B)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000164 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000165 return RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000166 }
Duncan Sands3421d902010-12-21 13:32:22 +0000167 // Otherwise return "L op' R" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000168 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000169 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000170 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000171 }
Duncan Sands3421d902010-12-21 13:32:22 +0000172 }
173 }
174
175 return 0;
176}
177
178/// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
179/// using the operation OpCodeToExtract. For example, when Opcode is Add and
180/// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
181/// Returns the simplified value, or null if no simplification was performed.
182static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000183 unsigned OpcToExtract, const Query &Q,
Chad Rosier618c1db2011-12-01 03:08:23 +0000184 unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000185 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
Duncan Sands3421d902010-12-21 13:32:22 +0000186 // Recursion is always used, so bail out at once if we already hit the limit.
187 if (!MaxRecurse--)
188 return 0;
189
190 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
191 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
192
193 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
194 !Op1 || Op1->getOpcode() != OpcodeToExtract)
195 return 0;
196
197 // The expression has the form "(A op' B) op (C op' D)".
Duncan Sands82fdab32010-12-21 14:00:22 +0000198 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
199 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
Duncan Sands3421d902010-12-21 13:32:22 +0000200
201 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
202 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
203 // commutative case, "(A op' B) op (C op' A)"?
Duncan Sands124708d2011-01-01 20:08:02 +0000204 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
205 Value *DD = A == C ? D : C;
Duncan Sands3421d902010-12-21 13:32:22 +0000206 // Form "A op' (B op DD)" if it simplifies completely.
207 // Does "B op DD" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000208 if (Value *V = SimplifyBinOp(Opcode, B, DD, Q, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000209 // It does! Return "A op' V" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000210 // If V equals B then "A op' V" is just the LHS. If V equals DD then
211 // "A op' V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000212 if (V == B || V == DD) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000213 ++NumFactor;
Duncan Sands124708d2011-01-01 20:08:02 +0000214 return V == B ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000215 }
Duncan Sands3421d902010-12-21 13:32:22 +0000216 // Otherwise return "A op' V" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000217 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000218 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000219 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000220 }
Duncan Sands3421d902010-12-21 13:32:22 +0000221 }
222 }
223
224 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
225 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
226 // commutative case, "(A op' B) op (B op' D)"?
Duncan Sands124708d2011-01-01 20:08:02 +0000227 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
228 Value *CC = B == D ? C : D;
Duncan Sands3421d902010-12-21 13:32:22 +0000229 // Form "(A op CC) op' B" if it simplifies completely..
230 // Does "A op CC" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000231 if (Value *V = SimplifyBinOp(Opcode, A, CC, Q, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000232 // It does! Return "V op' B" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000233 // If V equals A then "V op' B" is just the LHS. If V equals CC then
234 // "V op' B" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000235 if (V == A || V == CC) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000236 ++NumFactor;
Duncan Sands124708d2011-01-01 20:08:02 +0000237 return V == A ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000238 }
Duncan Sands3421d902010-12-21 13:32:22 +0000239 // Otherwise return "V op' B" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000240 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000241 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000242 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000243 }
Duncan Sands3421d902010-12-21 13:32:22 +0000244 }
245 }
246
247 return 0;
248}
249
250/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
251/// operations. Returns the simpler value, or null if none was found.
Benjamin Kramere21083a2010-12-28 13:52:52 +0000252static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000253 const Query &Q, unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000254 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands566edb02010-12-21 08:49:00 +0000255 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
256
257 // Recursion is always used, so bail out at once if we already hit the limit.
258 if (!MaxRecurse--)
259 return 0;
260
261 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
262 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
263
264 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
265 if (Op0 && Op0->getOpcode() == Opcode) {
266 Value *A = Op0->getOperand(0);
267 Value *B = Op0->getOperand(1);
268 Value *C = RHS;
269
270 // Does "B op C" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000271 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000272 // It does! Return "A op V" if it simplifies or is already available.
273 // If V equals B then "A op V" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000274 if (V == B) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000275 // Otherwise return "A op V" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000276 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000277 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000278 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000279 }
Duncan Sands566edb02010-12-21 08:49:00 +0000280 }
281 }
282
283 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
284 if (Op1 && Op1->getOpcode() == Opcode) {
285 Value *A = LHS;
286 Value *B = Op1->getOperand(0);
287 Value *C = Op1->getOperand(1);
288
289 // Does "A op B" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000290 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000291 // It does! Return "V op C" if it simplifies or is already available.
292 // If V equals B then "V op C" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000293 if (V == B) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000294 // Otherwise return "V op C" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000295 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000296 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000297 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000298 }
Duncan Sands566edb02010-12-21 08:49:00 +0000299 }
300 }
301
302 // The remaining transforms require commutativity as well as associativity.
303 if (!Instruction::isCommutative(Opcode))
304 return 0;
305
306 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
307 if (Op0 && Op0->getOpcode() == Opcode) {
308 Value *A = Op0->getOperand(0);
309 Value *B = Op0->getOperand(1);
310 Value *C = RHS;
311
312 // Does "C op A" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000313 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000314 // It does! Return "V op B" if it simplifies or is already available.
315 // If V equals A then "V op B" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000316 if (V == A) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000317 // Otherwise return "V op B" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000318 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000319 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000320 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000321 }
Duncan Sands566edb02010-12-21 08:49:00 +0000322 }
323 }
324
325 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
326 if (Op1 && Op1->getOpcode() == Opcode) {
327 Value *A = LHS;
328 Value *B = Op1->getOperand(0);
329 Value *C = Op1->getOperand(1);
330
331 // Does "C op A" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000332 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000333 // It does! Return "B op V" if it simplifies or is already available.
334 // If V equals C then "B op V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000335 if (V == C) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000336 // Otherwise return "B op V" if it simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000337 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000338 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000339 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000340 }
Duncan Sands566edb02010-12-21 08:49:00 +0000341 }
342 }
343
344 return 0;
345}
346
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000347/// ThreadBinOpOverSelect - In the case of a binary operation with a select
348/// instruction as an operand, try to simplify the binop by seeing whether
349/// evaluating it on both branches of the select results in the same value.
350/// Returns the common value if so, otherwise returns null.
351static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000352 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000353 // Recursion is always used, so bail out at once if we already hit the limit.
354 if (!MaxRecurse--)
355 return 0;
356
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000357 SelectInst *SI;
358 if (isa<SelectInst>(LHS)) {
359 SI = cast<SelectInst>(LHS);
360 } else {
361 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
362 SI = cast<SelectInst>(RHS);
363 }
364
365 // Evaluate the BinOp on the true and false branches of the select.
366 Value *TV;
367 Value *FV;
368 if (SI == LHS) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000369 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
370 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000371 } else {
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000372 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
373 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000374 }
375
Duncan Sands7cf85e72011-01-01 16:12:09 +0000376 // If they simplified to the same value, then return the common value.
Duncan Sands124708d2011-01-01 20:08:02 +0000377 // If they both failed to simplify then return null.
378 if (TV == FV)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000379 return TV;
380
381 // If one branch simplified to undef, return the other one.
382 if (TV && isa<UndefValue>(TV))
383 return FV;
384 if (FV && isa<UndefValue>(FV))
385 return TV;
386
387 // If applying the operation did not change the true and false select values,
388 // then the result of the binop is the select itself.
Duncan Sands124708d2011-01-01 20:08:02 +0000389 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000390 return SI;
391
392 // If one branch simplified and the other did not, and the simplified
393 // value is equal to the unsimplified one, return the simplified value.
394 // For example, select (cond, X, X & Z) & Z -> X & Z.
395 if ((FV && !TV) || (TV && !FV)) {
396 // Check that the simplified value has the form "X op Y" where "op" is the
397 // same as the original operation.
398 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
399 if (Simplified && Simplified->getOpcode() == Opcode) {
400 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
401 // We already know that "op" is the same as for the simplified value. See
402 // if the operands match too. If so, return the simplified value.
403 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
404 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
405 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands124708d2011-01-01 20:08:02 +0000406 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
407 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000408 return Simplified;
409 if (Simplified->isCommutative() &&
Duncan Sands124708d2011-01-01 20:08:02 +0000410 Simplified->getOperand(1) == UnsimplifiedLHS &&
411 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000412 return Simplified;
413 }
414 }
415
416 return 0;
417}
418
419/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
420/// try to simplify the comparison by seeing whether both branches of the select
421/// result in the same value. Returns the common value if so, otherwise returns
422/// null.
423static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000424 Value *RHS, const Query &Q,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000425 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000426 // Recursion is always used, so bail out at once if we already hit the limit.
427 if (!MaxRecurse--)
428 return 0;
429
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000430 // Make sure the select is on the LHS.
431 if (!isa<SelectInst>(LHS)) {
432 std::swap(LHS, RHS);
433 Pred = CmpInst::getSwappedPredicate(Pred);
434 }
435 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
436 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000437 Value *Cond = SI->getCondition();
438 Value *TV = SI->getTrueValue();
439 Value *FV = SI->getFalseValue();
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000440
Duncan Sands50ca4d32011-02-03 09:37:39 +0000441 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000442 // Does "cmp TV, RHS" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000443 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000444 if (TCmp == Cond) {
445 // It not only simplified, it simplified to the select condition. Replace
446 // it with 'true'.
447 TCmp = getTrue(Cond->getType());
448 } else if (!TCmp) {
449 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
450 // condition then we can replace it with 'true'. Otherwise give up.
451 if (!isSameCompare(Cond, Pred, TV, RHS))
452 return 0;
453 TCmp = getTrue(Cond->getType());
Duncan Sands50ca4d32011-02-03 09:37:39 +0000454 }
455
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000456 // Does "cmp FV, RHS" simplify?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000457 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000458 if (FCmp == Cond) {
459 // It not only simplified, it simplified to the select condition. Replace
460 // it with 'false'.
461 FCmp = getFalse(Cond->getType());
462 } else if (!FCmp) {
463 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
464 // condition then we can replace it with 'false'. Otherwise give up.
465 if (!isSameCompare(Cond, Pred, FV, RHS))
466 return 0;
467 FCmp = getFalse(Cond->getType());
468 }
469
470 // If both sides simplified to the same value, then use it as the result of
471 // the original comparison.
472 if (TCmp == FCmp)
473 return TCmp;
Duncan Sandsaa97bb52012-02-10 14:31:24 +0000474
475 // The remaining cases only make sense if the select condition has the same
476 // type as the result of the comparison, so bail out if this is not so.
477 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
478 return 0;
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000479 // If the false value simplified to false, then the result of the compare
480 // is equal to "Cond && TCmp". This also catches the case when the false
481 // value simplified to false and the true value to true, returning "Cond".
482 if (match(FCmp, m_Zero()))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000483 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000484 return V;
485 // If the true value simplified to true, then the result of the compare
486 // is equal to "Cond || FCmp".
487 if (match(TCmp, m_One()))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000488 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000489 return V;
490 // Finally, if the false value simplified to true and the true value to
491 // false, then the result of the compare is equal to "!Cond".
492 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
493 if (Value *V =
494 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000495 Q, MaxRecurse))
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000496 return V;
497
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000498 return 0;
499}
500
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000501/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
502/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
503/// it on the incoming phi values yields the same result for every value. If so
504/// returns the common value, otherwise returns null.
505static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000506 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000507 // Recursion is always used, so bail out at once if we already hit the limit.
508 if (!MaxRecurse--)
509 return 0;
510
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000511 PHINode *PI;
512 if (isa<PHINode>(LHS)) {
513 PI = cast<PHINode>(LHS);
Duncan Sands18450092010-11-16 12:16:38 +0000514 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000515 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Duncan Sands18450092010-11-16 12:16:38 +0000516 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000517 } else {
518 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
519 PI = cast<PHINode>(RHS);
Duncan Sands18450092010-11-16 12:16:38 +0000520 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000521 if (!ValueDominatesPHI(LHS, PI, Q.DT))
Duncan Sands18450092010-11-16 12:16:38 +0000522 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000523 }
524
525 // Evaluate the BinOp on the incoming phi values.
526 Value *CommonValue = 0;
527 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000528 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000529 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000530 if (Incoming == PI) continue;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000531 Value *V = PI == LHS ?
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000532 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
533 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000534 // If the operation failed to simplify, or simplified to a different value
535 // to previously, then give up.
536 if (!V || (CommonValue && V != CommonValue))
537 return 0;
538 CommonValue = V;
539 }
540
541 return CommonValue;
542}
543
544/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
545/// try to simplify the comparison by seeing whether comparing with all of the
546/// incoming phi values yields the same result every time. If so returns the
547/// common result, otherwise returns null.
548static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000549 const Query &Q, unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000550 // Recursion is always used, so bail out at once if we already hit the limit.
551 if (!MaxRecurse--)
552 return 0;
553
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000554 // Make sure the phi is on the LHS.
555 if (!isa<PHINode>(LHS)) {
556 std::swap(LHS, RHS);
557 Pred = CmpInst::getSwappedPredicate(Pred);
558 }
559 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
560 PHINode *PI = cast<PHINode>(LHS);
561
Duncan Sands18450092010-11-16 12:16:38 +0000562 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000563 if (!ValueDominatesPHI(RHS, PI, Q.DT))
Duncan Sands18450092010-11-16 12:16:38 +0000564 return 0;
565
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000566 // Evaluate the BinOp on the incoming phi values.
567 Value *CommonValue = 0;
568 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000569 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000570 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000571 if (Incoming == PI) continue;
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000572 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000573 // If the operation failed to simplify, or simplified to a different value
574 // to previously, then give up.
575 if (!V || (CommonValue && V != CommonValue))
576 return 0;
577 CommonValue = V;
578 }
579
580 return CommonValue;
581}
582
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000583/// SimplifyAddInst - Given operands for an Add, see if we can
584/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000585static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000586 const Query &Q, unsigned MaxRecurse) {
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000587 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
588 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
589 Constant *Ops[] = { CLHS, CRHS };
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000590 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(), Ops,
591 Q.TD, Q.TLI);
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000592 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000593
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000594 // Canonicalize the constant to the RHS.
595 std::swap(Op0, Op1);
596 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000597
Duncan Sandsfea3b212010-12-15 14:07:39 +0000598 // X + undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000599 if (match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000600 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000601
Duncan Sandsfea3b212010-12-15 14:07:39 +0000602 // X + 0 -> X
603 if (match(Op1, m_Zero()))
604 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000605
Duncan Sandsfea3b212010-12-15 14:07:39 +0000606 // X + (Y - X) -> Y
607 // (Y - X) + X -> Y
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000608 // Eg: X + -X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000609 Value *Y = 0;
610 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
611 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000612 return Y;
613
614 // X + ~X -> -1 since ~X = -X-1
Duncan Sands124708d2011-01-01 20:08:02 +0000615 if (match(Op0, m_Not(m_Specific(Op1))) ||
616 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000617 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands87689cf2010-11-19 09:20:39 +0000618
Duncan Sands82fdab32010-12-21 14:00:22 +0000619 /// i1 add -> xor.
Duncan Sands75d289e2010-12-21 14:48:48 +0000620 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000621 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000622 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000623
Duncan Sands566edb02010-12-21 08:49:00 +0000624 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000625 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
Duncan Sands566edb02010-12-21 08:49:00 +0000626 MaxRecurse))
627 return V;
628
Duncan Sands3421d902010-12-21 13:32:22 +0000629 // Mul distributes over Add. Try some generic simplifications based on this.
630 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000631 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +0000632 return V;
633
Duncan Sands87689cf2010-11-19 09:20:39 +0000634 // Threading Add over selects and phi nodes is pointless, so don't bother.
635 // Threading over the select in "A + select(cond, B, C)" means evaluating
636 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
637 // only if B and C are equal. If B and C are equal then (since we assume
638 // that operands have already been simplified) "select(cond, B, C)" should
639 // have been simplified to the common value of B and C already. Analysing
640 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
641 // for threading over phi nodes.
642
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000643 return 0;
644}
645
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000646Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +0000647 const TargetData *TD, const TargetLibraryInfo *TLI,
648 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000649 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
650 RecursionLimit);
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000651}
652
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000653/// \brief Accumulate the constant integer offset a GEP represents.
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000654///
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000655/// Given a getelementptr instruction/constantexpr, accumulate the constant
656/// offset from the base pointer into the provided APInt 'Offset'. Returns true
657/// if the GEP has all-constant indices. Returns false if any non-constant
658/// index is encountered leaving the 'Offset' in an undefined state. The
659/// 'Offset' APInt must be the bitwidth of the target's pointer size.
660static bool accumulateGEPOffset(const TargetData &TD, GEPOperator *GEP,
661 APInt &Offset) {
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000662 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000663 assert(IntPtrWidth == Offset.getBitWidth());
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000664
665 gep_type_iterator GTI = gep_type_begin(GEP);
666 for (User::op_iterator I = GEP->op_begin() + 1, E = GEP->op_end(); I != E;
667 ++I, ++GTI) {
668 ConstantInt *OpC = dyn_cast<ConstantInt>(*I);
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000669 if (!OpC) return false;
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000670 if (OpC->isZero()) continue;
671
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000672 // Handle a struct index, which adds its field offset to the pointer.
673 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000674 unsigned ElementIdx = OpC->getZExtValue();
675 const StructLayout *SL = TD.getStructLayout(STy);
Duncan Sandsf72e0ca2012-03-15 20:14:42 +0000676 Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000677 continue;
678 }
679
Duncan Sandsf72e0ca2012-03-15 20:14:42 +0000680 APInt TypeSize(IntPtrWidth, TD.getTypeAllocSize(GTI.getIndexedType()));
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000681 Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000682 }
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000683 return true;
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000684}
685
686/// \brief Compute the base pointer and cumulative constant offsets for V.
687///
688/// This strips all constant offsets off of V, leaving it the base pointer, and
689/// accumulates the total constant offset applied in the returned constant. It
690/// returns 0 if V is not a pointer, and returns the constant '0' if there are
691/// no constant offsets applied.
692static Constant *stripAndComputeConstantOffsets(const TargetData &TD,
693 Value *&V) {
694 if (!V->getType()->isPointerTy())
695 return 0;
696
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000697 unsigned IntPtrWidth = TD.getPointerSizeInBits();
698 APInt Offset = APInt::getNullValue(IntPtrWidth);
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000699
700 // Even though we don't look through PHI nodes, we could be called on an
701 // instruction in an unreachable block, which may be on a cycle.
702 SmallPtrSet<Value *, 4> Visited;
703 Visited.insert(V);
704 do {
705 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000706 if (!accumulateGEPOffset(TD, GEP, Offset))
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000707 break;
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000708 V = GEP->getPointerOperand();
709 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
710 V = cast<Operator>(V)->getOperand(0);
711 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
712 if (GA->mayBeOverridden())
713 break;
714 V = GA->getAliasee();
715 } else {
716 break;
717 }
718 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
719 } while (Visited.insert(V));
720
Chandler Carruth90c14fc2012-03-13 00:06:15 +0000721 Type *IntPtrTy = TD.getIntPtrType(V->getContext());
722 return ConstantInt::get(IntPtrTy, Offset);
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000723}
724
725/// \brief Compute the constant difference between two pointer values.
726/// If the difference is not a constant, returns zero.
727static Constant *computePointerDifference(const TargetData &TD,
728 Value *LHS, Value *RHS) {
729 Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
730 if (!LHSOffset)
731 return 0;
732 Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
733 if (!RHSOffset)
734 return 0;
735
736 // If LHS and RHS are not related via constant offsets to the same base
737 // value, there is nothing we can do here.
738 if (LHS != RHS)
739 return 0;
740
741 // Otherwise, the difference of LHS - RHS can be computed as:
742 // LHS - RHS
743 // = (LHSOffset + Base) - (RHSOffset + Base)
744 // = LHSOffset - RHSOffset
745 return ConstantExpr::getSub(LHSOffset, RHSOffset);
746}
747
Duncan Sandsfea3b212010-12-15 14:07:39 +0000748/// SimplifySubInst - Given operands for a Sub, see if we can
749/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000750static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000751 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsfea3b212010-12-15 14:07:39 +0000752 if (Constant *CLHS = dyn_cast<Constant>(Op0))
753 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
754 Constant *Ops[] = { CLHS, CRHS };
755 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000756 Ops, Q.TD, Q.TLI);
Duncan Sandsfea3b212010-12-15 14:07:39 +0000757 }
758
759 // X - undef -> undef
760 // undef - X -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000761 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000762 return UndefValue::get(Op0->getType());
763
764 // X - 0 -> X
765 if (match(Op1, m_Zero()))
766 return Op0;
767
768 // X - X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000769 if (Op0 == Op1)
Duncan Sandsfea3b212010-12-15 14:07:39 +0000770 return Constant::getNullValue(Op0->getType());
771
Duncan Sandsfe02c692011-01-18 09:24:58 +0000772 // (X*2) - X -> X
773 // (X<<1) - X -> X
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000774 Value *X = 0;
Duncan Sandsfe02c692011-01-18 09:24:58 +0000775 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
776 match(Op0, m_Shl(m_Specific(Op1), m_One())))
777 return Op1;
778
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000779 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
780 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
781 Value *Y = 0, *Z = Op1;
782 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
783 // See if "V === Y - Z" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000784 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000785 // It does! Now see if "X + V" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000786 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000787 // It does, we successfully reassociated!
788 ++NumReassoc;
789 return W;
790 }
791 // See if "V === X - Z" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000792 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000793 // It does! Now see if "Y + V" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000794 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000795 // It does, we successfully reassociated!
796 ++NumReassoc;
797 return W;
798 }
799 }
Duncan Sands82fdab32010-12-21 14:00:22 +0000800
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000801 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
802 // For example, X - (X + 1) -> -1
803 X = Op0;
804 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
805 // See if "V === X - Y" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000806 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000807 // It does! Now see if "V - Z" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000808 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000809 // It does, we successfully reassociated!
810 ++NumReassoc;
811 return W;
812 }
813 // See if "V === X - Z" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000814 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000815 // It does! Now see if "V - Y" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000816 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000817 // It does, we successfully reassociated!
818 ++NumReassoc;
819 return W;
820 }
821 }
822
823 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
824 // For example, X - (X - Y) -> Y.
825 Z = Op0;
Duncan Sandsc087e202011-01-14 15:26:10 +0000826 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
827 // See if "V === Z - X" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000828 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000829 // It does! Now see if "V + Y" simplifies.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000830 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
Duncan Sandsc087e202011-01-14 15:26:10 +0000831 // It does, we successfully reassociated!
832 ++NumReassoc;
833 return W;
834 }
835
Duncan Sandsbd0fe562012-03-13 14:07:05 +0000836 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
837 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
838 match(Op1, m_Trunc(m_Value(Y))))
839 if (X->getType() == Y->getType())
840 // See if "V === X - Y" simplifies.
841 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
842 // It does! Now see if "trunc V" simplifies.
843 if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
844 // It does, return the simplified "trunc V".
845 return W;
846
847 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
848 if (Q.TD && match(Op0, m_PtrToInt(m_Value(X))) &&
849 match(Op1, m_PtrToInt(m_Value(Y))))
850 if (Constant *Result = computePointerDifference(*Q.TD, X, Y))
851 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
852
Duncan Sands3421d902010-12-21 13:32:22 +0000853 // Mul distributes over Sub. Try some generic simplifications based on this.
854 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000855 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +0000856 return V;
857
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000858 // i1 sub -> xor.
859 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000860 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000861 return V;
862
Duncan Sandsfea3b212010-12-15 14:07:39 +0000863 // Threading Sub over selects and phi nodes is pointless, so don't bother.
864 // Threading over the select in "A - select(cond, B, C)" means evaluating
865 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
866 // only if B and C are equal. If B and C are equal then (since we assume
867 // that operands have already been simplified) "select(cond, B, C)" should
868 // have been simplified to the common value of B and C already. Analysing
869 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
870 // for threading over phi nodes.
871
872 return 0;
873}
874
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000875Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000876 const TargetData *TD, const TargetLibraryInfo *TLI,
Chad Rosier618c1db2011-12-01 03:08:23 +0000877 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000878 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
879 RecursionLimit);
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000880}
881
Duncan Sands82fdab32010-12-21 14:00:22 +0000882/// SimplifyMulInst - Given operands for a Mul, see if we can
883/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000884static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
885 unsigned MaxRecurse) {
Duncan Sands82fdab32010-12-21 14:00:22 +0000886 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
887 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
888 Constant *Ops[] = { CLHS, CRHS };
889 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000890 Ops, Q.TD, Q.TLI);
Duncan Sands82fdab32010-12-21 14:00:22 +0000891 }
892
893 // Canonicalize the constant to the RHS.
894 std::swap(Op0, Op1);
895 }
896
897 // X * undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000898 if (match(Op1, m_Undef()))
Duncan Sands82fdab32010-12-21 14:00:22 +0000899 return Constant::getNullValue(Op0->getType());
900
901 // X * 0 -> 0
902 if (match(Op1, m_Zero()))
903 return Op1;
904
905 // X * 1 -> X
906 if (match(Op1, m_One()))
907 return Op0;
908
Duncan Sands1895e982011-01-30 18:03:50 +0000909 // (X / Y) * Y -> X if the division is exact.
Benjamin Kramer55c6d572012-01-01 17:55:30 +0000910 Value *X = 0;
911 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
912 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
913 return X;
Duncan Sands1895e982011-01-30 18:03:50 +0000914
Nick Lewycky54138802011-01-29 19:55:23 +0000915 // i1 mul -> and.
Duncan Sands75d289e2010-12-21 14:48:48 +0000916 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000917 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000918 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000919
920 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000921 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
Duncan Sands82fdab32010-12-21 14:00:22 +0000922 MaxRecurse))
923 return V;
924
925 // Mul distributes over Add. Try some generic simplifications based on this.
926 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000927 Q, MaxRecurse))
Duncan Sands82fdab32010-12-21 14:00:22 +0000928 return V;
929
930 // If the operation is with the result of a select instruction, check whether
931 // operating on either branch of the select always yields the same value.
932 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000933 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
Duncan Sands82fdab32010-12-21 14:00:22 +0000934 MaxRecurse))
935 return V;
936
937 // If the operation is with the result of a phi instruction, check whether
938 // operating on all incoming values of the phi always yields the same value.
939 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000940 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
Duncan Sands82fdab32010-12-21 14:00:22 +0000941 MaxRecurse))
942 return V;
943
944 return 0;
945}
946
947Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000948 const TargetLibraryInfo *TLI,
Duncan Sands82fdab32010-12-21 14:00:22 +0000949 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000950 return ::SimplifyMulInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sands82fdab32010-12-21 14:00:22 +0000951}
952
Duncan Sands593faa52011-01-28 16:51:11 +0000953/// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
954/// fold the result. If not, this returns null.
Anders Carlsson479b4b92011-02-05 18:33:43 +0000955static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000956 const Query &Q, unsigned MaxRecurse) {
Duncan Sands593faa52011-01-28 16:51:11 +0000957 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
958 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
959 Constant *Ops[] = { C0, C1 };
Duncan Sands0aa85eb2012-03-13 11:42:19 +0000960 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
Duncan Sands593faa52011-01-28 16:51:11 +0000961 }
962 }
963
Duncan Sandsa3e292c2011-01-28 18:50:50 +0000964 bool isSigned = Opcode == Instruction::SDiv;
965
Duncan Sands593faa52011-01-28 16:51:11 +0000966 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000967 if (match(Op1, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +0000968 return Op1;
969
970 // undef / X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000971 if (match(Op0, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +0000972 return Constant::getNullValue(Op0->getType());
973
974 // 0 / X -> 0, we don't need to preserve faults!
975 if (match(Op0, m_Zero()))
976 return Op0;
977
978 // X / 1 -> X
979 if (match(Op1, m_One()))
980 return Op0;
Duncan Sands593faa52011-01-28 16:51:11 +0000981
982 if (Op0->getType()->isIntegerTy(1))
983 // It can't be division by zero, hence it must be division by one.
984 return Op0;
985
986 // X / X -> 1
987 if (Op0 == Op1)
988 return ConstantInt::get(Op0->getType(), 1);
989
990 // (X * Y) / Y -> X if the multiplication does not overflow.
991 Value *X = 0, *Y = 0;
992 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
993 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands32a43cc2011-10-27 19:16:21 +0000994 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands4b720712011-02-02 20:52:00 +0000995 // If the Mul knows it does not overflow, then we are good to go.
996 if ((isSigned && Mul->hasNoSignedWrap()) ||
997 (!isSigned && Mul->hasNoUnsignedWrap()))
998 return X;
Duncan Sands593faa52011-01-28 16:51:11 +0000999 // If X has the form X = A / Y then X * Y cannot overflow.
1000 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1001 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1002 return X;
1003 }
1004
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001005 // (X rem Y) / Y -> 0
1006 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1007 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1008 return Constant::getNullValue(Op0->getType());
1009
1010 // If the operation is with the result of a select instruction, check whether
1011 // operating on either branch of the select always yields the same value.
1012 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001013 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001014 return V;
1015
1016 // If the operation is with the result of a phi instruction, check whether
1017 // operating on all incoming values of the phi always yields the same value.
1018 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001019 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001020 return V;
1021
Duncan Sands593faa52011-01-28 16:51:11 +00001022 return 0;
1023}
1024
1025/// SimplifySDivInst - Given operands for an SDiv, see if we can
1026/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001027static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1028 unsigned MaxRecurse) {
1029 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands593faa52011-01-28 16:51:11 +00001030 return V;
1031
Duncan Sands593faa52011-01-28 16:51:11 +00001032 return 0;
1033}
1034
1035Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001036 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001037 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001038 return ::SimplifySDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sands593faa52011-01-28 16:51:11 +00001039}
1040
1041/// SimplifyUDivInst - Given operands for a UDiv, see if we can
1042/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001043static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1044 unsigned MaxRecurse) {
1045 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
Duncan Sands593faa52011-01-28 16:51:11 +00001046 return V;
1047
Duncan Sands593faa52011-01-28 16:51:11 +00001048 return 0;
1049}
1050
1051Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001052 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001053 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001054 return ::SimplifyUDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sands593faa52011-01-28 16:51:11 +00001055}
1056
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001057static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q,
1058 unsigned) {
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001059 // undef / X -> undef (the undef could be a snan).
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001060 if (match(Op0, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001061 return Op0;
1062
1063 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001064 if (match(Op1, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001065 return Op1;
1066
1067 return 0;
1068}
1069
1070Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001071 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001072 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001073 return ::SimplifyFDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001074}
1075
Duncan Sandsf24ed772011-05-02 16:27:02 +00001076/// SimplifyRem - Given operands for an SRem or URem, see if we can
1077/// fold the result. If not, this returns null.
1078static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001079 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsf24ed772011-05-02 16:27:02 +00001080 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1081 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1082 Constant *Ops[] = { C0, C1 };
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001083 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001084 }
1085 }
1086
Duncan Sandsf24ed772011-05-02 16:27:02 +00001087 // X % undef -> undef
1088 if (match(Op1, m_Undef()))
1089 return Op1;
1090
1091 // undef % X -> 0
1092 if (match(Op0, m_Undef()))
1093 return Constant::getNullValue(Op0->getType());
1094
1095 // 0 % X -> 0, we don't need to preserve faults!
1096 if (match(Op0, m_Zero()))
1097 return Op0;
1098
1099 // X % 0 -> undef, we don't need to preserve faults!
1100 if (match(Op1, m_Zero()))
1101 return UndefValue::get(Op0->getType());
1102
1103 // X % 1 -> 0
1104 if (match(Op1, m_One()))
1105 return Constant::getNullValue(Op0->getType());
1106
1107 if (Op0->getType()->isIntegerTy(1))
1108 // It can't be remainder by zero, hence it must be remainder by one.
1109 return Constant::getNullValue(Op0->getType());
1110
1111 // X % X -> 0
1112 if (Op0 == Op1)
1113 return Constant::getNullValue(Op0->getType());
1114
1115 // If the operation is with the result of a select instruction, check whether
1116 // operating on either branch of the select always yields the same value.
1117 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001118 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001119 return V;
1120
1121 // If the operation is with the result of a phi instruction, check whether
1122 // operating on all incoming values of the phi always yields the same value.
1123 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001124 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001125 return V;
1126
1127 return 0;
1128}
1129
1130/// SimplifySRemInst - Given operands for an SRem, see if we can
1131/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001132static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1133 unsigned MaxRecurse) {
1134 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001135 return V;
1136
1137 return 0;
1138}
1139
1140Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001141 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001142 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001143 return ::SimplifySRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001144}
1145
1146/// SimplifyURemInst - Given operands for a URem, see if we can
1147/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001148static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosier618c1db2011-12-01 03:08:23 +00001149 unsigned MaxRecurse) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001150 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001151 return V;
1152
1153 return 0;
1154}
1155
1156Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001157 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001158 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001159 return ::SimplifyURemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001160}
1161
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001162static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &,
Chad Rosier618c1db2011-12-01 03:08:23 +00001163 unsigned) {
Duncan Sandsf24ed772011-05-02 16:27:02 +00001164 // undef % X -> undef (the undef could be a snan).
1165 if (match(Op0, m_Undef()))
1166 return Op0;
1167
1168 // X % undef -> undef
1169 if (match(Op1, m_Undef()))
1170 return Op1;
1171
1172 return 0;
1173}
1174
1175Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001176 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001177 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001178 return ::SimplifyFRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001179}
1180
Duncan Sandscf80bc12011-01-14 14:44:12 +00001181/// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
Duncan Sandsc43cee32011-01-14 00:37:45 +00001182/// fold the result. If not, this returns null.
Duncan Sandscf80bc12011-01-14 14:44:12 +00001183static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001184 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsc43cee32011-01-14 00:37:45 +00001185 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1186 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1187 Constant *Ops[] = { C0, C1 };
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001188 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001189 }
1190 }
1191
Duncan Sandscf80bc12011-01-14 14:44:12 +00001192 // 0 shift by X -> 0
Duncan Sandsc43cee32011-01-14 00:37:45 +00001193 if (match(Op0, m_Zero()))
1194 return Op0;
1195
Duncan Sandscf80bc12011-01-14 14:44:12 +00001196 // X shift by 0 -> X
Duncan Sandsc43cee32011-01-14 00:37:45 +00001197 if (match(Op1, m_Zero()))
1198 return Op0;
1199
Duncan Sandscf80bc12011-01-14 14:44:12 +00001200 // X shift by undef -> undef because it may shift by the bitwidth.
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001201 if (match(Op1, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001202 return Op1;
1203
1204 // Shifting by the bitwidth or more is undefined.
1205 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1206 if (CI->getValue().getLimitedValue() >=
1207 Op0->getType()->getScalarSizeInBits())
1208 return UndefValue::get(Op0->getType());
1209
Duncan Sandscf80bc12011-01-14 14:44:12 +00001210 // If the operation is with the result of a select instruction, check whether
1211 // operating on either branch of the select always yields the same value.
1212 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001213 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001214 return V;
1215
1216 // If the operation is with the result of a phi instruction, check whether
1217 // operating on all incoming values of the phi always yields the same value.
1218 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001219 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001220 return V;
1221
1222 return 0;
1223}
1224
1225/// SimplifyShlInst - Given operands for an Shl, see if we can
1226/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001227static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001228 const Query &Q, unsigned MaxRecurse) {
1229 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001230 return V;
1231
1232 // undef << X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001233 if (match(Op0, m_Undef()))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001234 return Constant::getNullValue(Op0->getType());
1235
Chris Lattner81a0dc92011-02-09 17:15:04 +00001236 // (X >> A) << A -> X
1237 Value *X;
Benjamin Kramer55c6d572012-01-01 17:55:30 +00001238 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner81a0dc92011-02-09 17:15:04 +00001239 return X;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001240 return 0;
1241}
1242
Chris Lattner81a0dc92011-02-09 17:15:04 +00001243Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +00001244 const TargetData *TD, const TargetLibraryInfo *TLI,
1245 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001246 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
1247 RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001248}
1249
1250/// SimplifyLShrInst - Given operands for an LShr, see if we can
1251/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001252static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001253 const Query &Q, unsigned MaxRecurse) {
1254 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001255 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001256
1257 // undef >>l X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001258 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001259 return Constant::getNullValue(Op0->getType());
1260
Chris Lattner81a0dc92011-02-09 17:15:04 +00001261 // (X << A) >> A -> X
1262 Value *X;
1263 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1264 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1265 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001266
Duncan Sandsc43cee32011-01-14 00:37:45 +00001267 return 0;
1268}
1269
Chris Lattner81a0dc92011-02-09 17:15:04 +00001270Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Chad Rosier618c1db2011-12-01 03:08:23 +00001271 const TargetData *TD,
1272 const TargetLibraryInfo *TLI,
1273 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001274 return ::SimplifyLShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
1275 RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001276}
1277
1278/// SimplifyAShrInst - Given operands for an AShr, see if we can
1279/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001280static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001281 const Query &Q, unsigned MaxRecurse) {
1282 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001283 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001284
1285 // all ones >>a X -> all ones
1286 if (match(Op0, m_AllOnes()))
1287 return Op0;
1288
1289 // undef >>a X -> all ones
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001290 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001291 return Constant::getAllOnesValue(Op0->getType());
1292
Chris Lattner81a0dc92011-02-09 17:15:04 +00001293 // (X << A) >> A -> X
1294 Value *X;
1295 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1296 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1297 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001298
Duncan Sandsc43cee32011-01-14 00:37:45 +00001299 return 0;
1300}
1301
Chris Lattner81a0dc92011-02-09 17:15:04 +00001302Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Chad Rosier618c1db2011-12-01 03:08:23 +00001303 const TargetData *TD,
1304 const TargetLibraryInfo *TLI,
1305 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001306 return ::SimplifyAShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
1307 RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001308}
1309
Chris Lattnerd06094f2009-11-10 00:55:12 +00001310/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001311/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001312static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
Chad Rosier618c1db2011-12-01 03:08:23 +00001313 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001314 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1315 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1316 Constant *Ops[] = { CLHS, CRHS };
1317 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001318 Ops, Q.TD, Q.TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001319 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001320
Chris Lattnerd06094f2009-11-10 00:55:12 +00001321 // Canonicalize the constant to the RHS.
1322 std::swap(Op0, Op1);
1323 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001324
Chris Lattnerd06094f2009-11-10 00:55:12 +00001325 // X & undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001326 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001327 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001328
Chris Lattnerd06094f2009-11-10 00:55:12 +00001329 // X & X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001330 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001331 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001332
Duncan Sands2b749872010-11-17 18:52:15 +00001333 // X & 0 = 0
1334 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001335 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001336
Duncan Sands2b749872010-11-17 18:52:15 +00001337 // X & -1 = X
1338 if (match(Op1, m_AllOnes()))
1339 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001340
Chris Lattnerd06094f2009-11-10 00:55:12 +00001341 // A & ~A = ~A & A = 0
Chris Lattner81a0dc92011-02-09 17:15:04 +00001342 if (match(Op0, m_Not(m_Specific(Op1))) ||
1343 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001344 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001345
Chris Lattnerd06094f2009-11-10 00:55:12 +00001346 // (A | ?) & A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001347 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001348 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001349 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001350 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001351
Chris Lattnerd06094f2009-11-10 00:55:12 +00001352 // A & (A | ?) = A
1353 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001354 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001355 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001356
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001357 // A & (-A) = A if A is a power of two or zero.
1358 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1359 match(Op1, m_Neg(m_Specific(Op0)))) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001360 if (isPowerOfTwo(Op0, Q.TD, /*OrZero*/true))
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001361 return Op0;
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001362 if (isPowerOfTwo(Op1, Q.TD, /*OrZero*/true))
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001363 return Op1;
1364 }
1365
Duncan Sands566edb02010-12-21 08:49:00 +00001366 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001367 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1368 MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001369 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001370
Duncan Sands3421d902010-12-21 13:32:22 +00001371 // And distributes over Or. Try some generic simplifications based on this.
1372 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001373 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001374 return V;
1375
1376 // And distributes over Xor. Try some generic simplifications based on this.
1377 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001378 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001379 return V;
1380
1381 // Or distributes over And. Try some generic simplifications based on this.
1382 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001383 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001384 return V;
1385
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001386 // If the operation is with the result of a select instruction, check whether
1387 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001388 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001389 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1390 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001391 return V;
1392
1393 // If the operation is with the result of a phi instruction, check whether
1394 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001395 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001396 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
Duncan Sands0312a932010-12-21 09:09:15 +00001397 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001398 return V;
1399
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001400 return 0;
1401}
1402
Duncan Sands18450092010-11-16 12:16:38 +00001403Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001404 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +00001405 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001406 return ::SimplifyAndInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001407}
1408
Chris Lattnerd06094f2009-11-10 00:55:12 +00001409/// SimplifyOrInst - Given operands for an Or, see if we can
1410/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001411static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1412 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001413 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1414 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1415 Constant *Ops[] = { CLHS, CRHS };
1416 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001417 Ops, Q.TD, Q.TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001418 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001419
Chris Lattnerd06094f2009-11-10 00:55:12 +00001420 // Canonicalize the constant to the RHS.
1421 std::swap(Op0, Op1);
1422 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001423
Chris Lattnerd06094f2009-11-10 00:55:12 +00001424 // X | undef -> -1
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001425 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001426 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001427
Chris Lattnerd06094f2009-11-10 00:55:12 +00001428 // X | X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001429 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001430 return Op0;
1431
Duncan Sands2b749872010-11-17 18:52:15 +00001432 // X | 0 = X
1433 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001434 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001435
Duncan Sands2b749872010-11-17 18:52:15 +00001436 // X | -1 = -1
1437 if (match(Op1, m_AllOnes()))
1438 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001439
Chris Lattnerd06094f2009-11-10 00:55:12 +00001440 // A | ~A = ~A | A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001441 if (match(Op0, m_Not(m_Specific(Op1))) ||
1442 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001443 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001444
Chris Lattnerd06094f2009-11-10 00:55:12 +00001445 // (A & ?) | A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001446 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001447 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001448 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001449 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001450
Chris Lattnerd06094f2009-11-10 00:55:12 +00001451 // A | (A & ?) = A
1452 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001453 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001454 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001455
Benjamin Kramer38f7f662011-02-20 15:20:01 +00001456 // ~(A & ?) | A = -1
1457 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1458 (A == Op1 || B == Op1))
1459 return Constant::getAllOnesValue(Op1->getType());
1460
1461 // A | ~(A & ?) = -1
1462 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1463 (A == Op0 || B == Op0))
1464 return Constant::getAllOnesValue(Op0->getType());
1465
Duncan Sands566edb02010-12-21 08:49:00 +00001466 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001467 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1468 MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001469 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001470
Duncan Sands3421d902010-12-21 13:32:22 +00001471 // Or distributes over And. Try some generic simplifications based on this.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001472 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1473 MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001474 return V;
1475
1476 // And distributes over Or. Try some generic simplifications based on this.
1477 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001478 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001479 return V;
1480
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001481 // If the operation is with the result of a select instruction, check whether
1482 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001483 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001484 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
Duncan Sands0312a932010-12-21 09:09:15 +00001485 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001486 return V;
1487
1488 // If the operation is with the result of a phi instruction, check whether
1489 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001490 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001491 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001492 return V;
1493
Chris Lattnerd06094f2009-11-10 00:55:12 +00001494 return 0;
1495}
1496
Duncan Sands18450092010-11-16 12:16:38 +00001497Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001498 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +00001499 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001500 return ::SimplifyOrInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001501}
Chris Lattnerd06094f2009-11-10 00:55:12 +00001502
Duncan Sands2b749872010-11-17 18:52:15 +00001503/// SimplifyXorInst - Given operands for a Xor, see if we can
1504/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001505static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1506 unsigned MaxRecurse) {
Duncan Sands2b749872010-11-17 18:52:15 +00001507 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1508 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1509 Constant *Ops[] = { CLHS, CRHS };
1510 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001511 Ops, Q.TD, Q.TLI);
Duncan Sands2b749872010-11-17 18:52:15 +00001512 }
1513
1514 // Canonicalize the constant to the RHS.
1515 std::swap(Op0, Op1);
1516 }
1517
1518 // A ^ undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001519 if (match(Op1, m_Undef()))
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00001520 return Op1;
Duncan Sands2b749872010-11-17 18:52:15 +00001521
1522 // A ^ 0 = A
1523 if (match(Op1, m_Zero()))
1524 return Op0;
1525
Eli Friedmanf23d4ad2011-08-17 19:31:49 +00001526 // A ^ A = 0
1527 if (Op0 == Op1)
1528 return Constant::getNullValue(Op0->getType());
1529
Duncan Sands2b749872010-11-17 18:52:15 +00001530 // A ^ ~A = ~A ^ A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001531 if (match(Op0, m_Not(m_Specific(Op1))) ||
1532 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands2b749872010-11-17 18:52:15 +00001533 return Constant::getAllOnesValue(Op0->getType());
1534
Duncan Sands566edb02010-12-21 08:49:00 +00001535 // Try some generic simplifications for associative operations.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001536 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1537 MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001538 return V;
Duncan Sands2b749872010-11-17 18:52:15 +00001539
Duncan Sands3421d902010-12-21 13:32:22 +00001540 // And distributes over Xor. Try some generic simplifications based on this.
1541 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001542 Q, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001543 return V;
1544
Duncan Sands87689cf2010-11-19 09:20:39 +00001545 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1546 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1547 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1548 // only if B and C are equal. If B and C are equal then (since we assume
1549 // that operands have already been simplified) "select(cond, B, C)" should
1550 // have been simplified to the common value of B and C already. Analysing
1551 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1552 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +00001553
1554 return 0;
1555}
1556
1557Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001558 const TargetLibraryInfo *TLI,
Duncan Sands2b749872010-11-17 18:52:15 +00001559 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001560 return ::SimplifyXorInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
Duncan Sands2b749872010-11-17 18:52:15 +00001561}
1562
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001563static Type *GetCompareTy(Value *Op) {
Chris Lattner210c5d42009-11-09 23:55:12 +00001564 return CmpInst::makeCmpResultType(Op->getType());
1565}
1566
Duncan Sandse864b5b2011-05-07 16:56:49 +00001567/// ExtractEquivalentCondition - Rummage around inside V looking for something
1568/// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1569/// otherwise return null. Helper function for analyzing max/min idioms.
1570static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1571 Value *LHS, Value *RHS) {
1572 SelectInst *SI = dyn_cast<SelectInst>(V);
1573 if (!SI)
1574 return 0;
1575 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1576 if (!Cmp)
1577 return 0;
1578 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1579 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1580 return Cmp;
1581 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1582 LHS == CmpRHS && RHS == CmpLHS)
1583 return Cmp;
1584 return 0;
1585}
1586
Chris Lattner009e2652012-02-24 19:01:58 +00001587
Chris Lattner9dbb4292009-11-09 23:28:39 +00001588/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1589/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001590static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001591 const Query &Q, unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001592 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +00001593 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +00001594
Chris Lattnerd06094f2009-11-10 00:55:12 +00001595 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +00001596 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001597 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001598
1599 // If we have a constant, make sure it is on the RHS.
1600 std::swap(LHS, RHS);
1601 Pred = CmpInst::getSwappedPredicate(Pred);
1602 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001603
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001604 Type *ITy = GetCompareTy(LHS); // The return type.
1605 Type *OpTy = LHS->getType(); // The operand type.
Duncan Sands12a86f52010-11-14 11:23:23 +00001606
Chris Lattner210c5d42009-11-09 23:55:12 +00001607 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +00001608 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1609 // because X could be 0.
Duncan Sands124708d2011-01-01 20:08:02 +00001610 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +00001611 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +00001612
Duncan Sands6dc91252011-01-13 08:56:29 +00001613 // Special case logic when the operands have i1 type.
Nick Lewycky66d004e2011-12-01 02:39:36 +00001614 if (OpTy->getScalarType()->isIntegerTy(1)) {
Duncan Sands6dc91252011-01-13 08:56:29 +00001615 switch (Pred) {
1616 default: break;
1617 case ICmpInst::ICMP_EQ:
1618 // X == 1 -> X
1619 if (match(RHS, m_One()))
1620 return LHS;
1621 break;
1622 case ICmpInst::ICMP_NE:
1623 // X != 0 -> X
1624 if (match(RHS, m_Zero()))
1625 return LHS;
1626 break;
1627 case ICmpInst::ICMP_UGT:
1628 // X >u 0 -> X
1629 if (match(RHS, m_Zero()))
1630 return LHS;
1631 break;
1632 case ICmpInst::ICMP_UGE:
1633 // X >=u 1 -> X
1634 if (match(RHS, m_One()))
1635 return LHS;
1636 break;
1637 case ICmpInst::ICMP_SLT:
1638 // X <s 0 -> X
1639 if (match(RHS, m_Zero()))
1640 return LHS;
1641 break;
1642 case ICmpInst::ICMP_SLE:
1643 // X <=s -1 -> X
1644 if (match(RHS, m_One()))
1645 return LHS;
1646 break;
1647 }
1648 }
1649
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001650 // icmp <object*>, <object*/null> - Different identified objects have
1651 // different addresses (unless null), and what's more the address of an
1652 // identified local is never equal to another argument (again, barring null).
1653 // Note that generalizing to the case where LHS is a global variable address
1654 // or null is pointless, since if both LHS and RHS are constants then we
1655 // already constant folded the compare, and if only one of them is then we
1656 // moved it to RHS already.
Benjamin Kramerea79b8e2012-02-16 15:19:59 +00001657 Value *LHSPtr = LHS->stripPointerCasts();
1658 Value *RHSPtr = RHS->stripPointerCasts();
Eli Friedman2c3acb02012-02-18 03:29:25 +00001659 if (LHSPtr == RHSPtr)
1660 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001661
Chris Lattnerb053fc12012-02-20 00:42:49 +00001662 // Be more aggressive about stripping pointer adjustments when checking a
1663 // comparison of an alloca address to another object. We can rip off all
1664 // inbounds GEP operations, even if they are variable.
Chandler Carruth84dfc322012-03-10 08:39:09 +00001665 LHSPtr = LHSPtr->stripInBoundsOffsets();
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001666 if (llvm::isIdentifiedObject(LHSPtr)) {
Chandler Carruth84dfc322012-03-10 08:39:09 +00001667 RHSPtr = RHSPtr->stripInBoundsOffsets();
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001668 if (llvm::isKnownNonNull(LHSPtr) || llvm::isKnownNonNull(RHSPtr)) {
1669 // If both sides are different identified objects, they aren't equal
1670 // unless they're null.
Bill Wendlingc17731d652012-03-10 17:56:03 +00001671 if (LHSPtr != RHSPtr && llvm::isIdentifiedObject(RHSPtr) &&
Bill Wendling798d0132012-03-10 18:20:55 +00001672 Pred == CmpInst::ICMP_EQ)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001673 return ConstantInt::get(ITy, false);
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001674
1675 // A local identified object (alloca or noalias call) can't equal any
1676 // incoming argument, unless they're both null.
Bill Wendlingc17731d652012-03-10 17:56:03 +00001677 if (isa<Instruction>(LHSPtr) && isa<Argument>(RHSPtr) &&
Bill Wendling798d0132012-03-10 18:20:55 +00001678 Pred == CmpInst::ICMP_EQ)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001679 return ConstantInt::get(ITy, false);
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001680 }
1681
1682 // Assume that the constant null is on the right.
Bill Wendlingc17731d652012-03-10 17:56:03 +00001683 if (llvm::isKnownNonNull(LHSPtr) && isa<ConstantPointerNull>(RHSPtr)) {
Bill Wendling798d0132012-03-10 18:20:55 +00001684 if (Pred == CmpInst::ICMP_EQ)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001685 return ConstantInt::get(ITy, false);
Bill Wendling798d0132012-03-10 18:20:55 +00001686 else if (Pred == CmpInst::ICMP_NE)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001687 return ConstantInt::get(ITy, true);
1688 }
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001689 } else if (isa<Argument>(LHSPtr)) {
Chandler Carruth84dfc322012-03-10 08:39:09 +00001690 RHSPtr = RHSPtr->stripInBoundsOffsets();
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001691 // An alloca can't be equal to an argument.
Bill Wendlingc17731d652012-03-10 17:56:03 +00001692 if (isa<AllocaInst>(RHSPtr)) {
Bill Wendling798d0132012-03-10 18:20:55 +00001693 if (Pred == CmpInst::ICMP_EQ)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001694 return ConstantInt::get(ITy, false);
Bill Wendling798d0132012-03-10 18:20:55 +00001695 else if (Pred == CmpInst::ICMP_NE)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001696 return ConstantInt::get(ITy, true);
1697 }
Chris Lattnerb053fc12012-02-20 00:42:49 +00001698 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001699
1700 // If we are comparing with zero then try hard since this is a common case.
1701 if (match(RHS, m_Zero())) {
1702 bool LHSKnownNonNegative, LHSKnownNegative;
1703 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00001704 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001705 case ICmpInst::ICMP_ULT:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001706 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001707 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001708 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001709 case ICmpInst::ICMP_EQ:
1710 case ICmpInst::ICMP_ULE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001711 if (isKnownNonZero(LHS, Q.TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001712 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001713 break;
1714 case ICmpInst::ICMP_NE:
1715 case ICmpInst::ICMP_UGT:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001716 if (isKnownNonZero(LHS, Q.TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001717 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001718 break;
1719 case ICmpInst::ICMP_SLT:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001720 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001721 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001722 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001723 if (LHSKnownNonNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001724 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001725 break;
1726 case ICmpInst::ICMP_SLE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001727 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001728 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001729 return getTrue(ITy);
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001730 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001731 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001732 break;
1733 case ICmpInst::ICMP_SGE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001734 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001735 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001736 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001737 if (LHSKnownNonNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001738 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001739 break;
1740 case ICmpInst::ICMP_SGT:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001741 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001742 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001743 return getFalse(ITy);
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001744 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001745 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001746 break;
1747 }
1748 }
1749
1750 // See if we are doing a comparison with a constant integer.
Duncan Sands6dc91252011-01-13 08:56:29 +00001751 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Nick Lewycky3a73e342011-03-04 07:00:57 +00001752 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1753 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1754 if (RHS_CR.isEmptySet())
1755 return ConstantInt::getFalse(CI->getContext());
1756 if (RHS_CR.isFullSet())
1757 return ConstantInt::getTrue(CI->getContext());
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001758
Nick Lewycky3a73e342011-03-04 07:00:57 +00001759 // Many binary operators with constant RHS have easy to compute constant
1760 // range. Use them to check whether the comparison is a tautology.
1761 uint32_t Width = CI->getBitWidth();
1762 APInt Lower = APInt(Width, 0);
1763 APInt Upper = APInt(Width, 0);
1764 ConstantInt *CI2;
1765 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1766 // 'urem x, CI2' produces [0, CI2).
1767 Upper = CI2->getValue();
1768 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1769 // 'srem x, CI2' produces (-|CI2|, |CI2|).
1770 Upper = CI2->getValue().abs();
1771 Lower = (-Upper) + 1;
Duncan Sandsc65c7472011-10-28 18:17:44 +00001772 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
1773 // 'udiv CI2, x' produces [0, CI2].
Eli Friedman7781ae52011-11-08 21:08:02 +00001774 Upper = CI2->getValue() + 1;
Nick Lewycky3a73e342011-03-04 07:00:57 +00001775 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1776 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1777 APInt NegOne = APInt::getAllOnesValue(Width);
1778 if (!CI2->isZero())
1779 Upper = NegOne.udiv(CI2->getValue()) + 1;
1780 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1781 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1782 APInt IntMin = APInt::getSignedMinValue(Width);
1783 APInt IntMax = APInt::getSignedMaxValue(Width);
1784 APInt Val = CI2->getValue().abs();
1785 if (!Val.isMinValue()) {
1786 Lower = IntMin.sdiv(Val);
1787 Upper = IntMax.sdiv(Val) + 1;
1788 }
1789 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1790 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1791 APInt NegOne = APInt::getAllOnesValue(Width);
1792 if (CI2->getValue().ult(Width))
1793 Upper = NegOne.lshr(CI2->getValue()) + 1;
1794 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1795 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1796 APInt IntMin = APInt::getSignedMinValue(Width);
1797 APInt IntMax = APInt::getSignedMaxValue(Width);
1798 if (CI2->getValue().ult(Width)) {
1799 Lower = IntMin.ashr(CI2->getValue());
1800 Upper = IntMax.ashr(CI2->getValue()) + 1;
1801 }
1802 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1803 // 'or x, CI2' produces [CI2, UINT_MAX].
1804 Lower = CI2->getValue();
1805 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1806 // 'and x, CI2' produces [0, CI2].
1807 Upper = CI2->getValue() + 1;
1808 }
1809 if (Lower != Upper) {
1810 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1811 if (RHS_CR.contains(LHS_CR))
1812 return ConstantInt::getTrue(RHS->getContext());
1813 if (RHS_CR.inverse().contains(LHS_CR))
1814 return ConstantInt::getFalse(RHS->getContext());
1815 }
Duncan Sands6dc91252011-01-13 08:56:29 +00001816 }
1817
Duncan Sands9d32f602011-01-20 13:21:55 +00001818 // Compare of cast, for example (zext X) != 0 -> X != 0
1819 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1820 Instruction *LI = cast<CastInst>(LHS);
1821 Value *SrcOp = LI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001822 Type *SrcTy = SrcOp->getType();
1823 Type *DstTy = LI->getType();
Duncan Sands9d32f602011-01-20 13:21:55 +00001824
1825 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1826 // if the integer type is the same size as the pointer type.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001827 if (MaxRecurse && Q.TD && isa<PtrToIntInst>(LI) &&
1828 Q.TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
Duncan Sands9d32f602011-01-20 13:21:55 +00001829 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1830 // Transfer the cast to the constant.
1831 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1832 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001833 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001834 return V;
1835 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1836 if (RI->getOperand(0)->getType() == SrcTy)
1837 // Compare without the cast.
1838 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001839 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001840 return V;
1841 }
1842 }
1843
1844 if (isa<ZExtInst>(LHS)) {
1845 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1846 // same type.
1847 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1848 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1849 // Compare X and Y. Note that signed predicates become unsigned.
1850 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001851 SrcOp, RI->getOperand(0), Q,
Duncan Sands9d32f602011-01-20 13:21:55 +00001852 MaxRecurse-1))
1853 return V;
1854 }
1855 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1856 // too. If not, then try to deduce the result of the comparison.
1857 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1858 // Compute the constant that would happen if we truncated to SrcTy then
1859 // reextended to DstTy.
1860 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1861 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1862
1863 // If the re-extended constant didn't change then this is effectively
1864 // also a case of comparing two zero-extended values.
1865 if (RExt == CI && MaxRecurse)
1866 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001867 SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001868 return V;
1869
1870 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1871 // there. Use this to work out the result of the comparison.
1872 if (RExt != CI) {
1873 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00001874 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands9d32f602011-01-20 13:21:55 +00001875 // LHS <u RHS.
1876 case ICmpInst::ICMP_EQ:
1877 case ICmpInst::ICMP_UGT:
1878 case ICmpInst::ICMP_UGE:
1879 return ConstantInt::getFalse(CI->getContext());
1880
1881 case ICmpInst::ICMP_NE:
1882 case ICmpInst::ICMP_ULT:
1883 case ICmpInst::ICMP_ULE:
1884 return ConstantInt::getTrue(CI->getContext());
1885
1886 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
1887 // is non-negative then LHS <s RHS.
1888 case ICmpInst::ICMP_SGT:
1889 case ICmpInst::ICMP_SGE:
1890 return CI->getValue().isNegative() ?
1891 ConstantInt::getTrue(CI->getContext()) :
1892 ConstantInt::getFalse(CI->getContext());
1893
1894 case ICmpInst::ICMP_SLT:
1895 case ICmpInst::ICMP_SLE:
1896 return CI->getValue().isNegative() ?
1897 ConstantInt::getFalse(CI->getContext()) :
1898 ConstantInt::getTrue(CI->getContext());
1899 }
1900 }
1901 }
1902 }
1903
1904 if (isa<SExtInst>(LHS)) {
1905 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1906 // same type.
1907 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1908 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1909 // Compare X and Y. Note that the predicate does not change.
1910 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001911 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001912 return V;
1913 }
1914 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1915 // too. If not, then try to deduce the result of the comparison.
1916 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1917 // Compute the constant that would happen if we truncated to SrcTy then
1918 // reextended to DstTy.
1919 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1920 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1921
1922 // If the re-extended constant didn't change then this is effectively
1923 // also a case of comparing two sign-extended values.
1924 if (RExt == CI && MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001925 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001926 return V;
1927
1928 // Otherwise the upper bits of LHS are all equal, while RHS has varying
1929 // bits there. Use this to work out the result of the comparison.
1930 if (RExt != CI) {
1931 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00001932 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands9d32f602011-01-20 13:21:55 +00001933 case ICmpInst::ICMP_EQ:
1934 return ConstantInt::getFalse(CI->getContext());
1935 case ICmpInst::ICMP_NE:
1936 return ConstantInt::getTrue(CI->getContext());
1937
1938 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
1939 // LHS >s RHS.
1940 case ICmpInst::ICMP_SGT:
1941 case ICmpInst::ICMP_SGE:
1942 return CI->getValue().isNegative() ?
1943 ConstantInt::getTrue(CI->getContext()) :
1944 ConstantInt::getFalse(CI->getContext());
1945 case ICmpInst::ICMP_SLT:
1946 case ICmpInst::ICMP_SLE:
1947 return CI->getValue().isNegative() ?
1948 ConstantInt::getFalse(CI->getContext()) :
1949 ConstantInt::getTrue(CI->getContext());
1950
1951 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
1952 // LHS >u RHS.
1953 case ICmpInst::ICMP_UGT:
1954 case ICmpInst::ICMP_UGE:
1955 // Comparison is true iff the LHS <s 0.
1956 if (MaxRecurse)
1957 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
1958 Constant::getNullValue(SrcTy),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001959 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001960 return V;
1961 break;
1962 case ICmpInst::ICMP_ULT:
1963 case ICmpInst::ICMP_ULE:
1964 // Comparison is true iff the LHS >=s 0.
1965 if (MaxRecurse)
1966 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
1967 Constant::getNullValue(SrcTy),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00001968 Q, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001969 return V;
1970 break;
1971 }
1972 }
1973 }
1974 }
1975 }
1976
Duncan Sands52fb8462011-02-13 17:15:40 +00001977 // Special logic for binary operators.
1978 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
1979 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
1980 if (MaxRecurse && (LBO || RBO)) {
Duncan Sands52fb8462011-02-13 17:15:40 +00001981 // Analyze the case when either LHS or RHS is an add instruction.
1982 Value *A = 0, *B = 0, *C = 0, *D = 0;
1983 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
1984 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
1985 if (LBO && LBO->getOpcode() == Instruction::Add) {
1986 A = LBO->getOperand(0); B = LBO->getOperand(1);
1987 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
1988 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
1989 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
1990 }
1991 if (RBO && RBO->getOpcode() == Instruction::Add) {
1992 C = RBO->getOperand(0); D = RBO->getOperand(1);
1993 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
1994 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
1995 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
1996 }
1997
1998 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
1999 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2000 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2001 Constant::getNullValue(RHS->getType()),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002002 Q, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00002003 return V;
2004
2005 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2006 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2007 if (Value *V = SimplifyICmpInst(Pred,
2008 Constant::getNullValue(LHS->getType()),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002009 C == LHS ? D : C, Q, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00002010 return V;
2011
2012 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2013 if (A && C && (A == C || A == D || B == C || B == D) &&
2014 NoLHSWrapProblem && NoRHSWrapProblem) {
2015 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2016 Value *Y = (A == C || A == D) ? B : A;
2017 Value *Z = (C == A || C == B) ? D : C;
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002018 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00002019 return V;
2020 }
2021 }
2022
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002023 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Nick Lewycky78679272011-03-04 10:06:52 +00002024 bool KnownNonNegative, KnownNegative;
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002025 switch (Pred) {
2026 default:
2027 break;
Nick Lewycky78679272011-03-04 10:06:52 +00002028 case ICmpInst::ICMP_SGT:
2029 case ICmpInst::ICMP_SGE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002030 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
Nick Lewycky78679272011-03-04 10:06:52 +00002031 if (!KnownNonNegative)
2032 break;
2033 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002034 case ICmpInst::ICMP_EQ:
2035 case ICmpInst::ICMP_UGT:
2036 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002037 return getFalse(ITy);
Nick Lewycky78679272011-03-04 10:06:52 +00002038 case ICmpInst::ICMP_SLT:
2039 case ICmpInst::ICMP_SLE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002040 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
Nick Lewycky78679272011-03-04 10:06:52 +00002041 if (!KnownNonNegative)
2042 break;
2043 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002044 case ICmpInst::ICMP_NE:
2045 case ICmpInst::ICMP_ULT:
2046 case ICmpInst::ICMP_ULE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002047 return getTrue(ITy);
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002048 }
2049 }
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002050 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2051 bool KnownNonNegative, KnownNegative;
2052 switch (Pred) {
2053 default:
2054 break;
2055 case ICmpInst::ICMP_SGT:
2056 case ICmpInst::ICMP_SGE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002057 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002058 if (!KnownNonNegative)
2059 break;
2060 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00002061 case ICmpInst::ICMP_NE:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002062 case ICmpInst::ICMP_UGT:
2063 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002064 return getTrue(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002065 case ICmpInst::ICMP_SLT:
2066 case ICmpInst::ICMP_SLE:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002067 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002068 if (!KnownNonNegative)
2069 break;
2070 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00002071 case ICmpInst::ICMP_EQ:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002072 case ICmpInst::ICMP_ULT:
2073 case ICmpInst::ICMP_ULE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002074 return getFalse(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002075 }
2076 }
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002077
Duncan Sandsc65c7472011-10-28 18:17:44 +00002078 // x udiv y <=u x.
2079 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2080 // icmp pred (X /u Y), X
2081 if (Pred == ICmpInst::ICMP_UGT)
2082 return getFalse(ITy);
2083 if (Pred == ICmpInst::ICMP_ULE)
2084 return getTrue(ITy);
2085 }
2086
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002087 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2088 LBO->getOperand(1) == RBO->getOperand(1)) {
2089 switch (LBO->getOpcode()) {
2090 default: break;
2091 case Instruction::UDiv:
2092 case Instruction::LShr:
2093 if (ICmpInst::isSigned(Pred))
2094 break;
2095 // fall-through
2096 case Instruction::SDiv:
2097 case Instruction::AShr:
Eli Friedmanb6e7cd62011-05-05 21:59:18 +00002098 if (!LBO->isExact() || !RBO->isExact())
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002099 break;
2100 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002101 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002102 return V;
2103 break;
2104 case Instruction::Shl: {
Duncan Sandsc9d904e2011-08-04 10:02:21 +00002105 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002106 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2107 if (!NUW && !NSW)
2108 break;
2109 if (!NSW && ICmpInst::isSigned(Pred))
2110 break;
2111 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002112 RBO->getOperand(0), Q, MaxRecurse-1))
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002113 return V;
2114 break;
2115 }
2116 }
2117 }
2118
Duncan Sandsad206812011-05-03 19:53:10 +00002119 // Simplify comparisons involving max/min.
2120 Value *A, *B;
2121 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2122 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2123
Duncan Sands8140ad32011-05-04 16:05:05 +00002124 // Signed variants on "max(a,b)>=a -> true".
Duncan Sandsad206812011-05-03 19:53:10 +00002125 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2126 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2127 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2128 // We analyze this as smax(A, B) pred A.
2129 P = Pred;
2130 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2131 (A == LHS || B == LHS)) {
2132 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2133 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2134 // We analyze this as smax(A, B) swapped-pred A.
2135 P = CmpInst::getSwappedPredicate(Pred);
2136 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2137 (A == RHS || B == RHS)) {
2138 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2139 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2140 // We analyze this as smax(-A, -B) swapped-pred -A.
2141 // Note that we do not need to actually form -A or -B thanks to EqP.
2142 P = CmpInst::getSwappedPredicate(Pred);
2143 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2144 (A == LHS || B == LHS)) {
2145 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2146 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2147 // We analyze this as smax(-A, -B) pred -A.
2148 // Note that we do not need to actually form -A or -B thanks to EqP.
2149 P = Pred;
2150 }
2151 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2152 // Cases correspond to "max(A, B) p A".
2153 switch (P) {
2154 default:
2155 break;
2156 case CmpInst::ICMP_EQ:
2157 case CmpInst::ICMP_SLE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002158 // Equivalent to "A EqP B". This may be the same as the condition tested
2159 // in the max/min; if so, we can just return that.
2160 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2161 return V;
2162 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2163 return V;
2164 // Otherwise, see if "A EqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002165 if (MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002166 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002167 return V;
2168 break;
2169 case CmpInst::ICMP_NE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002170 case CmpInst::ICMP_SGT: {
2171 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2172 // Equivalent to "A InvEqP B". This may be the same as the condition
2173 // tested in the max/min; if so, we can just return that.
2174 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2175 return V;
2176 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2177 return V;
2178 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002179 if (MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002180 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002181 return V;
2182 break;
Duncan Sandse864b5b2011-05-07 16:56:49 +00002183 }
Duncan Sandsad206812011-05-03 19:53:10 +00002184 case CmpInst::ICMP_SGE:
2185 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002186 return getTrue(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002187 case CmpInst::ICMP_SLT:
2188 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002189 return getFalse(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002190 }
2191 }
2192
Duncan Sands8140ad32011-05-04 16:05:05 +00002193 // Unsigned variants on "max(a,b)>=a -> true".
Duncan Sandsad206812011-05-03 19:53:10 +00002194 P = CmpInst::BAD_ICMP_PREDICATE;
2195 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2196 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2197 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2198 // We analyze this as umax(A, B) pred A.
2199 P = Pred;
2200 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2201 (A == LHS || B == LHS)) {
2202 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2203 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2204 // We analyze this as umax(A, B) swapped-pred A.
2205 P = CmpInst::getSwappedPredicate(Pred);
2206 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2207 (A == RHS || B == RHS)) {
2208 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2209 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2210 // We analyze this as umax(-A, -B) swapped-pred -A.
2211 // Note that we do not need to actually form -A or -B thanks to EqP.
2212 P = CmpInst::getSwappedPredicate(Pred);
2213 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2214 (A == LHS || B == LHS)) {
2215 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2216 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2217 // We analyze this as umax(-A, -B) pred -A.
2218 // Note that we do not need to actually form -A or -B thanks to EqP.
2219 P = Pred;
2220 }
2221 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2222 // Cases correspond to "max(A, B) p A".
2223 switch (P) {
2224 default:
2225 break;
2226 case CmpInst::ICMP_EQ:
2227 case CmpInst::ICMP_ULE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002228 // Equivalent to "A EqP B". This may be the same as the condition tested
2229 // in the max/min; if so, we can just return that.
2230 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2231 return V;
2232 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2233 return V;
2234 // Otherwise, see if "A EqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002235 if (MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002236 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002237 return V;
2238 break;
2239 case CmpInst::ICMP_NE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002240 case CmpInst::ICMP_UGT: {
2241 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2242 // Equivalent to "A InvEqP B". This may be the same as the condition
2243 // tested in the max/min; if so, we can just return that.
2244 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2245 return V;
2246 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2247 return V;
2248 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002249 if (MaxRecurse)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002250 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002251 return V;
2252 break;
Duncan Sandse864b5b2011-05-07 16:56:49 +00002253 }
Duncan Sandsad206812011-05-03 19:53:10 +00002254 case CmpInst::ICMP_UGE:
2255 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002256 return getTrue(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002257 case CmpInst::ICMP_ULT:
2258 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002259 return getFalse(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002260 }
2261 }
2262
Duncan Sands8140ad32011-05-04 16:05:05 +00002263 // Variants on "max(x,y) >= min(x,z)".
2264 Value *C, *D;
2265 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2266 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2267 (A == C || A == D || B == C || B == D)) {
2268 // max(x, ?) pred min(x, ?).
2269 if (Pred == CmpInst::ICMP_SGE)
2270 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002271 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002272 if (Pred == CmpInst::ICMP_SLT)
2273 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002274 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002275 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2276 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2277 (A == C || A == D || B == C || B == D)) {
2278 // min(x, ?) pred max(x, ?).
2279 if (Pred == CmpInst::ICMP_SLE)
2280 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002281 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002282 if (Pred == CmpInst::ICMP_SGT)
2283 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002284 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002285 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2286 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2287 (A == C || A == D || B == C || B == D)) {
2288 // max(x, ?) pred min(x, ?).
2289 if (Pred == CmpInst::ICMP_UGE)
2290 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002291 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002292 if (Pred == CmpInst::ICMP_ULT)
2293 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002294 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002295 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2296 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2297 (A == C || A == D || B == C || B == D)) {
2298 // min(x, ?) pred max(x, ?).
2299 if (Pred == CmpInst::ICMP_ULE)
2300 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002301 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002302 if (Pred == CmpInst::ICMP_UGT)
2303 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002304 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002305 }
2306
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00002307 // Simplify comparisons of GEPs.
2308 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2309 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2310 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2311 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2312 (ICmpInst::isEquality(Pred) ||
2313 (GLHS->isInBounds() && GRHS->isInBounds() &&
2314 Pred == ICmpInst::getSignedPredicate(Pred)))) {
2315 // The bases are equal and the indices are constant. Build a constant
2316 // expression GEP with the same indices and a null base pointer to see
2317 // what constant folding can make out of it.
2318 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2319 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2320 Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2321
2322 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2323 Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2324 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2325 }
2326 }
2327 }
2328
Duncan Sands1ac7c992010-11-07 16:12:23 +00002329 // If the comparison is with the result of a select instruction, check whether
2330 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002331 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002332 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002333 return V;
2334
2335 // If the comparison is with the result of a phi instruction, check whether
2336 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00002337 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002338 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00002339 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +00002340
Chris Lattner9f3c25a2009-11-09 22:57:59 +00002341 return 0;
2342}
2343
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002344Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002345 const TargetData *TD,
2346 const TargetLibraryInfo *TLI,
2347 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002348 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2349 RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002350}
2351
Chris Lattner9dbb4292009-11-09 23:28:39 +00002352/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2353/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002354static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002355 const Query &Q, unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00002356 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2357 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2358
Chris Lattnerd06094f2009-11-10 00:55:12 +00002359 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00002360 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002361 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI);
Duncan Sands12a86f52010-11-14 11:23:23 +00002362
Chris Lattnerd06094f2009-11-10 00:55:12 +00002363 // If we have a constant, make sure it is on the RHS.
2364 std::swap(LHS, RHS);
2365 Pred = CmpInst::getSwappedPredicate(Pred);
2366 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002367
Chris Lattner210c5d42009-11-09 23:55:12 +00002368 // Fold trivial predicates.
2369 if (Pred == FCmpInst::FCMP_FALSE)
2370 return ConstantInt::get(GetCompareTy(LHS), 0);
2371 if (Pred == FCmpInst::FCMP_TRUE)
2372 return ConstantInt::get(GetCompareTy(LHS), 1);
2373
Chris Lattner210c5d42009-11-09 23:55:12 +00002374 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2375 return UndefValue::get(GetCompareTy(LHS));
2376
2377 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands124708d2011-01-01 20:08:02 +00002378 if (LHS == RHS) {
Chris Lattner210c5d42009-11-09 23:55:12 +00002379 if (CmpInst::isTrueWhenEqual(Pred))
2380 return ConstantInt::get(GetCompareTy(LHS), 1);
2381 if (CmpInst::isFalseWhenEqual(Pred))
2382 return ConstantInt::get(GetCompareTy(LHS), 0);
2383 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002384
Chris Lattner210c5d42009-11-09 23:55:12 +00002385 // Handle fcmp with constant RHS
2386 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2387 // If the constant is a nan, see if we can fold the comparison based on it.
2388 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2389 if (CFP->getValueAPF().isNaN()) {
2390 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2391 return ConstantInt::getFalse(CFP->getContext());
2392 assert(FCmpInst::isUnordered(Pred) &&
2393 "Comparison must be either ordered or unordered!");
2394 // True if unordered.
2395 return ConstantInt::getTrue(CFP->getContext());
2396 }
Dan Gohman6b617a72010-02-22 04:06:03 +00002397 // Check whether the constant is an infinity.
2398 if (CFP->getValueAPF().isInfinity()) {
2399 if (CFP->getValueAPF().isNegative()) {
2400 switch (Pred) {
2401 case FCmpInst::FCMP_OLT:
2402 // No value is ordered and less than negative infinity.
2403 return ConstantInt::getFalse(CFP->getContext());
2404 case FCmpInst::FCMP_UGE:
2405 // All values are unordered with or at least negative infinity.
2406 return ConstantInt::getTrue(CFP->getContext());
2407 default:
2408 break;
2409 }
2410 } else {
2411 switch (Pred) {
2412 case FCmpInst::FCMP_OGT:
2413 // No value is ordered and greater than infinity.
2414 return ConstantInt::getFalse(CFP->getContext());
2415 case FCmpInst::FCMP_ULE:
2416 // All values are unordered with and at most infinity.
2417 return ConstantInt::getTrue(CFP->getContext());
2418 default:
2419 break;
2420 }
2421 }
2422 }
Chris Lattner210c5d42009-11-09 23:55:12 +00002423 }
2424 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002425
Duncan Sands92826de2010-11-07 16:46:25 +00002426 // If the comparison is with the result of a select instruction, check whether
2427 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002428 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002429 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002430 return V;
2431
2432 // If the comparison is with the result of a phi instruction, check whether
2433 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00002434 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002435 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00002436 return V;
Duncan Sands92826de2010-11-07 16:46:25 +00002437
Chris Lattner9dbb4292009-11-09 23:28:39 +00002438 return 0;
2439}
2440
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002441Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002442 const TargetData *TD,
2443 const TargetLibraryInfo *TLI,
2444 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002445 return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2446 RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002447}
2448
Chris Lattner04754262010-04-20 05:32:14 +00002449/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2450/// the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002451static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
2452 Value *FalseVal, const Query &Q,
2453 unsigned MaxRecurse) {
Chris Lattner04754262010-04-20 05:32:14 +00002454 // select true, X, Y -> X
2455 // select false, X, Y -> Y
2456 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2457 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002458
Chris Lattner04754262010-04-20 05:32:14 +00002459 // select C, X, X -> X
Duncan Sands124708d2011-01-01 20:08:02 +00002460 if (TrueVal == FalseVal)
Chris Lattner04754262010-04-20 05:32:14 +00002461 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002462
Chris Lattner04754262010-04-20 05:32:14 +00002463 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2464 if (isa<Constant>(TrueVal))
2465 return TrueVal;
2466 return FalseVal;
2467 }
Dan Gohman68c0dbc2011-07-01 01:03:43 +00002468 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2469 return FalseVal;
2470 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2471 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002472
Chris Lattner04754262010-04-20 05:32:14 +00002473 return 0;
2474}
2475
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002476Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
2477 const TargetData *TD,
2478 const TargetLibraryInfo *TLI,
2479 const DominatorTree *DT) {
2480 return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Query (TD, TLI, DT),
2481 RecursionLimit);
2482}
2483
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002484/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2485/// fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002486static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) {
Duncan Sands85bbff62010-11-22 13:42:49 +00002487 // The type of the GEP pointer operand.
Nadav Rotem16087692011-12-05 06:29:09 +00002488 PointerType *PtrTy = dyn_cast<PointerType>(Ops[0]->getType());
2489 // The GEP pointer operand is not a pointer, it's a vector of pointers.
2490 if (!PtrTy)
2491 return 0;
Duncan Sands85bbff62010-11-22 13:42:49 +00002492
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002493 // getelementptr P -> P.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002494 if (Ops.size() == 1)
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002495 return Ops[0];
2496
Duncan Sands85bbff62010-11-22 13:42:49 +00002497 if (isa<UndefValue>(Ops[0])) {
2498 // Compute the (pointer) type returned by the GEP instruction.
Jay Foada9203102011-07-25 09:48:08 +00002499 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002500 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
Duncan Sands85bbff62010-11-22 13:42:49 +00002501 return UndefValue::get(GEPTy);
2502 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002503
Jay Foadb9b54eb2011-07-19 15:07:52 +00002504 if (Ops.size() == 2) {
Duncan Sandse60d79f2010-11-21 13:53:09 +00002505 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002506 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2507 if (C->isZero())
2508 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +00002509 // getelementptr P, N -> P if P points to a type of zero size.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002510 if (Q.TD) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002511 Type *Ty = PtrTy->getElementType();
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002512 if (Ty->isSized() && Q.TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +00002513 return Ops[0];
2514 }
2515 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002516
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002517 // Check to see if this is constant foldable.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002518 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002519 if (!isa<Constant>(Ops[i]))
2520 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +00002521
Jay Foaddab3d292011-07-21 14:31:17 +00002522 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002523}
2524
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002525Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const TargetData *TD,
2526 const TargetLibraryInfo *TLI,
2527 const DominatorTree *DT) {
2528 return ::SimplifyGEPInst(Ops, Query (TD, TLI, DT), RecursionLimit);
2529}
2530
Duncan Sandsdabc2802011-09-05 06:52:48 +00002531/// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2532/// can fold the result. If not, this returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002533static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
2534 ArrayRef<unsigned> Idxs, const Query &Q,
2535 unsigned) {
Duncan Sandsdabc2802011-09-05 06:52:48 +00002536 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2537 if (Constant *CVal = dyn_cast<Constant>(Val))
2538 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2539
2540 // insertvalue x, undef, n -> x
2541 if (match(Val, m_Undef()))
2542 return Agg;
2543
2544 // insertvalue x, (extractvalue y, n), n
2545 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramerae707bd2011-09-05 18:16:19 +00002546 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2547 EV->getIndices() == Idxs) {
Duncan Sandsdabc2802011-09-05 06:52:48 +00002548 // insertvalue undef, (extractvalue y, n), n -> y
2549 if (match(Agg, m_Undef()))
2550 return EV->getAggregateOperand();
2551
2552 // insertvalue y, (extractvalue y, n), n -> y
2553 if (Agg == EV->getAggregateOperand())
2554 return Agg;
2555 }
2556
2557 return 0;
2558}
2559
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002560Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2561 ArrayRef<unsigned> Idxs,
2562 const TargetData *TD,
2563 const TargetLibraryInfo *TLI,
2564 const DominatorTree *DT) {
2565 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query (TD, TLI, DT),
2566 RecursionLimit);
2567}
2568
Duncan Sandsff103412010-11-17 04:30:22 +00002569/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002570static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
Duncan Sandsff103412010-11-17 04:30:22 +00002571 // If all of the PHI's incoming values are the same then replace the PHI node
2572 // with the common value.
2573 Value *CommonValue = 0;
2574 bool HasUndefInput = false;
2575 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2576 Value *Incoming = PN->getIncomingValue(i);
2577 // If the incoming value is the phi node itself, it can safely be skipped.
2578 if (Incoming == PN) continue;
2579 if (isa<UndefValue>(Incoming)) {
2580 // Remember that we saw an undef value, but otherwise ignore them.
2581 HasUndefInput = true;
2582 continue;
2583 }
2584 if (CommonValue && Incoming != CommonValue)
2585 return 0; // Not the same, bail out.
2586 CommonValue = Incoming;
2587 }
2588
2589 // If CommonValue is null then all of the incoming values were either undef or
2590 // equal to the phi node itself.
2591 if (!CommonValue)
2592 return UndefValue::get(PN->getType());
2593
2594 // If we have a PHI node like phi(X, undef, X), where X is defined by some
2595 // instruction, we cannot return X as the result of the PHI node unless it
2596 // dominates the PHI block.
2597 if (HasUndefInput)
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002598 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : 0;
Duncan Sandsff103412010-11-17 04:30:22 +00002599
2600 return CommonValue;
2601}
2602
Duncan Sandsbd0fe562012-03-13 14:07:05 +00002603static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
2604 if (Constant *C = dyn_cast<Constant>(Op))
2605 return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.TD, Q.TLI);
2606
2607 return 0;
2608}
2609
2610Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const TargetData *TD,
2611 const TargetLibraryInfo *TLI,
2612 const DominatorTree *DT) {
2613 return ::SimplifyTruncInst(Op, Ty, Query (TD, TLI, DT), RecursionLimit);
2614}
2615
Chris Lattnerd06094f2009-11-10 00:55:12 +00002616//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +00002617
Chris Lattnerd06094f2009-11-10 00:55:12 +00002618/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2619/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002620static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002621 const Query &Q, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00002622 switch (Opcode) {
Chris Lattner81a0dc92011-02-09 17:15:04 +00002623 case Instruction::Add:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002624 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002625 Q, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002626 case Instruction::Sub:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002627 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002628 Q, MaxRecurse);
2629 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
2630 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
2631 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
2632 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse);
2633 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
2634 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
2635 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002636 case Instruction::Shl:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002637 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002638 Q, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002639 case Instruction::LShr:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002640 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002641 case Instruction::AShr:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002642 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
2643 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
2644 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
2645 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002646 default:
2647 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2648 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2649 Constant *COps[] = {CLHS, CRHS};
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002650 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.TD,
2651 Q.TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002652 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002653
Duncan Sands566edb02010-12-21 08:49:00 +00002654 // If the operation is associative, try some generic simplifications.
2655 if (Instruction::isAssociative(Opcode))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002656 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00002657 return V;
2658
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002659 // If the operation is with the result of a select instruction check whether
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002660 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002661 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002662 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002663 return V;
2664
2665 // If the operation is with the result of a phi instruction, check whether
2666 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002667 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002668 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002669 return V;
2670
Chris Lattnerd06094f2009-11-10 00:55:12 +00002671 return 0;
2672 }
2673}
Chris Lattner9dbb4292009-11-09 23:28:39 +00002674
Duncan Sands12a86f52010-11-14 11:23:23 +00002675Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002676 const TargetData *TD, const TargetLibraryInfo *TLI,
2677 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002678 return ::SimplifyBinOp(Opcode, LHS, RHS, Query (TD, TLI, DT), RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +00002679}
2680
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002681/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2682/// fold the result.
2683static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002684 const Query &Q, unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002685 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002686 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
2687 return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002688}
2689
2690Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002691 const TargetData *TD, const TargetLibraryInfo *TLI,
2692 const DominatorTree *DT) {
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002693 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2694 RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002695}
Chris Lattnere3453782009-11-10 01:08:51 +00002696
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002697static Value *SimplifyCallInst(CallInst *CI, const Query &) {
Dan Gohman71d05032011-11-04 18:32:42 +00002698 // call undef -> undef
2699 if (isa<UndefValue>(CI->getCalledValue()))
2700 return UndefValue::get(CI->getType());
2701
2702 return 0;
2703}
2704
Chris Lattnere3453782009-11-10 01:08:51 +00002705/// SimplifyInstruction - See if we can compute a simplified version of this
2706/// instruction. If not, this returns null.
Duncan Sandseff05812010-11-14 18:36:10 +00002707Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00002708 const TargetLibraryInfo *TLI,
Duncan Sandseff05812010-11-14 18:36:10 +00002709 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +00002710 Value *Result;
2711
Chris Lattnere3453782009-11-10 01:08:51 +00002712 switch (I->getOpcode()) {
2713 default:
Chad Rosier618c1db2011-12-01 03:08:23 +00002714 Result = ConstantFoldInstruction(I, TD, TLI);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002715 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002716 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002717 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2718 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2719 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002720 TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002721 break;
Duncan Sandsfea3b212010-12-15 14:07:39 +00002722 case Instruction::Sub:
2723 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2724 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2725 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002726 TD, TLI, DT);
Duncan Sandsfea3b212010-12-15 14:07:39 +00002727 break;
Duncan Sands82fdab32010-12-21 14:00:22 +00002728 case Instruction::Mul:
Chad Rosier618c1db2011-12-01 03:08:23 +00002729 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands82fdab32010-12-21 14:00:22 +00002730 break;
Duncan Sands593faa52011-01-28 16:51:11 +00002731 case Instruction::SDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002732 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands593faa52011-01-28 16:51:11 +00002733 break;
2734 case Instruction::UDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002735 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands593faa52011-01-28 16:51:11 +00002736 break;
Frits van Bommel1fca2c32011-01-29 15:26:31 +00002737 case Instruction::FDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002738 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Frits van Bommel1fca2c32011-01-29 15:26:31 +00002739 break;
Duncan Sandsf24ed772011-05-02 16:27:02 +00002740 case Instruction::SRem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002741 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002742 break;
2743 case Instruction::URem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002744 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002745 break;
2746 case Instruction::FRem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002747 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002748 break;
Duncan Sandsc43cee32011-01-14 00:37:45 +00002749 case Instruction::Shl:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002750 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2751 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2752 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002753 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002754 break;
2755 case Instruction::LShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002756 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2757 cast<BinaryOperator>(I)->isExact(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002758 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002759 break;
2760 case Instruction::AShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002761 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2762 cast<BinaryOperator>(I)->isExact(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002763 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002764 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002765 case Instruction::And:
Chad Rosier618c1db2011-12-01 03:08:23 +00002766 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002767 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002768 case Instruction::Or:
Chad Rosier618c1db2011-12-01 03:08:23 +00002769 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002770 break;
Duncan Sands2b749872010-11-17 18:52:15 +00002771 case Instruction::Xor:
Chad Rosier618c1db2011-12-01 03:08:23 +00002772 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands2b749872010-11-17 18:52:15 +00002773 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002774 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002775 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002776 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002777 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002778 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002779 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002780 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002781 break;
Chris Lattner04754262010-04-20 05:32:14 +00002782 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002783 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002784 I->getOperand(2), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002785 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002786 case Instruction::GetElementPtr: {
2787 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002788 Result = SimplifyGEPInst(Ops, TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002789 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002790 }
Duncan Sandsdabc2802011-09-05 06:52:48 +00002791 case Instruction::InsertValue: {
2792 InsertValueInst *IV = cast<InsertValueInst>(I);
2793 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
2794 IV->getInsertedValueOperand(),
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002795 IV->getIndices(), TD, TLI, DT);
Duncan Sandsdabc2802011-09-05 06:52:48 +00002796 break;
2797 }
Duncan Sandscd6636c2010-11-14 13:30:18 +00002798 case Instruction::PHI:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002799 Result = SimplifyPHINode(cast<PHINode>(I), Query (TD, TLI, DT));
Duncan Sandsd261dc62010-11-17 08:35:29 +00002800 break;
Dan Gohman71d05032011-11-04 18:32:42 +00002801 case Instruction::Call:
Duncan Sands0aa85eb2012-03-13 11:42:19 +00002802 Result = SimplifyCallInst(cast<CallInst>(I), Query (TD, TLI, DT));
Dan Gohman71d05032011-11-04 18:32:42 +00002803 break;
Duncan Sandsbd0fe562012-03-13 14:07:05 +00002804 case Instruction::Trunc:
2805 Result = SimplifyTruncInst(I->getOperand(0), I->getType(), TD, TLI, DT);
2806 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002807 }
Duncan Sandsd261dc62010-11-17 08:35:29 +00002808
2809 /// If called on unreachable code, the above logic may report that the
2810 /// instruction simplified to itself. Make life easier for users by
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00002811 /// detecting that case here, returning a safe value instead.
2812 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnere3453782009-11-10 01:08:51 +00002813}
2814
Chris Lattner40d8c282009-11-10 22:26:15 +00002815/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
2816/// delete the From instruction. In addition to a basic RAUW, this does a
2817/// recursive simplification of the newly formed instructions. This catches
2818/// things where one simplification exposes other opportunities. This only
2819/// simplifies and deletes scalar operations, it does not change the CFG.
2820///
2821void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
Duncan Sandseff05812010-11-14 18:36:10 +00002822 const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00002823 const TargetLibraryInfo *TLI,
Duncan Sandseff05812010-11-14 18:36:10 +00002824 const DominatorTree *DT) {
Chris Lattner40d8c282009-11-10 22:26:15 +00002825 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
Duncan Sands12a86f52010-11-14 11:23:23 +00002826
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002827 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
2828 // we can know if it gets deleted out from under us or replaced in a
2829 // recursive simplification.
Chris Lattner40d8c282009-11-10 22:26:15 +00002830 WeakVH FromHandle(From);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002831 WeakVH ToHandle(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00002832
Chris Lattner40d8c282009-11-10 22:26:15 +00002833 while (!From->use_empty()) {
2834 // Update the instruction to use the new value.
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002835 Use &TheUse = From->use_begin().getUse();
2836 Instruction *User = cast<Instruction>(TheUse.getUser());
2837 TheUse = To;
2838
2839 // Check to see if the instruction can be folded due to the operand
2840 // replacement. For example changing (or X, Y) into (or X, -1) can replace
2841 // the 'or' with -1.
2842 Value *SimplifiedVal;
2843 {
2844 // Sanity check to make sure 'User' doesn't dangle across
2845 // SimplifyInstruction.
2846 AssertingVH<> UserHandle(User);
Duncan Sands12a86f52010-11-14 11:23:23 +00002847
Chad Rosier618c1db2011-12-01 03:08:23 +00002848 SimplifiedVal = SimplifyInstruction(User, TD, TLI, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002849 if (SimplifiedVal == 0) continue;
Chris Lattner40d8c282009-11-10 22:26:15 +00002850 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002851
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002852 // Recursively simplify this user to the new value.
Chad Rosier618c1db2011-12-01 03:08:23 +00002853 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, TLI, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002854 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
2855 To = ToHandle;
Duncan Sands12a86f52010-11-14 11:23:23 +00002856
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002857 assert(ToHandle && "To value deleted by recursive simplification?");
Duncan Sands12a86f52010-11-14 11:23:23 +00002858
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002859 // If the recursive simplification ended up revisiting and deleting
2860 // 'From' then we're done.
2861 if (From == 0)
2862 return;
Chris Lattner40d8c282009-11-10 22:26:15 +00002863 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002864
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002865 // If 'From' has value handles referring to it, do a real RAUW to update them.
2866 From->replaceAllUsesWith(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00002867
Chris Lattner40d8c282009-11-10 22:26:15 +00002868 From->eraseFromParent();
2869}