blob: cd97dfb197d965aab2f8a4a19df898174893a1a7 [file] [log] [blame]
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001//===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements routines for folding instructions into simpler forms
Duncan Sands4cd2ad12010-11-23 10:50:08 +000011// that do not require creating new instructions. This does constant folding
12// ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
13// returning a constant ("and i32 %x, 0" -> "0") or an already existing value
Duncan Sandsee9a2e32010-12-20 14:47:04 +000014// ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been
15// simplified: This is usually true and assuming it simplifies the logic (if
16// they have not been simplified then results are correct but maybe suboptimal).
Chris Lattner9f3c25a2009-11-09 22:57:59 +000017//
18//===----------------------------------------------------------------------===//
19
Duncan Sandsa3c44a52010-12-22 09:40:51 +000020#define DEBUG_TYPE "instsimplify"
Chandler Carruthfc72ae62012-03-12 11:19:31 +000021#include "llvm/GlobalAlias.h"
Jay Foad562b84b2011-04-11 09:35:34 +000022#include "llvm/Operator.h"
Duncan Sandsa3c44a52010-12-22 09:40:51 +000023#include "llvm/ADT/Statistic.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000024#include "llvm/Analysis/InstructionSimplify.h"
Nick Lewyckyf7087ea2012-02-26 02:09:49 +000025#include "llvm/Analysis/AliasAnalysis.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000026#include "llvm/Analysis/ConstantFolding.h"
Duncan Sands18450092010-11-16 12:16:38 +000027#include "llvm/Analysis/Dominators.h"
Duncan Sandsd70d1a52011-01-25 09:38:29 +000028#include "llvm/Analysis/ValueTracking.h"
Nick Lewycky3a73e342011-03-04 07:00:57 +000029#include "llvm/Support/ConstantRange.h"
Chandler Carruthfc72ae62012-03-12 11:19:31 +000030#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerd06094f2009-11-10 00:55:12 +000031#include "llvm/Support/PatternMatch.h"
Duncan Sands18450092010-11-16 12:16:38 +000032#include "llvm/Support/ValueHandle.h"
Duncan Sandse60d79f2010-11-21 13:53:09 +000033#include "llvm/Target/TargetData.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000034using namespace llvm;
Chris Lattnerd06094f2009-11-10 00:55:12 +000035using namespace llvm::PatternMatch;
Chris Lattner9f3c25a2009-11-09 22:57:59 +000036
Chris Lattner81a0dc92011-02-09 17:15:04 +000037enum { RecursionLimit = 3 };
Duncan Sandsa74a58c2010-11-10 18:23:01 +000038
Duncan Sandsa3c44a52010-12-22 09:40:51 +000039STATISTIC(NumExpand, "Number of expansions");
40STATISTIC(NumFactor , "Number of factorizations");
41STATISTIC(NumReassoc, "Number of reassociations");
42
Duncan Sands82fdab32010-12-21 14:00:22 +000043static Value *SimplifyAndInst(Value *, Value *, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +000044 const TargetLibraryInfo *, const DominatorTree *,
45 unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000046static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +000047 const TargetLibraryInfo *, const DominatorTree *,
48 unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000049static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +000050 const TargetLibraryInfo *, const DominatorTree *,
51 unsigned);
Duncan Sands82fdab32010-12-21 14:00:22 +000052static Value *SimplifyOrInst(Value *, Value *, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +000053 const TargetLibraryInfo *, const DominatorTree *,
54 unsigned);
Duncan Sands82fdab32010-12-21 14:00:22 +000055static Value *SimplifyXorInst(Value *, Value *, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +000056 const TargetLibraryInfo *, const DominatorTree *,
57 unsigned);
Duncan Sands18450092010-11-16 12:16:38 +000058
Duncan Sandsf56138d2011-07-26 15:03:53 +000059/// getFalse - For a boolean type, or a vector of boolean type, return false, or
60/// a vector with every element false, as appropriate for the type.
61static Constant *getFalse(Type *Ty) {
Nick Lewycky66d004e2011-12-01 02:39:36 +000062 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsf56138d2011-07-26 15:03:53 +000063 "Expected i1 type or a vector of i1!");
64 return Constant::getNullValue(Ty);
65}
66
67/// getTrue - For a boolean type, or a vector of boolean type, return true, or
68/// a vector with every element true, as appropriate for the type.
69static Constant *getTrue(Type *Ty) {
Nick Lewycky66d004e2011-12-01 02:39:36 +000070 assert(Ty->getScalarType()->isIntegerTy(1) &&
Duncan Sandsf56138d2011-07-26 15:03:53 +000071 "Expected i1 type or a vector of i1!");
72 return Constant::getAllOnesValue(Ty);
73}
74
Duncan Sands6dc9e2b2011-10-30 19:56:36 +000075/// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
76static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
77 Value *RHS) {
78 CmpInst *Cmp = dyn_cast<CmpInst>(V);
79 if (!Cmp)
80 return false;
81 CmpInst::Predicate CPred = Cmp->getPredicate();
82 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
83 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
84 return true;
85 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
86 CRHS == LHS;
87}
88
Duncan Sands18450092010-11-16 12:16:38 +000089/// ValueDominatesPHI - Does the given value dominate the specified phi node?
90static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
91 Instruction *I = dyn_cast<Instruction>(V);
92 if (!I)
93 // Arguments and constants dominate all instructions.
94 return true;
95
96 // If we have a DominatorTree then do a precise test.
97 if (DT)
Rafael Espindola8c727f92012-02-26 01:50:14 +000098 return !DT->isReachableFromEntry(P->getParent()) ||
99 !DT->isReachableFromEntry(I->getParent()) || DT->dominates(I, P);
Duncan Sands18450092010-11-16 12:16:38 +0000100
101 // Otherwise, if the instruction is in the entry block, and is not an invoke,
102 // then it obviously dominates all phi nodes.
103 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
104 !isa<InvokeInst>(I))
105 return true;
106
107 return false;
108}
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000109
Duncan Sands3421d902010-12-21 13:32:22 +0000110/// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
111/// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
112/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
113/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
114/// Returns the simplified value, or null if no simplification was performed.
115static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Benjamin Kramere21083a2010-12-28 13:52:52 +0000116 unsigned OpcToExpand, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000117 const TargetLibraryInfo *TLI, const DominatorTree *DT,
118 unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000119 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000120 // Recursion is always used, so bail out at once if we already hit the limit.
121 if (!MaxRecurse--)
122 return 0;
123
124 // Check whether the expression has the form "(A op' B) op C".
125 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
126 if (Op0->getOpcode() == OpcodeToExpand) {
127 // It does! Try turning it into "(A op C) op' (B op C)".
128 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
129 // Do "A op C" and "B op C" both simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000130 if (Value *L = SimplifyBinOp(Opcode, A, C, TD, TLI, DT, MaxRecurse))
131 if (Value *R = SimplifyBinOp(Opcode, B, C, TD, TLI, DT, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000132 // They do! Return "L op' R" if it simplifies or is already available.
133 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000134 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
135 && L == B && R == A)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000136 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000137 return LHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000138 }
Duncan Sands3421d902010-12-21 13:32:22 +0000139 // Otherwise return "L op' R" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000140 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, TLI, DT,
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000141 MaxRecurse)) {
142 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000143 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000144 }
Duncan Sands3421d902010-12-21 13:32:22 +0000145 }
146 }
147
148 // Check whether the expression has the form "A op (B op' C)".
149 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
150 if (Op1->getOpcode() == OpcodeToExpand) {
151 // It does! Try turning it into "(A op B) op' (A op C)".
152 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
153 // Do "A op B" and "A op C" both simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000154 if (Value *L = SimplifyBinOp(Opcode, A, B, TD, TLI, DT, MaxRecurse))
155 if (Value *R = SimplifyBinOp(Opcode, A, C, TD, TLI, DT, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000156 // They do! Return "L op' R" if it simplifies or is already available.
157 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000158 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
159 && L == C && R == B)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000160 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000161 return RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000162 }
Duncan Sands3421d902010-12-21 13:32:22 +0000163 // Otherwise return "L op' R" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000164 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, TLI, DT,
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000165 MaxRecurse)) {
166 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000167 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000168 }
Duncan Sands3421d902010-12-21 13:32:22 +0000169 }
170 }
171
172 return 0;
173}
174
175/// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
176/// using the operation OpCodeToExtract. For example, when Opcode is Add and
177/// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
178/// Returns the simplified value, or null if no simplification was performed.
179static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +0000180 unsigned OpcToExtract, const TargetData *TD,
181 const TargetLibraryInfo *TLI,
182 const DominatorTree *DT,
183 unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000184 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
Duncan Sands3421d902010-12-21 13:32:22 +0000185 // Recursion is always used, so bail out at once if we already hit the limit.
186 if (!MaxRecurse--)
187 return 0;
188
189 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
190 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
191
192 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
193 !Op1 || Op1->getOpcode() != OpcodeToExtract)
194 return 0;
195
196 // The expression has the form "(A op' B) op (C op' D)".
Duncan Sands82fdab32010-12-21 14:00:22 +0000197 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
198 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
Duncan Sands3421d902010-12-21 13:32:22 +0000199
200 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
201 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
202 // commutative case, "(A op' B) op (C op' A)"?
Duncan Sands124708d2011-01-01 20:08:02 +0000203 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
204 Value *DD = A == C ? D : C;
Duncan Sands3421d902010-12-21 13:32:22 +0000205 // Form "A op' (B op DD)" if it simplifies completely.
206 // Does "B op DD" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000207 if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, TLI, DT, MaxRecurse)) {
Duncan Sands3421d902010-12-21 13:32:22 +0000208 // It does! Return "A op' V" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000209 // If V equals B then "A op' V" is just the LHS. If V equals DD then
210 // "A op' V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000211 if (V == B || V == DD) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000212 ++NumFactor;
Duncan Sands124708d2011-01-01 20:08:02 +0000213 return V == B ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000214 }
Duncan Sands3421d902010-12-21 13:32:22 +0000215 // Otherwise return "A op' V" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000216 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, TLI, DT,
217 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?
Chad Rosier618c1db2011-12-01 03:08:23 +0000231 if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, TLI, DT, 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.
Chad Rosier618c1db2011-12-01 03:08:23 +0000240 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, TLI, DT,
241 MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000242 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000243 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000244 }
Duncan Sands3421d902010-12-21 13:32:22 +0000245 }
246 }
247
248 return 0;
249}
250
251/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
252/// operations. Returns the simpler value, or null if none was found.
Benjamin Kramere21083a2010-12-28 13:52:52 +0000253static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sands566edb02010-12-21 08:49:00 +0000254 const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000255 const TargetLibraryInfo *TLI,
Duncan Sands566edb02010-12-21 08:49:00 +0000256 const DominatorTree *DT,
257 unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000258 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands566edb02010-12-21 08:49:00 +0000259 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
260
261 // Recursion is always used, so bail out at once if we already hit the limit.
262 if (!MaxRecurse--)
263 return 0;
264
265 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
266 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
267
268 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
269 if (Op0 && Op0->getOpcode() == Opcode) {
270 Value *A = Op0->getOperand(0);
271 Value *B = Op0->getOperand(1);
272 Value *C = RHS;
273
274 // Does "B op C" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000275 if (Value *V = SimplifyBinOp(Opcode, B, C, TD, TLI, DT, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000276 // It does! Return "A op V" if it simplifies or is already available.
277 // If V equals B then "A op V" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000278 if (V == B) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000279 // Otherwise return "A op V" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000280 if (Value *W = SimplifyBinOp(Opcode, A, V, TD, TLI, DT, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000281 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000282 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000283 }
Duncan Sands566edb02010-12-21 08:49:00 +0000284 }
285 }
286
287 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
288 if (Op1 && Op1->getOpcode() == Opcode) {
289 Value *A = LHS;
290 Value *B = Op1->getOperand(0);
291 Value *C = Op1->getOperand(1);
292
293 // Does "A op B" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000294 if (Value *V = SimplifyBinOp(Opcode, A, B, TD, TLI, DT, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000295 // It does! Return "V op C" if it simplifies or is already available.
296 // If V equals B then "V op C" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000297 if (V == B) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000298 // Otherwise return "V op C" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000299 if (Value *W = SimplifyBinOp(Opcode, V, C, TD, TLI, DT, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000300 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000301 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000302 }
Duncan Sands566edb02010-12-21 08:49:00 +0000303 }
304 }
305
306 // The remaining transforms require commutativity as well as associativity.
307 if (!Instruction::isCommutative(Opcode))
308 return 0;
309
310 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
311 if (Op0 && Op0->getOpcode() == Opcode) {
312 Value *A = Op0->getOperand(0);
313 Value *B = Op0->getOperand(1);
314 Value *C = RHS;
315
316 // Does "C op A" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000317 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, TLI, DT, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000318 // It does! Return "V op B" if it simplifies or is already available.
319 // If V equals A then "V op B" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000320 if (V == A) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000321 // Otherwise return "V op B" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000322 if (Value *W = SimplifyBinOp(Opcode, V, B, TD, TLI, DT, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000323 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000324 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000325 }
Duncan Sands566edb02010-12-21 08:49:00 +0000326 }
327 }
328
329 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
330 if (Op1 && Op1->getOpcode() == Opcode) {
331 Value *A = LHS;
332 Value *B = Op1->getOperand(0);
333 Value *C = Op1->getOperand(1);
334
335 // Does "C op A" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000336 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, TLI, DT, MaxRecurse)) {
Duncan Sands566edb02010-12-21 08:49:00 +0000337 // It does! Return "B op V" if it simplifies or is already available.
338 // If V equals C then "B op V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000339 if (V == C) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000340 // Otherwise return "B op V" if it simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000341 if (Value *W = SimplifyBinOp(Opcode, B, V, TD, TLI, DT, MaxRecurse)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000342 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000343 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000344 }
Duncan Sands566edb02010-12-21 08:49:00 +0000345 }
346 }
347
348 return 0;
349}
350
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000351/// ThreadBinOpOverSelect - In the case of a binary operation with a select
352/// instruction as an operand, try to simplify the binop by seeing whether
353/// evaluating it on both branches of the select results in the same value.
354/// Returns the common value if so, otherwise returns null.
355static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000356 const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000357 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +0000358 const DominatorTree *DT,
359 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000360 // Recursion is always used, so bail out at once if we already hit the limit.
361 if (!MaxRecurse--)
362 return 0;
363
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000364 SelectInst *SI;
365 if (isa<SelectInst>(LHS)) {
366 SI = cast<SelectInst>(LHS);
367 } else {
368 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
369 SI = cast<SelectInst>(RHS);
370 }
371
372 // Evaluate the BinOp on the true and false branches of the select.
373 Value *TV;
374 Value *FV;
375 if (SI == LHS) {
Chad Rosier618c1db2011-12-01 03:08:23 +0000376 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, TLI, DT, MaxRecurse);
377 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, TLI, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000378 } else {
Chad Rosier618c1db2011-12-01 03:08:23 +0000379 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, TLI, DT, MaxRecurse);
380 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, TLI, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000381 }
382
Duncan Sands7cf85e72011-01-01 16:12:09 +0000383 // If they simplified to the same value, then return the common value.
Duncan Sands124708d2011-01-01 20:08:02 +0000384 // If they both failed to simplify then return null.
385 if (TV == FV)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000386 return TV;
387
388 // If one branch simplified to undef, return the other one.
389 if (TV && isa<UndefValue>(TV))
390 return FV;
391 if (FV && isa<UndefValue>(FV))
392 return TV;
393
394 // If applying the operation did not change the true and false select values,
395 // then the result of the binop is the select itself.
Duncan Sands124708d2011-01-01 20:08:02 +0000396 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000397 return SI;
398
399 // If one branch simplified and the other did not, and the simplified
400 // value is equal to the unsimplified one, return the simplified value.
401 // For example, select (cond, X, X & Z) & Z -> X & Z.
402 if ((FV && !TV) || (TV && !FV)) {
403 // Check that the simplified value has the form "X op Y" where "op" is the
404 // same as the original operation.
405 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
406 if (Simplified && Simplified->getOpcode() == Opcode) {
407 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
408 // We already know that "op" is the same as for the simplified value. See
409 // if the operands match too. If so, return the simplified value.
410 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
411 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
412 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands124708d2011-01-01 20:08:02 +0000413 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
414 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000415 return Simplified;
416 if (Simplified->isCommutative() &&
Duncan Sands124708d2011-01-01 20:08:02 +0000417 Simplified->getOperand(1) == UnsimplifiedLHS &&
418 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000419 return Simplified;
420 }
421 }
422
423 return 0;
424}
425
426/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
427/// try to simplify the comparison by seeing whether both branches of the select
428/// result in the same value. Returns the common value if so, otherwise returns
429/// null.
430static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000431 Value *RHS, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000432 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +0000433 const DominatorTree *DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000434 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000435 // Recursion is always used, so bail out at once if we already hit the limit.
436 if (!MaxRecurse--)
437 return 0;
438
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000439 // Make sure the select is on the LHS.
440 if (!isa<SelectInst>(LHS)) {
441 std::swap(LHS, RHS);
442 Pred = CmpInst::getSwappedPredicate(Pred);
443 }
444 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
445 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000446 Value *Cond = SI->getCondition();
447 Value *TV = SI->getTrueValue();
448 Value *FV = SI->getFalseValue();
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000449
Duncan Sands50ca4d32011-02-03 09:37:39 +0000450 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000451 // Does "cmp TV, RHS" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000452 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, TD, TLI, DT, MaxRecurse);
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000453 if (TCmp == Cond) {
454 // It not only simplified, it simplified to the select condition. Replace
455 // it with 'true'.
456 TCmp = getTrue(Cond->getType());
457 } else if (!TCmp) {
458 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
459 // condition then we can replace it with 'true'. Otherwise give up.
460 if (!isSameCompare(Cond, Pred, TV, RHS))
461 return 0;
462 TCmp = getTrue(Cond->getType());
Duncan Sands50ca4d32011-02-03 09:37:39 +0000463 }
464
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000465 // Does "cmp FV, RHS" simplify?
Chad Rosier618c1db2011-12-01 03:08:23 +0000466 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, TD, TLI, DT, MaxRecurse);
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000467 if (FCmp == Cond) {
468 // It not only simplified, it simplified to the select condition. Replace
469 // it with 'false'.
470 FCmp = getFalse(Cond->getType());
471 } else if (!FCmp) {
472 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
473 // condition then we can replace it with 'false'. Otherwise give up.
474 if (!isSameCompare(Cond, Pred, FV, RHS))
475 return 0;
476 FCmp = getFalse(Cond->getType());
477 }
478
479 // If both sides simplified to the same value, then use it as the result of
480 // the original comparison.
481 if (TCmp == FCmp)
482 return TCmp;
Duncan Sandsaa97bb52012-02-10 14:31:24 +0000483
484 // The remaining cases only make sense if the select condition has the same
485 // type as the result of the comparison, so bail out if this is not so.
486 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
487 return 0;
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000488 // If the false value simplified to false, then the result of the compare
489 // is equal to "Cond && TCmp". This also catches the case when the false
490 // value simplified to false and the true value to true, returning "Cond".
491 if (match(FCmp, m_Zero()))
Chad Rosier618c1db2011-12-01 03:08:23 +0000492 if (Value *V = SimplifyAndInst(Cond, TCmp, TD, TLI, DT, MaxRecurse))
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000493 return V;
494 // If the true value simplified to true, then the result of the compare
495 // is equal to "Cond || FCmp".
496 if (match(TCmp, m_One()))
Chad Rosier618c1db2011-12-01 03:08:23 +0000497 if (Value *V = SimplifyOrInst(Cond, FCmp, TD, TLI, DT, MaxRecurse))
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000498 return V;
499 // Finally, if the false value simplified to true and the true value to
500 // false, then the result of the compare is equal to "!Cond".
501 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
502 if (Value *V =
503 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
Chad Rosier618c1db2011-12-01 03:08:23 +0000504 TD, TLI, DT, MaxRecurse))
Duncan Sands6dc9e2b2011-10-30 19:56:36 +0000505 return V;
506
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000507 return 0;
508}
509
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000510/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
511/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
512/// it on the incoming phi values yields the same result for every value. If so
513/// returns the common value, otherwise returns null.
514static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +0000515 const TargetData *TD,
516 const TargetLibraryInfo *TLI,
517 const DominatorTree *DT,
Duncan Sands18450092010-11-16 12:16:38 +0000518 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000519 // Recursion is always used, so bail out at once if we already hit the limit.
520 if (!MaxRecurse--)
521 return 0;
522
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000523 PHINode *PI;
524 if (isa<PHINode>(LHS)) {
525 PI = cast<PHINode>(LHS);
Duncan Sands18450092010-11-16 12:16:38 +0000526 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
527 if (!ValueDominatesPHI(RHS, PI, DT))
528 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000529 } else {
530 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
531 PI = cast<PHINode>(RHS);
Duncan Sands18450092010-11-16 12:16:38 +0000532 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
533 if (!ValueDominatesPHI(LHS, PI, DT))
534 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000535 }
536
537 // Evaluate the BinOp on the incoming phi values.
538 Value *CommonValue = 0;
539 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000540 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000541 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000542 if (Incoming == PI) continue;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000543 Value *V = PI == LHS ?
Chad Rosier618c1db2011-12-01 03:08:23 +0000544 SimplifyBinOp(Opcode, Incoming, RHS, TD, TLI, DT, MaxRecurse) :
545 SimplifyBinOp(Opcode, LHS, Incoming, TD, TLI, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000546 // If the operation failed to simplify, or simplified to a different value
547 // to previously, then give up.
548 if (!V || (CommonValue && V != CommonValue))
549 return 0;
550 CommonValue = V;
551 }
552
553 return CommonValue;
554}
555
556/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
557/// try to simplify the comparison by seeing whether comparing with all of the
558/// incoming phi values yields the same result every time. If so returns the
559/// common result, otherwise returns null.
560static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +0000561 const TargetData *TD,
562 const TargetLibraryInfo *TLI,
563 const DominatorTree *DT,
Duncan Sands18450092010-11-16 12:16:38 +0000564 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000565 // Recursion is always used, so bail out at once if we already hit the limit.
566 if (!MaxRecurse--)
567 return 0;
568
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000569 // Make sure the phi is on the LHS.
570 if (!isa<PHINode>(LHS)) {
571 std::swap(LHS, RHS);
572 Pred = CmpInst::getSwappedPredicate(Pred);
573 }
574 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
575 PHINode *PI = cast<PHINode>(LHS);
576
Duncan Sands18450092010-11-16 12:16:38 +0000577 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
578 if (!ValueDominatesPHI(RHS, PI, DT))
579 return 0;
580
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000581 // Evaluate the BinOp on the incoming phi values.
582 Value *CommonValue = 0;
583 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000584 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000585 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000586 if (Incoming == PI) continue;
Chad Rosier618c1db2011-12-01 03:08:23 +0000587 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, TLI, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000588 // If the operation failed to simplify, or simplified to a different value
589 // to previously, then give up.
590 if (!V || (CommonValue && V != CommonValue))
591 return 0;
592 CommonValue = V;
593 }
594
595 return CommonValue;
596}
597
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000598/// SimplifyAddInst - Given operands for an Add, see if we can
599/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000600static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +0000601 const TargetData *TD,
602 const TargetLibraryInfo *TLI,
603 const DominatorTree *DT,
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000604 unsigned MaxRecurse) {
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000605 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
606 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
607 Constant *Ops[] = { CLHS, CRHS };
608 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
Chad Rosier618c1db2011-12-01 03:08:23 +0000609 Ops, TD, TLI);
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000610 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000611
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000612 // Canonicalize the constant to the RHS.
613 std::swap(Op0, Op1);
614 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000615
Duncan Sandsfea3b212010-12-15 14:07:39 +0000616 // X + undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000617 if (match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000618 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000619
Duncan Sandsfea3b212010-12-15 14:07:39 +0000620 // X + 0 -> X
621 if (match(Op1, m_Zero()))
622 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000623
Duncan Sandsfea3b212010-12-15 14:07:39 +0000624 // X + (Y - X) -> Y
625 // (Y - X) + X -> Y
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000626 // Eg: X + -X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000627 Value *Y = 0;
628 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
629 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000630 return Y;
631
632 // X + ~X -> -1 since ~X = -X-1
Duncan Sands124708d2011-01-01 20:08:02 +0000633 if (match(Op0, m_Not(m_Specific(Op1))) ||
634 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000635 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands87689cf2010-11-19 09:20:39 +0000636
Duncan Sands82fdab32010-12-21 14:00:22 +0000637 /// i1 add -> xor.
Duncan Sands75d289e2010-12-21 14:48:48 +0000638 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Chad Rosier618c1db2011-12-01 03:08:23 +0000639 if (Value *V = SimplifyXorInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000640 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000641
Duncan Sands566edb02010-12-21 08:49:00 +0000642 // Try some generic simplifications for associative operations.
Chad Rosier618c1db2011-12-01 03:08:23 +0000643 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, TLI, DT,
Duncan Sands566edb02010-12-21 08:49:00 +0000644 MaxRecurse))
645 return V;
646
Duncan Sands3421d902010-12-21 13:32:22 +0000647 // Mul distributes over Add. Try some generic simplifications based on this.
648 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
Chad Rosier618c1db2011-12-01 03:08:23 +0000649 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +0000650 return V;
651
Duncan Sands87689cf2010-11-19 09:20:39 +0000652 // Threading Add over selects and phi nodes is pointless, so don't bother.
653 // Threading over the select in "A + select(cond, B, C)" means evaluating
654 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
655 // only if B and C are equal. If B and C are equal then (since we assume
656 // that operands have already been simplified) "select(cond, B, C)" should
657 // have been simplified to the common value of B and C already. Analysing
658 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
659 // for threading over phi nodes.
660
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000661 return 0;
662}
663
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000664Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +0000665 const TargetData *TD, const TargetLibraryInfo *TLI,
666 const DominatorTree *DT) {
667 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000668}
669
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000670/// \brief Compute the constant integer offset a GEP represents.
671///
672/// Given a getelementptr instruction/constantexpr, form a constant expression
673/// which computes the offset from the base pointer (without adding in the base
674/// pointer).
675static Constant *computeGEPOffset(const TargetData &TD, GEPOperator *GEP) {
676 Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
677 Constant *Result = Constant::getNullValue(IntPtrTy);
678
679 // If the GEP is inbounds, we know that none of the addressing operations will
680 // overflow in an unsigned sense.
681 bool IsInBounds = GEP->isInBounds();
682
683 // Build a mask for high order bits.
684 unsigned IntPtrWidth = TD.getPointerSizeInBits();
685 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
686
687 gep_type_iterator GTI = gep_type_begin(GEP);
688 for (User::op_iterator I = GEP->op_begin() + 1, E = GEP->op_end(); I != E;
689 ++I, ++GTI) {
690 ConstantInt *OpC = dyn_cast<ConstantInt>(*I);
691 if (!OpC) return 0;
692 if (OpC->isZero()) continue;
693
694 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
695
696 // Handle a struct index, which adds its field offset to the pointer.
697 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
698 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
699
700 if (Size)
701 Result = ConstantExpr::getAdd(Result, ConstantInt::get(IntPtrTy, Size));
702 continue;
703 }
704
705 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
706 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
707 Scale = ConstantExpr::getMul(OC, Scale, IsInBounds/*NUW*/);
708 Result = ConstantExpr::getAdd(Result, Scale);
709 }
710 return Result;
711}
712
713/// \brief Compute the base pointer and cumulative constant offsets for V.
714///
715/// This strips all constant offsets off of V, leaving it the base pointer, and
716/// accumulates the total constant offset applied in the returned constant. It
717/// returns 0 if V is not a pointer, and returns the constant '0' if there are
718/// no constant offsets applied.
719static Constant *stripAndComputeConstantOffsets(const TargetData &TD,
720 Value *&V) {
721 if (!V->getType()->isPointerTy())
722 return 0;
723
724 Type *IntPtrTy = TD.getIntPtrType(V->getContext());
725 Constant *Result = Constant::getNullValue(IntPtrTy);
726
727 // Even though we don't look through PHI nodes, we could be called on an
728 // instruction in an unreachable block, which may be on a cycle.
729 SmallPtrSet<Value *, 4> Visited;
730 Visited.insert(V);
731 do {
732 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
733 Constant *Offset = computeGEPOffset(TD, GEP);
734 if (!Offset)
735 break;
736 Result = ConstantExpr::getAdd(Result, Offset);
737 V = GEP->getPointerOperand();
738 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
739 V = cast<Operator>(V)->getOperand(0);
740 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
741 if (GA->mayBeOverridden())
742 break;
743 V = GA->getAliasee();
744 } else {
745 break;
746 }
747 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
748 } while (Visited.insert(V));
749
750 return Result;
751}
752
753/// \brief Compute the constant difference between two pointer values.
754/// If the difference is not a constant, returns zero.
755static Constant *computePointerDifference(const TargetData &TD,
756 Value *LHS, Value *RHS) {
757 Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
758 if (!LHSOffset)
759 return 0;
760 Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
761 if (!RHSOffset)
762 return 0;
763
764 // If LHS and RHS are not related via constant offsets to the same base
765 // value, there is nothing we can do here.
766 if (LHS != RHS)
767 return 0;
768
769 // Otherwise, the difference of LHS - RHS can be computed as:
770 // LHS - RHS
771 // = (LHSOffset + Base) - (RHSOffset + Base)
772 // = LHSOffset - RHSOffset
773 return ConstantExpr::getSub(LHSOffset, RHSOffset);
774}
775
Duncan Sandsfea3b212010-12-15 14:07:39 +0000776/// SimplifySubInst - Given operands for a Sub, see if we can
777/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000778static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +0000779 const TargetData *TD,
780 const TargetLibraryInfo *TLI,
781 const DominatorTree *DT,
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000782 unsigned MaxRecurse) {
Duncan Sandsfea3b212010-12-15 14:07:39 +0000783 if (Constant *CLHS = dyn_cast<Constant>(Op0))
784 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
785 Constant *Ops[] = { CLHS, CRHS };
786 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
Chad Rosier618c1db2011-12-01 03:08:23 +0000787 Ops, TD, TLI);
Duncan Sandsfea3b212010-12-15 14:07:39 +0000788 }
789
790 // X - undef -> undef
791 // undef - X -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000792 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000793 return UndefValue::get(Op0->getType());
794
795 // X - 0 -> X
796 if (match(Op1, m_Zero()))
797 return Op0;
798
799 // X - X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000800 if (Op0 == Op1)
Duncan Sandsfea3b212010-12-15 14:07:39 +0000801 return Constant::getNullValue(Op0->getType());
802
Duncan Sandsfe02c692011-01-18 09:24:58 +0000803 // (X*2) - X -> X
804 // (X<<1) - X -> X
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000805 Value *X = 0;
Duncan Sandsfe02c692011-01-18 09:24:58 +0000806 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
807 match(Op0, m_Shl(m_Specific(Op1), m_One())))
808 return Op1;
809
Chandler Carruthfc72ae62012-03-12 11:19:31 +0000810 if (TD) {
811 Value *LHSOp, *RHSOp;
812 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
813 match(Op1, m_PtrToInt(m_Value(RHSOp))))
814 if (Constant *Result = computePointerDifference(*TD, LHSOp, RHSOp))
815 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
816
817 // trunc(p)-trunc(q) -> trunc(p-q)
818 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
819 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
820 if (Constant *Result = computePointerDifference(*TD, LHSOp, RHSOp))
821 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
822 }
823
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000824 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
825 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
826 Value *Y = 0, *Z = Op1;
827 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
828 // See if "V === Y - Z" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000829 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000830 // It does! Now see if "X + V" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000831 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, TD, TLI, DT,
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000832 MaxRecurse-1)) {
833 // It does, we successfully reassociated!
834 ++NumReassoc;
835 return W;
836 }
837 // See if "V === X - Z" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000838 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000839 // It does! Now see if "Y + V" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000840 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, TD, TLI, DT,
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000841 MaxRecurse-1)) {
842 // It does, we successfully reassociated!
843 ++NumReassoc;
844 return W;
845 }
846 }
Duncan Sands82fdab32010-12-21 14:00:22 +0000847
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000848 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
849 // For example, X - (X + 1) -> -1
850 X = Op0;
851 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
852 // See if "V === X - Y" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000853 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000854 // It does! Now see if "V - Z" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000855 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, TD, TLI, DT,
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000856 MaxRecurse-1)) {
857 // It does, we successfully reassociated!
858 ++NumReassoc;
859 return W;
860 }
861 // See if "V === X - Z" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000862 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000863 // It does! Now see if "V - Y" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000864 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, TD, TLI, DT,
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000865 MaxRecurse-1)) {
866 // It does, we successfully reassociated!
867 ++NumReassoc;
868 return W;
869 }
870 }
871
872 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
873 // For example, X - (X - Y) -> Y.
874 Z = Op0;
Duncan Sandsc087e202011-01-14 15:26:10 +0000875 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
876 // See if "V === Z - X" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000877 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000878 // It does! Now see if "V + Y" simplifies.
Chad Rosier618c1db2011-12-01 03:08:23 +0000879 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, TD, TLI, DT,
Duncan Sandsc087e202011-01-14 15:26:10 +0000880 MaxRecurse-1)) {
881 // It does, we successfully reassociated!
882 ++NumReassoc;
883 return W;
884 }
885
Duncan Sands3421d902010-12-21 13:32:22 +0000886 // Mul distributes over Sub. Try some generic simplifications based on this.
887 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
Chad Rosier618c1db2011-12-01 03:08:23 +0000888 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +0000889 return V;
890
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000891 // i1 sub -> xor.
892 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Chad Rosier618c1db2011-12-01 03:08:23 +0000893 if (Value *V = SimplifyXorInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000894 return V;
895
Duncan Sandsfea3b212010-12-15 14:07:39 +0000896 // Threading Sub over selects and phi nodes is pointless, so don't bother.
897 // Threading over the select in "A - select(cond, B, C)" means evaluating
898 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
899 // only if B and C are equal. If B and C are equal then (since we assume
900 // that operands have already been simplified) "select(cond, B, C)" should
901 // have been simplified to the common value of B and C already. Analysing
902 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
903 // for threading over phi nodes.
904
905 return 0;
906}
907
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000908Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +0000909 const TargetData *TD,
910 const TargetLibraryInfo *TLI,
911 const DominatorTree *DT) {
912 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000913}
914
Duncan Sands82fdab32010-12-21 14:00:22 +0000915/// SimplifyMulInst - Given operands for a Mul, see if we can
916/// fold the result. If not, this returns null.
917static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000918 const TargetLibraryInfo *TLI,
Duncan Sands82fdab32010-12-21 14:00:22 +0000919 const DominatorTree *DT, unsigned MaxRecurse) {
920 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
921 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
922 Constant *Ops[] = { CLHS, CRHS };
923 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
Chad Rosier618c1db2011-12-01 03:08:23 +0000924 Ops, TD, TLI);
Duncan Sands82fdab32010-12-21 14:00:22 +0000925 }
926
927 // Canonicalize the constant to the RHS.
928 std::swap(Op0, Op1);
929 }
930
931 // X * undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000932 if (match(Op1, m_Undef()))
Duncan Sands82fdab32010-12-21 14:00:22 +0000933 return Constant::getNullValue(Op0->getType());
934
935 // X * 0 -> 0
936 if (match(Op1, m_Zero()))
937 return Op1;
938
939 // X * 1 -> X
940 if (match(Op1, m_One()))
941 return Op0;
942
Duncan Sands1895e982011-01-30 18:03:50 +0000943 // (X / Y) * Y -> X if the division is exact.
Benjamin Kramer55c6d572012-01-01 17:55:30 +0000944 Value *X = 0;
945 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
946 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
947 return X;
Duncan Sands1895e982011-01-30 18:03:50 +0000948
Nick Lewycky54138802011-01-29 19:55:23 +0000949 // i1 mul -> and.
Duncan Sands75d289e2010-12-21 14:48:48 +0000950 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Chad Rosier618c1db2011-12-01 03:08:23 +0000951 if (Value *V = SimplifyAndInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000952 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000953
954 // Try some generic simplifications for associative operations.
Chad Rosier618c1db2011-12-01 03:08:23 +0000955 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, TLI, DT,
Duncan Sands82fdab32010-12-21 14:00:22 +0000956 MaxRecurse))
957 return V;
958
959 // Mul distributes over Add. Try some generic simplifications based on this.
960 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
Chad Rosier618c1db2011-12-01 03:08:23 +0000961 TD, TLI, DT, MaxRecurse))
Duncan Sands82fdab32010-12-21 14:00:22 +0000962 return V;
963
964 // If the operation is with the result of a select instruction, check whether
965 // operating on either branch of the select always yields the same value.
966 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +0000967 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, TLI, DT,
Duncan Sands82fdab32010-12-21 14:00:22 +0000968 MaxRecurse))
969 return V;
970
971 // If the operation is with the result of a phi instruction, check whether
972 // operating on all incoming values of the phi always yields the same value.
973 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +0000974 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, TLI, DT,
Duncan Sands82fdab32010-12-21 14:00:22 +0000975 MaxRecurse))
976 return V;
977
978 return 0;
979}
980
981Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +0000982 const TargetLibraryInfo *TLI,
Duncan Sands82fdab32010-12-21 14:00:22 +0000983 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +0000984 return ::SimplifyMulInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sands82fdab32010-12-21 14:00:22 +0000985}
986
Duncan Sands593faa52011-01-28 16:51:11 +0000987/// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
988/// fold the result. If not, this returns null.
Anders Carlsson479b4b92011-02-05 18:33:43 +0000989static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Chad Rosier618c1db2011-12-01 03:08:23 +0000990 const TargetData *TD, const TargetLibraryInfo *TLI,
991 const DominatorTree *DT, unsigned MaxRecurse) {
Duncan Sands593faa52011-01-28 16:51:11 +0000992 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
993 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
994 Constant *Ops[] = { C0, C1 };
Chad Rosier618c1db2011-12-01 03:08:23 +0000995 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
Duncan Sands593faa52011-01-28 16:51:11 +0000996 }
997 }
998
Duncan Sandsa3e292c2011-01-28 18:50:50 +0000999 bool isSigned = Opcode == Instruction::SDiv;
1000
Duncan Sands593faa52011-01-28 16:51:11 +00001001 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001002 if (match(Op1, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +00001003 return Op1;
1004
1005 // undef / X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001006 if (match(Op0, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +00001007 return Constant::getNullValue(Op0->getType());
1008
1009 // 0 / X -> 0, we don't need to preserve faults!
1010 if (match(Op0, m_Zero()))
1011 return Op0;
1012
1013 // X / 1 -> X
1014 if (match(Op1, m_One()))
1015 return Op0;
Duncan Sands593faa52011-01-28 16:51:11 +00001016
1017 if (Op0->getType()->isIntegerTy(1))
1018 // It can't be division by zero, hence it must be division by one.
1019 return Op0;
1020
1021 // X / X -> 1
1022 if (Op0 == Op1)
1023 return ConstantInt::get(Op0->getType(), 1);
1024
1025 // (X * Y) / Y -> X if the multiplication does not overflow.
1026 Value *X = 0, *Y = 0;
1027 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1028 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands32a43cc2011-10-27 19:16:21 +00001029 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands4b720712011-02-02 20:52:00 +00001030 // If the Mul knows it does not overflow, then we are good to go.
1031 if ((isSigned && Mul->hasNoSignedWrap()) ||
1032 (!isSigned && Mul->hasNoUnsignedWrap()))
1033 return X;
Duncan Sands593faa52011-01-28 16:51:11 +00001034 // If X has the form X = A / Y then X * Y cannot overflow.
1035 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1036 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1037 return X;
1038 }
1039
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001040 // (X rem Y) / Y -> 0
1041 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1042 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1043 return Constant::getNullValue(Op0->getType());
1044
1045 // If the operation is with the result of a select instruction, check whether
1046 // operating on either branch of the select always yields the same value.
1047 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001048 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT,
1049 MaxRecurse))
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001050 return V;
1051
1052 // If the operation is with the result of a phi instruction, check whether
1053 // operating on all incoming values of the phi always yields the same value.
1054 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001055 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT,
1056 MaxRecurse))
Duncan Sandsa3e292c2011-01-28 18:50:50 +00001057 return V;
1058
Duncan Sands593faa52011-01-28 16:51:11 +00001059 return 0;
1060}
1061
1062/// SimplifySDivInst - Given operands for an SDiv, see if we can
1063/// fold the result. If not, this returns null.
1064static Value *SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001065 const TargetLibraryInfo *TLI,
Duncan Sands593faa52011-01-28 16:51:11 +00001066 const DominatorTree *DT, unsigned MaxRecurse) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001067 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, TD, TLI, DT,
1068 MaxRecurse))
Duncan Sands593faa52011-01-28 16:51:11 +00001069 return V;
1070
Duncan Sands593faa52011-01-28 16:51:11 +00001071 return 0;
1072}
1073
1074Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001075 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001076 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001077 return ::SimplifySDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sands593faa52011-01-28 16:51:11 +00001078}
1079
1080/// SimplifyUDivInst - Given operands for a UDiv, see if we can
1081/// fold the result. If not, this returns null.
1082static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001083 const TargetLibraryInfo *TLI,
Duncan Sands593faa52011-01-28 16:51:11 +00001084 const DominatorTree *DT, unsigned MaxRecurse) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001085 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, TD, TLI, DT,
1086 MaxRecurse))
Duncan Sands593faa52011-01-28 16:51:11 +00001087 return V;
1088
Duncan Sands593faa52011-01-28 16:51:11 +00001089 return 0;
1090}
1091
1092Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001093 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001094 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001095 return ::SimplifyUDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sands593faa52011-01-28 16:51:11 +00001096}
1097
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001098static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +00001099 const TargetLibraryInfo *,
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001100 const DominatorTree *, unsigned) {
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001101 // undef / X -> undef (the undef could be a snan).
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001102 if (match(Op0, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001103 return Op0;
1104
1105 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001106 if (match(Op1, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001107 return Op1;
1108
1109 return 0;
1110}
1111
1112Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001113 const TargetLibraryInfo *TLI,
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001114 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001115 return ::SimplifyFDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Frits van Bommel1fca2c32011-01-29 15:26:31 +00001116}
1117
Duncan Sandsf24ed772011-05-02 16:27:02 +00001118/// SimplifyRem - Given operands for an SRem or URem, see if we can
1119/// fold the result. If not, this returns null.
1120static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Chad Rosier618c1db2011-12-01 03:08:23 +00001121 const TargetData *TD, const TargetLibraryInfo *TLI,
1122 const DominatorTree *DT, unsigned MaxRecurse) {
Duncan Sandsf24ed772011-05-02 16:27:02 +00001123 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1124 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1125 Constant *Ops[] = { C0, C1 };
Chad Rosier618c1db2011-12-01 03:08:23 +00001126 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001127 }
1128 }
1129
Duncan Sandsf24ed772011-05-02 16:27:02 +00001130 // X % undef -> undef
1131 if (match(Op1, m_Undef()))
1132 return Op1;
1133
1134 // undef % X -> 0
1135 if (match(Op0, m_Undef()))
1136 return Constant::getNullValue(Op0->getType());
1137
1138 // 0 % X -> 0, we don't need to preserve faults!
1139 if (match(Op0, m_Zero()))
1140 return Op0;
1141
1142 // X % 0 -> undef, we don't need to preserve faults!
1143 if (match(Op1, m_Zero()))
1144 return UndefValue::get(Op0->getType());
1145
1146 // X % 1 -> 0
1147 if (match(Op1, m_One()))
1148 return Constant::getNullValue(Op0->getType());
1149
1150 if (Op0->getType()->isIntegerTy(1))
1151 // It can't be remainder by zero, hence it must be remainder by one.
1152 return Constant::getNullValue(Op0->getType());
1153
1154 // X % X -> 0
1155 if (Op0 == Op1)
1156 return Constant::getNullValue(Op0->getType());
1157
1158 // If the operation is with the result of a select instruction, check whether
1159 // operating on either branch of the select always yields the same value.
1160 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001161 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001162 return V;
1163
1164 // If the operation is with the result of a phi instruction, check whether
1165 // operating on all incoming values of the phi always yields the same value.
1166 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001167 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001168 return V;
1169
1170 return 0;
1171}
1172
1173/// SimplifySRemInst - Given operands for an SRem, see if we can
1174/// fold the result. If not, this returns null.
1175static Value *SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001176 const TargetLibraryInfo *TLI,
1177 const DominatorTree *DT,
1178 unsigned MaxRecurse) {
1179 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001180 return V;
1181
1182 return 0;
1183}
1184
1185Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001186 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001187 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001188 return ::SimplifySRemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001189}
1190
1191/// SimplifyURemInst - Given operands for a URem, see if we can
1192/// fold the result. If not, this returns null.
1193static Value *SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001194 const TargetLibraryInfo *TLI,
1195 const DominatorTree *DT,
1196 unsigned MaxRecurse) {
1197 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandsf24ed772011-05-02 16:27:02 +00001198 return V;
1199
1200 return 0;
1201}
1202
1203Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001204 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001205 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001206 return ::SimplifyURemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001207}
1208
1209static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *,
Chad Rosier618c1db2011-12-01 03:08:23 +00001210 const TargetLibraryInfo *,
1211 const DominatorTree *,
1212 unsigned) {
Duncan Sandsf24ed772011-05-02 16:27:02 +00001213 // undef % X -> undef (the undef could be a snan).
1214 if (match(Op0, m_Undef()))
1215 return Op0;
1216
1217 // X % undef -> undef
1218 if (match(Op1, m_Undef()))
1219 return Op1;
1220
1221 return 0;
1222}
1223
1224Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001225 const TargetLibraryInfo *TLI,
Duncan Sandsf24ed772011-05-02 16:27:02 +00001226 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001227 return ::SimplifyFRemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sandsf24ed772011-05-02 16:27:02 +00001228}
1229
Duncan Sandscf80bc12011-01-14 14:44:12 +00001230/// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
Duncan Sandsc43cee32011-01-14 00:37:45 +00001231/// fold the result. If not, this returns null.
Duncan Sandscf80bc12011-01-14 14:44:12 +00001232static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
Chad Rosier618c1db2011-12-01 03:08:23 +00001233 const TargetData *TD, const TargetLibraryInfo *TLI,
1234 const DominatorTree *DT, unsigned MaxRecurse) {
Duncan Sandsc43cee32011-01-14 00:37:45 +00001235 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1236 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1237 Constant *Ops[] = { C0, C1 };
Chad Rosier618c1db2011-12-01 03:08:23 +00001238 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001239 }
1240 }
1241
Duncan Sandscf80bc12011-01-14 14:44:12 +00001242 // 0 shift by X -> 0
Duncan Sandsc43cee32011-01-14 00:37:45 +00001243 if (match(Op0, m_Zero()))
1244 return Op0;
1245
Duncan Sandscf80bc12011-01-14 14:44:12 +00001246 // X shift by 0 -> X
Duncan Sandsc43cee32011-01-14 00:37:45 +00001247 if (match(Op1, m_Zero()))
1248 return Op0;
1249
Duncan Sandscf80bc12011-01-14 14:44:12 +00001250 // X shift by undef -> undef because it may shift by the bitwidth.
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001251 if (match(Op1, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001252 return Op1;
1253
1254 // Shifting by the bitwidth or more is undefined.
1255 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1256 if (CI->getValue().getLimitedValue() >=
1257 Op0->getType()->getScalarSizeInBits())
1258 return UndefValue::get(Op0->getType());
1259
Duncan Sandscf80bc12011-01-14 14:44:12 +00001260 // If the operation is with the result of a select instruction, check whether
1261 // operating on either branch of the select always yields the same value.
1262 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001263 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001264 return V;
1265
1266 // If the operation is with the result of a phi instruction, check whether
1267 // operating on all incoming values of the phi always yields the same value.
1268 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001269 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001270 return V;
1271
1272 return 0;
1273}
1274
1275/// SimplifyShlInst - Given operands for an Shl, see if we can
1276/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001277static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +00001278 const TargetData *TD,
1279 const TargetLibraryInfo *TLI,
1280 const DominatorTree *DT, unsigned MaxRecurse) {
1281 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001282 return V;
1283
1284 // undef << X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001285 if (match(Op0, m_Undef()))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001286 return Constant::getNullValue(Op0->getType());
1287
Chris Lattner81a0dc92011-02-09 17:15:04 +00001288 // (X >> A) << A -> X
1289 Value *X;
Benjamin Kramer55c6d572012-01-01 17:55:30 +00001290 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
Chris Lattner81a0dc92011-02-09 17:15:04 +00001291 return X;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001292 return 0;
1293}
1294
Chris Lattner81a0dc92011-02-09 17:15:04 +00001295Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Chad Rosier618c1db2011-12-01 03:08:23 +00001296 const TargetData *TD, const TargetLibraryInfo *TLI,
1297 const DominatorTree *DT) {
1298 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001299}
1300
1301/// SimplifyLShrInst - Given operands for an LShr, see if we can
1302/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001303static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Chad Rosier618c1db2011-12-01 03:08:23 +00001304 const TargetData *TD,
1305 const TargetLibraryInfo *TLI,
1306 const DominatorTree *DT,
Chris Lattner81a0dc92011-02-09 17:15:04 +00001307 unsigned MaxRecurse) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001308 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001309 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001310
1311 // undef >>l X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001312 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001313 return Constant::getNullValue(Op0->getType());
1314
Chris Lattner81a0dc92011-02-09 17:15:04 +00001315 // (X << A) >> A -> X
1316 Value *X;
1317 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1318 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1319 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001320
Duncan Sandsc43cee32011-01-14 00:37:45 +00001321 return 0;
1322}
1323
Chris Lattner81a0dc92011-02-09 17:15:04 +00001324Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
Chad Rosier618c1db2011-12-01 03:08:23 +00001325 const TargetData *TD,
1326 const TargetLibraryInfo *TLI,
1327 const DominatorTree *DT) {
1328 return ::SimplifyLShrInst(Op0, Op1, isExact, TD, TLI, DT, RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001329}
1330
1331/// SimplifyAShrInst - Given operands for an AShr, see if we can
1332/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001333static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Chad Rosier618c1db2011-12-01 03:08:23 +00001334 const TargetData *TD,
1335 const TargetLibraryInfo *TLI,
1336 const DominatorTree *DT,
Chris Lattner81a0dc92011-02-09 17:15:04 +00001337 unsigned MaxRecurse) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001338 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, TD, TLI, DT, MaxRecurse))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001339 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001340
1341 // all ones >>a X -> all ones
1342 if (match(Op0, m_AllOnes()))
1343 return Op0;
1344
1345 // undef >>a X -> all ones
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001346 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001347 return Constant::getAllOnesValue(Op0->getType());
1348
Chris Lattner81a0dc92011-02-09 17:15:04 +00001349 // (X << A) >> A -> X
1350 Value *X;
1351 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1352 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1353 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001354
Duncan Sandsc43cee32011-01-14 00:37:45 +00001355 return 0;
1356}
1357
Chris Lattner81a0dc92011-02-09 17:15:04 +00001358Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
Chad Rosier618c1db2011-12-01 03:08:23 +00001359 const TargetData *TD,
1360 const TargetLibraryInfo *TLI,
1361 const DominatorTree *DT) {
1362 return ::SimplifyAShrInst(Op0, Op1, isExact, TD, TLI, DT, RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001363}
1364
Chris Lattnerd06094f2009-11-10 00:55:12 +00001365/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001366/// fold the result. If not, this returns null.
Chad Rosier618c1db2011-12-01 03:08:23 +00001367static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1368 const TargetLibraryInfo *TLI,
1369 const DominatorTree *DT,
1370 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001371 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1372 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1373 Constant *Ops[] = { CLHS, CRHS };
1374 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
Chad Rosier618c1db2011-12-01 03:08:23 +00001375 Ops, TD, TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001376 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001377
Chris Lattnerd06094f2009-11-10 00:55:12 +00001378 // Canonicalize the constant to the RHS.
1379 std::swap(Op0, Op1);
1380 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001381
Chris Lattnerd06094f2009-11-10 00:55:12 +00001382 // X & undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001383 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001384 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001385
Chris Lattnerd06094f2009-11-10 00:55:12 +00001386 // X & X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001387 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001388 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001389
Duncan Sands2b749872010-11-17 18:52:15 +00001390 // X & 0 = 0
1391 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001392 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001393
Duncan Sands2b749872010-11-17 18:52:15 +00001394 // X & -1 = X
1395 if (match(Op1, m_AllOnes()))
1396 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001397
Chris Lattnerd06094f2009-11-10 00:55:12 +00001398 // A & ~A = ~A & A = 0
Chris Lattner81a0dc92011-02-09 17:15:04 +00001399 if (match(Op0, m_Not(m_Specific(Op1))) ||
1400 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001401 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001402
Chris Lattnerd06094f2009-11-10 00:55:12 +00001403 // (A | ?) & A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001404 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001405 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001406 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001407 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001408
Chris Lattnerd06094f2009-11-10 00:55:12 +00001409 // A & (A | ?) = A
1410 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001411 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001412 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001413
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001414 // A & (-A) = A if A is a power of two or zero.
1415 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1416 match(Op1, m_Neg(m_Specific(Op0)))) {
1417 if (isPowerOfTwo(Op0, TD, /*OrZero*/true))
1418 return Op0;
1419 if (isPowerOfTwo(Op1, TD, /*OrZero*/true))
1420 return Op1;
1421 }
1422
Duncan Sands566edb02010-12-21 08:49:00 +00001423 // Try some generic simplifications for associative operations.
Chad Rosier618c1db2011-12-01 03:08:23 +00001424 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, TLI,
1425 DT, MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001426 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001427
Duncan Sands3421d902010-12-21 13:32:22 +00001428 // And distributes over Or. Try some generic simplifications based on this.
1429 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Chad Rosier618c1db2011-12-01 03:08:23 +00001430 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001431 return V;
1432
1433 // And distributes over Xor. Try some generic simplifications based on this.
1434 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
Chad Rosier618c1db2011-12-01 03:08:23 +00001435 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001436 return V;
1437
1438 // Or distributes over And. Try some generic simplifications based on this.
1439 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
Chad Rosier618c1db2011-12-01 03:08:23 +00001440 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001441 return V;
1442
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001443 // If the operation is with the result of a select instruction, check whether
1444 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001445 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001446 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, TLI,
1447 DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001448 return V;
1449
1450 // If the operation is with the result of a phi instruction, check whether
1451 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001452 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001453 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, TLI, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001454 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001455 return V;
1456
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001457 return 0;
1458}
1459
Duncan Sands18450092010-11-16 12:16:38 +00001460Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001461 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +00001462 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001463 return ::SimplifyAndInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001464}
1465
Chris Lattnerd06094f2009-11-10 00:55:12 +00001466/// SimplifyOrInst - Given operands for an Or, see if we can
1467/// fold the result. If not, this returns null.
Chad Rosier618c1db2011-12-01 03:08:23 +00001468static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1469 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +00001470 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001471 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1472 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1473 Constant *Ops[] = { CLHS, CRHS };
1474 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
Chad Rosier618c1db2011-12-01 03:08:23 +00001475 Ops, TD, TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001476 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001477
Chris Lattnerd06094f2009-11-10 00:55:12 +00001478 // Canonicalize the constant to the RHS.
1479 std::swap(Op0, Op1);
1480 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001481
Chris Lattnerd06094f2009-11-10 00:55:12 +00001482 // X | undef -> -1
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001483 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001484 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001485
Chris Lattnerd06094f2009-11-10 00:55:12 +00001486 // X | X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001487 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001488 return Op0;
1489
Duncan Sands2b749872010-11-17 18:52:15 +00001490 // X | 0 = X
1491 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001492 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001493
Duncan Sands2b749872010-11-17 18:52:15 +00001494 // X | -1 = -1
1495 if (match(Op1, m_AllOnes()))
1496 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001497
Chris Lattnerd06094f2009-11-10 00:55:12 +00001498 // A | ~A = ~A | A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001499 if (match(Op0, m_Not(m_Specific(Op1))) ||
1500 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001501 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001502
Chris Lattnerd06094f2009-11-10 00:55:12 +00001503 // (A & ?) | A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001504 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001505 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001506 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001507 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001508
Chris Lattnerd06094f2009-11-10 00:55:12 +00001509 // A | (A & ?) = A
1510 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001511 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001512 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001513
Benjamin Kramer38f7f662011-02-20 15:20:01 +00001514 // ~(A & ?) | A = -1
1515 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1516 (A == Op1 || B == Op1))
1517 return Constant::getAllOnesValue(Op1->getType());
1518
1519 // A | ~(A & ?) = -1
1520 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1521 (A == Op0 || B == Op0))
1522 return Constant::getAllOnesValue(Op0->getType());
1523
Duncan Sands566edb02010-12-21 08:49:00 +00001524 // Try some generic simplifications for associative operations.
Chad Rosier618c1db2011-12-01 03:08:23 +00001525 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, TLI,
1526 DT, MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001527 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001528
Duncan Sands3421d902010-12-21 13:32:22 +00001529 // Or distributes over And. Try some generic simplifications based on this.
Chad Rosier618c1db2011-12-01 03:08:23 +00001530 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, TD,
1531 TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001532 return V;
1533
1534 // And distributes over Or. Try some generic simplifications based on this.
1535 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
Chad Rosier618c1db2011-12-01 03:08:23 +00001536 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001537 return V;
1538
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001539 // If the operation is with the result of a select instruction, check whether
1540 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001541 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001542 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, TLI, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001543 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001544 return V;
1545
1546 // If the operation is with the result of a phi instruction, check whether
1547 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001548 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Chad Rosier618c1db2011-12-01 03:08:23 +00001549 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, TLI, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001550 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001551 return V;
1552
Chris Lattnerd06094f2009-11-10 00:55:12 +00001553 return 0;
1554}
1555
Duncan Sands18450092010-11-16 12:16:38 +00001556Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001557 const TargetLibraryInfo *TLI,
Duncan Sands18450092010-11-16 12:16:38 +00001558 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001559 return ::SimplifyOrInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001560}
Chris Lattnerd06094f2009-11-10 00:55:12 +00001561
Duncan Sands2b749872010-11-17 18:52:15 +00001562/// SimplifyXorInst - Given operands for a Xor, see if we can
1563/// fold the result. If not, this returns null.
1564static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001565 const TargetLibraryInfo *TLI,
Duncan Sands2b749872010-11-17 18:52:15 +00001566 const DominatorTree *DT, unsigned MaxRecurse) {
1567 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1568 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1569 Constant *Ops[] = { CLHS, CRHS };
1570 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
Chad Rosier618c1db2011-12-01 03:08:23 +00001571 Ops, TD, TLI);
Duncan Sands2b749872010-11-17 18:52:15 +00001572 }
1573
1574 // Canonicalize the constant to the RHS.
1575 std::swap(Op0, Op1);
1576 }
1577
1578 // A ^ undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001579 if (match(Op1, m_Undef()))
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00001580 return Op1;
Duncan Sands2b749872010-11-17 18:52:15 +00001581
1582 // A ^ 0 = A
1583 if (match(Op1, m_Zero()))
1584 return Op0;
1585
Eli Friedmanf23d4ad2011-08-17 19:31:49 +00001586 // A ^ A = 0
1587 if (Op0 == Op1)
1588 return Constant::getNullValue(Op0->getType());
1589
Duncan Sands2b749872010-11-17 18:52:15 +00001590 // A ^ ~A = ~A ^ A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001591 if (match(Op0, m_Not(m_Specific(Op1))) ||
1592 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands2b749872010-11-17 18:52:15 +00001593 return Constant::getAllOnesValue(Op0->getType());
1594
Duncan Sands566edb02010-12-21 08:49:00 +00001595 // Try some generic simplifications for associative operations.
Chad Rosier618c1db2011-12-01 03:08:23 +00001596 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, TLI,
1597 DT, MaxRecurse))
Duncan Sands566edb02010-12-21 08:49:00 +00001598 return V;
Duncan Sands2b749872010-11-17 18:52:15 +00001599
Duncan Sands3421d902010-12-21 13:32:22 +00001600 // And distributes over Xor. Try some generic simplifications based on this.
1601 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
Chad Rosier618c1db2011-12-01 03:08:23 +00001602 TD, TLI, DT, MaxRecurse))
Duncan Sands3421d902010-12-21 13:32:22 +00001603 return V;
1604
Duncan Sands87689cf2010-11-19 09:20:39 +00001605 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1606 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1607 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1608 // only if B and C are equal. If B and C are equal then (since we assume
1609 // that operands have already been simplified) "select(cond, B, C)" should
1610 // have been simplified to the common value of B and C already. Analysing
1611 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1612 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +00001613
1614 return 0;
1615}
1616
1617Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00001618 const TargetLibraryInfo *TLI,
Duncan Sands2b749872010-11-17 18:52:15 +00001619 const DominatorTree *DT) {
Chad Rosier618c1db2011-12-01 03:08:23 +00001620 return ::SimplifyXorInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
Duncan Sands2b749872010-11-17 18:52:15 +00001621}
1622
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001623static Type *GetCompareTy(Value *Op) {
Chris Lattner210c5d42009-11-09 23:55:12 +00001624 return CmpInst::makeCmpResultType(Op->getType());
1625}
1626
Duncan Sandse864b5b2011-05-07 16:56:49 +00001627/// ExtractEquivalentCondition - Rummage around inside V looking for something
1628/// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1629/// otherwise return null. Helper function for analyzing max/min idioms.
1630static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1631 Value *LHS, Value *RHS) {
1632 SelectInst *SI = dyn_cast<SelectInst>(V);
1633 if (!SI)
1634 return 0;
1635 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1636 if (!Cmp)
1637 return 0;
1638 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1639 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1640 return Cmp;
1641 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1642 LHS == CmpRHS && RHS == CmpLHS)
1643 return Cmp;
1644 return 0;
1645}
1646
Chris Lattner009e2652012-02-24 19:01:58 +00001647
Chris Lattner9dbb4292009-11-09 23:28:39 +00001648/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1649/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001650static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00001651 const TargetData *TD,
1652 const TargetLibraryInfo *TLI,
1653 const DominatorTree *DT,
Duncan Sands18450092010-11-16 12:16:38 +00001654 unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001655 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +00001656 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +00001657
Chris Lattnerd06094f2009-11-10 00:55:12 +00001658 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +00001659 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00001660 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD, TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001661
1662 // If we have a constant, make sure it is on the RHS.
1663 std::swap(LHS, RHS);
1664 Pred = CmpInst::getSwappedPredicate(Pred);
1665 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001666
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001667 Type *ITy = GetCompareTy(LHS); // The return type.
1668 Type *OpTy = LHS->getType(); // The operand type.
Duncan Sands12a86f52010-11-14 11:23:23 +00001669
Chris Lattner210c5d42009-11-09 23:55:12 +00001670 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +00001671 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1672 // because X could be 0.
Duncan Sands124708d2011-01-01 20:08:02 +00001673 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +00001674 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +00001675
Duncan Sands6dc91252011-01-13 08:56:29 +00001676 // Special case logic when the operands have i1 type.
Nick Lewycky66d004e2011-12-01 02:39:36 +00001677 if (OpTy->getScalarType()->isIntegerTy(1)) {
Duncan Sands6dc91252011-01-13 08:56:29 +00001678 switch (Pred) {
1679 default: break;
1680 case ICmpInst::ICMP_EQ:
1681 // X == 1 -> X
1682 if (match(RHS, m_One()))
1683 return LHS;
1684 break;
1685 case ICmpInst::ICMP_NE:
1686 // X != 0 -> X
1687 if (match(RHS, m_Zero()))
1688 return LHS;
1689 break;
1690 case ICmpInst::ICMP_UGT:
1691 // X >u 0 -> X
1692 if (match(RHS, m_Zero()))
1693 return LHS;
1694 break;
1695 case ICmpInst::ICMP_UGE:
1696 // X >=u 1 -> X
1697 if (match(RHS, m_One()))
1698 return LHS;
1699 break;
1700 case ICmpInst::ICMP_SLT:
1701 // X <s 0 -> X
1702 if (match(RHS, m_Zero()))
1703 return LHS;
1704 break;
1705 case ICmpInst::ICMP_SLE:
1706 // X <=s -1 -> X
1707 if (match(RHS, m_One()))
1708 return LHS;
1709 break;
1710 }
1711 }
1712
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001713 // icmp <object*>, <object*/null> - Different identified objects have
1714 // different addresses (unless null), and what's more the address of an
1715 // identified local is never equal to another argument (again, barring null).
1716 // Note that generalizing to the case where LHS is a global variable address
1717 // or null is pointless, since if both LHS and RHS are constants then we
1718 // already constant folded the compare, and if only one of them is then we
1719 // moved it to RHS already.
Benjamin Kramerea79b8e2012-02-16 15:19:59 +00001720 Value *LHSPtr = LHS->stripPointerCasts();
1721 Value *RHSPtr = RHS->stripPointerCasts();
Eli Friedman2c3acb02012-02-18 03:29:25 +00001722 if (LHSPtr == RHSPtr)
1723 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001724
Chris Lattnerb053fc12012-02-20 00:42:49 +00001725 // Be more aggressive about stripping pointer adjustments when checking a
1726 // comparison of an alloca address to another object. We can rip off all
1727 // inbounds GEP operations, even if they are variable.
Chandler Carruth84dfc322012-03-10 08:39:09 +00001728 LHSPtr = LHSPtr->stripInBoundsOffsets();
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001729 if (llvm::isIdentifiedObject(LHSPtr)) {
Chandler Carruth84dfc322012-03-10 08:39:09 +00001730 RHSPtr = RHSPtr->stripInBoundsOffsets();
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001731 if (llvm::isKnownNonNull(LHSPtr) || llvm::isKnownNonNull(RHSPtr)) {
1732 // If both sides are different identified objects, they aren't equal
1733 // unless they're null.
Bill Wendlingc17731d652012-03-10 17:56:03 +00001734 if (LHSPtr != RHSPtr && llvm::isIdentifiedObject(RHSPtr) &&
Bill Wendling798d0132012-03-10 18:20:55 +00001735 Pred == CmpInst::ICMP_EQ)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001736 return ConstantInt::get(ITy, false);
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001737
1738 // A local identified object (alloca or noalias call) can't equal any
1739 // incoming argument, unless they're both null.
Bill Wendlingc17731d652012-03-10 17:56:03 +00001740 if (isa<Instruction>(LHSPtr) && isa<Argument>(RHSPtr) &&
Bill Wendling798d0132012-03-10 18:20:55 +00001741 Pred == CmpInst::ICMP_EQ)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001742 return ConstantInt::get(ITy, false);
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001743 }
1744
1745 // Assume that the constant null is on the right.
Bill Wendlingc17731d652012-03-10 17:56:03 +00001746 if (llvm::isKnownNonNull(LHSPtr) && isa<ConstantPointerNull>(RHSPtr)) {
Bill Wendling798d0132012-03-10 18:20:55 +00001747 if (Pred == CmpInst::ICMP_EQ)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001748 return ConstantInt::get(ITy, false);
Bill Wendling798d0132012-03-10 18:20:55 +00001749 else if (Pred == CmpInst::ICMP_NE)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001750 return ConstantInt::get(ITy, true);
1751 }
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001752 } else if (isa<Argument>(LHSPtr)) {
Chandler Carruth84dfc322012-03-10 08:39:09 +00001753 RHSPtr = RHSPtr->stripInBoundsOffsets();
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00001754 // An alloca can't be equal to an argument.
Bill Wendlingc17731d652012-03-10 17:56:03 +00001755 if (isa<AllocaInst>(RHSPtr)) {
Bill Wendling798d0132012-03-10 18:20:55 +00001756 if (Pred == CmpInst::ICMP_EQ)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001757 return ConstantInt::get(ITy, false);
Bill Wendling798d0132012-03-10 18:20:55 +00001758 else if (Pred == CmpInst::ICMP_NE)
Bill Wendlingc17731d652012-03-10 17:56:03 +00001759 return ConstantInt::get(ITy, true);
1760 }
Chris Lattnerb053fc12012-02-20 00:42:49 +00001761 }
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001762
1763 // If we are comparing with zero then try hard since this is a common case.
1764 if (match(RHS, m_Zero())) {
1765 bool LHSKnownNonNegative, LHSKnownNegative;
1766 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00001767 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001768 case ICmpInst::ICMP_ULT:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001769 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001770 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001771 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001772 case ICmpInst::ICMP_EQ:
1773 case ICmpInst::ICMP_ULE:
1774 if (isKnownNonZero(LHS, TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001775 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001776 break;
1777 case ICmpInst::ICMP_NE:
1778 case ICmpInst::ICMP_UGT:
1779 if (isKnownNonZero(LHS, TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001780 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001781 break;
1782 case ICmpInst::ICMP_SLT:
1783 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1784 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001785 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001786 if (LHSKnownNonNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001787 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001788 break;
1789 case ICmpInst::ICMP_SLE:
1790 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1791 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001792 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001793 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001794 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001795 break;
1796 case ICmpInst::ICMP_SGE:
1797 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1798 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001799 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001800 if (LHSKnownNonNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001801 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001802 break;
1803 case ICmpInst::ICMP_SGT:
1804 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1805 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001806 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001807 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001808 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001809 break;
1810 }
1811 }
1812
1813 // See if we are doing a comparison with a constant integer.
Duncan Sands6dc91252011-01-13 08:56:29 +00001814 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Nick Lewycky3a73e342011-03-04 07:00:57 +00001815 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1816 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1817 if (RHS_CR.isEmptySet())
1818 return ConstantInt::getFalse(CI->getContext());
1819 if (RHS_CR.isFullSet())
1820 return ConstantInt::getTrue(CI->getContext());
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001821
Nick Lewycky3a73e342011-03-04 07:00:57 +00001822 // Many binary operators with constant RHS have easy to compute constant
1823 // range. Use them to check whether the comparison is a tautology.
1824 uint32_t Width = CI->getBitWidth();
1825 APInt Lower = APInt(Width, 0);
1826 APInt Upper = APInt(Width, 0);
1827 ConstantInt *CI2;
1828 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1829 // 'urem x, CI2' produces [0, CI2).
1830 Upper = CI2->getValue();
1831 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1832 // 'srem x, CI2' produces (-|CI2|, |CI2|).
1833 Upper = CI2->getValue().abs();
1834 Lower = (-Upper) + 1;
Duncan Sandsc65c7472011-10-28 18:17:44 +00001835 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
1836 // 'udiv CI2, x' produces [0, CI2].
Eli Friedman7781ae52011-11-08 21:08:02 +00001837 Upper = CI2->getValue() + 1;
Nick Lewycky3a73e342011-03-04 07:00:57 +00001838 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1839 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1840 APInt NegOne = APInt::getAllOnesValue(Width);
1841 if (!CI2->isZero())
1842 Upper = NegOne.udiv(CI2->getValue()) + 1;
1843 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1844 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1845 APInt IntMin = APInt::getSignedMinValue(Width);
1846 APInt IntMax = APInt::getSignedMaxValue(Width);
1847 APInt Val = CI2->getValue().abs();
1848 if (!Val.isMinValue()) {
1849 Lower = IntMin.sdiv(Val);
1850 Upper = IntMax.sdiv(Val) + 1;
1851 }
1852 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1853 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1854 APInt NegOne = APInt::getAllOnesValue(Width);
1855 if (CI2->getValue().ult(Width))
1856 Upper = NegOne.lshr(CI2->getValue()) + 1;
1857 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1858 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1859 APInt IntMin = APInt::getSignedMinValue(Width);
1860 APInt IntMax = APInt::getSignedMaxValue(Width);
1861 if (CI2->getValue().ult(Width)) {
1862 Lower = IntMin.ashr(CI2->getValue());
1863 Upper = IntMax.ashr(CI2->getValue()) + 1;
1864 }
1865 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1866 // 'or x, CI2' produces [CI2, UINT_MAX].
1867 Lower = CI2->getValue();
1868 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1869 // 'and x, CI2' produces [0, CI2].
1870 Upper = CI2->getValue() + 1;
1871 }
1872 if (Lower != Upper) {
1873 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1874 if (RHS_CR.contains(LHS_CR))
1875 return ConstantInt::getTrue(RHS->getContext());
1876 if (RHS_CR.inverse().contains(LHS_CR))
1877 return ConstantInt::getFalse(RHS->getContext());
1878 }
Duncan Sands6dc91252011-01-13 08:56:29 +00001879 }
1880
Duncan Sands9d32f602011-01-20 13:21:55 +00001881 // Compare of cast, for example (zext X) != 0 -> X != 0
1882 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1883 Instruction *LI = cast<CastInst>(LHS);
1884 Value *SrcOp = LI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001885 Type *SrcTy = SrcOp->getType();
1886 Type *DstTy = LI->getType();
Duncan Sands9d32f602011-01-20 13:21:55 +00001887
1888 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1889 // if the integer type is the same size as the pointer type.
1890 if (MaxRecurse && TD && isa<PtrToIntInst>(LI) &&
1891 TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
1892 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1893 // Transfer the cast to the constant.
1894 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1895 ConstantExpr::getIntToPtr(RHSC, SrcTy),
Chad Rosier618c1db2011-12-01 03:08:23 +00001896 TD, TLI, DT, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001897 return V;
1898 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1899 if (RI->getOperand(0)->getType() == SrcTy)
1900 // Compare without the cast.
1901 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Chad Rosier618c1db2011-12-01 03:08:23 +00001902 TD, TLI, DT, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001903 return V;
1904 }
1905 }
1906
1907 if (isa<ZExtInst>(LHS)) {
1908 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1909 // same type.
1910 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1911 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1912 // Compare X and Y. Note that signed predicates become unsigned.
1913 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Chad Rosier618c1db2011-12-01 03:08:23 +00001914 SrcOp, RI->getOperand(0), TD, TLI, DT,
Duncan Sands9d32f602011-01-20 13:21:55 +00001915 MaxRecurse-1))
1916 return V;
1917 }
1918 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1919 // too. If not, then try to deduce the result of the comparison.
1920 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1921 // Compute the constant that would happen if we truncated to SrcTy then
1922 // reextended to DstTy.
1923 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1924 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1925
1926 // If the re-extended constant didn't change then this is effectively
1927 // also a case of comparing two zero-extended values.
1928 if (RExt == CI && MaxRecurse)
1929 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
Nadav Rotem16087692011-12-05 06:29:09 +00001930 SrcOp, Trunc, TD, TLI, DT, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001931 return V;
1932
1933 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1934 // there. Use this to work out the result of the comparison.
1935 if (RExt != CI) {
1936 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00001937 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands9d32f602011-01-20 13:21:55 +00001938 // LHS <u RHS.
1939 case ICmpInst::ICMP_EQ:
1940 case ICmpInst::ICMP_UGT:
1941 case ICmpInst::ICMP_UGE:
1942 return ConstantInt::getFalse(CI->getContext());
1943
1944 case ICmpInst::ICMP_NE:
1945 case ICmpInst::ICMP_ULT:
1946 case ICmpInst::ICMP_ULE:
1947 return ConstantInt::getTrue(CI->getContext());
1948
1949 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
1950 // is non-negative then LHS <s RHS.
1951 case ICmpInst::ICMP_SGT:
1952 case ICmpInst::ICMP_SGE:
1953 return CI->getValue().isNegative() ?
1954 ConstantInt::getTrue(CI->getContext()) :
1955 ConstantInt::getFalse(CI->getContext());
1956
1957 case ICmpInst::ICMP_SLT:
1958 case ICmpInst::ICMP_SLE:
1959 return CI->getValue().isNegative() ?
1960 ConstantInt::getFalse(CI->getContext()) :
1961 ConstantInt::getTrue(CI->getContext());
1962 }
1963 }
1964 }
1965 }
1966
1967 if (isa<SExtInst>(LHS)) {
1968 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1969 // same type.
1970 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1971 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1972 // Compare X and Y. Note that the predicate does not change.
1973 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
Chad Rosier618c1db2011-12-01 03:08:23 +00001974 TD, TLI, DT, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00001975 return V;
1976 }
1977 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1978 // too. If not, then try to deduce the result of the comparison.
1979 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1980 // Compute the constant that would happen if we truncated to SrcTy then
1981 // reextended to DstTy.
1982 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1983 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1984
1985 // If the re-extended constant didn't change then this is effectively
1986 // also a case of comparing two sign-extended values.
1987 if (RExt == CI && MaxRecurse)
Chad Rosier618c1db2011-12-01 03:08:23 +00001988 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, TD, TLI, DT,
Duncan Sands9d32f602011-01-20 13:21:55 +00001989 MaxRecurse-1))
1990 return V;
1991
1992 // Otherwise the upper bits of LHS are all equal, while RHS has varying
1993 // bits there. Use this to work out the result of the comparison.
1994 if (RExt != CI) {
1995 switch (Pred) {
Craig Topper85814382012-02-07 05:05:23 +00001996 default: llvm_unreachable("Unknown ICmp predicate!");
Duncan Sands9d32f602011-01-20 13:21:55 +00001997 case ICmpInst::ICMP_EQ:
1998 return ConstantInt::getFalse(CI->getContext());
1999 case ICmpInst::ICMP_NE:
2000 return ConstantInt::getTrue(CI->getContext());
2001
2002 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
2003 // LHS >s RHS.
2004 case ICmpInst::ICMP_SGT:
2005 case ICmpInst::ICMP_SGE:
2006 return CI->getValue().isNegative() ?
2007 ConstantInt::getTrue(CI->getContext()) :
2008 ConstantInt::getFalse(CI->getContext());
2009 case ICmpInst::ICMP_SLT:
2010 case ICmpInst::ICMP_SLE:
2011 return CI->getValue().isNegative() ?
2012 ConstantInt::getFalse(CI->getContext()) :
2013 ConstantInt::getTrue(CI->getContext());
2014
2015 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
2016 // LHS >u RHS.
2017 case ICmpInst::ICMP_UGT:
2018 case ICmpInst::ICMP_UGE:
2019 // Comparison is true iff the LHS <s 0.
2020 if (MaxRecurse)
2021 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2022 Constant::getNullValue(SrcTy),
Chad Rosier618c1db2011-12-01 03:08:23 +00002023 TD, TLI, DT, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00002024 return V;
2025 break;
2026 case ICmpInst::ICMP_ULT:
2027 case ICmpInst::ICMP_ULE:
2028 // Comparison is true iff the LHS >=s 0.
2029 if (MaxRecurse)
2030 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2031 Constant::getNullValue(SrcTy),
Chad Rosier618c1db2011-12-01 03:08:23 +00002032 TD, TLI, DT, MaxRecurse-1))
Duncan Sands9d32f602011-01-20 13:21:55 +00002033 return V;
2034 break;
2035 }
2036 }
2037 }
2038 }
2039 }
2040
Duncan Sands52fb8462011-02-13 17:15:40 +00002041 // Special logic for binary operators.
2042 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2043 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2044 if (MaxRecurse && (LBO || RBO)) {
Duncan Sands52fb8462011-02-13 17:15:40 +00002045 // Analyze the case when either LHS or RHS is an add instruction.
2046 Value *A = 0, *B = 0, *C = 0, *D = 0;
2047 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2048 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2049 if (LBO && LBO->getOpcode() == Instruction::Add) {
2050 A = LBO->getOperand(0); B = LBO->getOperand(1);
2051 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2052 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2053 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2054 }
2055 if (RBO && RBO->getOpcode() == Instruction::Add) {
2056 C = RBO->getOperand(0); D = RBO->getOperand(1);
2057 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2058 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2059 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2060 }
2061
2062 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2063 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2064 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2065 Constant::getNullValue(RHS->getType()),
Chad Rosier618c1db2011-12-01 03:08:23 +00002066 TD, TLI, DT, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00002067 return V;
2068
2069 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2070 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2071 if (Value *V = SimplifyICmpInst(Pred,
2072 Constant::getNullValue(LHS->getType()),
Chad Rosier618c1db2011-12-01 03:08:23 +00002073 C == LHS ? D : C, TD, TLI, DT, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00002074 return V;
2075
2076 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2077 if (A && C && (A == C || A == D || B == C || B == D) &&
2078 NoLHSWrapProblem && NoRHSWrapProblem) {
2079 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2080 Value *Y = (A == C || A == D) ? B : A;
2081 Value *Z = (C == A || C == B) ? D : C;
Chad Rosier618c1db2011-12-01 03:08:23 +00002082 if (Value *V = SimplifyICmpInst(Pred, Y, Z, TD, TLI, DT, MaxRecurse-1))
Duncan Sands52fb8462011-02-13 17:15:40 +00002083 return V;
2084 }
2085 }
2086
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002087 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Nick Lewycky78679272011-03-04 10:06:52 +00002088 bool KnownNonNegative, KnownNegative;
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002089 switch (Pred) {
2090 default:
2091 break;
Nick Lewycky78679272011-03-04 10:06:52 +00002092 case ICmpInst::ICMP_SGT:
2093 case ICmpInst::ICMP_SGE:
2094 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
2095 if (!KnownNonNegative)
2096 break;
2097 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002098 case ICmpInst::ICMP_EQ:
2099 case ICmpInst::ICMP_UGT:
2100 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002101 return getFalse(ITy);
Nick Lewycky78679272011-03-04 10:06:52 +00002102 case ICmpInst::ICMP_SLT:
2103 case ICmpInst::ICMP_SLE:
2104 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
2105 if (!KnownNonNegative)
2106 break;
2107 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002108 case ICmpInst::ICMP_NE:
2109 case ICmpInst::ICMP_ULT:
2110 case ICmpInst::ICMP_ULE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002111 return getTrue(ITy);
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002112 }
2113 }
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002114 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2115 bool KnownNonNegative, KnownNegative;
2116 switch (Pred) {
2117 default:
2118 break;
2119 case ICmpInst::ICMP_SGT:
2120 case ICmpInst::ICMP_SGE:
2121 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
2122 if (!KnownNonNegative)
2123 break;
2124 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00002125 case ICmpInst::ICMP_NE:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002126 case ICmpInst::ICMP_UGT:
2127 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002128 return getTrue(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002129 case ICmpInst::ICMP_SLT:
2130 case ICmpInst::ICMP_SLE:
2131 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
2132 if (!KnownNonNegative)
2133 break;
2134 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00002135 case ICmpInst::ICMP_EQ:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002136 case ICmpInst::ICMP_ULT:
2137 case ICmpInst::ICMP_ULE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00002138 return getFalse(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00002139 }
2140 }
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00002141
Duncan Sandsc65c7472011-10-28 18:17:44 +00002142 // x udiv y <=u x.
2143 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2144 // icmp pred (X /u Y), X
2145 if (Pred == ICmpInst::ICMP_UGT)
2146 return getFalse(ITy);
2147 if (Pred == ICmpInst::ICMP_ULE)
2148 return getTrue(ITy);
2149 }
2150
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002151 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2152 LBO->getOperand(1) == RBO->getOperand(1)) {
2153 switch (LBO->getOpcode()) {
2154 default: break;
2155 case Instruction::UDiv:
2156 case Instruction::LShr:
2157 if (ICmpInst::isSigned(Pred))
2158 break;
2159 // fall-through
2160 case Instruction::SDiv:
2161 case Instruction::AShr:
Eli Friedmanb6e7cd62011-05-05 21:59:18 +00002162 if (!LBO->isExact() || !RBO->isExact())
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002163 break;
2164 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Chad Rosier618c1db2011-12-01 03:08:23 +00002165 RBO->getOperand(0), TD, TLI, DT, MaxRecurse-1))
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002166 return V;
2167 break;
2168 case Instruction::Shl: {
Duncan Sandsc9d904e2011-08-04 10:02:21 +00002169 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002170 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2171 if (!NUW && !NSW)
2172 break;
2173 if (!NSW && ICmpInst::isSigned(Pred))
2174 break;
2175 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
Chad Rosier618c1db2011-12-01 03:08:23 +00002176 RBO->getOperand(0), TD, TLI, DT, MaxRecurse-1))
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00002177 return V;
2178 break;
2179 }
2180 }
2181 }
2182
Duncan Sandsad206812011-05-03 19:53:10 +00002183 // Simplify comparisons involving max/min.
2184 Value *A, *B;
2185 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2186 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2187
Duncan Sands8140ad32011-05-04 16:05:05 +00002188 // Signed variants on "max(a,b)>=a -> true".
Duncan Sandsad206812011-05-03 19:53:10 +00002189 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2190 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2191 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2192 // We analyze this as smax(A, B) pred A.
2193 P = Pred;
2194 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2195 (A == LHS || B == LHS)) {
2196 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2197 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2198 // We analyze this as smax(A, B) swapped-pred A.
2199 P = CmpInst::getSwappedPredicate(Pred);
2200 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2201 (A == RHS || B == RHS)) {
2202 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2203 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2204 // We analyze this as smax(-A, -B) swapped-pred -A.
2205 // Note that we do not need to actually form -A or -B thanks to EqP.
2206 P = CmpInst::getSwappedPredicate(Pred);
2207 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2208 (A == LHS || B == LHS)) {
2209 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2210 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2211 // We analyze this as smax(-A, -B) pred -A.
2212 // Note that we do not need to actually form -A or -B thanks to EqP.
2213 P = Pred;
2214 }
2215 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2216 // Cases correspond to "max(A, B) p A".
2217 switch (P) {
2218 default:
2219 break;
2220 case CmpInst::ICMP_EQ:
2221 case CmpInst::ICMP_SLE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002222 // Equivalent to "A EqP B". This may be the same as the condition tested
2223 // in the max/min; if so, we can just return that.
2224 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2225 return V;
2226 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2227 return V;
2228 // Otherwise, see if "A EqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002229 if (MaxRecurse)
Chad Rosier618c1db2011-12-01 03:08:23 +00002230 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002231 return V;
2232 break;
2233 case CmpInst::ICMP_NE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002234 case CmpInst::ICMP_SGT: {
2235 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2236 // Equivalent to "A InvEqP B". This may be the same as the condition
2237 // tested in the max/min; if so, we can just return that.
2238 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2239 return V;
2240 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2241 return V;
2242 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002243 if (MaxRecurse)
Chad Rosier618c1db2011-12-01 03:08:23 +00002244 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002245 return V;
2246 break;
Duncan Sandse864b5b2011-05-07 16:56:49 +00002247 }
Duncan Sandsad206812011-05-03 19:53:10 +00002248 case CmpInst::ICMP_SGE:
2249 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002250 return getTrue(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002251 case CmpInst::ICMP_SLT:
2252 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002253 return getFalse(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002254 }
2255 }
2256
Duncan Sands8140ad32011-05-04 16:05:05 +00002257 // Unsigned variants on "max(a,b)>=a -> true".
Duncan Sandsad206812011-05-03 19:53:10 +00002258 P = CmpInst::BAD_ICMP_PREDICATE;
2259 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2260 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2261 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2262 // We analyze this as umax(A, B) pred A.
2263 P = Pred;
2264 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2265 (A == LHS || B == LHS)) {
2266 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2267 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2268 // We analyze this as umax(A, B) swapped-pred A.
2269 P = CmpInst::getSwappedPredicate(Pred);
2270 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2271 (A == RHS || B == RHS)) {
2272 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2273 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2274 // We analyze this as umax(-A, -B) swapped-pred -A.
2275 // Note that we do not need to actually form -A or -B thanks to EqP.
2276 P = CmpInst::getSwappedPredicate(Pred);
2277 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2278 (A == LHS || B == LHS)) {
2279 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2280 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2281 // We analyze this as umax(-A, -B) pred -A.
2282 // Note that we do not need to actually form -A or -B thanks to EqP.
2283 P = Pred;
2284 }
2285 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2286 // Cases correspond to "max(A, B) p A".
2287 switch (P) {
2288 default:
2289 break;
2290 case CmpInst::ICMP_EQ:
2291 case CmpInst::ICMP_ULE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002292 // Equivalent to "A EqP B". This may be the same as the condition tested
2293 // in the max/min; if so, we can just return that.
2294 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2295 return V;
2296 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2297 return V;
2298 // Otherwise, see if "A EqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002299 if (MaxRecurse)
Chad Rosier618c1db2011-12-01 03:08:23 +00002300 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002301 return V;
2302 break;
2303 case CmpInst::ICMP_NE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002304 case CmpInst::ICMP_UGT: {
2305 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2306 // Equivalent to "A InvEqP B". This may be the same as the condition
2307 // tested in the max/min; if so, we can just return that.
2308 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2309 return V;
2310 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2311 return V;
2312 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002313 if (MaxRecurse)
Chad Rosier618c1db2011-12-01 03:08:23 +00002314 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, TLI, DT, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002315 return V;
2316 break;
Duncan Sandse864b5b2011-05-07 16:56:49 +00002317 }
Duncan Sandsad206812011-05-03 19:53:10 +00002318 case CmpInst::ICMP_UGE:
2319 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002320 return getTrue(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002321 case CmpInst::ICMP_ULT:
2322 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002323 return getFalse(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002324 }
2325 }
2326
Duncan Sands8140ad32011-05-04 16:05:05 +00002327 // Variants on "max(x,y) >= min(x,z)".
2328 Value *C, *D;
2329 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2330 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2331 (A == C || A == D || B == C || B == D)) {
2332 // max(x, ?) pred min(x, ?).
2333 if (Pred == CmpInst::ICMP_SGE)
2334 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002335 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002336 if (Pred == CmpInst::ICMP_SLT)
2337 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002338 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002339 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2340 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2341 (A == C || A == D || B == C || B == D)) {
2342 // min(x, ?) pred max(x, ?).
2343 if (Pred == CmpInst::ICMP_SLE)
2344 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002345 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002346 if (Pred == CmpInst::ICMP_SGT)
2347 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002348 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002349 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2350 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2351 (A == C || A == D || B == C || B == D)) {
2352 // max(x, ?) pred min(x, ?).
2353 if (Pred == CmpInst::ICMP_UGE)
2354 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002355 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002356 if (Pred == CmpInst::ICMP_ULT)
2357 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002358 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002359 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2360 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2361 (A == C || A == D || B == C || B == D)) {
2362 // min(x, ?) pred max(x, ?).
2363 if (Pred == CmpInst::ICMP_ULE)
2364 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002365 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002366 if (Pred == CmpInst::ICMP_UGT)
2367 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002368 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002369 }
2370
Nick Lewyckyf7087ea2012-02-26 02:09:49 +00002371 // Simplify comparisons of GEPs.
2372 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2373 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2374 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2375 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2376 (ICmpInst::isEquality(Pred) ||
2377 (GLHS->isInBounds() && GRHS->isInBounds() &&
2378 Pred == ICmpInst::getSignedPredicate(Pred)))) {
2379 // The bases are equal and the indices are constant. Build a constant
2380 // expression GEP with the same indices and a null base pointer to see
2381 // what constant folding can make out of it.
2382 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2383 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2384 Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2385
2386 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2387 Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2388 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2389 }
2390 }
2391 }
2392
Duncan Sands1ac7c992010-11-07 16:12:23 +00002393 // If the comparison is with the result of a select instruction, check whether
2394 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002395 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002396 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002397 return V;
2398
2399 // If the comparison is with the result of a phi instruction, check whether
2400 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00002401 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002402 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00002403 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +00002404
Chris Lattner9f3c25a2009-11-09 22:57:59 +00002405 return 0;
2406}
2407
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002408Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002409 const TargetData *TD,
2410 const TargetLibraryInfo *TLI,
2411 const DominatorTree *DT) {
2412 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002413}
2414
Chris Lattner9dbb4292009-11-09 23:28:39 +00002415/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2416/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002417static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002418 const TargetData *TD,
2419 const TargetLibraryInfo *TLI,
2420 const DominatorTree *DT,
Duncan Sands18450092010-11-16 12:16:38 +00002421 unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00002422 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2423 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2424
Chris Lattnerd06094f2009-11-10 00:55:12 +00002425 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00002426 if (Constant *CRHS = dyn_cast<Constant>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002427 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD, TLI);
Duncan Sands12a86f52010-11-14 11:23:23 +00002428
Chris Lattnerd06094f2009-11-10 00:55:12 +00002429 // If we have a constant, make sure it is on the RHS.
2430 std::swap(LHS, RHS);
2431 Pred = CmpInst::getSwappedPredicate(Pred);
2432 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002433
Chris Lattner210c5d42009-11-09 23:55:12 +00002434 // Fold trivial predicates.
2435 if (Pred == FCmpInst::FCMP_FALSE)
2436 return ConstantInt::get(GetCompareTy(LHS), 0);
2437 if (Pred == FCmpInst::FCMP_TRUE)
2438 return ConstantInt::get(GetCompareTy(LHS), 1);
2439
Chris Lattner210c5d42009-11-09 23:55:12 +00002440 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2441 return UndefValue::get(GetCompareTy(LHS));
2442
2443 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands124708d2011-01-01 20:08:02 +00002444 if (LHS == RHS) {
Chris Lattner210c5d42009-11-09 23:55:12 +00002445 if (CmpInst::isTrueWhenEqual(Pred))
2446 return ConstantInt::get(GetCompareTy(LHS), 1);
2447 if (CmpInst::isFalseWhenEqual(Pred))
2448 return ConstantInt::get(GetCompareTy(LHS), 0);
2449 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002450
Chris Lattner210c5d42009-11-09 23:55:12 +00002451 // Handle fcmp with constant RHS
2452 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2453 // If the constant is a nan, see if we can fold the comparison based on it.
2454 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2455 if (CFP->getValueAPF().isNaN()) {
2456 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2457 return ConstantInt::getFalse(CFP->getContext());
2458 assert(FCmpInst::isUnordered(Pred) &&
2459 "Comparison must be either ordered or unordered!");
2460 // True if unordered.
2461 return ConstantInt::getTrue(CFP->getContext());
2462 }
Dan Gohman6b617a72010-02-22 04:06:03 +00002463 // Check whether the constant is an infinity.
2464 if (CFP->getValueAPF().isInfinity()) {
2465 if (CFP->getValueAPF().isNegative()) {
2466 switch (Pred) {
2467 case FCmpInst::FCMP_OLT:
2468 // No value is ordered and less than negative infinity.
2469 return ConstantInt::getFalse(CFP->getContext());
2470 case FCmpInst::FCMP_UGE:
2471 // All values are unordered with or at least negative infinity.
2472 return ConstantInt::getTrue(CFP->getContext());
2473 default:
2474 break;
2475 }
2476 } else {
2477 switch (Pred) {
2478 case FCmpInst::FCMP_OGT:
2479 // No value is ordered and greater than infinity.
2480 return ConstantInt::getFalse(CFP->getContext());
2481 case FCmpInst::FCMP_ULE:
2482 // All values are unordered with and at most infinity.
2483 return ConstantInt::getTrue(CFP->getContext());
2484 default:
2485 break;
2486 }
2487 }
2488 }
Chris Lattner210c5d42009-11-09 23:55:12 +00002489 }
2490 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002491
Duncan Sands92826de2010-11-07 16:46:25 +00002492 // If the comparison is with the result of a select instruction, check whether
2493 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002494 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002495 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002496 return V;
2497
2498 // If the comparison is with the result of a phi instruction, check whether
2499 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00002500 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002501 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00002502 return V;
Duncan Sands92826de2010-11-07 16:46:25 +00002503
Chris Lattner9dbb4292009-11-09 23:28:39 +00002504 return 0;
2505}
2506
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002507Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002508 const TargetData *TD,
2509 const TargetLibraryInfo *TLI,
2510 const DominatorTree *DT) {
2511 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002512}
2513
Chris Lattner04754262010-04-20 05:32:14 +00002514/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2515/// the result. If not, this returns null.
Duncan Sands124708d2011-01-01 20:08:02 +00002516Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
2517 const TargetData *TD, const DominatorTree *) {
Chris Lattner04754262010-04-20 05:32:14 +00002518 // select true, X, Y -> X
2519 // select false, X, Y -> Y
2520 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2521 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002522
Chris Lattner04754262010-04-20 05:32:14 +00002523 // select C, X, X -> X
Duncan Sands124708d2011-01-01 20:08:02 +00002524 if (TrueVal == FalseVal)
Chris Lattner04754262010-04-20 05:32:14 +00002525 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002526
Chris Lattner04754262010-04-20 05:32:14 +00002527 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2528 if (isa<Constant>(TrueVal))
2529 return TrueVal;
2530 return FalseVal;
2531 }
Dan Gohman68c0dbc2011-07-01 01:03:43 +00002532 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2533 return FalseVal;
2534 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2535 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002536
Chris Lattner04754262010-04-20 05:32:14 +00002537 return 0;
2538}
2539
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002540/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2541/// fold the result. If not, this returns null.
Chad Rosier618c1db2011-12-01 03:08:23 +00002542Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const TargetData *TD,
2543 const DominatorTree *) {
Duncan Sands85bbff62010-11-22 13:42:49 +00002544 // The type of the GEP pointer operand.
Nadav Rotem16087692011-12-05 06:29:09 +00002545 PointerType *PtrTy = dyn_cast<PointerType>(Ops[0]->getType());
2546 // The GEP pointer operand is not a pointer, it's a vector of pointers.
2547 if (!PtrTy)
2548 return 0;
Duncan Sands85bbff62010-11-22 13:42:49 +00002549
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002550 // getelementptr P -> P.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002551 if (Ops.size() == 1)
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002552 return Ops[0];
2553
Duncan Sands85bbff62010-11-22 13:42:49 +00002554 if (isa<UndefValue>(Ops[0])) {
2555 // Compute the (pointer) type returned by the GEP instruction.
Jay Foada9203102011-07-25 09:48:08 +00002556 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002557 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
Duncan Sands85bbff62010-11-22 13:42:49 +00002558 return UndefValue::get(GEPTy);
2559 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002560
Jay Foadb9b54eb2011-07-19 15:07:52 +00002561 if (Ops.size() == 2) {
Duncan Sandse60d79f2010-11-21 13:53:09 +00002562 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002563 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2564 if (C->isZero())
2565 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +00002566 // getelementptr P, N -> P if P points to a type of zero size.
2567 if (TD) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002568 Type *Ty = PtrTy->getElementType();
Duncan Sandsa63395a2010-11-22 16:32:50 +00002569 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +00002570 return Ops[0];
2571 }
2572 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002573
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002574 // Check to see if this is constant foldable.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002575 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002576 if (!isa<Constant>(Ops[i]))
2577 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +00002578
Jay Foaddab3d292011-07-21 14:31:17 +00002579 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002580}
2581
Duncan Sandsdabc2802011-09-05 06:52:48 +00002582/// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2583/// can fold the result. If not, this returns null.
2584Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2585 ArrayRef<unsigned> Idxs,
2586 const TargetData *,
2587 const DominatorTree *) {
2588 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2589 if (Constant *CVal = dyn_cast<Constant>(Val))
2590 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2591
2592 // insertvalue x, undef, n -> x
2593 if (match(Val, m_Undef()))
2594 return Agg;
2595
2596 // insertvalue x, (extractvalue y, n), n
2597 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramerae707bd2011-09-05 18:16:19 +00002598 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2599 EV->getIndices() == Idxs) {
Duncan Sandsdabc2802011-09-05 06:52:48 +00002600 // insertvalue undef, (extractvalue y, n), n -> y
2601 if (match(Agg, m_Undef()))
2602 return EV->getAggregateOperand();
2603
2604 // insertvalue y, (extractvalue y, n), n -> y
2605 if (Agg == EV->getAggregateOperand())
2606 return Agg;
2607 }
2608
2609 return 0;
2610}
2611
Duncan Sandsff103412010-11-17 04:30:22 +00002612/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
2613static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
2614 // If all of the PHI's incoming values are the same then replace the PHI node
2615 // with the common value.
2616 Value *CommonValue = 0;
2617 bool HasUndefInput = false;
2618 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2619 Value *Incoming = PN->getIncomingValue(i);
2620 // If the incoming value is the phi node itself, it can safely be skipped.
2621 if (Incoming == PN) continue;
2622 if (isa<UndefValue>(Incoming)) {
2623 // Remember that we saw an undef value, but otherwise ignore them.
2624 HasUndefInput = true;
2625 continue;
2626 }
2627 if (CommonValue && Incoming != CommonValue)
2628 return 0; // Not the same, bail out.
2629 CommonValue = Incoming;
2630 }
2631
2632 // If CommonValue is null then all of the incoming values were either undef or
2633 // equal to the phi node itself.
2634 if (!CommonValue)
2635 return UndefValue::get(PN->getType());
2636
2637 // If we have a PHI node like phi(X, undef, X), where X is defined by some
2638 // instruction, we cannot return X as the result of the PHI node unless it
2639 // dominates the PHI block.
2640 if (HasUndefInput)
2641 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
2642
2643 return CommonValue;
2644}
2645
Chris Lattnerd06094f2009-11-10 00:55:12 +00002646//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +00002647
Chris Lattnerd06094f2009-11-10 00:55:12 +00002648/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2649/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002650static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002651 const TargetData *TD,
2652 const TargetLibraryInfo *TLI,
2653 const DominatorTree *DT,
Duncan Sands18450092010-11-16 12:16:38 +00002654 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00002655 switch (Opcode) {
Chris Lattner81a0dc92011-02-09 17:15:04 +00002656 case Instruction::Add:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002657 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Chad Rosier618c1db2011-12-01 03:08:23 +00002658 TD, TLI, DT, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002659 case Instruction::Sub:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002660 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Chad Rosier618c1db2011-12-01 03:08:23 +00002661 TD, TLI, DT, MaxRecurse);
2662 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, TD, TLI, DT,
2663 MaxRecurse);
2664 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, TD, TLI, DT,
2665 MaxRecurse);
2666 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, TD, TLI, DT,
2667 MaxRecurse);
2668 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, TD, TLI, DT,
2669 MaxRecurse);
2670 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, TD, TLI, DT,
2671 MaxRecurse);
2672 case Instruction::URem: return SimplifyURemInst(LHS, RHS, TD, TLI, DT,
2673 MaxRecurse);
2674 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, TD, TLI, DT,
2675 MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002676 case Instruction::Shl:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002677 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Chad Rosier618c1db2011-12-01 03:08:23 +00002678 TD, TLI, DT, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002679 case Instruction::LShr:
Chad Rosier618c1db2011-12-01 03:08:23 +00002680 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, TD, TLI, DT,
2681 MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002682 case Instruction::AShr:
Chad Rosier618c1db2011-12-01 03:08:23 +00002683 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, TD, TLI, DT,
2684 MaxRecurse);
2685 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, TLI, DT,
2686 MaxRecurse);
2687 case Instruction::Or: return SimplifyOrInst (LHS, RHS, TD, TLI, DT,
2688 MaxRecurse);
2689 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, TLI, DT,
2690 MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002691 default:
2692 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2693 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2694 Constant *COps[] = {CLHS, CRHS};
Chad Rosier618c1db2011-12-01 03:08:23 +00002695 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, TD, TLI);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002696 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002697
Duncan Sands566edb02010-12-21 08:49:00 +00002698 // If the operation is associative, try some generic simplifications.
2699 if (Instruction::isAssociative(Opcode))
Chad Rosier618c1db2011-12-01 03:08:23 +00002700 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, TLI, DT,
Duncan Sands566edb02010-12-21 08:49:00 +00002701 MaxRecurse))
2702 return V;
2703
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002704 // If the operation is with the result of a select instruction, check whether
2705 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002706 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002707 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, TLI, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00002708 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002709 return V;
2710
2711 // If the operation is with the result of a phi instruction, check whether
2712 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002713 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
Chad Rosier618c1db2011-12-01 03:08:23 +00002714 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, TLI, DT,
2715 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002716 return V;
2717
Chris Lattnerd06094f2009-11-10 00:55:12 +00002718 return 0;
2719 }
2720}
Chris Lattner9dbb4292009-11-09 23:28:39 +00002721
Duncan Sands12a86f52010-11-14 11:23:23 +00002722Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002723 const TargetData *TD, const TargetLibraryInfo *TLI,
2724 const DominatorTree *DT) {
2725 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, TLI, DT, RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +00002726}
2727
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002728/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2729/// fold the result.
2730static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002731 const TargetData *TD,
2732 const TargetLibraryInfo *TLI,
2733 const DominatorTree *DT,
Duncan Sands18450092010-11-16 12:16:38 +00002734 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002735 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Chad Rosier618c1db2011-12-01 03:08:23 +00002736 return SimplifyICmpInst(Predicate, LHS, RHS, TD, TLI, DT, MaxRecurse);
2737 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, TLI, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002738}
2739
2740Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Chad Rosier618c1db2011-12-01 03:08:23 +00002741 const TargetData *TD, const TargetLibraryInfo *TLI,
2742 const DominatorTree *DT) {
2743 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002744}
Chris Lattnere3453782009-11-10 01:08:51 +00002745
Dan Gohman71d05032011-11-04 18:32:42 +00002746static Value *SimplifyCallInst(CallInst *CI) {
2747 // call undef -> undef
2748 if (isa<UndefValue>(CI->getCalledValue()))
2749 return UndefValue::get(CI->getType());
2750
2751 return 0;
2752}
2753
Chris Lattnere3453782009-11-10 01:08:51 +00002754/// SimplifyInstruction - See if we can compute a simplified version of this
2755/// instruction. If not, this returns null.
Duncan Sandseff05812010-11-14 18:36:10 +00002756Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00002757 const TargetLibraryInfo *TLI,
Duncan Sandseff05812010-11-14 18:36:10 +00002758 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +00002759 Value *Result;
2760
Chris Lattnere3453782009-11-10 01:08:51 +00002761 switch (I->getOpcode()) {
2762 default:
Chad Rosier618c1db2011-12-01 03:08:23 +00002763 Result = ConstantFoldInstruction(I, TD, TLI);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002764 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002765 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002766 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2767 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2768 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002769 TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002770 break;
Duncan Sandsfea3b212010-12-15 14:07:39 +00002771 case Instruction::Sub:
2772 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2773 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2774 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002775 TD, TLI, DT);
Duncan Sandsfea3b212010-12-15 14:07:39 +00002776 break;
Duncan Sands82fdab32010-12-21 14:00:22 +00002777 case Instruction::Mul:
Chad Rosier618c1db2011-12-01 03:08:23 +00002778 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands82fdab32010-12-21 14:00:22 +00002779 break;
Duncan Sands593faa52011-01-28 16:51:11 +00002780 case Instruction::SDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002781 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands593faa52011-01-28 16:51:11 +00002782 break;
2783 case Instruction::UDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002784 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands593faa52011-01-28 16:51:11 +00002785 break;
Frits van Bommel1fca2c32011-01-29 15:26:31 +00002786 case Instruction::FDiv:
Chad Rosier618c1db2011-12-01 03:08:23 +00002787 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Frits van Bommel1fca2c32011-01-29 15:26:31 +00002788 break;
Duncan Sandsf24ed772011-05-02 16:27:02 +00002789 case Instruction::SRem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002790 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002791 break;
2792 case Instruction::URem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002793 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002794 break;
2795 case Instruction::FRem:
Chad Rosier618c1db2011-12-01 03:08:23 +00002796 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002797 break;
Duncan Sandsc43cee32011-01-14 00:37:45 +00002798 case Instruction::Shl:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002799 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2800 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2801 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002802 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002803 break;
2804 case Instruction::LShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002805 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2806 cast<BinaryOperator>(I)->isExact(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002807 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002808 break;
2809 case Instruction::AShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002810 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2811 cast<BinaryOperator>(I)->isExact(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002812 TD, TLI, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002813 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002814 case Instruction::And:
Chad Rosier618c1db2011-12-01 03:08:23 +00002815 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002816 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002817 case Instruction::Or:
Chad Rosier618c1db2011-12-01 03:08:23 +00002818 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002819 break;
Duncan Sands2b749872010-11-17 18:52:15 +00002820 case Instruction::Xor:
Chad Rosier618c1db2011-12-01 03:08:23 +00002821 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sands2b749872010-11-17 18:52:15 +00002822 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002823 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002824 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002825 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002826 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002827 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002828 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
Chad Rosier618c1db2011-12-01 03:08:23 +00002829 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002830 break;
Chris Lattner04754262010-04-20 05:32:14 +00002831 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002832 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
2833 I->getOperand(2), TD, DT);
2834 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002835 case Instruction::GetElementPtr: {
2836 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Jay Foadb9b54eb2011-07-19 15:07:52 +00002837 Result = SimplifyGEPInst(Ops, TD, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002838 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002839 }
Duncan Sandsdabc2802011-09-05 06:52:48 +00002840 case Instruction::InsertValue: {
2841 InsertValueInst *IV = cast<InsertValueInst>(I);
2842 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
2843 IV->getInsertedValueOperand(),
2844 IV->getIndices(), TD, DT);
2845 break;
2846 }
Duncan Sandscd6636c2010-11-14 13:30:18 +00002847 case Instruction::PHI:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002848 Result = SimplifyPHINode(cast<PHINode>(I), DT);
2849 break;
Dan Gohman71d05032011-11-04 18:32:42 +00002850 case Instruction::Call:
2851 Result = SimplifyCallInst(cast<CallInst>(I));
2852 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002853 }
Duncan Sandsd261dc62010-11-17 08:35:29 +00002854
2855 /// If called on unreachable code, the above logic may report that the
2856 /// instruction simplified to itself. Make life easier for users by
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00002857 /// detecting that case here, returning a safe value instead.
2858 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnere3453782009-11-10 01:08:51 +00002859}
2860
Chris Lattner40d8c282009-11-10 22:26:15 +00002861/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
2862/// delete the From instruction. In addition to a basic RAUW, this does a
2863/// recursive simplification of the newly formed instructions. This catches
2864/// things where one simplification exposes other opportunities. This only
2865/// simplifies and deletes scalar operations, it does not change the CFG.
2866///
2867void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
Duncan Sandseff05812010-11-14 18:36:10 +00002868 const TargetData *TD,
Chad Rosier618c1db2011-12-01 03:08:23 +00002869 const TargetLibraryInfo *TLI,
Duncan Sandseff05812010-11-14 18:36:10 +00002870 const DominatorTree *DT) {
Chris Lattner40d8c282009-11-10 22:26:15 +00002871 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
Duncan Sands12a86f52010-11-14 11:23:23 +00002872
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002873 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
2874 // we can know if it gets deleted out from under us or replaced in a
2875 // recursive simplification.
Chris Lattner40d8c282009-11-10 22:26:15 +00002876 WeakVH FromHandle(From);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002877 WeakVH ToHandle(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00002878
Chris Lattner40d8c282009-11-10 22:26:15 +00002879 while (!From->use_empty()) {
2880 // Update the instruction to use the new value.
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002881 Use &TheUse = From->use_begin().getUse();
2882 Instruction *User = cast<Instruction>(TheUse.getUser());
2883 TheUse = To;
2884
2885 // Check to see if the instruction can be folded due to the operand
2886 // replacement. For example changing (or X, Y) into (or X, -1) can replace
2887 // the 'or' with -1.
2888 Value *SimplifiedVal;
2889 {
2890 // Sanity check to make sure 'User' doesn't dangle across
2891 // SimplifyInstruction.
2892 AssertingVH<> UserHandle(User);
Duncan Sands12a86f52010-11-14 11:23:23 +00002893
Chad Rosier618c1db2011-12-01 03:08:23 +00002894 SimplifiedVal = SimplifyInstruction(User, TD, TLI, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002895 if (SimplifiedVal == 0) continue;
Chris Lattner40d8c282009-11-10 22:26:15 +00002896 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002897
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002898 // Recursively simplify this user to the new value.
Chad Rosier618c1db2011-12-01 03:08:23 +00002899 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, TLI, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002900 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
2901 To = ToHandle;
Duncan Sands12a86f52010-11-14 11:23:23 +00002902
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002903 assert(ToHandle && "To value deleted by recursive simplification?");
Duncan Sands12a86f52010-11-14 11:23:23 +00002904
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002905 // If the recursive simplification ended up revisiting and deleting
2906 // 'From' then we're done.
2907 if (From == 0)
2908 return;
Chris Lattner40d8c282009-11-10 22:26:15 +00002909 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002910
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002911 // If 'From' has value handles referring to it, do a real RAUW to update them.
2912 From->replaceAllUsesWith(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00002913
Chris Lattner40d8c282009-11-10 22:26:15 +00002914 From->eraseFromParent();
2915}