blob: 83881deccf4069253c9e6454d22708db16195ebd [file] [log] [blame]
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001//===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements routines for folding instructions into simpler forms
Duncan Sands4cd2ad12010-11-23 10:50:08 +000011// that do not require creating new instructions. This does constant folding
12// ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
13// returning a constant ("and i32 %x, 0" -> "0") or an already existing value
Duncan Sandsee9a2e32010-12-20 14:47:04 +000014// ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been
15// simplified: This is usually true and assuming it simplifies the logic (if
16// they have not been simplified then results are correct but maybe suboptimal).
Chris Lattner9f3c25a2009-11-09 22:57:59 +000017//
18//===----------------------------------------------------------------------===//
19
Duncan Sandsa3c44a52010-12-22 09:40:51 +000020#define DEBUG_TYPE "instsimplify"
Jay Foad562b84b2011-04-11 09:35:34 +000021#include "llvm/Operator.h"
Duncan Sandsa3c44a52010-12-22 09:40:51 +000022#include "llvm/ADT/Statistic.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000023#include "llvm/Analysis/InstructionSimplify.h"
24#include "llvm/Analysis/ConstantFolding.h"
Duncan Sands18450092010-11-16 12:16:38 +000025#include "llvm/Analysis/Dominators.h"
Duncan Sandsd70d1a52011-01-25 09:38:29 +000026#include "llvm/Analysis/ValueTracking.h"
Nick Lewycky3a73e342011-03-04 07:00:57 +000027#include "llvm/Support/ConstantRange.h"
Chris Lattnerd06094f2009-11-10 00:55:12 +000028#include "llvm/Support/PatternMatch.h"
Duncan Sands18450092010-11-16 12:16:38 +000029#include "llvm/Support/ValueHandle.h"
Duncan Sandse60d79f2010-11-21 13:53:09 +000030#include "llvm/Target/TargetData.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000031using namespace llvm;
Chris Lattnerd06094f2009-11-10 00:55:12 +000032using namespace llvm::PatternMatch;
Chris Lattner9f3c25a2009-11-09 22:57:59 +000033
Chris Lattner81a0dc92011-02-09 17:15:04 +000034enum { RecursionLimit = 3 };
Duncan Sandsa74a58c2010-11-10 18:23:01 +000035
Duncan Sandsa3c44a52010-12-22 09:40:51 +000036STATISTIC(NumExpand, "Number of expansions");
37STATISTIC(NumFactor , "Number of factorizations");
38STATISTIC(NumReassoc, "Number of reassociations");
39
Duncan Sands82fdab32010-12-21 14:00:22 +000040static Value *SimplifyAndInst(Value *, Value *, const TargetData *,
41 const DominatorTree *, unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000042static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
Duncan Sands18450092010-11-16 12:16:38 +000043 const DominatorTree *, unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000044static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
Duncan Sands18450092010-11-16 12:16:38 +000045 const DominatorTree *, unsigned);
Duncan Sands82fdab32010-12-21 14:00:22 +000046static Value *SimplifyOrInst(Value *, Value *, const TargetData *,
47 const DominatorTree *, unsigned);
48static Value *SimplifyXorInst(Value *, Value *, const TargetData *,
49 const DominatorTree *, unsigned);
Duncan Sands18450092010-11-16 12:16:38 +000050
Duncan Sandsf56138d2011-07-26 15:03:53 +000051/// getFalse - For a boolean type, or a vector of boolean type, return false, or
52/// a vector with every element false, as appropriate for the type.
53static Constant *getFalse(Type *Ty) {
54 assert((Ty->isIntegerTy(1) ||
55 (Ty->isVectorTy() &&
56 cast<VectorType>(Ty)->getElementType()->isIntegerTy(1))) &&
57 "Expected i1 type or a vector of i1!");
58 return Constant::getNullValue(Ty);
59}
60
61/// getTrue - For a boolean type, or a vector of boolean type, return true, or
62/// a vector with every element true, as appropriate for the type.
63static Constant *getTrue(Type *Ty) {
64 assert((Ty->isIntegerTy(1) ||
65 (Ty->isVectorTy() &&
66 cast<VectorType>(Ty)->getElementType()->isIntegerTy(1))) &&
67 "Expected i1 type or a vector of i1!");
68 return Constant::getAllOnesValue(Ty);
69}
70
Duncan Sands18450092010-11-16 12:16:38 +000071/// ValueDominatesPHI - Does the given value dominate the specified phi node?
72static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
73 Instruction *I = dyn_cast<Instruction>(V);
74 if (!I)
75 // Arguments and constants dominate all instructions.
76 return true;
77
78 // If we have a DominatorTree then do a precise test.
79 if (DT)
80 return DT->dominates(I, P);
81
82 // Otherwise, if the instruction is in the entry block, and is not an invoke,
83 // then it obviously dominates all phi nodes.
84 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
85 !isa<InvokeInst>(I))
86 return true;
87
88 return false;
89}
Duncan Sandsa74a58c2010-11-10 18:23:01 +000090
Duncan Sands3421d902010-12-21 13:32:22 +000091/// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
92/// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
93/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
94/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
95/// Returns the simplified value, or null if no simplification was performed.
96static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Benjamin Kramere21083a2010-12-28 13:52:52 +000097 unsigned OpcToExpand, const TargetData *TD,
Duncan Sands3421d902010-12-21 13:32:22 +000098 const DominatorTree *DT, unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +000099 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000100 // Recursion is always used, so bail out at once if we already hit the limit.
101 if (!MaxRecurse--)
102 return 0;
103
104 // Check whether the expression has the form "(A op' B) op C".
105 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
106 if (Op0->getOpcode() == OpcodeToExpand) {
107 // It does! Try turning it into "(A op C) op' (B op C)".
108 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
109 // Do "A op C" and "B op C" both simplify?
110 if (Value *L = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse))
111 if (Value *R = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
112 // They do! Return "L op' R" if it simplifies or is already available.
113 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000114 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
115 && L == B && R == A)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000116 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000117 return LHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000118 }
Duncan Sands3421d902010-12-21 13:32:22 +0000119 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000120 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
121 MaxRecurse)) {
122 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000123 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000124 }
Duncan Sands3421d902010-12-21 13:32:22 +0000125 }
126 }
127
128 // Check whether the expression has the form "A op (B op' C)".
129 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
130 if (Op1->getOpcode() == OpcodeToExpand) {
131 // It does! Try turning it into "(A op B) op' (A op C)".
132 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
133 // Do "A op B" and "A op C" both simplify?
134 if (Value *L = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse))
135 if (Value *R = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse)) {
136 // They do! Return "L op' R" if it simplifies or is already available.
137 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000138 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
139 && L == C && R == B)) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000140 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000141 return RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000142 }
Duncan Sands3421d902010-12-21 13:32:22 +0000143 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000144 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
145 MaxRecurse)) {
146 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000147 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000148 }
Duncan Sands3421d902010-12-21 13:32:22 +0000149 }
150 }
151
152 return 0;
153}
154
155/// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
156/// using the operation OpCodeToExtract. For example, when Opcode is Add and
157/// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
158/// Returns the simplified value, or null if no simplification was performed.
159static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Benjamin Kramere21083a2010-12-28 13:52:52 +0000160 unsigned OpcToExtract, const TargetData *TD,
Duncan Sands3421d902010-12-21 13:32:22 +0000161 const DominatorTree *DT, unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000162 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
Duncan Sands3421d902010-12-21 13:32:22 +0000163 // Recursion is always used, so bail out at once if we already hit the limit.
164 if (!MaxRecurse--)
165 return 0;
166
167 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
168 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
169
170 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
171 !Op1 || Op1->getOpcode() != OpcodeToExtract)
172 return 0;
173
174 // The expression has the form "(A op' B) op (C op' D)".
Duncan Sands82fdab32010-12-21 14:00:22 +0000175 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
176 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
Duncan Sands3421d902010-12-21 13:32:22 +0000177
178 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
179 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
180 // commutative case, "(A op' B) op (C op' A)"?
Duncan Sands124708d2011-01-01 20:08:02 +0000181 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
182 Value *DD = A == C ? D : C;
Duncan Sands3421d902010-12-21 13:32:22 +0000183 // Form "A op' (B op DD)" if it simplifies completely.
184 // Does "B op DD" simplify?
185 if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, DT, MaxRecurse)) {
186 // It does! Return "A op' V" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000187 // If V equals B then "A op' V" is just the LHS. If V equals DD then
188 // "A op' V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000189 if (V == B || V == DD) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000190 ++NumFactor;
Duncan Sands124708d2011-01-01 20:08:02 +0000191 return V == B ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000192 }
Duncan Sands3421d902010-12-21 13:32:22 +0000193 // Otherwise return "A op' V" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000194 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, DT, MaxRecurse)) {
195 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000196 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000197 }
Duncan Sands3421d902010-12-21 13:32:22 +0000198 }
199 }
200
201 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
202 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
203 // commutative case, "(A op' B) op (B op' D)"?
Duncan Sands124708d2011-01-01 20:08:02 +0000204 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
205 Value *CC = B == D ? C : D;
Duncan Sands3421d902010-12-21 13:32:22 +0000206 // Form "(A op CC) op' B" if it simplifies completely..
207 // Does "A op CC" simplify?
208 if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, DT, MaxRecurse)) {
209 // It does! Return "V op' B" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000210 // If V equals A then "V op' B" is just the LHS. If V equals CC then
211 // "V op' B" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000212 if (V == A || V == CC) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000213 ++NumFactor;
Duncan Sands124708d2011-01-01 20:08:02 +0000214 return V == A ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000215 }
Duncan Sands3421d902010-12-21 13:32:22 +0000216 // Otherwise return "V op' B" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000217 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, DT, MaxRecurse)) {
218 ++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 return 0;
225}
226
227/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
228/// operations. Returns the simpler value, or null if none was found.
Benjamin Kramere21083a2010-12-28 13:52:52 +0000229static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
Duncan Sands566edb02010-12-21 08:49:00 +0000230 const TargetData *TD,
231 const DominatorTree *DT,
232 unsigned MaxRecurse) {
Benjamin Kramere21083a2010-12-28 13:52:52 +0000233 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
Duncan Sands566edb02010-12-21 08:49:00 +0000234 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
235
236 // Recursion is always used, so bail out at once if we already hit the limit.
237 if (!MaxRecurse--)
238 return 0;
239
240 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
241 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
242
243 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
244 if (Op0 && Op0->getOpcode() == Opcode) {
245 Value *A = Op0->getOperand(0);
246 Value *B = Op0->getOperand(1);
247 Value *C = RHS;
248
249 // Does "B op C" simplify?
250 if (Value *V = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
251 // It does! Return "A op V" if it simplifies or is already available.
252 // If V equals B then "A op V" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000253 if (V == B) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000254 // Otherwise return "A op V" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000255 if (Value *W = SimplifyBinOp(Opcode, A, V, TD, DT, MaxRecurse)) {
256 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000257 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000258 }
Duncan Sands566edb02010-12-21 08:49:00 +0000259 }
260 }
261
262 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
263 if (Op1 && Op1->getOpcode() == Opcode) {
264 Value *A = LHS;
265 Value *B = Op1->getOperand(0);
266 Value *C = Op1->getOperand(1);
267
268 // Does "A op B" simplify?
269 if (Value *V = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse)) {
270 // It does! Return "V op C" if it simplifies or is already available.
271 // If V equals B then "V op C" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000272 if (V == B) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000273 // Otherwise return "V op C" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000274 if (Value *W = SimplifyBinOp(Opcode, V, C, TD, DT, MaxRecurse)) {
275 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000276 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000277 }
Duncan Sands566edb02010-12-21 08:49:00 +0000278 }
279 }
280
281 // The remaining transforms require commutativity as well as associativity.
282 if (!Instruction::isCommutative(Opcode))
283 return 0;
284
285 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
286 if (Op0 && Op0->getOpcode() == Opcode) {
287 Value *A = Op0->getOperand(0);
288 Value *B = Op0->getOperand(1);
289 Value *C = RHS;
290
291 // Does "C op A" simplify?
292 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
293 // It does! Return "V op B" if it simplifies or is already available.
294 // If V equals A then "V op B" is just the LHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000295 if (V == A) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000296 // Otherwise return "V op B" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000297 if (Value *W = SimplifyBinOp(Opcode, V, B, TD, DT, MaxRecurse)) {
298 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000299 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000300 }
Duncan Sands566edb02010-12-21 08:49:00 +0000301 }
302 }
303
304 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
305 if (Op1 && Op1->getOpcode() == Opcode) {
306 Value *A = LHS;
307 Value *B = Op1->getOperand(0);
308 Value *C = Op1->getOperand(1);
309
310 // Does "C op A" simplify?
311 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
312 // It does! Return "B op V" if it simplifies or is already available.
313 // If V equals C then "B op V" is just the RHS.
Duncan Sands124708d2011-01-01 20:08:02 +0000314 if (V == C) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000315 // Otherwise return "B op V" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000316 if (Value *W = SimplifyBinOp(Opcode, B, V, TD, DT, MaxRecurse)) {
317 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000318 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000319 }
Duncan Sands566edb02010-12-21 08:49:00 +0000320 }
321 }
322
323 return 0;
324}
325
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000326/// ThreadBinOpOverSelect - In the case of a binary operation with a select
327/// instruction as an operand, try to simplify the binop by seeing whether
328/// evaluating it on both branches of the select results in the same value.
329/// Returns the common value if so, otherwise returns null.
330static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000331 const TargetData *TD,
332 const DominatorTree *DT,
333 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000334 // Recursion is always used, so bail out at once if we already hit the limit.
335 if (!MaxRecurse--)
336 return 0;
337
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000338 SelectInst *SI;
339 if (isa<SelectInst>(LHS)) {
340 SI = cast<SelectInst>(LHS);
341 } else {
342 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
343 SI = cast<SelectInst>(RHS);
344 }
345
346 // Evaluate the BinOp on the true and false branches of the select.
347 Value *TV;
348 Value *FV;
349 if (SI == LHS) {
Duncan Sands18450092010-11-16 12:16:38 +0000350 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
351 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000352 } else {
Duncan Sands18450092010-11-16 12:16:38 +0000353 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
354 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000355 }
356
Duncan Sands7cf85e72011-01-01 16:12:09 +0000357 // If they simplified to the same value, then return the common value.
Duncan Sands124708d2011-01-01 20:08:02 +0000358 // If they both failed to simplify then return null.
359 if (TV == FV)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000360 return TV;
361
362 // If one branch simplified to undef, return the other one.
363 if (TV && isa<UndefValue>(TV))
364 return FV;
365 if (FV && isa<UndefValue>(FV))
366 return TV;
367
368 // If applying the operation did not change the true and false select values,
369 // then the result of the binop is the select itself.
Duncan Sands124708d2011-01-01 20:08:02 +0000370 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000371 return SI;
372
373 // If one branch simplified and the other did not, and the simplified
374 // value is equal to the unsimplified one, return the simplified value.
375 // For example, select (cond, X, X & Z) & Z -> X & Z.
376 if ((FV && !TV) || (TV && !FV)) {
377 // Check that the simplified value has the form "X op Y" where "op" is the
378 // same as the original operation.
379 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
380 if (Simplified && Simplified->getOpcode() == Opcode) {
381 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
382 // We already know that "op" is the same as for the simplified value. See
383 // if the operands match too. If so, return the simplified value.
384 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
385 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
386 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
Duncan Sands124708d2011-01-01 20:08:02 +0000387 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
388 Simplified->getOperand(1) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000389 return Simplified;
390 if (Simplified->isCommutative() &&
Duncan Sands124708d2011-01-01 20:08:02 +0000391 Simplified->getOperand(1) == UnsimplifiedLHS &&
392 Simplified->getOperand(0) == UnsimplifiedRHS)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000393 return Simplified;
394 }
395 }
396
397 return 0;
398}
399
400/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
401/// try to simplify the comparison by seeing whether both branches of the select
402/// result in the same value. Returns the common value if so, otherwise returns
403/// null.
404static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000405 Value *RHS, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000406 const DominatorTree *DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000407 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000408 // Recursion is always used, so bail out at once if we already hit the limit.
409 if (!MaxRecurse--)
410 return 0;
411
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000412 // Make sure the select is on the LHS.
413 if (!isa<SelectInst>(LHS)) {
414 std::swap(LHS, RHS);
415 Pred = CmpInst::getSwappedPredicate(Pred);
416 }
417 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
418 SelectInst *SI = cast<SelectInst>(LHS);
Duncan Sands012f8542011-10-28 19:01:20 +0000419 Value *Cond = SI->getCondition();
420 Value *TV = SI->getTrueValue();
421 Value *FV = SI->getFalseValue();
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000422
Duncan Sands50ca4d32011-02-03 09:37:39 +0000423 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000424 // Does "cmp TV, RHS" simplify?
Duncan Sands012f8542011-10-28 19:01:20 +0000425 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, TD, DT, MaxRecurse);
426 if (!TCmp) {
427 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
428 // condition itself then we can replace it with 'true'.
429 if (match(Cond, m_ICmp(Pred, m_Specific(TV), m_Specific(RHS))))
430 TCmp = getTrue(Cond->getType());
Duncan Sands50ca4d32011-02-03 09:37:39 +0000431 }
Duncan Sands012f8542011-10-28 19:01:20 +0000432 if (!TCmp)
433 return 0;
434
435 // Does "cmp FV, RHS" simplify?
436 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, TD, DT, MaxRecurse);
437 if (!FCmp) {
438 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
439 // condition itself then we can replace it with 'false'.
440 if (match(Cond, m_ICmp(Pred, m_Specific(FV), m_Specific(RHS))))
441 FCmp = getFalse(Cond->getType());
442 }
443 if (!FCmp)
444 return 0;
445
446 // If both sides simplified to the same value, then use it as the result of
447 // the original comparison.
448 if (TCmp == FCmp)
449 return TCmp;
450 // If the false value simplified to false, then the result of the compare
451 // is equal to "Cond && TCmp". This also catches the case when the false
452 // value simplified to false and the true value to true, returning "Cond".
453 if (match(FCmp, m_Zero()))
454 if (Value *V = SimplifyAndInst(Cond, TCmp, TD, DT, MaxRecurse))
455 return V;
456 // If the true value simplified to true, then the result of the compare
457 // is equal to "Cond || FCmp".
458 if (match(TCmp, m_One()))
459 if (Value *V = SimplifyOrInst(Cond, FCmp, TD, DT, MaxRecurse))
460 return V;
461 // Finally, if the false value simplified to true and the true value to
462 // false, then the result of the compare is equal to "!Cond".
463 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
464 if (Value *V =
465 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
466 TD, DT, MaxRecurse))
467 return V;
Duncan Sands50ca4d32011-02-03 09:37:39 +0000468
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000469 return 0;
470}
471
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000472/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
473/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
474/// it on the incoming phi values yields the same result for every value. If so
475/// returns the common value, otherwise returns null.
476static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000477 const TargetData *TD, const DominatorTree *DT,
478 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000479 // Recursion is always used, so bail out at once if we already hit the limit.
480 if (!MaxRecurse--)
481 return 0;
482
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000483 PHINode *PI;
484 if (isa<PHINode>(LHS)) {
485 PI = cast<PHINode>(LHS);
Duncan Sands18450092010-11-16 12:16:38 +0000486 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
487 if (!ValueDominatesPHI(RHS, PI, DT))
488 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000489 } else {
490 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
491 PI = cast<PHINode>(RHS);
Duncan Sands18450092010-11-16 12:16:38 +0000492 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
493 if (!ValueDominatesPHI(LHS, PI, DT))
494 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000495 }
496
497 // Evaluate the BinOp on the incoming phi values.
498 Value *CommonValue = 0;
499 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000500 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000501 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000502 if (Incoming == PI) continue;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000503 Value *V = PI == LHS ?
Duncan Sands18450092010-11-16 12:16:38 +0000504 SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
505 SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000506 // If the operation failed to simplify, or simplified to a different value
507 // to previously, then give up.
508 if (!V || (CommonValue && V != CommonValue))
509 return 0;
510 CommonValue = V;
511 }
512
513 return CommonValue;
514}
515
516/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
517/// try to simplify the comparison by seeing whether comparing with all of the
518/// incoming phi values yields the same result every time. If so returns the
519/// common result, otherwise returns null.
520static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000521 const TargetData *TD, const DominatorTree *DT,
522 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000523 // Recursion is always used, so bail out at once if we already hit the limit.
524 if (!MaxRecurse--)
525 return 0;
526
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000527 // Make sure the phi is on the LHS.
528 if (!isa<PHINode>(LHS)) {
529 std::swap(LHS, RHS);
530 Pred = CmpInst::getSwappedPredicate(Pred);
531 }
532 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
533 PHINode *PI = cast<PHINode>(LHS);
534
Duncan Sands18450092010-11-16 12:16:38 +0000535 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
536 if (!ValueDominatesPHI(RHS, PI, DT))
537 return 0;
538
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000539 // Evaluate the BinOp on the incoming phi values.
540 Value *CommonValue = 0;
541 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000542 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000543 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000544 if (Incoming == PI) continue;
Duncan Sands18450092010-11-16 12:16:38 +0000545 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, 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
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000556/// SimplifyAddInst - Given operands for an Add, see if we can
557/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000558static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
559 const TargetData *TD, const DominatorTree *DT,
560 unsigned MaxRecurse) {
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000561 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
562 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
563 Constant *Ops[] = { CLHS, CRHS };
564 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
Jay Foad1d2f5692011-07-19 13:32:40 +0000565 Ops, TD);
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000566 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000567
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000568 // Canonicalize the constant to the RHS.
569 std::swap(Op0, Op1);
570 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000571
Duncan Sandsfea3b212010-12-15 14:07:39 +0000572 // X + undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000573 if (match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000574 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000575
Duncan Sandsfea3b212010-12-15 14:07:39 +0000576 // X + 0 -> X
577 if (match(Op1, m_Zero()))
578 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000579
Duncan Sandsfea3b212010-12-15 14:07:39 +0000580 // X + (Y - X) -> Y
581 // (Y - X) + X -> Y
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000582 // Eg: X + -X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000583 Value *Y = 0;
584 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
585 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000586 return Y;
587
588 // X + ~X -> -1 since ~X = -X-1
Duncan Sands124708d2011-01-01 20:08:02 +0000589 if (match(Op0, m_Not(m_Specific(Op1))) ||
590 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000591 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands87689cf2010-11-19 09:20:39 +0000592
Duncan Sands82fdab32010-12-21 14:00:22 +0000593 /// i1 add -> xor.
Duncan Sands75d289e2010-12-21 14:48:48 +0000594 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000595 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
596 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000597
Duncan Sands566edb02010-12-21 08:49:00 +0000598 // Try some generic simplifications for associative operations.
599 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, DT,
600 MaxRecurse))
601 return V;
602
Duncan Sands3421d902010-12-21 13:32:22 +0000603 // Mul distributes over Add. Try some generic simplifications based on this.
604 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
605 TD, DT, MaxRecurse))
606 return V;
607
Duncan Sands87689cf2010-11-19 09:20:39 +0000608 // Threading Add over selects and phi nodes is pointless, so don't bother.
609 // Threading over the select in "A + select(cond, B, C)" means evaluating
610 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
611 // only if B and C are equal. If B and C are equal then (since we assume
612 // that operands have already been simplified) "select(cond, B, C)" should
613 // have been simplified to the common value of B and C already. Analysing
614 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
615 // for threading over phi nodes.
616
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000617 return 0;
618}
619
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000620Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
621 const TargetData *TD, const DominatorTree *DT) {
622 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
623}
624
Duncan Sandsfea3b212010-12-15 14:07:39 +0000625/// SimplifySubInst - Given operands for a Sub, see if we can
626/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000627static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands3421d902010-12-21 13:32:22 +0000628 const TargetData *TD, const DominatorTree *DT,
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000629 unsigned MaxRecurse) {
Duncan Sandsfea3b212010-12-15 14:07:39 +0000630 if (Constant *CLHS = dyn_cast<Constant>(Op0))
631 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
632 Constant *Ops[] = { CLHS, CRHS };
633 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
Jay Foad1d2f5692011-07-19 13:32:40 +0000634 Ops, TD);
Duncan Sandsfea3b212010-12-15 14:07:39 +0000635 }
636
637 // X - undef -> undef
638 // undef - X -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000639 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000640 return UndefValue::get(Op0->getType());
641
642 // X - 0 -> X
643 if (match(Op1, m_Zero()))
644 return Op0;
645
646 // X - X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000647 if (Op0 == Op1)
Duncan Sandsfea3b212010-12-15 14:07:39 +0000648 return Constant::getNullValue(Op0->getType());
649
Duncan Sandsfe02c692011-01-18 09:24:58 +0000650 // (X*2) - X -> X
651 // (X<<1) - X -> X
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000652 Value *X = 0;
Duncan Sandsfe02c692011-01-18 09:24:58 +0000653 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
654 match(Op0, m_Shl(m_Specific(Op1), m_One())))
655 return Op1;
656
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000657 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
658 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
659 Value *Y = 0, *Z = Op1;
660 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
661 // See if "V === Y - Z" simplifies.
662 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, TD, DT, MaxRecurse-1))
663 // It does! Now see if "X + V" simplifies.
664 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, TD, DT,
665 MaxRecurse-1)) {
666 // It does, we successfully reassociated!
667 ++NumReassoc;
668 return W;
669 }
670 // See if "V === X - Z" simplifies.
671 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecurse-1))
672 // It does! Now see if "Y + V" simplifies.
673 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, TD, DT,
674 MaxRecurse-1)) {
675 // It does, we successfully reassociated!
676 ++NumReassoc;
677 return W;
678 }
679 }
Duncan Sands82fdab32010-12-21 14:00:22 +0000680
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000681 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
682 // For example, X - (X + 1) -> -1
683 X = Op0;
684 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
685 // See if "V === X - Y" simplifies.
686 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, TD, DT, MaxRecurse-1))
687 // It does! Now see if "V - Z" simplifies.
688 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, TD, DT,
689 MaxRecurse-1)) {
690 // It does, we successfully reassociated!
691 ++NumReassoc;
692 return W;
693 }
694 // See if "V === X - Z" simplifies.
695 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecurse-1))
696 // It does! Now see if "V - Y" simplifies.
697 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, TD, DT,
698 MaxRecurse-1)) {
699 // It does, we successfully reassociated!
700 ++NumReassoc;
701 return W;
702 }
703 }
704
705 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
706 // For example, X - (X - Y) -> Y.
707 Z = Op0;
Duncan Sandsc087e202011-01-14 15:26:10 +0000708 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
709 // See if "V === Z - X" simplifies.
710 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, TD, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000711 // It does! Now see if "V + Y" simplifies.
Duncan Sandsc087e202011-01-14 15:26:10 +0000712 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, TD, DT,
713 MaxRecurse-1)) {
714 // It does, we successfully reassociated!
715 ++NumReassoc;
716 return W;
717 }
718
Duncan Sands3421d902010-12-21 13:32:22 +0000719 // Mul distributes over Sub. Try some generic simplifications based on this.
720 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
721 TD, DT, MaxRecurse))
722 return V;
723
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000724 // i1 sub -> xor.
725 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
726 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
727 return V;
728
Duncan Sandsfea3b212010-12-15 14:07:39 +0000729 // Threading Sub over selects and phi nodes is pointless, so don't bother.
730 // Threading over the select in "A - select(cond, B, C)" means evaluating
731 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
732 // only if B and C are equal. If B and C are equal then (since we assume
733 // that operands have already been simplified) "select(cond, B, C)" should
734 // have been simplified to the common value of B and C already. Analysing
735 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
736 // for threading over phi nodes.
737
738 return 0;
739}
740
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000741Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
742 const TargetData *TD, const DominatorTree *DT) {
743 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
744}
745
Duncan Sands82fdab32010-12-21 14:00:22 +0000746/// SimplifyMulInst - Given operands for a Mul, see if we can
747/// fold the result. If not, this returns null.
748static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
749 const DominatorTree *DT, unsigned MaxRecurse) {
750 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
751 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
752 Constant *Ops[] = { CLHS, CRHS };
753 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
Jay Foad1d2f5692011-07-19 13:32:40 +0000754 Ops, TD);
Duncan Sands82fdab32010-12-21 14:00:22 +0000755 }
756
757 // Canonicalize the constant to the RHS.
758 std::swap(Op0, Op1);
759 }
760
761 // X * undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000762 if (match(Op1, m_Undef()))
Duncan Sands82fdab32010-12-21 14:00:22 +0000763 return Constant::getNullValue(Op0->getType());
764
765 // X * 0 -> 0
766 if (match(Op1, m_Zero()))
767 return Op1;
768
769 // X * 1 -> X
770 if (match(Op1, m_One()))
771 return Op0;
772
Duncan Sands1895e982011-01-30 18:03:50 +0000773 // (X / Y) * Y -> X if the division is exact.
774 Value *X = 0, *Y = 0;
Chris Lattneraeaf3d42011-02-09 17:00:45 +0000775 if ((match(Op0, m_IDiv(m_Value(X), m_Value(Y))) && Y == Op1) || // (X / Y) * Y
776 (match(Op1, m_IDiv(m_Value(X), m_Value(Y))) && Y == Op0)) { // Y * (X / Y)
Duncan Sands32a43cc2011-10-27 19:16:21 +0000777 PossiblyExactOperator *Div =
778 cast<PossiblyExactOperator>(Y == Op1 ? Op0 : Op1);
Chris Lattnerc6ee9182011-02-06 22:05:31 +0000779 if (Div->isExact())
Duncan Sands1895e982011-01-30 18:03:50 +0000780 return X;
781 }
782
Nick Lewycky54138802011-01-29 19:55:23 +0000783 // i1 mul -> and.
Duncan Sands75d289e2010-12-21 14:48:48 +0000784 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000785 if (Value *V = SimplifyAndInst(Op0, Op1, TD, DT, MaxRecurse-1))
786 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000787
788 // Try some generic simplifications for associative operations.
789 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, DT,
790 MaxRecurse))
791 return V;
792
793 // Mul distributes over Add. Try some generic simplifications based on this.
794 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
795 TD, DT, MaxRecurse))
796 return V;
797
798 // If the operation is with the result of a select instruction, check whether
799 // operating on either branch of the select always yields the same value.
800 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
801 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, DT,
802 MaxRecurse))
803 return V;
804
805 // If the operation is with the result of a phi instruction, check whether
806 // operating on all incoming values of the phi always yields the same value.
807 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
808 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, DT,
809 MaxRecurse))
810 return V;
811
812 return 0;
813}
814
815Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
816 const DominatorTree *DT) {
817 return ::SimplifyMulInst(Op0, Op1, TD, DT, RecursionLimit);
818}
819
Duncan Sands593faa52011-01-28 16:51:11 +0000820/// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
821/// fold the result. If not, this returns null.
Anders Carlsson479b4b92011-02-05 18:33:43 +0000822static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sands593faa52011-01-28 16:51:11 +0000823 const TargetData *TD, const DominatorTree *DT,
824 unsigned MaxRecurse) {
825 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
826 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
827 Constant *Ops[] = { C0, C1 };
Jay Foad1d2f5692011-07-19 13:32:40 +0000828 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD);
Duncan Sands593faa52011-01-28 16:51:11 +0000829 }
830 }
831
Duncan Sandsa3e292c2011-01-28 18:50:50 +0000832 bool isSigned = Opcode == Instruction::SDiv;
833
Duncan Sands593faa52011-01-28 16:51:11 +0000834 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000835 if (match(Op1, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +0000836 return Op1;
837
838 // undef / X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000839 if (match(Op0, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +0000840 return Constant::getNullValue(Op0->getType());
841
842 // 0 / X -> 0, we don't need to preserve faults!
843 if (match(Op0, m_Zero()))
844 return Op0;
845
846 // X / 1 -> X
847 if (match(Op1, m_One()))
848 return Op0;
Duncan Sands593faa52011-01-28 16:51:11 +0000849
850 if (Op0->getType()->isIntegerTy(1))
851 // It can't be division by zero, hence it must be division by one.
852 return Op0;
853
854 // X / X -> 1
855 if (Op0 == Op1)
856 return ConstantInt::get(Op0->getType(), 1);
857
858 // (X * Y) / Y -> X if the multiplication does not overflow.
859 Value *X = 0, *Y = 0;
860 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
861 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands32a43cc2011-10-27 19:16:21 +0000862 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
Duncan Sands4b720712011-02-02 20:52:00 +0000863 // If the Mul knows it does not overflow, then we are good to go.
864 if ((isSigned && Mul->hasNoSignedWrap()) ||
865 (!isSigned && Mul->hasNoUnsignedWrap()))
866 return X;
Duncan Sands593faa52011-01-28 16:51:11 +0000867 // If X has the form X = A / Y then X * Y cannot overflow.
868 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
869 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
870 return X;
871 }
872
Duncan Sandsa3e292c2011-01-28 18:50:50 +0000873 // (X rem Y) / Y -> 0
874 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
875 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
876 return Constant::getNullValue(Op0->getType());
877
878 // If the operation is with the result of a select instruction, check whether
879 // operating on either branch of the select always yields the same value.
880 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
881 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
882 return V;
883
884 // If the operation is with the result of a phi instruction, check whether
885 // operating on all incoming values of the phi always yields the same value.
886 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
887 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
888 return V;
889
Duncan Sands593faa52011-01-28 16:51:11 +0000890 return 0;
891}
892
893/// SimplifySDivInst - Given operands for an SDiv, see if we can
894/// fold the result. If not, this returns null.
895static Value *SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
896 const DominatorTree *DT, unsigned MaxRecurse) {
897 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, TD, DT, MaxRecurse))
898 return V;
899
Duncan Sands593faa52011-01-28 16:51:11 +0000900 return 0;
901}
902
903Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000904 const DominatorTree *DT) {
Duncan Sands593faa52011-01-28 16:51:11 +0000905 return ::SimplifySDivInst(Op0, Op1, TD, DT, RecursionLimit);
906}
907
908/// SimplifyUDivInst - Given operands for a UDiv, see if we can
909/// fold the result. If not, this returns null.
910static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
911 const DominatorTree *DT, unsigned MaxRecurse) {
912 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, TD, DT, MaxRecurse))
913 return V;
914
Duncan Sands593faa52011-01-28 16:51:11 +0000915 return 0;
916}
917
918Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000919 const DominatorTree *DT) {
Duncan Sands593faa52011-01-28 16:51:11 +0000920 return ::SimplifyUDivInst(Op0, Op1, TD, DT, RecursionLimit);
921}
922
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000923static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *,
924 const DominatorTree *, unsigned) {
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000925 // undef / X -> undef (the undef could be a snan).
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000926 if (match(Op0, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000927 return Op0;
928
929 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000930 if (match(Op1, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000931 return Op1;
932
933 return 0;
934}
935
936Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *TD,
937 const DominatorTree *DT) {
938 return ::SimplifyFDivInst(Op0, Op1, TD, DT, RecursionLimit);
939}
940
Duncan Sandsf24ed772011-05-02 16:27:02 +0000941/// SimplifyRem - Given operands for an SRem or URem, see if we can
942/// fold the result. If not, this returns null.
943static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
944 const TargetData *TD, const DominatorTree *DT,
945 unsigned MaxRecurse) {
946 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
947 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
948 Constant *Ops[] = { C0, C1 };
Jay Foad1d2f5692011-07-19 13:32:40 +0000949 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD);
Duncan Sandsf24ed772011-05-02 16:27:02 +0000950 }
951 }
952
Duncan Sandsf24ed772011-05-02 16:27:02 +0000953 // X % undef -> undef
954 if (match(Op1, m_Undef()))
955 return Op1;
956
957 // undef % X -> 0
958 if (match(Op0, m_Undef()))
959 return Constant::getNullValue(Op0->getType());
960
961 // 0 % X -> 0, we don't need to preserve faults!
962 if (match(Op0, m_Zero()))
963 return Op0;
964
965 // X % 0 -> undef, we don't need to preserve faults!
966 if (match(Op1, m_Zero()))
967 return UndefValue::get(Op0->getType());
968
969 // X % 1 -> 0
970 if (match(Op1, m_One()))
971 return Constant::getNullValue(Op0->getType());
972
973 if (Op0->getType()->isIntegerTy(1))
974 // It can't be remainder by zero, hence it must be remainder by one.
975 return Constant::getNullValue(Op0->getType());
976
977 // X % X -> 0
978 if (Op0 == Op1)
979 return Constant::getNullValue(Op0->getType());
980
981 // If the operation is with the result of a select instruction, check whether
982 // operating on either branch of the select always yields the same value.
983 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
984 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
985 return V;
986
987 // If the operation is with the result of a phi instruction, check whether
988 // operating on all incoming values of the phi always yields the same value.
989 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
990 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
991 return V;
992
993 return 0;
994}
995
996/// SimplifySRemInst - Given operands for an SRem, see if we can
997/// fold the result. If not, this returns null.
998static Value *SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
999 const DominatorTree *DT, unsigned MaxRecurse) {
1000 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, TD, DT, MaxRecurse))
1001 return V;
1002
1003 return 0;
1004}
1005
1006Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1007 const DominatorTree *DT) {
1008 return ::SimplifySRemInst(Op0, Op1, TD, DT, RecursionLimit);
1009}
1010
1011/// SimplifyURemInst - Given operands for a URem, see if we can
1012/// fold the result. If not, this returns null.
1013static Value *SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
1014 const DominatorTree *DT, unsigned MaxRecurse) {
1015 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, TD, DT, MaxRecurse))
1016 return V;
1017
1018 return 0;
1019}
1020
1021Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
1022 const DominatorTree *DT) {
1023 return ::SimplifyURemInst(Op0, Op1, TD, DT, RecursionLimit);
1024}
1025
1026static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *,
1027 const DominatorTree *, unsigned) {
1028 // undef % X -> undef (the undef could be a snan).
1029 if (match(Op0, m_Undef()))
1030 return Op0;
1031
1032 // X % undef -> undef
1033 if (match(Op1, m_Undef()))
1034 return Op1;
1035
1036 return 0;
1037}
1038
1039Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1040 const DominatorTree *DT) {
1041 return ::SimplifyFRemInst(Op0, Op1, TD, DT, RecursionLimit);
1042}
1043
Duncan Sandscf80bc12011-01-14 14:44:12 +00001044/// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
Duncan Sandsc43cee32011-01-14 00:37:45 +00001045/// fold the result. If not, this returns null.
Duncan Sandscf80bc12011-01-14 14:44:12 +00001046static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1047 const TargetData *TD, const DominatorTree *DT,
1048 unsigned MaxRecurse) {
Duncan Sandsc43cee32011-01-14 00:37:45 +00001049 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1050 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1051 Constant *Ops[] = { C0, C1 };
Jay Foad1d2f5692011-07-19 13:32:40 +00001052 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001053 }
1054 }
1055
Duncan Sandscf80bc12011-01-14 14:44:12 +00001056 // 0 shift by X -> 0
Duncan Sandsc43cee32011-01-14 00:37:45 +00001057 if (match(Op0, m_Zero()))
1058 return Op0;
1059
Duncan Sandscf80bc12011-01-14 14:44:12 +00001060 // X shift by 0 -> X
Duncan Sandsc43cee32011-01-14 00:37:45 +00001061 if (match(Op1, m_Zero()))
1062 return Op0;
1063
Duncan Sandscf80bc12011-01-14 14:44:12 +00001064 // X shift by undef -> undef because it may shift by the bitwidth.
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001065 if (match(Op1, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001066 return Op1;
1067
1068 // Shifting by the bitwidth or more is undefined.
1069 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1070 if (CI->getValue().getLimitedValue() >=
1071 Op0->getType()->getScalarSizeInBits())
1072 return UndefValue::get(Op0->getType());
1073
Duncan Sandscf80bc12011-01-14 14:44:12 +00001074 // If the operation is with the result of a select instruction, check whether
1075 // operating on either branch of the select always yields the same value.
1076 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1077 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
1078 return V;
1079
1080 // If the operation is with the result of a phi instruction, check whether
1081 // operating on all incoming values of the phi always yields the same value.
1082 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1083 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
1084 return V;
1085
1086 return 0;
1087}
1088
1089/// SimplifyShlInst - Given operands for an Shl, see if we can
1090/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001091static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1092 const TargetData *TD, const DominatorTree *DT,
1093 unsigned MaxRecurse) {
Duncan Sandscf80bc12011-01-14 14:44:12 +00001094 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, TD, DT, MaxRecurse))
1095 return V;
1096
1097 // undef << X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001098 if (match(Op0, m_Undef()))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001099 return Constant::getNullValue(Op0->getType());
1100
Chris Lattner81a0dc92011-02-09 17:15:04 +00001101 // (X >> A) << A -> X
1102 Value *X;
1103 if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1))) &&
1104 cast<PossiblyExactOperator>(Op0)->isExact())
1105 return X;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001106 return 0;
1107}
1108
Chris Lattner81a0dc92011-02-09 17:15:04 +00001109Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1110 const TargetData *TD, const DominatorTree *DT) {
1111 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001112}
1113
1114/// SimplifyLShrInst - Given operands for an LShr, see if we can
1115/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001116static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1117 const TargetData *TD, const DominatorTree *DT,
1118 unsigned MaxRecurse) {
Duncan Sandscf80bc12011-01-14 14:44:12 +00001119 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, TD, DT, MaxRecurse))
1120 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001121
1122 // undef >>l X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001123 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001124 return Constant::getNullValue(Op0->getType());
1125
Chris Lattner81a0dc92011-02-09 17:15:04 +00001126 // (X << A) >> A -> X
1127 Value *X;
1128 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1129 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1130 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001131
Duncan Sandsc43cee32011-01-14 00:37:45 +00001132 return 0;
1133}
1134
Chris Lattner81a0dc92011-02-09 17:15:04 +00001135Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1136 const TargetData *TD, const DominatorTree *DT) {
1137 return ::SimplifyLShrInst(Op0, Op1, isExact, TD, DT, RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001138}
1139
1140/// SimplifyAShrInst - Given operands for an AShr, see if we can
1141/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001142static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1143 const TargetData *TD, const DominatorTree *DT,
1144 unsigned MaxRecurse) {
Duncan Sandscf80bc12011-01-14 14:44:12 +00001145 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, TD, DT, MaxRecurse))
1146 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001147
1148 // all ones >>a X -> all ones
1149 if (match(Op0, m_AllOnes()))
1150 return Op0;
1151
1152 // undef >>a X -> all ones
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001153 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001154 return Constant::getAllOnesValue(Op0->getType());
1155
Chris Lattner81a0dc92011-02-09 17:15:04 +00001156 // (X << A) >> A -> X
1157 Value *X;
1158 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1159 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1160 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001161
Duncan Sandsc43cee32011-01-14 00:37:45 +00001162 return 0;
1163}
1164
Chris Lattner81a0dc92011-02-09 17:15:04 +00001165Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1166 const TargetData *TD, const DominatorTree *DT) {
1167 return ::SimplifyAShrInst(Op0, Op1, isExact, TD, DT, RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001168}
1169
Chris Lattnerd06094f2009-11-10 00:55:12 +00001170/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001171/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001172static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +00001173 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001174 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1175 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1176 Constant *Ops[] = { CLHS, CRHS };
1177 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
Jay Foad1d2f5692011-07-19 13:32:40 +00001178 Ops, TD);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001179 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001180
Chris Lattnerd06094f2009-11-10 00:55:12 +00001181 // Canonicalize the constant to the RHS.
1182 std::swap(Op0, Op1);
1183 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001184
Chris Lattnerd06094f2009-11-10 00:55:12 +00001185 // X & undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001186 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001187 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001188
Chris Lattnerd06094f2009-11-10 00:55:12 +00001189 // X & X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001190 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001191 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001192
Duncan Sands2b749872010-11-17 18:52:15 +00001193 // X & 0 = 0
1194 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001195 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001196
Duncan Sands2b749872010-11-17 18:52:15 +00001197 // X & -1 = X
1198 if (match(Op1, m_AllOnes()))
1199 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001200
Chris Lattnerd06094f2009-11-10 00:55:12 +00001201 // A & ~A = ~A & A = 0
Chris Lattner81a0dc92011-02-09 17:15:04 +00001202 if (match(Op0, m_Not(m_Specific(Op1))) ||
1203 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001204 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001205
Chris Lattnerd06094f2009-11-10 00:55:12 +00001206 // (A | ?) & A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001207 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001208 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001209 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001210 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001211
Chris Lattnerd06094f2009-11-10 00:55:12 +00001212 // A & (A | ?) = A
1213 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001214 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001215 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001216
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001217 // A & (-A) = A if A is a power of two or zero.
1218 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1219 match(Op1, m_Neg(m_Specific(Op0)))) {
1220 if (isPowerOfTwo(Op0, TD, /*OrZero*/true))
1221 return Op0;
1222 if (isPowerOfTwo(Op1, TD, /*OrZero*/true))
1223 return Op1;
1224 }
1225
Duncan Sands566edb02010-12-21 08:49:00 +00001226 // Try some generic simplifications for associative operations.
1227 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, DT,
1228 MaxRecurse))
1229 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001230
Duncan Sands3421d902010-12-21 13:32:22 +00001231 // And distributes over Or. Try some generic simplifications based on this.
1232 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1233 TD, DT, MaxRecurse))
1234 return V;
1235
1236 // And distributes over Xor. Try some generic simplifications based on this.
1237 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1238 TD, DT, MaxRecurse))
1239 return V;
1240
1241 // Or distributes over And. Try some generic simplifications based on this.
1242 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1243 TD, DT, MaxRecurse))
1244 return V;
1245
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001246 // If the operation is with the result of a select instruction, check whether
1247 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001248 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +00001249 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001250 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001251 return V;
1252
1253 // If the operation is with the result of a phi instruction, check whether
1254 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001255 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +00001256 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001257 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001258 return V;
1259
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001260 return 0;
1261}
1262
Duncan Sands18450092010-11-16 12:16:38 +00001263Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1264 const DominatorTree *DT) {
1265 return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001266}
1267
Chris Lattnerd06094f2009-11-10 00:55:12 +00001268/// SimplifyOrInst - Given operands for an Or, see if we can
1269/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001270static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +00001271 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001272 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1273 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1274 Constant *Ops[] = { CLHS, CRHS };
1275 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
Jay Foad1d2f5692011-07-19 13:32:40 +00001276 Ops, TD);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001277 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001278
Chris Lattnerd06094f2009-11-10 00:55:12 +00001279 // Canonicalize the constant to the RHS.
1280 std::swap(Op0, Op1);
1281 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001282
Chris Lattnerd06094f2009-11-10 00:55:12 +00001283 // X | undef -> -1
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001284 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001285 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001286
Chris Lattnerd06094f2009-11-10 00:55:12 +00001287 // X | X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001288 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001289 return Op0;
1290
Duncan Sands2b749872010-11-17 18:52:15 +00001291 // X | 0 = X
1292 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001293 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001294
Duncan Sands2b749872010-11-17 18:52:15 +00001295 // X | -1 = -1
1296 if (match(Op1, m_AllOnes()))
1297 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001298
Chris Lattnerd06094f2009-11-10 00:55:12 +00001299 // A | ~A = ~A | A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001300 if (match(Op0, m_Not(m_Specific(Op1))) ||
1301 match(Op1, m_Not(m_Specific(Op0))))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001302 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001303
Chris Lattnerd06094f2009-11-10 00:55:12 +00001304 // (A & ?) | A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001305 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001306 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001307 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001308 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001309
Chris Lattnerd06094f2009-11-10 00:55:12 +00001310 // A | (A & ?) = A
1311 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001312 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001313 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001314
Benjamin Kramer38f7f662011-02-20 15:20:01 +00001315 // ~(A & ?) | A = -1
1316 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1317 (A == Op1 || B == Op1))
1318 return Constant::getAllOnesValue(Op1->getType());
1319
1320 // A | ~(A & ?) = -1
1321 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1322 (A == Op0 || B == Op0))
1323 return Constant::getAllOnesValue(Op0->getType());
1324
Duncan Sands566edb02010-12-21 08:49:00 +00001325 // Try some generic simplifications for associative operations.
1326 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, DT,
1327 MaxRecurse))
1328 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001329
Duncan Sands3421d902010-12-21 13:32:22 +00001330 // Or distributes over And. Try some generic simplifications based on this.
1331 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1332 TD, DT, MaxRecurse))
1333 return V;
1334
1335 // And distributes over Or. Try some generic simplifications based on this.
1336 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1337 TD, DT, MaxRecurse))
1338 return V;
1339
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001340 // If the operation is with the result of a select instruction, check whether
1341 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001342 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +00001343 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001344 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001345 return V;
1346
1347 // If the operation is with the result of a phi instruction, check whether
1348 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001349 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +00001350 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001351 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001352 return V;
1353
Chris Lattnerd06094f2009-11-10 00:55:12 +00001354 return 0;
1355}
1356
Duncan Sands18450092010-11-16 12:16:38 +00001357Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1358 const DominatorTree *DT) {
1359 return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001360}
Chris Lattnerd06094f2009-11-10 00:55:12 +00001361
Duncan Sands2b749872010-11-17 18:52:15 +00001362/// SimplifyXorInst - Given operands for a Xor, see if we can
1363/// fold the result. If not, this returns null.
1364static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1365 const DominatorTree *DT, unsigned MaxRecurse) {
1366 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1367 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1368 Constant *Ops[] = { CLHS, CRHS };
1369 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
Jay Foad1d2f5692011-07-19 13:32:40 +00001370 Ops, TD);
Duncan Sands2b749872010-11-17 18:52:15 +00001371 }
1372
1373 // Canonicalize the constant to the RHS.
1374 std::swap(Op0, Op1);
1375 }
1376
1377 // A ^ undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001378 if (match(Op1, m_Undef()))
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00001379 return Op1;
Duncan Sands2b749872010-11-17 18:52:15 +00001380
1381 // A ^ 0 = A
1382 if (match(Op1, m_Zero()))
1383 return Op0;
1384
Eli Friedmanf23d4ad2011-08-17 19:31:49 +00001385 // A ^ A = 0
1386 if (Op0 == Op1)
1387 return Constant::getNullValue(Op0->getType());
1388
Duncan Sands2b749872010-11-17 18:52:15 +00001389 // A ^ ~A = ~A ^ A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001390 if (match(Op0, m_Not(m_Specific(Op1))) ||
1391 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands2b749872010-11-17 18:52:15 +00001392 return Constant::getAllOnesValue(Op0->getType());
1393
Duncan Sands566edb02010-12-21 08:49:00 +00001394 // Try some generic simplifications for associative operations.
1395 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, DT,
1396 MaxRecurse))
1397 return V;
Duncan Sands2b749872010-11-17 18:52:15 +00001398
Duncan Sands3421d902010-12-21 13:32:22 +00001399 // And distributes over Xor. Try some generic simplifications based on this.
1400 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1401 TD, DT, MaxRecurse))
1402 return V;
1403
Duncan Sands87689cf2010-11-19 09:20:39 +00001404 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1405 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1406 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1407 // only if B and C are equal. If B and C are equal then (since we assume
1408 // that operands have already been simplified) "select(cond, B, C)" should
1409 // have been simplified to the common value of B and C already. Analysing
1410 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1411 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +00001412
1413 return 0;
1414}
1415
1416Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1417 const DominatorTree *DT) {
1418 return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
1419}
1420
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001421static Type *GetCompareTy(Value *Op) {
Chris Lattner210c5d42009-11-09 23:55:12 +00001422 return CmpInst::makeCmpResultType(Op->getType());
1423}
1424
Duncan Sandse864b5b2011-05-07 16:56:49 +00001425/// ExtractEquivalentCondition - Rummage around inside V looking for something
1426/// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1427/// otherwise return null. Helper function for analyzing max/min idioms.
1428static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1429 Value *LHS, Value *RHS) {
1430 SelectInst *SI = dyn_cast<SelectInst>(V);
1431 if (!SI)
1432 return 0;
1433 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1434 if (!Cmp)
1435 return 0;
1436 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1437 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1438 return Cmp;
1439 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1440 LHS == CmpRHS && RHS == CmpLHS)
1441 return Cmp;
1442 return 0;
1443}
1444
Chris Lattner9dbb4292009-11-09 23:28:39 +00001445/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1446/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001447static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001448 const TargetData *TD, const DominatorTree *DT,
1449 unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001450 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +00001451 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +00001452
Chris Lattnerd06094f2009-11-10 00:55:12 +00001453 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +00001454 if (Constant *CRHS = dyn_cast<Constant>(RHS))
1455 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001456
1457 // If we have a constant, make sure it is on the RHS.
1458 std::swap(LHS, RHS);
1459 Pred = CmpInst::getSwappedPredicate(Pred);
1460 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001461
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001462 Type *ITy = GetCompareTy(LHS); // The return type.
1463 Type *OpTy = LHS->getType(); // The operand type.
Duncan Sands12a86f52010-11-14 11:23:23 +00001464
Chris Lattner210c5d42009-11-09 23:55:12 +00001465 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +00001466 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1467 // because X could be 0.
Duncan Sands124708d2011-01-01 20:08:02 +00001468 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +00001469 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +00001470
Duncan Sands6dc91252011-01-13 08:56:29 +00001471 // Special case logic when the operands have i1 type.
1472 if (OpTy->isIntegerTy(1) || (OpTy->isVectorTy() &&
1473 cast<VectorType>(OpTy)->getElementType()->isIntegerTy(1))) {
1474 switch (Pred) {
1475 default: break;
1476 case ICmpInst::ICMP_EQ:
1477 // X == 1 -> X
1478 if (match(RHS, m_One()))
1479 return LHS;
1480 break;
1481 case ICmpInst::ICMP_NE:
1482 // X != 0 -> X
1483 if (match(RHS, m_Zero()))
1484 return LHS;
1485 break;
1486 case ICmpInst::ICMP_UGT:
1487 // X >u 0 -> X
1488 if (match(RHS, m_Zero()))
1489 return LHS;
1490 break;
1491 case ICmpInst::ICMP_UGE:
1492 // X >=u 1 -> X
1493 if (match(RHS, m_One()))
1494 return LHS;
1495 break;
1496 case ICmpInst::ICMP_SLT:
1497 // X <s 0 -> X
1498 if (match(RHS, m_Zero()))
1499 return LHS;
1500 break;
1501 case ICmpInst::ICMP_SLE:
1502 // X <=s -1 -> X
1503 if (match(RHS, m_One()))
1504 return LHS;
1505 break;
1506 }
1507 }
1508
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001509 // icmp <alloca*>, <global/alloca*/null> - Different stack variables have
1510 // different addresses, and what's more the address of a stack variable is
1511 // never null or equal to the address of a global. Note that generalizing
1512 // to the case where LHS is a global variable address or null is pointless,
1513 // since if both LHS and RHS are constants then we already constant folded
1514 // the compare, and if only one of them is then we moved it to RHS already.
1515 if (isa<AllocaInst>(LHS) && (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
1516 isa<ConstantPointerNull>(RHS)))
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00001517 // We already know that LHS != RHS.
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001518 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1519
1520 // If we are comparing with zero then try hard since this is a common case.
1521 if (match(RHS, m_Zero())) {
1522 bool LHSKnownNonNegative, LHSKnownNegative;
1523 switch (Pred) {
1524 default:
1525 assert(false && "Unknown ICmp predicate!");
1526 case ICmpInst::ICMP_ULT:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001527 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001528 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001529 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001530 case ICmpInst::ICMP_EQ:
1531 case ICmpInst::ICMP_ULE:
1532 if (isKnownNonZero(LHS, TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001533 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001534 break;
1535 case ICmpInst::ICMP_NE:
1536 case ICmpInst::ICMP_UGT:
1537 if (isKnownNonZero(LHS, TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001538 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001539 break;
1540 case ICmpInst::ICMP_SLT:
1541 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1542 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001543 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001544 if (LHSKnownNonNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001545 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001546 break;
1547 case ICmpInst::ICMP_SLE:
1548 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1549 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001550 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001551 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001552 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001553 break;
1554 case ICmpInst::ICMP_SGE:
1555 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1556 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001557 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001558 if (LHSKnownNonNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001559 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001560 break;
1561 case ICmpInst::ICMP_SGT:
1562 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1563 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001564 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001565 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001566 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001567 break;
1568 }
1569 }
1570
1571 // See if we are doing a comparison with a constant integer.
Duncan Sands6dc91252011-01-13 08:56:29 +00001572 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Nick Lewycky3a73e342011-03-04 07:00:57 +00001573 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1574 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1575 if (RHS_CR.isEmptySet())
1576 return ConstantInt::getFalse(CI->getContext());
1577 if (RHS_CR.isFullSet())
1578 return ConstantInt::getTrue(CI->getContext());
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001579
Nick Lewycky3a73e342011-03-04 07:00:57 +00001580 // Many binary operators with constant RHS have easy to compute constant
1581 // range. Use them to check whether the comparison is a tautology.
1582 uint32_t Width = CI->getBitWidth();
1583 APInt Lower = APInt(Width, 0);
1584 APInt Upper = APInt(Width, 0);
1585 ConstantInt *CI2;
1586 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1587 // 'urem x, CI2' produces [0, CI2).
1588 Upper = CI2->getValue();
1589 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1590 // 'srem x, CI2' produces (-|CI2|, |CI2|).
1591 Upper = CI2->getValue().abs();
1592 Lower = (-Upper) + 1;
Duncan Sandsc65c7472011-10-28 18:17:44 +00001593 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
1594 // 'udiv CI2, x' produces [0, CI2].
1595 Upper = CI2->getValue();
Nick Lewycky3a73e342011-03-04 07:00:57 +00001596 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1597 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1598 APInt NegOne = APInt::getAllOnesValue(Width);
1599 if (!CI2->isZero())
1600 Upper = NegOne.udiv(CI2->getValue()) + 1;
1601 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1602 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1603 APInt IntMin = APInt::getSignedMinValue(Width);
1604 APInt IntMax = APInt::getSignedMaxValue(Width);
1605 APInt Val = CI2->getValue().abs();
1606 if (!Val.isMinValue()) {
1607 Lower = IntMin.sdiv(Val);
1608 Upper = IntMax.sdiv(Val) + 1;
1609 }
1610 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1611 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1612 APInt NegOne = APInt::getAllOnesValue(Width);
1613 if (CI2->getValue().ult(Width))
1614 Upper = NegOne.lshr(CI2->getValue()) + 1;
1615 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1616 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1617 APInt IntMin = APInt::getSignedMinValue(Width);
1618 APInt IntMax = APInt::getSignedMaxValue(Width);
1619 if (CI2->getValue().ult(Width)) {
1620 Lower = IntMin.ashr(CI2->getValue());
1621 Upper = IntMax.ashr(CI2->getValue()) + 1;
1622 }
1623 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1624 // 'or x, CI2' produces [CI2, UINT_MAX].
1625 Lower = CI2->getValue();
1626 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1627 // 'and x, CI2' produces [0, CI2].
1628 Upper = CI2->getValue() + 1;
1629 }
1630 if (Lower != Upper) {
1631 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1632 if (RHS_CR.contains(LHS_CR))
1633 return ConstantInt::getTrue(RHS->getContext());
1634 if (RHS_CR.inverse().contains(LHS_CR))
1635 return ConstantInt::getFalse(RHS->getContext());
1636 }
Duncan Sands6dc91252011-01-13 08:56:29 +00001637 }
1638
Duncan Sands9d32f602011-01-20 13:21:55 +00001639 // Compare of cast, for example (zext X) != 0 -> X != 0
1640 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1641 Instruction *LI = cast<CastInst>(LHS);
1642 Value *SrcOp = LI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001643 Type *SrcTy = SrcOp->getType();
1644 Type *DstTy = LI->getType();
Duncan Sands9d32f602011-01-20 13:21:55 +00001645
1646 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1647 // if the integer type is the same size as the pointer type.
1648 if (MaxRecurse && TD && isa<PtrToIntInst>(LI) &&
1649 TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
1650 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1651 // Transfer the cast to the constant.
1652 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1653 ConstantExpr::getIntToPtr(RHSC, SrcTy),
1654 TD, DT, MaxRecurse-1))
1655 return V;
1656 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1657 if (RI->getOperand(0)->getType() == SrcTy)
1658 // Compare without the cast.
1659 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1660 TD, DT, MaxRecurse-1))
1661 return V;
1662 }
1663 }
1664
1665 if (isa<ZExtInst>(LHS)) {
1666 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1667 // same type.
1668 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1669 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1670 // Compare X and Y. Note that signed predicates become unsigned.
1671 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1672 SrcOp, RI->getOperand(0), TD, DT,
1673 MaxRecurse-1))
1674 return V;
1675 }
1676 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1677 // too. If not, then try to deduce the result of the comparison.
1678 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1679 // Compute the constant that would happen if we truncated to SrcTy then
1680 // reextended to DstTy.
1681 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1682 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1683
1684 // If the re-extended constant didn't change then this is effectively
1685 // also a case of comparing two zero-extended values.
1686 if (RExt == CI && MaxRecurse)
1687 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1688 SrcOp, Trunc, TD, DT, MaxRecurse-1))
1689 return V;
1690
1691 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1692 // there. Use this to work out the result of the comparison.
1693 if (RExt != CI) {
1694 switch (Pred) {
1695 default:
1696 assert(false && "Unknown ICmp predicate!");
1697 // LHS <u RHS.
1698 case ICmpInst::ICMP_EQ:
1699 case ICmpInst::ICMP_UGT:
1700 case ICmpInst::ICMP_UGE:
1701 return ConstantInt::getFalse(CI->getContext());
1702
1703 case ICmpInst::ICMP_NE:
1704 case ICmpInst::ICMP_ULT:
1705 case ICmpInst::ICMP_ULE:
1706 return ConstantInt::getTrue(CI->getContext());
1707
1708 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
1709 // is non-negative then LHS <s RHS.
1710 case ICmpInst::ICMP_SGT:
1711 case ICmpInst::ICMP_SGE:
1712 return CI->getValue().isNegative() ?
1713 ConstantInt::getTrue(CI->getContext()) :
1714 ConstantInt::getFalse(CI->getContext());
1715
1716 case ICmpInst::ICMP_SLT:
1717 case ICmpInst::ICMP_SLE:
1718 return CI->getValue().isNegative() ?
1719 ConstantInt::getFalse(CI->getContext()) :
1720 ConstantInt::getTrue(CI->getContext());
1721 }
1722 }
1723 }
1724 }
1725
1726 if (isa<SExtInst>(LHS)) {
1727 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1728 // same type.
1729 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1730 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1731 // Compare X and Y. Note that the predicate does not change.
1732 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1733 TD, DT, MaxRecurse-1))
1734 return V;
1735 }
1736 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1737 // too. If not, then try to deduce the result of the comparison.
1738 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1739 // Compute the constant that would happen if we truncated to SrcTy then
1740 // reextended to DstTy.
1741 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1742 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1743
1744 // If the re-extended constant didn't change then this is effectively
1745 // also a case of comparing two sign-extended values.
1746 if (RExt == CI && MaxRecurse)
1747 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, TD, DT,
1748 MaxRecurse-1))
1749 return V;
1750
1751 // Otherwise the upper bits of LHS are all equal, while RHS has varying
1752 // bits there. Use this to work out the result of the comparison.
1753 if (RExt != CI) {
1754 switch (Pred) {
1755 default:
1756 assert(false && "Unknown ICmp predicate!");
1757 case ICmpInst::ICMP_EQ:
1758 return ConstantInt::getFalse(CI->getContext());
1759 case ICmpInst::ICMP_NE:
1760 return ConstantInt::getTrue(CI->getContext());
1761
1762 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
1763 // LHS >s RHS.
1764 case ICmpInst::ICMP_SGT:
1765 case ICmpInst::ICMP_SGE:
1766 return CI->getValue().isNegative() ?
1767 ConstantInt::getTrue(CI->getContext()) :
1768 ConstantInt::getFalse(CI->getContext());
1769 case ICmpInst::ICMP_SLT:
1770 case ICmpInst::ICMP_SLE:
1771 return CI->getValue().isNegative() ?
1772 ConstantInt::getFalse(CI->getContext()) :
1773 ConstantInt::getTrue(CI->getContext());
1774
1775 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
1776 // LHS >u RHS.
1777 case ICmpInst::ICMP_UGT:
1778 case ICmpInst::ICMP_UGE:
1779 // Comparison is true iff the LHS <s 0.
1780 if (MaxRecurse)
1781 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
1782 Constant::getNullValue(SrcTy),
1783 TD, DT, MaxRecurse-1))
1784 return V;
1785 break;
1786 case ICmpInst::ICMP_ULT:
1787 case ICmpInst::ICMP_ULE:
1788 // Comparison is true iff the LHS >=s 0.
1789 if (MaxRecurse)
1790 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
1791 Constant::getNullValue(SrcTy),
1792 TD, DT, MaxRecurse-1))
1793 return V;
1794 break;
1795 }
1796 }
1797 }
1798 }
1799 }
1800
Duncan Sands52fb8462011-02-13 17:15:40 +00001801 // Special logic for binary operators.
1802 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
1803 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
1804 if (MaxRecurse && (LBO || RBO)) {
Duncan Sands52fb8462011-02-13 17:15:40 +00001805 // Analyze the case when either LHS or RHS is an add instruction.
1806 Value *A = 0, *B = 0, *C = 0, *D = 0;
1807 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
1808 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
1809 if (LBO && LBO->getOpcode() == Instruction::Add) {
1810 A = LBO->getOperand(0); B = LBO->getOperand(1);
1811 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
1812 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
1813 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
1814 }
1815 if (RBO && RBO->getOpcode() == Instruction::Add) {
1816 C = RBO->getOperand(0); D = RBO->getOperand(1);
1817 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
1818 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
1819 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
1820 }
1821
1822 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
1823 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
1824 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
1825 Constant::getNullValue(RHS->getType()),
1826 TD, DT, MaxRecurse-1))
1827 return V;
1828
1829 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
1830 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
1831 if (Value *V = SimplifyICmpInst(Pred,
1832 Constant::getNullValue(LHS->getType()),
1833 C == LHS ? D : C, TD, DT, MaxRecurse-1))
1834 return V;
1835
1836 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
1837 if (A && C && (A == C || A == D || B == C || B == D) &&
1838 NoLHSWrapProblem && NoRHSWrapProblem) {
1839 // Determine Y and Z in the form icmp (X+Y), (X+Z).
1840 Value *Y = (A == C || A == D) ? B : A;
1841 Value *Z = (C == A || C == B) ? D : C;
1842 if (Value *V = SimplifyICmpInst(Pred, Y, Z, TD, DT, MaxRecurse-1))
1843 return V;
1844 }
1845 }
1846
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001847 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Nick Lewycky78679272011-03-04 10:06:52 +00001848 bool KnownNonNegative, KnownNegative;
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001849 switch (Pred) {
1850 default:
1851 break;
Nick Lewycky78679272011-03-04 10:06:52 +00001852 case ICmpInst::ICMP_SGT:
1853 case ICmpInst::ICMP_SGE:
1854 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1855 if (!KnownNonNegative)
1856 break;
1857 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001858 case ICmpInst::ICMP_EQ:
1859 case ICmpInst::ICMP_UGT:
1860 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001861 return getFalse(ITy);
Nick Lewycky78679272011-03-04 10:06:52 +00001862 case ICmpInst::ICMP_SLT:
1863 case ICmpInst::ICMP_SLE:
1864 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1865 if (!KnownNonNegative)
1866 break;
1867 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001868 case ICmpInst::ICMP_NE:
1869 case ICmpInst::ICMP_ULT:
1870 case ICmpInst::ICMP_ULE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001871 return getTrue(ITy);
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001872 }
1873 }
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001874 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
1875 bool KnownNonNegative, KnownNegative;
1876 switch (Pred) {
1877 default:
1878 break;
1879 case ICmpInst::ICMP_SGT:
1880 case ICmpInst::ICMP_SGE:
1881 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1882 if (!KnownNonNegative)
1883 break;
1884 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00001885 case ICmpInst::ICMP_NE:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001886 case ICmpInst::ICMP_UGT:
1887 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001888 return getTrue(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001889 case ICmpInst::ICMP_SLT:
1890 case ICmpInst::ICMP_SLE:
1891 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1892 if (!KnownNonNegative)
1893 break;
1894 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00001895 case ICmpInst::ICMP_EQ:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001896 case ICmpInst::ICMP_ULT:
1897 case ICmpInst::ICMP_ULE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001898 return getFalse(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001899 }
1900 }
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001901
Duncan Sandsc65c7472011-10-28 18:17:44 +00001902 // x udiv y <=u x.
1903 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
1904 // icmp pred (X /u Y), X
1905 if (Pred == ICmpInst::ICMP_UGT)
1906 return getFalse(ITy);
1907 if (Pred == ICmpInst::ICMP_ULE)
1908 return getTrue(ITy);
1909 }
1910
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00001911 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
1912 LBO->getOperand(1) == RBO->getOperand(1)) {
1913 switch (LBO->getOpcode()) {
1914 default: break;
1915 case Instruction::UDiv:
1916 case Instruction::LShr:
1917 if (ICmpInst::isSigned(Pred))
1918 break;
1919 // fall-through
1920 case Instruction::SDiv:
1921 case Instruction::AShr:
Eli Friedmanb6e7cd62011-05-05 21:59:18 +00001922 if (!LBO->isExact() || !RBO->isExact())
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00001923 break;
1924 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
1925 RBO->getOperand(0), TD, DT, MaxRecurse-1))
1926 return V;
1927 break;
1928 case Instruction::Shl: {
Duncan Sandsc9d904e2011-08-04 10:02:21 +00001929 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00001930 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
1931 if (!NUW && !NSW)
1932 break;
1933 if (!NSW && ICmpInst::isSigned(Pred))
1934 break;
1935 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
1936 RBO->getOperand(0), TD, DT, MaxRecurse-1))
1937 return V;
1938 break;
1939 }
1940 }
1941 }
1942
Duncan Sandsad206812011-05-03 19:53:10 +00001943 // Simplify comparisons involving max/min.
1944 Value *A, *B;
1945 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
1946 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
1947
Duncan Sands8140ad32011-05-04 16:05:05 +00001948 // Signed variants on "max(a,b)>=a -> true".
Duncan Sandsad206812011-05-03 19:53:10 +00001949 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
1950 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
1951 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
1952 // We analyze this as smax(A, B) pred A.
1953 P = Pred;
1954 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
1955 (A == LHS || B == LHS)) {
1956 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
1957 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
1958 // We analyze this as smax(A, B) swapped-pred A.
1959 P = CmpInst::getSwappedPredicate(Pred);
1960 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
1961 (A == RHS || B == RHS)) {
1962 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
1963 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
1964 // We analyze this as smax(-A, -B) swapped-pred -A.
1965 // Note that we do not need to actually form -A or -B thanks to EqP.
1966 P = CmpInst::getSwappedPredicate(Pred);
1967 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
1968 (A == LHS || B == LHS)) {
1969 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
1970 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
1971 // We analyze this as smax(-A, -B) pred -A.
1972 // Note that we do not need to actually form -A or -B thanks to EqP.
1973 P = Pred;
1974 }
1975 if (P != CmpInst::BAD_ICMP_PREDICATE) {
1976 // Cases correspond to "max(A, B) p A".
1977 switch (P) {
1978 default:
1979 break;
1980 case CmpInst::ICMP_EQ:
1981 case CmpInst::ICMP_SLE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00001982 // Equivalent to "A EqP B". This may be the same as the condition tested
1983 // in the max/min; if so, we can just return that.
1984 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
1985 return V;
1986 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
1987 return V;
1988 // Otherwise, see if "A EqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00001989 if (MaxRecurse)
1990 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, DT, MaxRecurse-1))
1991 return V;
1992 break;
1993 case CmpInst::ICMP_NE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00001994 case CmpInst::ICMP_SGT: {
1995 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
1996 // Equivalent to "A InvEqP B". This may be the same as the condition
1997 // tested in the max/min; if so, we can just return that.
1998 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
1999 return V;
2000 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2001 return V;
2002 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002003 if (MaxRecurse)
Duncan Sandse864b5b2011-05-07 16:56:49 +00002004 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, DT, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002005 return V;
2006 break;
Duncan Sandse864b5b2011-05-07 16:56:49 +00002007 }
Duncan Sandsad206812011-05-03 19:53:10 +00002008 case CmpInst::ICMP_SGE:
2009 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002010 return getTrue(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002011 case CmpInst::ICMP_SLT:
2012 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002013 return getFalse(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002014 }
2015 }
2016
Duncan Sands8140ad32011-05-04 16:05:05 +00002017 // Unsigned variants on "max(a,b)>=a -> true".
Duncan Sandsad206812011-05-03 19:53:10 +00002018 P = CmpInst::BAD_ICMP_PREDICATE;
2019 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2020 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2021 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2022 // We analyze this as umax(A, B) pred A.
2023 P = Pred;
2024 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2025 (A == LHS || B == LHS)) {
2026 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2027 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2028 // We analyze this as umax(A, B) swapped-pred A.
2029 P = CmpInst::getSwappedPredicate(Pred);
2030 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2031 (A == RHS || B == RHS)) {
2032 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2033 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2034 // We analyze this as umax(-A, -B) swapped-pred -A.
2035 // Note that we do not need to actually form -A or -B thanks to EqP.
2036 P = CmpInst::getSwappedPredicate(Pred);
2037 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2038 (A == LHS || B == LHS)) {
2039 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2040 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2041 // We analyze this as umax(-A, -B) pred -A.
2042 // Note that we do not need to actually form -A or -B thanks to EqP.
2043 P = Pred;
2044 }
2045 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2046 // Cases correspond to "max(A, B) p A".
2047 switch (P) {
2048 default:
2049 break;
2050 case CmpInst::ICMP_EQ:
2051 case CmpInst::ICMP_ULE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002052 // Equivalent to "A EqP B". This may be the same as the condition tested
2053 // in the max/min; if so, we can just return that.
2054 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2055 return V;
2056 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2057 return V;
2058 // Otherwise, see if "A EqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002059 if (MaxRecurse)
2060 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, DT, MaxRecurse-1))
2061 return V;
2062 break;
2063 case CmpInst::ICMP_NE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002064 case CmpInst::ICMP_UGT: {
2065 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2066 // Equivalent to "A InvEqP B". This may be the same as the condition
2067 // tested in the max/min; if so, we can just return that.
2068 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2069 return V;
2070 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2071 return V;
2072 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002073 if (MaxRecurse)
Duncan Sandse864b5b2011-05-07 16:56:49 +00002074 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, DT, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002075 return V;
2076 break;
Duncan Sandse864b5b2011-05-07 16:56:49 +00002077 }
Duncan Sandsad206812011-05-03 19:53:10 +00002078 case CmpInst::ICMP_UGE:
2079 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002080 return getTrue(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002081 case CmpInst::ICMP_ULT:
2082 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002083 return getFalse(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002084 }
2085 }
2086
Duncan Sands8140ad32011-05-04 16:05:05 +00002087 // Variants on "max(x,y) >= min(x,z)".
2088 Value *C, *D;
2089 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2090 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2091 (A == C || A == D || B == C || B == D)) {
2092 // max(x, ?) pred min(x, ?).
2093 if (Pred == CmpInst::ICMP_SGE)
2094 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002095 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002096 if (Pred == CmpInst::ICMP_SLT)
2097 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002098 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002099 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2100 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2101 (A == C || A == D || B == C || B == D)) {
2102 // min(x, ?) pred max(x, ?).
2103 if (Pred == CmpInst::ICMP_SLE)
2104 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002105 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002106 if (Pred == CmpInst::ICMP_SGT)
2107 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002108 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002109 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2110 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2111 (A == C || A == D || B == C || B == D)) {
2112 // max(x, ?) pred min(x, ?).
2113 if (Pred == CmpInst::ICMP_UGE)
2114 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002115 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002116 if (Pred == CmpInst::ICMP_ULT)
2117 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002118 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002119 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2120 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2121 (A == C || A == D || B == C || B == D)) {
2122 // min(x, ?) pred max(x, ?).
2123 if (Pred == CmpInst::ICMP_ULE)
2124 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002125 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002126 if (Pred == CmpInst::ICMP_UGT)
2127 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002128 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002129 }
2130
Duncan Sands1ac7c992010-11-07 16:12:23 +00002131 // If the comparison is with the result of a select instruction, check whether
2132 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002133 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2134 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002135 return V;
2136
2137 // If the comparison is with the result of a phi instruction, check whether
2138 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00002139 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2140 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00002141 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +00002142
Chris Lattner9f3c25a2009-11-09 22:57:59 +00002143 return 0;
2144}
2145
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002146Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00002147 const TargetData *TD, const DominatorTree *DT) {
2148 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002149}
2150
Chris Lattner9dbb4292009-11-09 23:28:39 +00002151/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2152/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002153static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00002154 const TargetData *TD, const DominatorTree *DT,
2155 unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00002156 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2157 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2158
Chris Lattnerd06094f2009-11-10 00:55:12 +00002159 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00002160 if (Constant *CRHS = dyn_cast<Constant>(RHS))
2161 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Duncan Sands12a86f52010-11-14 11:23:23 +00002162
Chris Lattnerd06094f2009-11-10 00:55:12 +00002163 // If we have a constant, make sure it is on the RHS.
2164 std::swap(LHS, RHS);
2165 Pred = CmpInst::getSwappedPredicate(Pred);
2166 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002167
Chris Lattner210c5d42009-11-09 23:55:12 +00002168 // Fold trivial predicates.
2169 if (Pred == FCmpInst::FCMP_FALSE)
2170 return ConstantInt::get(GetCompareTy(LHS), 0);
2171 if (Pred == FCmpInst::FCMP_TRUE)
2172 return ConstantInt::get(GetCompareTy(LHS), 1);
2173
Chris Lattner210c5d42009-11-09 23:55:12 +00002174 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2175 return UndefValue::get(GetCompareTy(LHS));
2176
2177 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands124708d2011-01-01 20:08:02 +00002178 if (LHS == RHS) {
Chris Lattner210c5d42009-11-09 23:55:12 +00002179 if (CmpInst::isTrueWhenEqual(Pred))
2180 return ConstantInt::get(GetCompareTy(LHS), 1);
2181 if (CmpInst::isFalseWhenEqual(Pred))
2182 return ConstantInt::get(GetCompareTy(LHS), 0);
2183 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002184
Chris Lattner210c5d42009-11-09 23:55:12 +00002185 // Handle fcmp with constant RHS
2186 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2187 // If the constant is a nan, see if we can fold the comparison based on it.
2188 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2189 if (CFP->getValueAPF().isNaN()) {
2190 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2191 return ConstantInt::getFalse(CFP->getContext());
2192 assert(FCmpInst::isUnordered(Pred) &&
2193 "Comparison must be either ordered or unordered!");
2194 // True if unordered.
2195 return ConstantInt::getTrue(CFP->getContext());
2196 }
Dan Gohman6b617a72010-02-22 04:06:03 +00002197 // Check whether the constant is an infinity.
2198 if (CFP->getValueAPF().isInfinity()) {
2199 if (CFP->getValueAPF().isNegative()) {
2200 switch (Pred) {
2201 case FCmpInst::FCMP_OLT:
2202 // No value is ordered and less than negative infinity.
2203 return ConstantInt::getFalse(CFP->getContext());
2204 case FCmpInst::FCMP_UGE:
2205 // All values are unordered with or at least negative infinity.
2206 return ConstantInt::getTrue(CFP->getContext());
2207 default:
2208 break;
2209 }
2210 } else {
2211 switch (Pred) {
2212 case FCmpInst::FCMP_OGT:
2213 // No value is ordered and greater than infinity.
2214 return ConstantInt::getFalse(CFP->getContext());
2215 case FCmpInst::FCMP_ULE:
2216 // All values are unordered with and at most infinity.
2217 return ConstantInt::getTrue(CFP->getContext());
2218 default:
2219 break;
2220 }
2221 }
2222 }
Chris Lattner210c5d42009-11-09 23:55:12 +00002223 }
2224 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002225
Duncan Sands92826de2010-11-07 16:46:25 +00002226 // If the comparison is with the result of a select instruction, check whether
2227 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002228 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2229 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002230 return V;
2231
2232 // If the comparison is with the result of a phi instruction, check whether
2233 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00002234 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2235 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00002236 return V;
Duncan Sands92826de2010-11-07 16:46:25 +00002237
Chris Lattner9dbb4292009-11-09 23:28:39 +00002238 return 0;
2239}
2240
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002241Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00002242 const TargetData *TD, const DominatorTree *DT) {
2243 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002244}
2245
Chris Lattner04754262010-04-20 05:32:14 +00002246/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2247/// the result. If not, this returns null.
Duncan Sands124708d2011-01-01 20:08:02 +00002248Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
2249 const TargetData *TD, const DominatorTree *) {
Chris Lattner04754262010-04-20 05:32:14 +00002250 // select true, X, Y -> X
2251 // select false, X, Y -> Y
2252 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2253 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002254
Chris Lattner04754262010-04-20 05:32:14 +00002255 // select C, X, X -> X
Duncan Sands124708d2011-01-01 20:08:02 +00002256 if (TrueVal == FalseVal)
Chris Lattner04754262010-04-20 05:32:14 +00002257 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002258
Chris Lattner04754262010-04-20 05:32:14 +00002259 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2260 if (isa<Constant>(TrueVal))
2261 return TrueVal;
2262 return FalseVal;
2263 }
Dan Gohman68c0dbc2011-07-01 01:03:43 +00002264 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2265 return FalseVal;
2266 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2267 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002268
Chris Lattner04754262010-04-20 05:32:14 +00002269 return 0;
2270}
2271
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002272/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2273/// fold the result. If not, this returns null.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002274Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops,
Duncan Sands18450092010-11-16 12:16:38 +00002275 const TargetData *TD, const DominatorTree *) {
Duncan Sands85bbff62010-11-22 13:42:49 +00002276 // The type of the GEP pointer operand.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002277 PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
Duncan Sands85bbff62010-11-22 13:42:49 +00002278
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002279 // getelementptr P -> P.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002280 if (Ops.size() == 1)
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002281 return Ops[0];
2282
Duncan Sands85bbff62010-11-22 13:42:49 +00002283 if (isa<UndefValue>(Ops[0])) {
2284 // Compute the (pointer) type returned by the GEP instruction.
Jay Foada9203102011-07-25 09:48:08 +00002285 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002286 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
Duncan Sands85bbff62010-11-22 13:42:49 +00002287 return UndefValue::get(GEPTy);
2288 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002289
Jay Foadb9b54eb2011-07-19 15:07:52 +00002290 if (Ops.size() == 2) {
Duncan Sandse60d79f2010-11-21 13:53:09 +00002291 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002292 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2293 if (C->isZero())
2294 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +00002295 // getelementptr P, N -> P if P points to a type of zero size.
2296 if (TD) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002297 Type *Ty = PtrTy->getElementType();
Duncan Sandsa63395a2010-11-22 16:32:50 +00002298 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +00002299 return Ops[0];
2300 }
2301 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002302
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002303 // Check to see if this is constant foldable.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002304 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002305 if (!isa<Constant>(Ops[i]))
2306 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +00002307
Jay Foaddab3d292011-07-21 14:31:17 +00002308 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002309}
2310
Duncan Sandsdabc2802011-09-05 06:52:48 +00002311/// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2312/// can fold the result. If not, this returns null.
2313Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2314 ArrayRef<unsigned> Idxs,
2315 const TargetData *,
2316 const DominatorTree *) {
2317 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2318 if (Constant *CVal = dyn_cast<Constant>(Val))
2319 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2320
2321 // insertvalue x, undef, n -> x
2322 if (match(Val, m_Undef()))
2323 return Agg;
2324
2325 // insertvalue x, (extractvalue y, n), n
2326 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramerae707bd2011-09-05 18:16:19 +00002327 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2328 EV->getIndices() == Idxs) {
Duncan Sandsdabc2802011-09-05 06:52:48 +00002329 // insertvalue undef, (extractvalue y, n), n -> y
2330 if (match(Agg, m_Undef()))
2331 return EV->getAggregateOperand();
2332
2333 // insertvalue y, (extractvalue y, n), n -> y
2334 if (Agg == EV->getAggregateOperand())
2335 return Agg;
2336 }
2337
2338 return 0;
2339}
2340
Duncan Sandsff103412010-11-17 04:30:22 +00002341/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
2342static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
2343 // If all of the PHI's incoming values are the same then replace the PHI node
2344 // with the common value.
2345 Value *CommonValue = 0;
2346 bool HasUndefInput = false;
2347 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2348 Value *Incoming = PN->getIncomingValue(i);
2349 // If the incoming value is the phi node itself, it can safely be skipped.
2350 if (Incoming == PN) continue;
2351 if (isa<UndefValue>(Incoming)) {
2352 // Remember that we saw an undef value, but otherwise ignore them.
2353 HasUndefInput = true;
2354 continue;
2355 }
2356 if (CommonValue && Incoming != CommonValue)
2357 return 0; // Not the same, bail out.
2358 CommonValue = Incoming;
2359 }
2360
2361 // If CommonValue is null then all of the incoming values were either undef or
2362 // equal to the phi node itself.
2363 if (!CommonValue)
2364 return UndefValue::get(PN->getType());
2365
2366 // If we have a PHI node like phi(X, undef, X), where X is defined by some
2367 // instruction, we cannot return X as the result of the PHI node unless it
2368 // dominates the PHI block.
2369 if (HasUndefInput)
2370 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
2371
2372 return CommonValue;
2373}
2374
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002375
Chris Lattnerd06094f2009-11-10 00:55:12 +00002376//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +00002377
Chris Lattnerd06094f2009-11-10 00:55:12 +00002378/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2379/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002380static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00002381 const TargetData *TD, const DominatorTree *DT,
2382 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00002383 switch (Opcode) {
Chris Lattner81a0dc92011-02-09 17:15:04 +00002384 case Instruction::Add:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002385 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Chris Lattner81a0dc92011-02-09 17:15:04 +00002386 TD, DT, MaxRecurse);
2387 case Instruction::Sub:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002388 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Chris Lattner81a0dc92011-02-09 17:15:04 +00002389 TD, DT, MaxRecurse);
2390 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, TD, DT, MaxRecurse);
Duncan Sands593faa52011-01-28 16:51:11 +00002391 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, TD, DT, MaxRecurse);
2392 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, TD, DT, MaxRecurse);
Frits van Bommel1fca2c32011-01-29 15:26:31 +00002393 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002394 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, TD, DT, MaxRecurse);
2395 case Instruction::URem: return SimplifyURemInst(LHS, RHS, TD, DT, MaxRecurse);
2396 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, TD, DT, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002397 case Instruction::Shl:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002398 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Chris Lattner81a0dc92011-02-09 17:15:04 +00002399 TD, DT, MaxRecurse);
2400 case Instruction::LShr:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002401 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, TD, DT, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002402 case Instruction::AShr:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002403 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, TD, DT, MaxRecurse);
Duncan Sands82fdab32010-12-21 14:00:22 +00002404 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002405 case Instruction::Or: return SimplifyOrInst (LHS, RHS, TD, DT, MaxRecurse);
Duncan Sands82fdab32010-12-21 14:00:22 +00002406 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002407 default:
2408 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2409 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2410 Constant *COps[] = {CLHS, CRHS};
Jay Foad1d2f5692011-07-19 13:32:40 +00002411 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, TD);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002412 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002413
Duncan Sands566edb02010-12-21 08:49:00 +00002414 // If the operation is associative, try some generic simplifications.
2415 if (Instruction::isAssociative(Opcode))
2416 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, DT,
2417 MaxRecurse))
2418 return V;
2419
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002420 // If the operation is with the result of a select instruction, check whether
2421 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002422 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands18450092010-11-16 12:16:38 +00002423 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00002424 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002425 return V;
2426
2427 // If the operation is with the result of a phi instruction, check whether
2428 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002429 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2430 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002431 return V;
2432
Chris Lattnerd06094f2009-11-10 00:55:12 +00002433 return 0;
2434 }
2435}
Chris Lattner9dbb4292009-11-09 23:28:39 +00002436
Duncan Sands12a86f52010-11-14 11:23:23 +00002437Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00002438 const TargetData *TD, const DominatorTree *DT) {
2439 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +00002440}
2441
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002442/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2443/// fold the result.
2444static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00002445 const TargetData *TD, const DominatorTree *DT,
2446 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002447 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sands18450092010-11-16 12:16:38 +00002448 return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
2449 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002450}
2451
2452Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00002453 const TargetData *TD, const DominatorTree *DT) {
2454 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002455}
Chris Lattnere3453782009-11-10 01:08:51 +00002456
2457/// SimplifyInstruction - See if we can compute a simplified version of this
2458/// instruction. If not, this returns null.
Duncan Sandseff05812010-11-14 18:36:10 +00002459Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
2460 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +00002461 Value *Result;
2462
Chris Lattnere3453782009-11-10 01:08:51 +00002463 switch (I->getOpcode()) {
2464 default:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002465 Result = ConstantFoldInstruction(I, TD);
2466 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002467 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002468 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2469 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2470 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2471 TD, DT);
2472 break;
Duncan Sandsfea3b212010-12-15 14:07:39 +00002473 case Instruction::Sub:
2474 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2475 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2476 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2477 TD, DT);
2478 break;
Duncan Sands82fdab32010-12-21 14:00:22 +00002479 case Instruction::Mul:
2480 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, DT);
2481 break;
Duncan Sands593faa52011-01-28 16:51:11 +00002482 case Instruction::SDiv:
2483 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2484 break;
2485 case Instruction::UDiv:
2486 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2487 break;
Frits van Bommel1fca2c32011-01-29 15:26:31 +00002488 case Instruction::FDiv:
2489 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2490 break;
Duncan Sandsf24ed772011-05-02 16:27:02 +00002491 case Instruction::SRem:
2492 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2493 break;
2494 case Instruction::URem:
2495 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2496 break;
2497 case Instruction::FRem:
2498 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2499 break;
Duncan Sandsc43cee32011-01-14 00:37:45 +00002500 case Instruction::Shl:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002501 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2502 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2503 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2504 TD, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002505 break;
2506 case Instruction::LShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002507 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2508 cast<BinaryOperator>(I)->isExact(),
2509 TD, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002510 break;
2511 case Instruction::AShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002512 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2513 cast<BinaryOperator>(I)->isExact(),
2514 TD, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002515 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002516 case Instruction::And:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002517 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
2518 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002519 case Instruction::Or:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002520 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
2521 break;
Duncan Sands2b749872010-11-17 18:52:15 +00002522 case Instruction::Xor:
2523 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
2524 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002525 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002526 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
2527 I->getOperand(0), I->getOperand(1), TD, DT);
2528 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002529 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002530 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
2531 I->getOperand(0), I->getOperand(1), TD, DT);
2532 break;
Chris Lattner04754262010-04-20 05:32:14 +00002533 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002534 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
2535 I->getOperand(2), TD, DT);
2536 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002537 case Instruction::GetElementPtr: {
2538 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Jay Foadb9b54eb2011-07-19 15:07:52 +00002539 Result = SimplifyGEPInst(Ops, TD, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002540 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002541 }
Duncan Sandsdabc2802011-09-05 06:52:48 +00002542 case Instruction::InsertValue: {
2543 InsertValueInst *IV = cast<InsertValueInst>(I);
2544 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
2545 IV->getInsertedValueOperand(),
2546 IV->getIndices(), TD, DT);
2547 break;
2548 }
Duncan Sandscd6636c2010-11-14 13:30:18 +00002549 case Instruction::PHI:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002550 Result = SimplifyPHINode(cast<PHINode>(I), DT);
2551 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002552 }
Duncan Sandsd261dc62010-11-17 08:35:29 +00002553
2554 /// If called on unreachable code, the above logic may report that the
2555 /// instruction simplified to itself. Make life easier for users by
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00002556 /// detecting that case here, returning a safe value instead.
2557 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnere3453782009-11-10 01:08:51 +00002558}
2559
Chris Lattner40d8c282009-11-10 22:26:15 +00002560/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
2561/// delete the From instruction. In addition to a basic RAUW, this does a
2562/// recursive simplification of the newly formed instructions. This catches
2563/// things where one simplification exposes other opportunities. This only
2564/// simplifies and deletes scalar operations, it does not change the CFG.
2565///
2566void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
Duncan Sandseff05812010-11-14 18:36:10 +00002567 const TargetData *TD,
2568 const DominatorTree *DT) {
Chris Lattner40d8c282009-11-10 22:26:15 +00002569 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
Duncan Sands12a86f52010-11-14 11:23:23 +00002570
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002571 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
2572 // we can know if it gets deleted out from under us or replaced in a
2573 // recursive simplification.
Chris Lattner40d8c282009-11-10 22:26:15 +00002574 WeakVH FromHandle(From);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002575 WeakVH ToHandle(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00002576
Chris Lattner40d8c282009-11-10 22:26:15 +00002577 while (!From->use_empty()) {
2578 // Update the instruction to use the new value.
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002579 Use &TheUse = From->use_begin().getUse();
2580 Instruction *User = cast<Instruction>(TheUse.getUser());
2581 TheUse = To;
2582
2583 // Check to see if the instruction can be folded due to the operand
2584 // replacement. For example changing (or X, Y) into (or X, -1) can replace
2585 // the 'or' with -1.
2586 Value *SimplifiedVal;
2587 {
2588 // Sanity check to make sure 'User' doesn't dangle across
2589 // SimplifyInstruction.
2590 AssertingVH<> UserHandle(User);
Duncan Sands12a86f52010-11-14 11:23:23 +00002591
Duncan Sandseff05812010-11-14 18:36:10 +00002592 SimplifiedVal = SimplifyInstruction(User, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002593 if (SimplifiedVal == 0) continue;
Chris Lattner40d8c282009-11-10 22:26:15 +00002594 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002595
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002596 // Recursively simplify this user to the new value.
Duncan Sandseff05812010-11-14 18:36:10 +00002597 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002598 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
2599 To = ToHandle;
Duncan Sands12a86f52010-11-14 11:23:23 +00002600
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002601 assert(ToHandle && "To value deleted by recursive simplification?");
Duncan Sands12a86f52010-11-14 11:23:23 +00002602
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002603 // If the recursive simplification ended up revisiting and deleting
2604 // 'From' then we're done.
2605 if (From == 0)
2606 return;
Chris Lattner40d8c282009-11-10 22:26:15 +00002607 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002608
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002609 // If 'From' has value handles referring to it, do a real RAUW to update them.
2610 From->replaceAllUsesWith(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00002611
Chris Lattner40d8c282009-11-10 22:26:15 +00002612 From->eraseFromParent();
2613}