blob: d9e3400f89542d1341c3bbb028a6bf0ba4c0dc76 [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);
419
Duncan Sands50ca4d32011-02-03 09:37:39 +0000420 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000421 // Does "cmp TV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000422 if (Value *TCmp = SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, DT,
Duncan Sands50ca4d32011-02-03 09:37:39 +0000423 MaxRecurse)) {
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000424 // It does! Does "cmp FV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000425 if (Value *FCmp = SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD, DT,
Duncan Sands50ca4d32011-02-03 09:37:39 +0000426 MaxRecurse)) {
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000427 // It does! If they simplified to the same value, then use it as the
428 // result of the original comparison.
Duncan Sands124708d2011-01-01 20:08:02 +0000429 if (TCmp == FCmp)
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000430 return TCmp;
Duncan Sands50ca4d32011-02-03 09:37:39 +0000431 Value *Cond = SI->getCondition();
432 // If the false value simplified to false, then the result of the compare
433 // is equal to "Cond && TCmp". This also catches the case when the false
434 // value simplified to false and the true value to true, returning "Cond".
435 if (match(FCmp, m_Zero()))
436 if (Value *V = SimplifyAndInst(Cond, TCmp, TD, DT, MaxRecurse))
437 return V;
438 // If the true value simplified to true, then the result of the compare
439 // is equal to "Cond || FCmp".
440 if (match(TCmp, m_One()))
441 if (Value *V = SimplifyOrInst(Cond, FCmp, TD, DT, MaxRecurse))
442 return V;
443 // Finally, if the false value simplified to true and the true value to
444 // false, then the result of the compare is equal to "!Cond".
445 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
446 if (Value *V =
447 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
448 TD, DT, MaxRecurse))
449 return V;
450 }
451 }
452
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000453 return 0;
454}
455
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000456/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
457/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
458/// it on the incoming phi values yields the same result for every value. If so
459/// returns the common value, otherwise returns null.
460static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000461 const TargetData *TD, const DominatorTree *DT,
462 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000463 // Recursion is always used, so bail out at once if we already hit the limit.
464 if (!MaxRecurse--)
465 return 0;
466
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000467 PHINode *PI;
468 if (isa<PHINode>(LHS)) {
469 PI = cast<PHINode>(LHS);
Duncan Sands18450092010-11-16 12:16:38 +0000470 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
471 if (!ValueDominatesPHI(RHS, PI, DT))
472 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000473 } else {
474 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
475 PI = cast<PHINode>(RHS);
Duncan Sands18450092010-11-16 12:16:38 +0000476 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
477 if (!ValueDominatesPHI(LHS, PI, DT))
478 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000479 }
480
481 // Evaluate the BinOp on the incoming phi values.
482 Value *CommonValue = 0;
483 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000484 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000485 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000486 if (Incoming == PI) continue;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000487 Value *V = PI == LHS ?
Duncan Sands18450092010-11-16 12:16:38 +0000488 SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
489 SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000490 // If the operation failed to simplify, or simplified to a different value
491 // to previously, then give up.
492 if (!V || (CommonValue && V != CommonValue))
493 return 0;
494 CommonValue = V;
495 }
496
497 return CommonValue;
498}
499
500/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
501/// try to simplify the comparison by seeing whether comparing with all of the
502/// incoming phi values yields the same result every time. If so returns the
503/// common result, otherwise returns null.
504static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000505 const TargetData *TD, const DominatorTree *DT,
506 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000507 // Recursion is always used, so bail out at once if we already hit the limit.
508 if (!MaxRecurse--)
509 return 0;
510
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000511 // Make sure the phi is on the LHS.
512 if (!isa<PHINode>(LHS)) {
513 std::swap(LHS, RHS);
514 Pred = CmpInst::getSwappedPredicate(Pred);
515 }
516 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
517 PHINode *PI = cast<PHINode>(LHS);
518
Duncan Sands18450092010-11-16 12:16:38 +0000519 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
520 if (!ValueDominatesPHI(RHS, PI, DT))
521 return 0;
522
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000523 // Evaluate the BinOp on the incoming phi values.
524 Value *CommonValue = 0;
525 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000526 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000527 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000528 if (Incoming == PI) continue;
Duncan Sands18450092010-11-16 12:16:38 +0000529 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000530 // If the operation failed to simplify, or simplified to a different value
531 // to previously, then give up.
532 if (!V || (CommonValue && V != CommonValue))
533 return 0;
534 CommonValue = V;
535 }
536
537 return CommonValue;
538}
539
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000540/// SimplifyAddInst - Given operands for an Add, see if we can
541/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000542static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
543 const TargetData *TD, const DominatorTree *DT,
544 unsigned MaxRecurse) {
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000545 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
546 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
547 Constant *Ops[] = { CLHS, CRHS };
548 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
Jay Foad1d2f5692011-07-19 13:32:40 +0000549 Ops, TD);
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000550 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000551
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000552 // Canonicalize the constant to the RHS.
553 std::swap(Op0, Op1);
554 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000555
Duncan Sandsfea3b212010-12-15 14:07:39 +0000556 // X + undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000557 if (match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000558 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000559
Duncan Sandsfea3b212010-12-15 14:07:39 +0000560 // X + 0 -> X
561 if (match(Op1, m_Zero()))
562 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000563
Duncan Sandsfea3b212010-12-15 14:07:39 +0000564 // X + (Y - X) -> Y
565 // (Y - X) + X -> Y
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000566 // Eg: X + -X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000567 Value *Y = 0;
568 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
569 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000570 return Y;
571
572 // X + ~X -> -1 since ~X = -X-1
Duncan Sands124708d2011-01-01 20:08:02 +0000573 if (match(Op0, m_Not(m_Specific(Op1))) ||
574 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000575 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands87689cf2010-11-19 09:20:39 +0000576
Duncan Sands82fdab32010-12-21 14:00:22 +0000577 /// i1 add -> xor.
Duncan Sands75d289e2010-12-21 14:48:48 +0000578 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000579 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
580 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000581
Duncan Sands566edb02010-12-21 08:49:00 +0000582 // Try some generic simplifications for associative operations.
583 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, DT,
584 MaxRecurse))
585 return V;
586
Duncan Sands3421d902010-12-21 13:32:22 +0000587 // Mul distributes over Add. Try some generic simplifications based on this.
588 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
589 TD, DT, MaxRecurse))
590 return V;
591
Duncan Sands87689cf2010-11-19 09:20:39 +0000592 // Threading Add over selects and phi nodes is pointless, so don't bother.
593 // Threading over the select in "A + select(cond, B, C)" means evaluating
594 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
595 // only if B and C are equal. If B and C are equal then (since we assume
596 // that operands have already been simplified) "select(cond, B, C)" should
597 // have been simplified to the common value of B and C already. Analysing
598 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
599 // for threading over phi nodes.
600
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000601 return 0;
602}
603
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000604Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
605 const TargetData *TD, const DominatorTree *DT) {
606 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
607}
608
Duncan Sandsfea3b212010-12-15 14:07:39 +0000609/// SimplifySubInst - Given operands for a Sub, see if we can
610/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000611static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands3421d902010-12-21 13:32:22 +0000612 const TargetData *TD, const DominatorTree *DT,
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000613 unsigned MaxRecurse) {
Duncan Sandsfea3b212010-12-15 14:07:39 +0000614 if (Constant *CLHS = dyn_cast<Constant>(Op0))
615 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
616 Constant *Ops[] = { CLHS, CRHS };
617 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
Jay Foad1d2f5692011-07-19 13:32:40 +0000618 Ops, TD);
Duncan Sandsfea3b212010-12-15 14:07:39 +0000619 }
620
621 // X - undef -> undef
622 // undef - X -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000623 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
Duncan Sandsfea3b212010-12-15 14:07:39 +0000624 return UndefValue::get(Op0->getType());
625
626 // X - 0 -> X
627 if (match(Op1, m_Zero()))
628 return Op0;
629
630 // X - X -> 0
Duncan Sands124708d2011-01-01 20:08:02 +0000631 if (Op0 == Op1)
Duncan Sandsfea3b212010-12-15 14:07:39 +0000632 return Constant::getNullValue(Op0->getType());
633
Duncan Sandsfe02c692011-01-18 09:24:58 +0000634 // (X*2) - X -> X
635 // (X<<1) - X -> X
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000636 Value *X = 0;
Duncan Sandsfe02c692011-01-18 09:24:58 +0000637 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
638 match(Op0, m_Shl(m_Specific(Op1), m_One())))
639 return Op1;
640
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000641 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
642 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
643 Value *Y = 0, *Z = Op1;
644 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
645 // See if "V === Y - Z" simplifies.
646 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, TD, DT, MaxRecurse-1))
647 // It does! Now see if "X + V" simplifies.
648 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, TD, DT,
649 MaxRecurse-1)) {
650 // It does, we successfully reassociated!
651 ++NumReassoc;
652 return W;
653 }
654 // See if "V === X - Z" simplifies.
655 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecurse-1))
656 // It does! Now see if "Y + V" simplifies.
657 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, TD, DT,
658 MaxRecurse-1)) {
659 // It does, we successfully reassociated!
660 ++NumReassoc;
661 return W;
662 }
663 }
Duncan Sands82fdab32010-12-21 14:00:22 +0000664
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000665 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
666 // For example, X - (X + 1) -> -1
667 X = Op0;
668 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
669 // See if "V === X - Y" simplifies.
670 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, TD, DT, MaxRecurse-1))
671 // It does! Now see if "V - Z" simplifies.
672 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, TD, DT,
673 MaxRecurse-1)) {
674 // It does, we successfully reassociated!
675 ++NumReassoc;
676 return W;
677 }
678 // See if "V === X - Z" simplifies.
679 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecurse-1))
680 // It does! Now see if "V - Y" simplifies.
681 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, TD, DT,
682 MaxRecurse-1)) {
683 // It does, we successfully reassociated!
684 ++NumReassoc;
685 return W;
686 }
687 }
688
689 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
690 // For example, X - (X - Y) -> Y.
691 Z = Op0;
Duncan Sandsc087e202011-01-14 15:26:10 +0000692 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
693 // See if "V === Z - X" simplifies.
694 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, TD, DT, MaxRecurse-1))
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000695 // It does! Now see if "V + Y" simplifies.
Duncan Sandsc087e202011-01-14 15:26:10 +0000696 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, TD, DT,
697 MaxRecurse-1)) {
698 // It does, we successfully reassociated!
699 ++NumReassoc;
700 return W;
701 }
702
Duncan Sands3421d902010-12-21 13:32:22 +0000703 // Mul distributes over Sub. Try some generic simplifications based on this.
704 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
705 TD, DT, MaxRecurse))
706 return V;
707
Duncan Sandsb2f3c382011-01-18 11:50:19 +0000708 // i1 sub -> xor.
709 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
710 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
711 return V;
712
Duncan Sandsfea3b212010-12-15 14:07:39 +0000713 // Threading Sub over selects and phi nodes is pointless, so don't bother.
714 // Threading over the select in "A - select(cond, B, C)" means evaluating
715 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
716 // only if B and C are equal. If B and C are equal then (since we assume
717 // that operands have already been simplified) "select(cond, B, C)" should
718 // have been simplified to the common value of B and C already. Analysing
719 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
720 // for threading over phi nodes.
721
722 return 0;
723}
724
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000725Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
726 const TargetData *TD, const DominatorTree *DT) {
727 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
728}
729
Duncan Sands82fdab32010-12-21 14:00:22 +0000730/// SimplifyMulInst - Given operands for a Mul, see if we can
731/// fold the result. If not, this returns null.
732static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
733 const DominatorTree *DT, unsigned MaxRecurse) {
734 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
735 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
736 Constant *Ops[] = { CLHS, CRHS };
737 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
Jay Foad1d2f5692011-07-19 13:32:40 +0000738 Ops, TD);
Duncan Sands82fdab32010-12-21 14:00:22 +0000739 }
740
741 // Canonicalize the constant to the RHS.
742 std::swap(Op0, Op1);
743 }
744
745 // X * undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000746 if (match(Op1, m_Undef()))
Duncan Sands82fdab32010-12-21 14:00:22 +0000747 return Constant::getNullValue(Op0->getType());
748
749 // X * 0 -> 0
750 if (match(Op1, m_Zero()))
751 return Op1;
752
753 // X * 1 -> X
754 if (match(Op1, m_One()))
755 return Op0;
756
Duncan Sands1895e982011-01-30 18:03:50 +0000757 // (X / Y) * Y -> X if the division is exact.
758 Value *X = 0, *Y = 0;
Chris Lattneraeaf3d42011-02-09 17:00:45 +0000759 if ((match(Op0, m_IDiv(m_Value(X), m_Value(Y))) && Y == Op1) || // (X / Y) * Y
760 (match(Op1, m_IDiv(m_Value(X), m_Value(Y))) && Y == Op0)) { // Y * (X / Y)
Chris Lattnerc6ee9182011-02-06 22:05:31 +0000761 BinaryOperator *Div = cast<BinaryOperator>(Y == Op1 ? Op0 : Op1);
762 if (Div->isExact())
Duncan Sands1895e982011-01-30 18:03:50 +0000763 return X;
764 }
765
Nick Lewycky54138802011-01-29 19:55:23 +0000766 // i1 mul -> and.
Duncan Sands75d289e2010-12-21 14:48:48 +0000767 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000768 if (Value *V = SimplifyAndInst(Op0, Op1, TD, DT, MaxRecurse-1))
769 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000770
771 // Try some generic simplifications for associative operations.
772 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, DT,
773 MaxRecurse))
774 return V;
775
776 // Mul distributes over Add. Try some generic simplifications based on this.
777 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
778 TD, DT, MaxRecurse))
779 return V;
780
781 // If the operation is with the result of a select instruction, check whether
782 // operating on either branch of the select always yields the same value.
783 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
784 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, DT,
785 MaxRecurse))
786 return V;
787
788 // If the operation is with the result of a phi instruction, check whether
789 // operating on all incoming values of the phi always yields the same value.
790 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
791 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, DT,
792 MaxRecurse))
793 return V;
794
795 return 0;
796}
797
798Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
799 const DominatorTree *DT) {
800 return ::SimplifyMulInst(Op0, Op1, TD, DT, RecursionLimit);
801}
802
Duncan Sands593faa52011-01-28 16:51:11 +0000803/// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
804/// fold the result. If not, this returns null.
Anders Carlsson479b4b92011-02-05 18:33:43 +0000805static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
Duncan Sands593faa52011-01-28 16:51:11 +0000806 const TargetData *TD, const DominatorTree *DT,
807 unsigned MaxRecurse) {
808 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
809 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
810 Constant *Ops[] = { C0, C1 };
Jay Foad1d2f5692011-07-19 13:32:40 +0000811 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD);
Duncan Sands593faa52011-01-28 16:51:11 +0000812 }
813 }
814
Duncan Sandsa3e292c2011-01-28 18:50:50 +0000815 bool isSigned = Opcode == Instruction::SDiv;
816
Duncan Sands593faa52011-01-28 16:51:11 +0000817 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000818 if (match(Op1, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +0000819 return Op1;
820
821 // undef / X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000822 if (match(Op0, m_Undef()))
Duncan Sands593faa52011-01-28 16:51:11 +0000823 return Constant::getNullValue(Op0->getType());
824
825 // 0 / X -> 0, we don't need to preserve faults!
826 if (match(Op0, m_Zero()))
827 return Op0;
828
829 // X / 1 -> X
830 if (match(Op1, m_One()))
831 return Op0;
Duncan Sands593faa52011-01-28 16:51:11 +0000832
833 if (Op0->getType()->isIntegerTy(1))
834 // It can't be division by zero, hence it must be division by one.
835 return Op0;
836
837 // X / X -> 1
838 if (Op0 == Op1)
839 return ConstantInt::get(Op0->getType(), 1);
840
841 // (X * Y) / Y -> X if the multiplication does not overflow.
842 Value *X = 0, *Y = 0;
843 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
844 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
Duncan Sands4b720712011-02-02 20:52:00 +0000845 BinaryOperator *Mul = cast<BinaryOperator>(Op0);
846 // If the Mul knows it does not overflow, then we are good to go.
847 if ((isSigned && Mul->hasNoSignedWrap()) ||
848 (!isSigned && Mul->hasNoUnsignedWrap()))
849 return X;
Duncan Sands593faa52011-01-28 16:51:11 +0000850 // If X has the form X = A / Y then X * Y cannot overflow.
851 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
852 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
853 return X;
854 }
855
Duncan Sandsa3e292c2011-01-28 18:50:50 +0000856 // (X rem Y) / Y -> 0
857 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
858 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
859 return Constant::getNullValue(Op0->getType());
860
861 // If the operation is with the result of a select instruction, check whether
862 // operating on either branch of the select always yields the same value.
863 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
864 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
865 return V;
866
867 // If the operation is with the result of a phi instruction, check whether
868 // operating on all incoming values of the phi always yields the same value.
869 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
870 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
871 return V;
872
Duncan Sands593faa52011-01-28 16:51:11 +0000873 return 0;
874}
875
876/// SimplifySDivInst - Given operands for an SDiv, see if we can
877/// fold the result. If not, this returns null.
878static Value *SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
879 const DominatorTree *DT, unsigned MaxRecurse) {
880 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, TD, DT, MaxRecurse))
881 return V;
882
Duncan Sands593faa52011-01-28 16:51:11 +0000883 return 0;
884}
885
886Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000887 const DominatorTree *DT) {
Duncan Sands593faa52011-01-28 16:51:11 +0000888 return ::SimplifySDivInst(Op0, Op1, TD, DT, RecursionLimit);
889}
890
891/// SimplifyUDivInst - Given operands for a UDiv, see if we can
892/// fold the result. If not, this returns null.
893static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
894 const DominatorTree *DT, unsigned MaxRecurse) {
895 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, TD, DT, MaxRecurse))
896 return V;
897
Duncan Sands593faa52011-01-28 16:51:11 +0000898 return 0;
899}
900
901Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000902 const DominatorTree *DT) {
Duncan Sands593faa52011-01-28 16:51:11 +0000903 return ::SimplifyUDivInst(Op0, Op1, TD, DT, RecursionLimit);
904}
905
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000906static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *,
907 const DominatorTree *, unsigned) {
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000908 // undef / X -> undef (the undef could be a snan).
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000909 if (match(Op0, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000910 return Op0;
911
912 // X / undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +0000913 if (match(Op1, m_Undef()))
Frits van Bommel1fca2c32011-01-29 15:26:31 +0000914 return Op1;
915
916 return 0;
917}
918
919Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *TD,
920 const DominatorTree *DT) {
921 return ::SimplifyFDivInst(Op0, Op1, TD, DT, RecursionLimit);
922}
923
Duncan Sandsf24ed772011-05-02 16:27:02 +0000924/// SimplifyRem - Given operands for an SRem or URem, see if we can
925/// fold the result. If not, this returns null.
926static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
927 const TargetData *TD, const DominatorTree *DT,
928 unsigned MaxRecurse) {
929 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
930 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
931 Constant *Ops[] = { C0, C1 };
Jay Foad1d2f5692011-07-19 13:32:40 +0000932 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD);
Duncan Sandsf24ed772011-05-02 16:27:02 +0000933 }
934 }
935
Duncan Sandsf24ed772011-05-02 16:27:02 +0000936 // X % undef -> undef
937 if (match(Op1, m_Undef()))
938 return Op1;
939
940 // undef % X -> 0
941 if (match(Op0, m_Undef()))
942 return Constant::getNullValue(Op0->getType());
943
944 // 0 % X -> 0, we don't need to preserve faults!
945 if (match(Op0, m_Zero()))
946 return Op0;
947
948 // X % 0 -> undef, we don't need to preserve faults!
949 if (match(Op1, m_Zero()))
950 return UndefValue::get(Op0->getType());
951
952 // X % 1 -> 0
953 if (match(Op1, m_One()))
954 return Constant::getNullValue(Op0->getType());
955
956 if (Op0->getType()->isIntegerTy(1))
957 // It can't be remainder by zero, hence it must be remainder by one.
958 return Constant::getNullValue(Op0->getType());
959
960 // X % X -> 0
961 if (Op0 == Op1)
962 return Constant::getNullValue(Op0->getType());
963
964 // If the operation is with the result of a select instruction, check whether
965 // operating on either branch of the select always yields the same value.
966 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
967 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
968 return V;
969
970 // If the operation is with the result of a phi instruction, check whether
971 // operating on all incoming values of the phi always yields the same value.
972 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
973 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
974 return V;
975
976 return 0;
977}
978
979/// SimplifySRemInst - Given operands for an SRem, see if we can
980/// fold the result. If not, this returns null.
981static Value *SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
982 const DominatorTree *DT, unsigned MaxRecurse) {
983 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, TD, DT, MaxRecurse))
984 return V;
985
986 return 0;
987}
988
989Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
990 const DominatorTree *DT) {
991 return ::SimplifySRemInst(Op0, Op1, TD, DT, RecursionLimit);
992}
993
994/// SimplifyURemInst - Given operands for a URem, see if we can
995/// fold the result. If not, this returns null.
996static Value *SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
997 const DominatorTree *DT, unsigned MaxRecurse) {
998 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, TD, DT, MaxRecurse))
999 return V;
1000
1001 return 0;
1002}
1003
1004Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
1005 const DominatorTree *DT) {
1006 return ::SimplifyURemInst(Op0, Op1, TD, DT, RecursionLimit);
1007}
1008
1009static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *,
1010 const DominatorTree *, unsigned) {
1011 // undef % X -> undef (the undef could be a snan).
1012 if (match(Op0, m_Undef()))
1013 return Op0;
1014
1015 // X % undef -> undef
1016 if (match(Op1, m_Undef()))
1017 return Op1;
1018
1019 return 0;
1020}
1021
1022Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1023 const DominatorTree *DT) {
1024 return ::SimplifyFRemInst(Op0, Op1, TD, DT, RecursionLimit);
1025}
1026
Duncan Sandscf80bc12011-01-14 14:44:12 +00001027/// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
Duncan Sandsc43cee32011-01-14 00:37:45 +00001028/// fold the result. If not, this returns null.
Duncan Sandscf80bc12011-01-14 14:44:12 +00001029static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1030 const TargetData *TD, const DominatorTree *DT,
1031 unsigned MaxRecurse) {
Duncan Sandsc43cee32011-01-14 00:37:45 +00001032 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1033 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1034 Constant *Ops[] = { C0, C1 };
Jay Foad1d2f5692011-07-19 13:32:40 +00001035 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001036 }
1037 }
1038
Duncan Sandscf80bc12011-01-14 14:44:12 +00001039 // 0 shift by X -> 0
Duncan Sandsc43cee32011-01-14 00:37:45 +00001040 if (match(Op0, m_Zero()))
1041 return Op0;
1042
Duncan Sandscf80bc12011-01-14 14:44:12 +00001043 // X shift by 0 -> X
Duncan Sandsc43cee32011-01-14 00:37:45 +00001044 if (match(Op1, m_Zero()))
1045 return Op0;
1046
Duncan Sandscf80bc12011-01-14 14:44:12 +00001047 // X shift by undef -> undef because it may shift by the bitwidth.
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001048 if (match(Op1, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001049 return Op1;
1050
1051 // Shifting by the bitwidth or more is undefined.
1052 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1053 if (CI->getValue().getLimitedValue() >=
1054 Op0->getType()->getScalarSizeInBits())
1055 return UndefValue::get(Op0->getType());
1056
Duncan Sandscf80bc12011-01-14 14:44:12 +00001057 // If the operation is with the result of a select instruction, check whether
1058 // operating on either branch of the select always yields the same value.
1059 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1060 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
1061 return V;
1062
1063 // If the operation is with the result of a phi instruction, check whether
1064 // operating on all incoming values of the phi always yields the same value.
1065 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1066 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
1067 return V;
1068
1069 return 0;
1070}
1071
1072/// SimplifyShlInst - Given operands for an Shl, see if we can
1073/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001074static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1075 const TargetData *TD, const DominatorTree *DT,
1076 unsigned MaxRecurse) {
Duncan Sandscf80bc12011-01-14 14:44:12 +00001077 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, TD, DT, MaxRecurse))
1078 return V;
1079
1080 // undef << X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001081 if (match(Op0, m_Undef()))
Duncan Sandscf80bc12011-01-14 14:44:12 +00001082 return Constant::getNullValue(Op0->getType());
1083
Chris Lattner81a0dc92011-02-09 17:15:04 +00001084 // (X >> A) << A -> X
1085 Value *X;
1086 if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1))) &&
1087 cast<PossiblyExactOperator>(Op0)->isExact())
1088 return X;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001089 return 0;
1090}
1091
Chris Lattner81a0dc92011-02-09 17:15:04 +00001092Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1093 const TargetData *TD, const DominatorTree *DT) {
1094 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001095}
1096
1097/// SimplifyLShrInst - Given operands for an LShr, see if we can
1098/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001099static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1100 const TargetData *TD, const DominatorTree *DT,
1101 unsigned MaxRecurse) {
Duncan Sandscf80bc12011-01-14 14:44:12 +00001102 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, TD, DT, MaxRecurse))
1103 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001104
1105 // undef >>l X -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001106 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001107 return Constant::getNullValue(Op0->getType());
1108
Chris Lattner81a0dc92011-02-09 17:15:04 +00001109 // (X << A) >> A -> X
1110 Value *X;
1111 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1112 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1113 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001114
Duncan Sandsc43cee32011-01-14 00:37:45 +00001115 return 0;
1116}
1117
Chris Lattner81a0dc92011-02-09 17:15:04 +00001118Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1119 const TargetData *TD, const DominatorTree *DT) {
1120 return ::SimplifyLShrInst(Op0, Op1, isExact, TD, DT, RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001121}
1122
1123/// SimplifyAShrInst - Given operands for an AShr, see if we can
1124/// fold the result. If not, this returns null.
Chris Lattner81a0dc92011-02-09 17:15:04 +00001125static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1126 const TargetData *TD, const DominatorTree *DT,
1127 unsigned MaxRecurse) {
Duncan Sandscf80bc12011-01-14 14:44:12 +00001128 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, TD, DT, MaxRecurse))
1129 return V;
Duncan Sandsc43cee32011-01-14 00:37:45 +00001130
1131 // all ones >>a X -> all ones
1132 if (match(Op0, m_AllOnes()))
1133 return Op0;
1134
1135 // undef >>a X -> all ones
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001136 if (match(Op0, m_Undef()))
Duncan Sandsc43cee32011-01-14 00:37:45 +00001137 return Constant::getAllOnesValue(Op0->getType());
1138
Chris Lattner81a0dc92011-02-09 17:15:04 +00001139 // (X << A) >> A -> X
1140 Value *X;
1141 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1142 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1143 return X;
Duncan Sands52fb8462011-02-13 17:15:40 +00001144
Duncan Sandsc43cee32011-01-14 00:37:45 +00001145 return 0;
1146}
1147
Chris Lattner81a0dc92011-02-09 17:15:04 +00001148Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1149 const TargetData *TD, const DominatorTree *DT) {
1150 return ::SimplifyAShrInst(Op0, Op1, isExact, TD, DT, RecursionLimit);
Duncan Sandsc43cee32011-01-14 00:37:45 +00001151}
1152
Chris Lattnerd06094f2009-11-10 00:55:12 +00001153/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001154/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001155static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +00001156 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001157 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1158 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1159 Constant *Ops[] = { CLHS, CRHS };
1160 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
Jay Foad1d2f5692011-07-19 13:32:40 +00001161 Ops, TD);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001162 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001163
Chris Lattnerd06094f2009-11-10 00:55:12 +00001164 // Canonicalize the constant to the RHS.
1165 std::swap(Op0, Op1);
1166 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001167
Chris Lattnerd06094f2009-11-10 00:55:12 +00001168 // X & undef -> 0
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001169 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001170 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001171
Chris Lattnerd06094f2009-11-10 00:55:12 +00001172 // X & X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001173 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001174 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001175
Duncan Sands2b749872010-11-17 18:52:15 +00001176 // X & 0 = 0
1177 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001178 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001179
Duncan Sands2b749872010-11-17 18:52:15 +00001180 // X & -1 = X
1181 if (match(Op1, m_AllOnes()))
1182 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001183
Chris Lattnerd06094f2009-11-10 00:55:12 +00001184 // A & ~A = ~A & A = 0
Chris Lattner81a0dc92011-02-09 17:15:04 +00001185 if (match(Op0, m_Not(m_Specific(Op1))) ||
1186 match(Op1, m_Not(m_Specific(Op0))))
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 // (A | ?) & A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001190 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001191 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001192 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001193 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001194
Chris Lattnerd06094f2009-11-10 00:55:12 +00001195 // A & (A | ?) = A
1196 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001197 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001198 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001199
Duncan Sandsdd3149d2011-10-26 20:55:21 +00001200 // A & (-A) = A if A is a power of two or zero.
1201 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1202 match(Op1, m_Neg(m_Specific(Op0)))) {
1203 if (isPowerOfTwo(Op0, TD, /*OrZero*/true))
1204 return Op0;
1205 if (isPowerOfTwo(Op1, TD, /*OrZero*/true))
1206 return Op1;
1207 }
1208
Duncan Sands566edb02010-12-21 08:49:00 +00001209 // Try some generic simplifications for associative operations.
1210 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, DT,
1211 MaxRecurse))
1212 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001213
Duncan Sands3421d902010-12-21 13:32:22 +00001214 // And distributes over Or. Try some generic simplifications based on this.
1215 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1216 TD, DT, MaxRecurse))
1217 return V;
1218
1219 // And distributes over Xor. Try some generic simplifications based on this.
1220 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1221 TD, DT, MaxRecurse))
1222 return V;
1223
1224 // Or distributes over And. Try some generic simplifications based on this.
1225 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1226 TD, DT, MaxRecurse))
1227 return V;
1228
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001229 // If the operation is with the result of a select instruction, check whether
1230 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001231 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +00001232 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001233 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001234 return V;
1235
1236 // If the operation is with the result of a phi instruction, check whether
1237 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001238 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +00001239 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001240 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001241 return V;
1242
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001243 return 0;
1244}
1245
Duncan Sands18450092010-11-16 12:16:38 +00001246Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1247 const DominatorTree *DT) {
1248 return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001249}
1250
Chris Lattnerd06094f2009-11-10 00:55:12 +00001251/// SimplifyOrInst - Given operands for an Or, see if we can
1252/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001253static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +00001254 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001255 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1256 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1257 Constant *Ops[] = { CLHS, CRHS };
1258 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
Jay Foad1d2f5692011-07-19 13:32:40 +00001259 Ops, TD);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001260 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001261
Chris Lattnerd06094f2009-11-10 00:55:12 +00001262 // Canonicalize the constant to the RHS.
1263 std::swap(Op0, Op1);
1264 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001265
Chris Lattnerd06094f2009-11-10 00:55:12 +00001266 // X | undef -> -1
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001267 if (match(Op1, m_Undef()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001268 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +00001269
Chris Lattnerd06094f2009-11-10 00:55:12 +00001270 // X | X = X
Duncan Sands124708d2011-01-01 20:08:02 +00001271 if (Op0 == Op1)
Chris Lattnerd06094f2009-11-10 00:55:12 +00001272 return Op0;
1273
Duncan Sands2b749872010-11-17 18:52:15 +00001274 // X | 0 = X
1275 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001276 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001277
Duncan Sands2b749872010-11-17 18:52:15 +00001278 // X | -1 = -1
1279 if (match(Op1, m_AllOnes()))
1280 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001281
Chris Lattnerd06094f2009-11-10 00:55:12 +00001282 // A | ~A = ~A | A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001283 if (match(Op0, m_Not(m_Specific(Op1))) ||
1284 match(Op1, m_Not(m_Specific(Op0))))
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 // (A & ?) | A = A
Chris Lattner81a0dc92011-02-09 17:15:04 +00001288 Value *A = 0, *B = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00001289 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001290 (A == Op1 || B == Op1))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001291 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +00001292
Chris Lattnerd06094f2009-11-10 00:55:12 +00001293 // A | (A & ?) = A
1294 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
Duncan Sands124708d2011-01-01 20:08:02 +00001295 (A == Op0 || B == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +00001296 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001297
Benjamin Kramer38f7f662011-02-20 15:20:01 +00001298 // ~(A & ?) | A = -1
1299 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1300 (A == Op1 || B == Op1))
1301 return Constant::getAllOnesValue(Op1->getType());
1302
1303 // A | ~(A & ?) = -1
1304 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1305 (A == Op0 || B == Op0))
1306 return Constant::getAllOnesValue(Op0->getType());
1307
Duncan Sands566edb02010-12-21 08:49:00 +00001308 // Try some generic simplifications for associative operations.
1309 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, DT,
1310 MaxRecurse))
1311 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +00001312
Duncan Sands3421d902010-12-21 13:32:22 +00001313 // Or distributes over And. Try some generic simplifications based on this.
1314 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1315 TD, DT, MaxRecurse))
1316 return V;
1317
1318 // And distributes over Or. Try some generic simplifications based on this.
1319 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1320 TD, DT, MaxRecurse))
1321 return V;
1322
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001323 // If the operation is with the result of a select instruction, check whether
1324 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001325 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +00001326 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001327 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001328 return V;
1329
1330 // If the operation is with the result of a phi instruction, check whether
1331 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001332 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +00001333 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001334 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001335 return V;
1336
Chris Lattnerd06094f2009-11-10 00:55:12 +00001337 return 0;
1338}
1339
Duncan Sands18450092010-11-16 12:16:38 +00001340Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1341 const DominatorTree *DT) {
1342 return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001343}
Chris Lattnerd06094f2009-11-10 00:55:12 +00001344
Duncan Sands2b749872010-11-17 18:52:15 +00001345/// SimplifyXorInst - Given operands for a Xor, see if we can
1346/// fold the result. If not, this returns null.
1347static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1348 const DominatorTree *DT, unsigned MaxRecurse) {
1349 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1350 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1351 Constant *Ops[] = { CLHS, CRHS };
1352 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
Jay Foad1d2f5692011-07-19 13:32:40 +00001353 Ops, TD);
Duncan Sands2b749872010-11-17 18:52:15 +00001354 }
1355
1356 // Canonicalize the constant to the RHS.
1357 std::swap(Op0, Op1);
1358 }
1359
1360 // A ^ undef -> undef
Duncan Sandsf9e4a982011-02-01 09:06:20 +00001361 if (match(Op1, m_Undef()))
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00001362 return Op1;
Duncan Sands2b749872010-11-17 18:52:15 +00001363
1364 // A ^ 0 = A
1365 if (match(Op1, m_Zero()))
1366 return Op0;
1367
Eli Friedmanf23d4ad2011-08-17 19:31:49 +00001368 // A ^ A = 0
1369 if (Op0 == Op1)
1370 return Constant::getNullValue(Op0->getType());
1371
Duncan Sands2b749872010-11-17 18:52:15 +00001372 // A ^ ~A = ~A ^ A = -1
Chris Lattner81a0dc92011-02-09 17:15:04 +00001373 if (match(Op0, m_Not(m_Specific(Op1))) ||
1374 match(Op1, m_Not(m_Specific(Op0))))
Duncan Sands2b749872010-11-17 18:52:15 +00001375 return Constant::getAllOnesValue(Op0->getType());
1376
Duncan Sands566edb02010-12-21 08:49:00 +00001377 // Try some generic simplifications for associative operations.
1378 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, DT,
1379 MaxRecurse))
1380 return V;
Duncan Sands2b749872010-11-17 18:52:15 +00001381
Duncan Sands3421d902010-12-21 13:32:22 +00001382 // And distributes over Xor. Try some generic simplifications based on this.
1383 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1384 TD, DT, MaxRecurse))
1385 return V;
1386
Duncan Sands87689cf2010-11-19 09:20:39 +00001387 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1388 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1389 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1390 // only if B and C are equal. If B and C are equal then (since we assume
1391 // that operands have already been simplified) "select(cond, B, C)" should
1392 // have been simplified to the common value of B and C already. Analysing
1393 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1394 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +00001395
1396 return 0;
1397}
1398
1399Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1400 const DominatorTree *DT) {
1401 return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
1402}
1403
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001404static Type *GetCompareTy(Value *Op) {
Chris Lattner210c5d42009-11-09 23:55:12 +00001405 return CmpInst::makeCmpResultType(Op->getType());
1406}
1407
Duncan Sandse864b5b2011-05-07 16:56:49 +00001408/// ExtractEquivalentCondition - Rummage around inside V looking for something
1409/// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1410/// otherwise return null. Helper function for analyzing max/min idioms.
1411static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1412 Value *LHS, Value *RHS) {
1413 SelectInst *SI = dyn_cast<SelectInst>(V);
1414 if (!SI)
1415 return 0;
1416 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1417 if (!Cmp)
1418 return 0;
1419 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1420 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1421 return Cmp;
1422 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1423 LHS == CmpRHS && RHS == CmpLHS)
1424 return Cmp;
1425 return 0;
1426}
1427
Chris Lattner9dbb4292009-11-09 23:28:39 +00001428/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1429/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001430static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001431 const TargetData *TD, const DominatorTree *DT,
1432 unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +00001433 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +00001434 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +00001435
Chris Lattnerd06094f2009-11-10 00:55:12 +00001436 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +00001437 if (Constant *CRHS = dyn_cast<Constant>(RHS))
1438 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001439
1440 // If we have a constant, make sure it is on the RHS.
1441 std::swap(LHS, RHS);
1442 Pred = CmpInst::getSwappedPredicate(Pred);
1443 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001444
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001445 Type *ITy = GetCompareTy(LHS); // The return type.
1446 Type *OpTy = LHS->getType(); // The operand type.
Duncan Sands12a86f52010-11-14 11:23:23 +00001447
Chris Lattner210c5d42009-11-09 23:55:12 +00001448 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +00001449 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1450 // because X could be 0.
Duncan Sands124708d2011-01-01 20:08:02 +00001451 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +00001452 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +00001453
Duncan Sands6dc91252011-01-13 08:56:29 +00001454 // Special case logic when the operands have i1 type.
1455 if (OpTy->isIntegerTy(1) || (OpTy->isVectorTy() &&
1456 cast<VectorType>(OpTy)->getElementType()->isIntegerTy(1))) {
1457 switch (Pred) {
1458 default: break;
1459 case ICmpInst::ICMP_EQ:
1460 // X == 1 -> X
1461 if (match(RHS, m_One()))
1462 return LHS;
1463 break;
1464 case ICmpInst::ICMP_NE:
1465 // X != 0 -> X
1466 if (match(RHS, m_Zero()))
1467 return LHS;
1468 break;
1469 case ICmpInst::ICMP_UGT:
1470 // X >u 0 -> X
1471 if (match(RHS, m_Zero()))
1472 return LHS;
1473 break;
1474 case ICmpInst::ICMP_UGE:
1475 // X >=u 1 -> X
1476 if (match(RHS, m_One()))
1477 return LHS;
1478 break;
1479 case ICmpInst::ICMP_SLT:
1480 // X <s 0 -> X
1481 if (match(RHS, m_Zero()))
1482 return LHS;
1483 break;
1484 case ICmpInst::ICMP_SLE:
1485 // X <=s -1 -> X
1486 if (match(RHS, m_One()))
1487 return LHS;
1488 break;
1489 }
1490 }
1491
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001492 // icmp <alloca*>, <global/alloca*/null> - Different stack variables have
1493 // different addresses, and what's more the address of a stack variable is
1494 // never null or equal to the address of a global. Note that generalizing
1495 // to the case where LHS is a global variable address or null is pointless,
1496 // since if both LHS and RHS are constants then we already constant folded
1497 // the compare, and if only one of them is then we moved it to RHS already.
1498 if (isa<AllocaInst>(LHS) && (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
1499 isa<ConstantPointerNull>(RHS)))
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00001500 // We already know that LHS != RHS.
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001501 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1502
1503 // If we are comparing with zero then try hard since this is a common case.
1504 if (match(RHS, m_Zero())) {
1505 bool LHSKnownNonNegative, LHSKnownNegative;
1506 switch (Pred) {
1507 default:
1508 assert(false && "Unknown ICmp predicate!");
1509 case ICmpInst::ICMP_ULT:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001510 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001511 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001512 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001513 case ICmpInst::ICMP_EQ:
1514 case ICmpInst::ICMP_ULE:
1515 if (isKnownNonZero(LHS, TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001516 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001517 break;
1518 case ICmpInst::ICMP_NE:
1519 case ICmpInst::ICMP_UGT:
1520 if (isKnownNonZero(LHS, TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001521 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001522 break;
1523 case ICmpInst::ICMP_SLT:
1524 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1525 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001526 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001527 if (LHSKnownNonNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001528 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001529 break;
1530 case ICmpInst::ICMP_SLE:
1531 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1532 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001533 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001534 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001535 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001536 break;
1537 case ICmpInst::ICMP_SGE:
1538 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1539 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001540 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001541 if (LHSKnownNonNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001542 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001543 break;
1544 case ICmpInst::ICMP_SGT:
1545 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1546 if (LHSKnownNegative)
Duncan Sandsf56138d2011-07-26 15:03:53 +00001547 return getFalse(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001548 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
Duncan Sandsf56138d2011-07-26 15:03:53 +00001549 return getTrue(ITy);
Duncan Sandsd70d1a52011-01-25 09:38:29 +00001550 break;
1551 }
1552 }
1553
1554 // See if we are doing a comparison with a constant integer.
Duncan Sands6dc91252011-01-13 08:56:29 +00001555 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
Nick Lewycky3a73e342011-03-04 07:00:57 +00001556 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1557 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1558 if (RHS_CR.isEmptySet())
1559 return ConstantInt::getFalse(CI->getContext());
1560 if (RHS_CR.isFullSet())
1561 return ConstantInt::getTrue(CI->getContext());
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001562
Nick Lewycky3a73e342011-03-04 07:00:57 +00001563 // Many binary operators with constant RHS have easy to compute constant
1564 // range. Use them to check whether the comparison is a tautology.
1565 uint32_t Width = CI->getBitWidth();
1566 APInt Lower = APInt(Width, 0);
1567 APInt Upper = APInt(Width, 0);
1568 ConstantInt *CI2;
1569 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1570 // 'urem x, CI2' produces [0, CI2).
1571 Upper = CI2->getValue();
1572 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1573 // 'srem x, CI2' produces (-|CI2|, |CI2|).
1574 Upper = CI2->getValue().abs();
1575 Lower = (-Upper) + 1;
1576 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1577 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1578 APInt NegOne = APInt::getAllOnesValue(Width);
1579 if (!CI2->isZero())
1580 Upper = NegOne.udiv(CI2->getValue()) + 1;
1581 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1582 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1583 APInt IntMin = APInt::getSignedMinValue(Width);
1584 APInt IntMax = APInt::getSignedMaxValue(Width);
1585 APInt Val = CI2->getValue().abs();
1586 if (!Val.isMinValue()) {
1587 Lower = IntMin.sdiv(Val);
1588 Upper = IntMax.sdiv(Val) + 1;
1589 }
1590 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1591 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1592 APInt NegOne = APInt::getAllOnesValue(Width);
1593 if (CI2->getValue().ult(Width))
1594 Upper = NegOne.lshr(CI2->getValue()) + 1;
1595 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1596 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1597 APInt IntMin = APInt::getSignedMinValue(Width);
1598 APInt IntMax = APInt::getSignedMaxValue(Width);
1599 if (CI2->getValue().ult(Width)) {
1600 Lower = IntMin.ashr(CI2->getValue());
1601 Upper = IntMax.ashr(CI2->getValue()) + 1;
1602 }
1603 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1604 // 'or x, CI2' produces [CI2, UINT_MAX].
1605 Lower = CI2->getValue();
1606 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1607 // 'and x, CI2' produces [0, CI2].
1608 Upper = CI2->getValue() + 1;
1609 }
1610 if (Lower != Upper) {
1611 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1612 if (RHS_CR.contains(LHS_CR))
1613 return ConstantInt::getTrue(RHS->getContext());
1614 if (RHS_CR.inverse().contains(LHS_CR))
1615 return ConstantInt::getFalse(RHS->getContext());
1616 }
Duncan Sands6dc91252011-01-13 08:56:29 +00001617 }
1618
Duncan Sands9d32f602011-01-20 13:21:55 +00001619 // Compare of cast, for example (zext X) != 0 -> X != 0
1620 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1621 Instruction *LI = cast<CastInst>(LHS);
1622 Value *SrcOp = LI->getOperand(0);
Chris Lattnerdb125cf2011-07-18 04:54:35 +00001623 Type *SrcTy = SrcOp->getType();
1624 Type *DstTy = LI->getType();
Duncan Sands9d32f602011-01-20 13:21:55 +00001625
1626 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1627 // if the integer type is the same size as the pointer type.
1628 if (MaxRecurse && TD && isa<PtrToIntInst>(LI) &&
1629 TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
1630 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1631 // Transfer the cast to the constant.
1632 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1633 ConstantExpr::getIntToPtr(RHSC, SrcTy),
1634 TD, DT, MaxRecurse-1))
1635 return V;
1636 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1637 if (RI->getOperand(0)->getType() == SrcTy)
1638 // Compare without the cast.
1639 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1640 TD, DT, MaxRecurse-1))
1641 return V;
1642 }
1643 }
1644
1645 if (isa<ZExtInst>(LHS)) {
1646 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1647 // same type.
1648 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1649 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1650 // Compare X and Y. Note that signed predicates become unsigned.
1651 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1652 SrcOp, RI->getOperand(0), TD, DT,
1653 MaxRecurse-1))
1654 return V;
1655 }
1656 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1657 // too. If not, then try to deduce the result of the comparison.
1658 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1659 // Compute the constant that would happen if we truncated to SrcTy then
1660 // reextended to DstTy.
1661 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1662 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1663
1664 // If the re-extended constant didn't change then this is effectively
1665 // also a case of comparing two zero-extended values.
1666 if (RExt == CI && MaxRecurse)
1667 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1668 SrcOp, Trunc, TD, DT, MaxRecurse-1))
1669 return V;
1670
1671 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1672 // there. Use this to work out the result of the comparison.
1673 if (RExt != CI) {
1674 switch (Pred) {
1675 default:
1676 assert(false && "Unknown ICmp predicate!");
1677 // LHS <u RHS.
1678 case ICmpInst::ICMP_EQ:
1679 case ICmpInst::ICMP_UGT:
1680 case ICmpInst::ICMP_UGE:
1681 return ConstantInt::getFalse(CI->getContext());
1682
1683 case ICmpInst::ICMP_NE:
1684 case ICmpInst::ICMP_ULT:
1685 case ICmpInst::ICMP_ULE:
1686 return ConstantInt::getTrue(CI->getContext());
1687
1688 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
1689 // is non-negative then LHS <s RHS.
1690 case ICmpInst::ICMP_SGT:
1691 case ICmpInst::ICMP_SGE:
1692 return CI->getValue().isNegative() ?
1693 ConstantInt::getTrue(CI->getContext()) :
1694 ConstantInt::getFalse(CI->getContext());
1695
1696 case ICmpInst::ICMP_SLT:
1697 case ICmpInst::ICMP_SLE:
1698 return CI->getValue().isNegative() ?
1699 ConstantInt::getFalse(CI->getContext()) :
1700 ConstantInt::getTrue(CI->getContext());
1701 }
1702 }
1703 }
1704 }
1705
1706 if (isa<SExtInst>(LHS)) {
1707 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1708 // same type.
1709 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1710 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1711 // Compare X and Y. Note that the predicate does not change.
1712 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1713 TD, DT, MaxRecurse-1))
1714 return V;
1715 }
1716 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1717 // too. If not, then try to deduce the result of the comparison.
1718 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1719 // Compute the constant that would happen if we truncated to SrcTy then
1720 // reextended to DstTy.
1721 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1722 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1723
1724 // If the re-extended constant didn't change then this is effectively
1725 // also a case of comparing two sign-extended values.
1726 if (RExt == CI && MaxRecurse)
1727 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, TD, DT,
1728 MaxRecurse-1))
1729 return V;
1730
1731 // Otherwise the upper bits of LHS are all equal, while RHS has varying
1732 // bits there. Use this to work out the result of the comparison.
1733 if (RExt != CI) {
1734 switch (Pred) {
1735 default:
1736 assert(false && "Unknown ICmp predicate!");
1737 case ICmpInst::ICMP_EQ:
1738 return ConstantInt::getFalse(CI->getContext());
1739 case ICmpInst::ICMP_NE:
1740 return ConstantInt::getTrue(CI->getContext());
1741
1742 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
1743 // LHS >s RHS.
1744 case ICmpInst::ICMP_SGT:
1745 case ICmpInst::ICMP_SGE:
1746 return CI->getValue().isNegative() ?
1747 ConstantInt::getTrue(CI->getContext()) :
1748 ConstantInt::getFalse(CI->getContext());
1749 case ICmpInst::ICMP_SLT:
1750 case ICmpInst::ICMP_SLE:
1751 return CI->getValue().isNegative() ?
1752 ConstantInt::getFalse(CI->getContext()) :
1753 ConstantInt::getTrue(CI->getContext());
1754
1755 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
1756 // LHS >u RHS.
1757 case ICmpInst::ICMP_UGT:
1758 case ICmpInst::ICMP_UGE:
1759 // Comparison is true iff the LHS <s 0.
1760 if (MaxRecurse)
1761 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
1762 Constant::getNullValue(SrcTy),
1763 TD, DT, MaxRecurse-1))
1764 return V;
1765 break;
1766 case ICmpInst::ICMP_ULT:
1767 case ICmpInst::ICMP_ULE:
1768 // Comparison is true iff the LHS >=s 0.
1769 if (MaxRecurse)
1770 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
1771 Constant::getNullValue(SrcTy),
1772 TD, DT, MaxRecurse-1))
1773 return V;
1774 break;
1775 }
1776 }
1777 }
1778 }
1779 }
1780
Duncan Sands52fb8462011-02-13 17:15:40 +00001781 // Special logic for binary operators.
1782 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
1783 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
1784 if (MaxRecurse && (LBO || RBO)) {
Duncan Sands52fb8462011-02-13 17:15:40 +00001785 // Analyze the case when either LHS or RHS is an add instruction.
1786 Value *A = 0, *B = 0, *C = 0, *D = 0;
1787 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
1788 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
1789 if (LBO && LBO->getOpcode() == Instruction::Add) {
1790 A = LBO->getOperand(0); B = LBO->getOperand(1);
1791 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
1792 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
1793 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
1794 }
1795 if (RBO && RBO->getOpcode() == Instruction::Add) {
1796 C = RBO->getOperand(0); D = RBO->getOperand(1);
1797 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
1798 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
1799 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
1800 }
1801
1802 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
1803 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
1804 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
1805 Constant::getNullValue(RHS->getType()),
1806 TD, DT, MaxRecurse-1))
1807 return V;
1808
1809 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
1810 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
1811 if (Value *V = SimplifyICmpInst(Pred,
1812 Constant::getNullValue(LHS->getType()),
1813 C == LHS ? D : C, TD, DT, MaxRecurse-1))
1814 return V;
1815
1816 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
1817 if (A && C && (A == C || A == D || B == C || B == D) &&
1818 NoLHSWrapProblem && NoRHSWrapProblem) {
1819 // Determine Y and Z in the form icmp (X+Y), (X+Z).
1820 Value *Y = (A == C || A == D) ? B : A;
1821 Value *Z = (C == A || C == B) ? D : C;
1822 if (Value *V = SimplifyICmpInst(Pred, Y, Z, TD, DT, MaxRecurse-1))
1823 return V;
1824 }
1825 }
1826
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001827 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
Nick Lewycky78679272011-03-04 10:06:52 +00001828 bool KnownNonNegative, KnownNegative;
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001829 switch (Pred) {
1830 default:
1831 break;
Nick Lewycky78679272011-03-04 10:06:52 +00001832 case ICmpInst::ICMP_SGT:
1833 case ICmpInst::ICMP_SGE:
1834 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1835 if (!KnownNonNegative)
1836 break;
1837 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001838 case ICmpInst::ICMP_EQ:
1839 case ICmpInst::ICMP_UGT:
1840 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001841 return getFalse(ITy);
Nick Lewycky78679272011-03-04 10:06:52 +00001842 case ICmpInst::ICMP_SLT:
1843 case ICmpInst::ICMP_SLE:
1844 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1845 if (!KnownNonNegative)
1846 break;
1847 // fall-through
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001848 case ICmpInst::ICMP_NE:
1849 case ICmpInst::ICMP_ULT:
1850 case ICmpInst::ICMP_ULE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001851 return getTrue(ITy);
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001852 }
1853 }
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001854 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
1855 bool KnownNonNegative, KnownNegative;
1856 switch (Pred) {
1857 default:
1858 break;
1859 case ICmpInst::ICMP_SGT:
1860 case ICmpInst::ICMP_SGE:
1861 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1862 if (!KnownNonNegative)
1863 break;
1864 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00001865 case ICmpInst::ICMP_NE:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001866 case ICmpInst::ICMP_UGT:
1867 case ICmpInst::ICMP_UGE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001868 return getTrue(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001869 case ICmpInst::ICMP_SLT:
1870 case ICmpInst::ICMP_SLE:
1871 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1872 if (!KnownNonNegative)
1873 break;
1874 // fall-through
Nick Lewyckya0e2f382011-03-09 08:20:06 +00001875 case ICmpInst::ICMP_EQ:
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001876 case ICmpInst::ICMP_ULT:
1877 case ICmpInst::ICMP_ULE:
Duncan Sandsf56138d2011-07-26 15:03:53 +00001878 return getFalse(ITy);
Nick Lewycky84dd4fa2011-03-09 06:26:03 +00001879 }
1880 }
Nick Lewycky88cd0aa2011-03-01 08:15:50 +00001881
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00001882 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
1883 LBO->getOperand(1) == RBO->getOperand(1)) {
1884 switch (LBO->getOpcode()) {
1885 default: break;
1886 case Instruction::UDiv:
1887 case Instruction::LShr:
1888 if (ICmpInst::isSigned(Pred))
1889 break;
1890 // fall-through
1891 case Instruction::SDiv:
1892 case Instruction::AShr:
Eli Friedmanb6e7cd62011-05-05 21:59:18 +00001893 if (!LBO->isExact() || !RBO->isExact())
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00001894 break;
1895 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
1896 RBO->getOperand(0), TD, DT, MaxRecurse-1))
1897 return V;
1898 break;
1899 case Instruction::Shl: {
Duncan Sandsc9d904e2011-08-04 10:02:21 +00001900 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
Nick Lewycky58bfcdb2011-03-05 05:19:11 +00001901 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
1902 if (!NUW && !NSW)
1903 break;
1904 if (!NSW && ICmpInst::isSigned(Pred))
1905 break;
1906 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
1907 RBO->getOperand(0), TD, DT, MaxRecurse-1))
1908 return V;
1909 break;
1910 }
1911 }
1912 }
1913
Duncan Sandsad206812011-05-03 19:53:10 +00001914 // Simplify comparisons involving max/min.
1915 Value *A, *B;
1916 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
1917 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
1918
Duncan Sands8140ad32011-05-04 16:05:05 +00001919 // Signed variants on "max(a,b)>=a -> true".
Duncan Sandsad206812011-05-03 19:53:10 +00001920 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
1921 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
1922 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
1923 // We analyze this as smax(A, B) pred A.
1924 P = Pred;
1925 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
1926 (A == LHS || B == LHS)) {
1927 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
1928 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
1929 // We analyze this as smax(A, B) swapped-pred A.
1930 P = CmpInst::getSwappedPredicate(Pred);
1931 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
1932 (A == RHS || B == RHS)) {
1933 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
1934 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
1935 // We analyze this as smax(-A, -B) swapped-pred -A.
1936 // Note that we do not need to actually form -A or -B thanks to EqP.
1937 P = CmpInst::getSwappedPredicate(Pred);
1938 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
1939 (A == LHS || B == LHS)) {
1940 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
1941 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
1942 // We analyze this as smax(-A, -B) pred -A.
1943 // Note that we do not need to actually form -A or -B thanks to EqP.
1944 P = Pred;
1945 }
1946 if (P != CmpInst::BAD_ICMP_PREDICATE) {
1947 // Cases correspond to "max(A, B) p A".
1948 switch (P) {
1949 default:
1950 break;
1951 case CmpInst::ICMP_EQ:
1952 case CmpInst::ICMP_SLE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00001953 // Equivalent to "A EqP B". This may be the same as the condition tested
1954 // in the max/min; if so, we can just return that.
1955 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
1956 return V;
1957 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
1958 return V;
1959 // Otherwise, see if "A EqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00001960 if (MaxRecurse)
1961 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, DT, MaxRecurse-1))
1962 return V;
1963 break;
1964 case CmpInst::ICMP_NE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00001965 case CmpInst::ICMP_SGT: {
1966 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
1967 // Equivalent to "A InvEqP B". This may be the same as the condition
1968 // tested in the max/min; if so, we can just return that.
1969 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
1970 return V;
1971 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
1972 return V;
1973 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00001974 if (MaxRecurse)
Duncan Sandse864b5b2011-05-07 16:56:49 +00001975 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, DT, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00001976 return V;
1977 break;
Duncan Sandse864b5b2011-05-07 16:56:49 +00001978 }
Duncan Sandsad206812011-05-03 19:53:10 +00001979 case CmpInst::ICMP_SGE:
1980 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00001981 return getTrue(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00001982 case CmpInst::ICMP_SLT:
1983 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00001984 return getFalse(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00001985 }
1986 }
1987
Duncan Sands8140ad32011-05-04 16:05:05 +00001988 // Unsigned variants on "max(a,b)>=a -> true".
Duncan Sandsad206812011-05-03 19:53:10 +00001989 P = CmpInst::BAD_ICMP_PREDICATE;
1990 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
1991 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
1992 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
1993 // We analyze this as umax(A, B) pred A.
1994 P = Pred;
1995 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
1996 (A == LHS || B == LHS)) {
1997 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
1998 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
1999 // We analyze this as umax(A, B) swapped-pred A.
2000 P = CmpInst::getSwappedPredicate(Pred);
2001 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2002 (A == RHS || B == RHS)) {
2003 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2004 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2005 // We analyze this as umax(-A, -B) swapped-pred -A.
2006 // Note that we do not need to actually form -A or -B thanks to EqP.
2007 P = CmpInst::getSwappedPredicate(Pred);
2008 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2009 (A == LHS || B == LHS)) {
2010 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2011 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2012 // We analyze this as umax(-A, -B) pred -A.
2013 // Note that we do not need to actually form -A or -B thanks to EqP.
2014 P = Pred;
2015 }
2016 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2017 // Cases correspond to "max(A, B) p A".
2018 switch (P) {
2019 default:
2020 break;
2021 case CmpInst::ICMP_EQ:
2022 case CmpInst::ICMP_ULE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002023 // Equivalent to "A EqP B". This may be the same as the condition tested
2024 // in the max/min; if so, we can just return that.
2025 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2026 return V;
2027 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2028 return V;
2029 // Otherwise, see if "A EqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002030 if (MaxRecurse)
2031 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, DT, MaxRecurse-1))
2032 return V;
2033 break;
2034 case CmpInst::ICMP_NE:
Duncan Sandse864b5b2011-05-07 16:56:49 +00002035 case CmpInst::ICMP_UGT: {
2036 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2037 // Equivalent to "A InvEqP B". This may be the same as the condition
2038 // tested in the max/min; if so, we can just return that.
2039 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2040 return V;
2041 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2042 return V;
2043 // Otherwise, see if "A InvEqP B" simplifies.
Duncan Sandsad206812011-05-03 19:53:10 +00002044 if (MaxRecurse)
Duncan Sandse864b5b2011-05-07 16:56:49 +00002045 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, DT, MaxRecurse-1))
Duncan Sandsad206812011-05-03 19:53:10 +00002046 return V;
2047 break;
Duncan Sandse864b5b2011-05-07 16:56:49 +00002048 }
Duncan Sandsad206812011-05-03 19:53:10 +00002049 case CmpInst::ICMP_UGE:
2050 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002051 return getTrue(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002052 case CmpInst::ICMP_ULT:
2053 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002054 return getFalse(ITy);
Duncan Sandsad206812011-05-03 19:53:10 +00002055 }
2056 }
2057
Duncan Sands8140ad32011-05-04 16:05:05 +00002058 // Variants on "max(x,y) >= min(x,z)".
2059 Value *C, *D;
2060 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2061 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2062 (A == C || A == D || B == C || B == D)) {
2063 // max(x, ?) pred min(x, ?).
2064 if (Pred == CmpInst::ICMP_SGE)
2065 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002066 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002067 if (Pred == CmpInst::ICMP_SLT)
2068 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002069 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002070 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2071 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2072 (A == C || A == D || B == C || B == D)) {
2073 // min(x, ?) pred max(x, ?).
2074 if (Pred == CmpInst::ICMP_SLE)
2075 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002076 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002077 if (Pred == CmpInst::ICMP_SGT)
2078 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002079 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002080 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2081 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2082 (A == C || A == D || B == C || B == D)) {
2083 // max(x, ?) pred min(x, ?).
2084 if (Pred == CmpInst::ICMP_UGE)
2085 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002086 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002087 if (Pred == CmpInst::ICMP_ULT)
2088 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002089 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002090 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2091 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2092 (A == C || A == D || B == C || B == D)) {
2093 // min(x, ?) pred max(x, ?).
2094 if (Pred == CmpInst::ICMP_ULE)
2095 // Always true.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002096 return getTrue(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002097 if (Pred == CmpInst::ICMP_UGT)
2098 // Always false.
Duncan Sandsf56138d2011-07-26 15:03:53 +00002099 return getFalse(ITy);
Duncan Sands8140ad32011-05-04 16:05:05 +00002100 }
2101
Duncan Sands1ac7c992010-11-07 16:12:23 +00002102 // If the comparison is with the result of a select instruction, check whether
2103 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002104 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2105 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002106 return V;
2107
2108 // If the comparison is with the result of a phi instruction, check whether
2109 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00002110 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2111 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00002112 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +00002113
Chris Lattner9f3c25a2009-11-09 22:57:59 +00002114 return 0;
2115}
2116
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002117Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00002118 const TargetData *TD, const DominatorTree *DT) {
2119 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002120}
2121
Chris Lattner9dbb4292009-11-09 23:28:39 +00002122/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2123/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002124static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00002125 const TargetData *TD, const DominatorTree *DT,
2126 unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00002127 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2128 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2129
Chris Lattnerd06094f2009-11-10 00:55:12 +00002130 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00002131 if (Constant *CRHS = dyn_cast<Constant>(RHS))
2132 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Duncan Sands12a86f52010-11-14 11:23:23 +00002133
Chris Lattnerd06094f2009-11-10 00:55:12 +00002134 // If we have a constant, make sure it is on the RHS.
2135 std::swap(LHS, RHS);
2136 Pred = CmpInst::getSwappedPredicate(Pred);
2137 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002138
Chris Lattner210c5d42009-11-09 23:55:12 +00002139 // Fold trivial predicates.
2140 if (Pred == FCmpInst::FCMP_FALSE)
2141 return ConstantInt::get(GetCompareTy(LHS), 0);
2142 if (Pred == FCmpInst::FCMP_TRUE)
2143 return ConstantInt::get(GetCompareTy(LHS), 1);
2144
Chris Lattner210c5d42009-11-09 23:55:12 +00002145 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2146 return UndefValue::get(GetCompareTy(LHS));
2147
2148 // fcmp x,x -> true/false. Not all compares are foldable.
Duncan Sands124708d2011-01-01 20:08:02 +00002149 if (LHS == RHS) {
Chris Lattner210c5d42009-11-09 23:55:12 +00002150 if (CmpInst::isTrueWhenEqual(Pred))
2151 return ConstantInt::get(GetCompareTy(LHS), 1);
2152 if (CmpInst::isFalseWhenEqual(Pred))
2153 return ConstantInt::get(GetCompareTy(LHS), 0);
2154 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002155
Chris Lattner210c5d42009-11-09 23:55:12 +00002156 // Handle fcmp with constant RHS
2157 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2158 // If the constant is a nan, see if we can fold the comparison based on it.
2159 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2160 if (CFP->getValueAPF().isNaN()) {
2161 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2162 return ConstantInt::getFalse(CFP->getContext());
2163 assert(FCmpInst::isUnordered(Pred) &&
2164 "Comparison must be either ordered or unordered!");
2165 // True if unordered.
2166 return ConstantInt::getTrue(CFP->getContext());
2167 }
Dan Gohman6b617a72010-02-22 04:06:03 +00002168 // Check whether the constant is an infinity.
2169 if (CFP->getValueAPF().isInfinity()) {
2170 if (CFP->getValueAPF().isNegative()) {
2171 switch (Pred) {
2172 case FCmpInst::FCMP_OLT:
2173 // No value is ordered and less than negative infinity.
2174 return ConstantInt::getFalse(CFP->getContext());
2175 case FCmpInst::FCMP_UGE:
2176 // All values are unordered with or at least negative infinity.
2177 return ConstantInt::getTrue(CFP->getContext());
2178 default:
2179 break;
2180 }
2181 } else {
2182 switch (Pred) {
2183 case FCmpInst::FCMP_OGT:
2184 // No value is ordered and greater than infinity.
2185 return ConstantInt::getFalse(CFP->getContext());
2186 case FCmpInst::FCMP_ULE:
2187 // All values are unordered with and at most infinity.
2188 return ConstantInt::getTrue(CFP->getContext());
2189 default:
2190 break;
2191 }
2192 }
2193 }
Chris Lattner210c5d42009-11-09 23:55:12 +00002194 }
2195 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002196
Duncan Sands92826de2010-11-07 16:46:25 +00002197 // If the comparison is with the result of a select instruction, check whether
2198 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002199 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2200 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002201 return V;
2202
2203 // If the comparison is with the result of a phi instruction, check whether
2204 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00002205 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2206 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00002207 return V;
Duncan Sands92826de2010-11-07 16:46:25 +00002208
Chris Lattner9dbb4292009-11-09 23:28:39 +00002209 return 0;
2210}
2211
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002212Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00002213 const TargetData *TD, const DominatorTree *DT) {
2214 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002215}
2216
Chris Lattner04754262010-04-20 05:32:14 +00002217/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2218/// the result. If not, this returns null.
Duncan Sands124708d2011-01-01 20:08:02 +00002219Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
2220 const TargetData *TD, const DominatorTree *) {
Chris Lattner04754262010-04-20 05:32:14 +00002221 // select true, X, Y -> X
2222 // select false, X, Y -> Y
2223 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2224 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002225
Chris Lattner04754262010-04-20 05:32:14 +00002226 // select C, X, X -> X
Duncan Sands124708d2011-01-01 20:08:02 +00002227 if (TrueVal == FalseVal)
Chris Lattner04754262010-04-20 05:32:14 +00002228 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002229
Chris Lattner04754262010-04-20 05:32:14 +00002230 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2231 if (isa<Constant>(TrueVal))
2232 return TrueVal;
2233 return FalseVal;
2234 }
Dan Gohman68c0dbc2011-07-01 01:03:43 +00002235 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2236 return FalseVal;
2237 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2238 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00002239
Chris Lattner04754262010-04-20 05:32:14 +00002240 return 0;
2241}
2242
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002243/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2244/// fold the result. If not, this returns null.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002245Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops,
Duncan Sands18450092010-11-16 12:16:38 +00002246 const TargetData *TD, const DominatorTree *) {
Duncan Sands85bbff62010-11-22 13:42:49 +00002247 // The type of the GEP pointer operand.
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002248 PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
Duncan Sands85bbff62010-11-22 13:42:49 +00002249
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002250 // getelementptr P -> P.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002251 if (Ops.size() == 1)
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002252 return Ops[0];
2253
Duncan Sands85bbff62010-11-22 13:42:49 +00002254 if (isa<UndefValue>(Ops[0])) {
2255 // Compute the (pointer) type returned by the GEP instruction.
Jay Foada9203102011-07-25 09:48:08 +00002256 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002257 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
Duncan Sands85bbff62010-11-22 13:42:49 +00002258 return UndefValue::get(GEPTy);
2259 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002260
Jay Foadb9b54eb2011-07-19 15:07:52 +00002261 if (Ops.size() == 2) {
Duncan Sandse60d79f2010-11-21 13:53:09 +00002262 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002263 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2264 if (C->isZero())
2265 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +00002266 // getelementptr P, N -> P if P points to a type of zero size.
2267 if (TD) {
Chris Lattnerdb125cf2011-07-18 04:54:35 +00002268 Type *Ty = PtrTy->getElementType();
Duncan Sandsa63395a2010-11-22 16:32:50 +00002269 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +00002270 return Ops[0];
2271 }
2272 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002273
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002274 // Check to see if this is constant foldable.
Jay Foadb9b54eb2011-07-19 15:07:52 +00002275 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002276 if (!isa<Constant>(Ops[i]))
2277 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +00002278
Jay Foaddab3d292011-07-21 14:31:17 +00002279 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002280}
2281
Duncan Sandsdabc2802011-09-05 06:52:48 +00002282/// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2283/// can fold the result. If not, this returns null.
2284Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2285 ArrayRef<unsigned> Idxs,
2286 const TargetData *,
2287 const DominatorTree *) {
2288 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2289 if (Constant *CVal = dyn_cast<Constant>(Val))
2290 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2291
2292 // insertvalue x, undef, n -> x
2293 if (match(Val, m_Undef()))
2294 return Agg;
2295
2296 // insertvalue x, (extractvalue y, n), n
2297 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
Benjamin Kramerae707bd2011-09-05 18:16:19 +00002298 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2299 EV->getIndices() == Idxs) {
Duncan Sandsdabc2802011-09-05 06:52:48 +00002300 // insertvalue undef, (extractvalue y, n), n -> y
2301 if (match(Agg, m_Undef()))
2302 return EV->getAggregateOperand();
2303
2304 // insertvalue y, (extractvalue y, n), n -> y
2305 if (Agg == EV->getAggregateOperand())
2306 return Agg;
2307 }
2308
2309 return 0;
2310}
2311
Duncan Sandsff103412010-11-17 04:30:22 +00002312/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
2313static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
2314 // If all of the PHI's incoming values are the same then replace the PHI node
2315 // with the common value.
2316 Value *CommonValue = 0;
2317 bool HasUndefInput = false;
2318 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2319 Value *Incoming = PN->getIncomingValue(i);
2320 // If the incoming value is the phi node itself, it can safely be skipped.
2321 if (Incoming == PN) continue;
2322 if (isa<UndefValue>(Incoming)) {
2323 // Remember that we saw an undef value, but otherwise ignore them.
2324 HasUndefInput = true;
2325 continue;
2326 }
2327 if (CommonValue && Incoming != CommonValue)
2328 return 0; // Not the same, bail out.
2329 CommonValue = Incoming;
2330 }
2331
2332 // If CommonValue is null then all of the incoming values were either undef or
2333 // equal to the phi node itself.
2334 if (!CommonValue)
2335 return UndefValue::get(PN->getType());
2336
2337 // If we have a PHI node like phi(X, undef, X), where X is defined by some
2338 // instruction, we cannot return X as the result of the PHI node unless it
2339 // dominates the PHI block.
2340 if (HasUndefInput)
2341 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
2342
2343 return CommonValue;
2344}
2345
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002346
Chris Lattnerd06094f2009-11-10 00:55:12 +00002347//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +00002348
Chris Lattnerd06094f2009-11-10 00:55:12 +00002349/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2350/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002351static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00002352 const TargetData *TD, const DominatorTree *DT,
2353 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00002354 switch (Opcode) {
Chris Lattner81a0dc92011-02-09 17:15:04 +00002355 case Instruction::Add:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002356 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Chris Lattner81a0dc92011-02-09 17:15:04 +00002357 TD, DT, MaxRecurse);
2358 case Instruction::Sub:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002359 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Chris Lattner81a0dc92011-02-09 17:15:04 +00002360 TD, DT, MaxRecurse);
2361 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, TD, DT, MaxRecurse);
Duncan Sands593faa52011-01-28 16:51:11 +00002362 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, TD, DT, MaxRecurse);
2363 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, TD, DT, MaxRecurse);
Frits van Bommel1fca2c32011-01-29 15:26:31 +00002364 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsf24ed772011-05-02 16:27:02 +00002365 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, TD, DT, MaxRecurse);
2366 case Instruction::URem: return SimplifyURemInst(LHS, RHS, TD, DT, MaxRecurse);
2367 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, TD, DT, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002368 case Instruction::Shl:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002369 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
Chris Lattner81a0dc92011-02-09 17:15:04 +00002370 TD, DT, MaxRecurse);
2371 case Instruction::LShr:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002372 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, TD, DT, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002373 case Instruction::AShr:
Duncan Sandsffeb98a2011-02-09 17:45:03 +00002374 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, TD, DT, MaxRecurse);
Duncan Sands82fdab32010-12-21 14:00:22 +00002375 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
Chris Lattner81a0dc92011-02-09 17:15:04 +00002376 case Instruction::Or: return SimplifyOrInst (LHS, RHS, TD, DT, MaxRecurse);
Duncan Sands82fdab32010-12-21 14:00:22 +00002377 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002378 default:
2379 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2380 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2381 Constant *COps[] = {CLHS, CRHS};
Jay Foad1d2f5692011-07-19 13:32:40 +00002382 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, TD);
Chris Lattnerd06094f2009-11-10 00:55:12 +00002383 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002384
Duncan Sands566edb02010-12-21 08:49:00 +00002385 // If the operation is associative, try some generic simplifications.
2386 if (Instruction::isAssociative(Opcode))
2387 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, DT,
2388 MaxRecurse))
2389 return V;
2390
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002391 // If the operation is with the result of a select instruction, check whether
2392 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002393 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands18450092010-11-16 12:16:38 +00002394 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00002395 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002396 return V;
2397
2398 // If the operation is with the result of a phi instruction, check whether
2399 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00002400 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2401 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00002402 return V;
2403
Chris Lattnerd06094f2009-11-10 00:55:12 +00002404 return 0;
2405 }
2406}
Chris Lattner9dbb4292009-11-09 23:28:39 +00002407
Duncan Sands12a86f52010-11-14 11:23:23 +00002408Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00002409 const TargetData *TD, const DominatorTree *DT) {
2410 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +00002411}
2412
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002413/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2414/// fold the result.
2415static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00002416 const TargetData *TD, const DominatorTree *DT,
2417 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002418 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sands18450092010-11-16 12:16:38 +00002419 return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
2420 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002421}
2422
2423Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00002424 const TargetData *TD, const DominatorTree *DT) {
2425 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00002426}
Chris Lattnere3453782009-11-10 01:08:51 +00002427
2428/// SimplifyInstruction - See if we can compute a simplified version of this
2429/// instruction. If not, this returns null.
Duncan Sandseff05812010-11-14 18:36:10 +00002430Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
2431 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +00002432 Value *Result;
2433
Chris Lattnere3453782009-11-10 01:08:51 +00002434 switch (I->getOpcode()) {
2435 default:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002436 Result = ConstantFoldInstruction(I, TD);
2437 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002438 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002439 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2440 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2441 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2442 TD, DT);
2443 break;
Duncan Sandsfea3b212010-12-15 14:07:39 +00002444 case Instruction::Sub:
2445 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2446 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2447 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2448 TD, DT);
2449 break;
Duncan Sands82fdab32010-12-21 14:00:22 +00002450 case Instruction::Mul:
2451 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, DT);
2452 break;
Duncan Sands593faa52011-01-28 16:51:11 +00002453 case Instruction::SDiv:
2454 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2455 break;
2456 case Instruction::UDiv:
2457 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2458 break;
Frits van Bommel1fca2c32011-01-29 15:26:31 +00002459 case Instruction::FDiv:
2460 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2461 break;
Duncan Sandsf24ed772011-05-02 16:27:02 +00002462 case Instruction::SRem:
2463 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2464 break;
2465 case Instruction::URem:
2466 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2467 break;
2468 case Instruction::FRem:
2469 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2470 break;
Duncan Sandsc43cee32011-01-14 00:37:45 +00002471 case Instruction::Shl:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002472 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2473 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2474 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2475 TD, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002476 break;
2477 case Instruction::LShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002478 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2479 cast<BinaryOperator>(I)->isExact(),
2480 TD, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002481 break;
2482 case Instruction::AShr:
Chris Lattner81a0dc92011-02-09 17:15:04 +00002483 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2484 cast<BinaryOperator>(I)->isExact(),
2485 TD, DT);
Duncan Sandsc43cee32011-01-14 00:37:45 +00002486 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002487 case Instruction::And:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002488 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
2489 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002490 case Instruction::Or:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002491 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
2492 break;
Duncan Sands2b749872010-11-17 18:52:15 +00002493 case Instruction::Xor:
2494 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
2495 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002496 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002497 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
2498 I->getOperand(0), I->getOperand(1), TD, DT);
2499 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002500 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002501 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
2502 I->getOperand(0), I->getOperand(1), TD, DT);
2503 break;
Chris Lattner04754262010-04-20 05:32:14 +00002504 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002505 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
2506 I->getOperand(2), TD, DT);
2507 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002508 case Instruction::GetElementPtr: {
2509 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Jay Foadb9b54eb2011-07-19 15:07:52 +00002510 Result = SimplifyGEPInst(Ops, TD, DT);
Duncan Sandsd261dc62010-11-17 08:35:29 +00002511 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00002512 }
Duncan Sandsdabc2802011-09-05 06:52:48 +00002513 case Instruction::InsertValue: {
2514 InsertValueInst *IV = cast<InsertValueInst>(I);
2515 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
2516 IV->getInsertedValueOperand(),
2517 IV->getIndices(), TD, DT);
2518 break;
2519 }
Duncan Sandscd6636c2010-11-14 13:30:18 +00002520 case Instruction::PHI:
Duncan Sandsd261dc62010-11-17 08:35:29 +00002521 Result = SimplifyPHINode(cast<PHINode>(I), DT);
2522 break;
Chris Lattnere3453782009-11-10 01:08:51 +00002523 }
Duncan Sandsd261dc62010-11-17 08:35:29 +00002524
2525 /// If called on unreachable code, the above logic may report that the
2526 /// instruction simplified to itself. Make life easier for users by
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00002527 /// detecting that case here, returning a safe value instead.
2528 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnere3453782009-11-10 01:08:51 +00002529}
2530
Chris Lattner40d8c282009-11-10 22:26:15 +00002531/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
2532/// delete the From instruction. In addition to a basic RAUW, this does a
2533/// recursive simplification of the newly formed instructions. This catches
2534/// things where one simplification exposes other opportunities. This only
2535/// simplifies and deletes scalar operations, it does not change the CFG.
2536///
2537void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
Duncan Sandseff05812010-11-14 18:36:10 +00002538 const TargetData *TD,
2539 const DominatorTree *DT) {
Chris Lattner40d8c282009-11-10 22:26:15 +00002540 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
Duncan Sands12a86f52010-11-14 11:23:23 +00002541
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002542 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
2543 // we can know if it gets deleted out from under us or replaced in a
2544 // recursive simplification.
Chris Lattner40d8c282009-11-10 22:26:15 +00002545 WeakVH FromHandle(From);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002546 WeakVH ToHandle(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00002547
Chris Lattner40d8c282009-11-10 22:26:15 +00002548 while (!From->use_empty()) {
2549 // Update the instruction to use the new value.
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002550 Use &TheUse = From->use_begin().getUse();
2551 Instruction *User = cast<Instruction>(TheUse.getUser());
2552 TheUse = To;
2553
2554 // Check to see if the instruction can be folded due to the operand
2555 // replacement. For example changing (or X, Y) into (or X, -1) can replace
2556 // the 'or' with -1.
2557 Value *SimplifiedVal;
2558 {
2559 // Sanity check to make sure 'User' doesn't dangle across
2560 // SimplifyInstruction.
2561 AssertingVH<> UserHandle(User);
Duncan Sands12a86f52010-11-14 11:23:23 +00002562
Duncan Sandseff05812010-11-14 18:36:10 +00002563 SimplifiedVal = SimplifyInstruction(User, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002564 if (SimplifiedVal == 0) continue;
Chris Lattner40d8c282009-11-10 22:26:15 +00002565 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002566
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002567 // Recursively simplify this user to the new value.
Duncan Sandseff05812010-11-14 18:36:10 +00002568 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002569 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
2570 To = ToHandle;
Duncan Sands12a86f52010-11-14 11:23:23 +00002571
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002572 assert(ToHandle && "To value deleted by recursive simplification?");
Duncan Sands12a86f52010-11-14 11:23:23 +00002573
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002574 // If the recursive simplification ended up revisiting and deleting
2575 // 'From' then we're done.
2576 if (From == 0)
2577 return;
Chris Lattner40d8c282009-11-10 22:26:15 +00002578 }
Duncan Sands12a86f52010-11-14 11:23:23 +00002579
Chris Lattnerd2bfe542010-07-15 06:36:08 +00002580 // If 'From' has value handles referring to it, do a real RAUW to update them.
2581 From->replaceAllUsesWith(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00002582
Chris Lattner40d8c282009-11-10 22:26:15 +00002583 From->eraseFromParent();
2584}