blob: fb51fa5315b219495b9f2ef25d130d074931cacc [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"
21#include "llvm/ADT/Statistic.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000022#include "llvm/Analysis/InstructionSimplify.h"
23#include "llvm/Analysis/ConstantFolding.h"
Duncan Sands18450092010-11-16 12:16:38 +000024#include "llvm/Analysis/Dominators.h"
Chris Lattnerd06094f2009-11-10 00:55:12 +000025#include "llvm/Support/PatternMatch.h"
Duncan Sands18450092010-11-16 12:16:38 +000026#include "llvm/Support/ValueHandle.h"
Duncan Sandse60d79f2010-11-21 13:53:09 +000027#include "llvm/Target/TargetData.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000028using namespace llvm;
Chris Lattnerd06094f2009-11-10 00:55:12 +000029using namespace llvm::PatternMatch;
Chris Lattner9f3c25a2009-11-09 22:57:59 +000030
Duncan Sands18450092010-11-16 12:16:38 +000031#define RecursionLimit 3
Duncan Sandsa74a58c2010-11-10 18:23:01 +000032
Duncan Sandsa3c44a52010-12-22 09:40:51 +000033STATISTIC(NumExpand, "Number of expansions");
34STATISTIC(NumFactor , "Number of factorizations");
35STATISTIC(NumReassoc, "Number of reassociations");
36
Duncan Sands82fdab32010-12-21 14:00:22 +000037static Value *SimplifyAndInst(Value *, Value *, const TargetData *,
38 const DominatorTree *, unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000039static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
Duncan Sands18450092010-11-16 12:16:38 +000040 const DominatorTree *, unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000041static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
Duncan Sands18450092010-11-16 12:16:38 +000042 const DominatorTree *, unsigned);
Duncan Sands82fdab32010-12-21 14:00:22 +000043static Value *SimplifyOrInst(Value *, Value *, const TargetData *,
44 const DominatorTree *, unsigned);
45static Value *SimplifyXorInst(Value *, Value *, const TargetData *,
46 const DominatorTree *, unsigned);
Duncan Sands18450092010-11-16 12:16:38 +000047
48/// ValueDominatesPHI - Does the given value dominate the specified phi node?
49static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
50 Instruction *I = dyn_cast<Instruction>(V);
51 if (!I)
52 // Arguments and constants dominate all instructions.
53 return true;
54
55 // If we have a DominatorTree then do a precise test.
56 if (DT)
57 return DT->dominates(I, P);
58
59 // Otherwise, if the instruction is in the entry block, and is not an invoke,
60 // then it obviously dominates all phi nodes.
61 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
62 !isa<InvokeInst>(I))
63 return true;
64
65 return false;
66}
Duncan Sandsa74a58c2010-11-10 18:23:01 +000067
Duncan Sands3421d902010-12-21 13:32:22 +000068/// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
69/// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
70/// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
71/// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
72/// Returns the simplified value, or null if no simplification was performed.
73static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
74 unsigned OpcodeToExpand, const TargetData *TD,
75 const DominatorTree *DT, unsigned MaxRecurse) {
76 // Recursion is always used, so bail out at once if we already hit the limit.
77 if (!MaxRecurse--)
78 return 0;
79
80 // Check whether the expression has the form "(A op' B) op C".
81 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
82 if (Op0->getOpcode() == OpcodeToExpand) {
83 // It does! Try turning it into "(A op C) op' (B op C)".
84 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
85 // Do "A op C" and "B op C" both simplify?
86 if (Value *L = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse))
87 if (Value *R = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
88 // They do! Return "L op' R" if it simplifies or is already available.
89 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
Duncan Sandsa3c44a52010-12-22 09:40:51 +000090 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
91 && L == B && R == A)) {
92 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +000093 return LHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +000094 }
Duncan Sands3421d902010-12-21 13:32:22 +000095 // Otherwise return "L op' R" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +000096 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
97 MaxRecurse)) {
98 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +000099 return V;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000100 }
Duncan Sands3421d902010-12-21 13:32:22 +0000101 }
102 }
103
104 // Check whether the expression has the form "A op (B op' C)".
105 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
106 if (Op1->getOpcode() == OpcodeToExpand) {
107 // It does! Try turning it into "(A op B) op' (A op C)".
108 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
109 // Do "A op B" and "A op C" both simplify?
110 if (Value *L = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse))
111 if (Value *R = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse)) {
112 // They do! Return "L op' R" if it simplifies or is already available.
113 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000114 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
115 && L == C && R == B)) {
116 ++NumExpand;
Duncan Sands3421d902010-12-21 13:32:22 +0000117 return RHS;
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 return 0;
129}
130
131/// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
132/// using the operation OpCodeToExtract. For example, when Opcode is Add and
133/// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
134/// Returns the simplified value, or null if no simplification was performed.
135static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
136 unsigned OpcodeToExtract, const TargetData *TD,
137 const DominatorTree *DT, unsigned MaxRecurse) {
138 // Recursion is always used, so bail out at once if we already hit the limit.
139 if (!MaxRecurse--)
140 return 0;
141
142 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
143 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
144
145 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
146 !Op1 || Op1->getOpcode() != OpcodeToExtract)
147 return 0;
148
149 // The expression has the form "(A op' B) op (C op' D)".
Duncan Sands82fdab32010-12-21 14:00:22 +0000150 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
151 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
Duncan Sands3421d902010-12-21 13:32:22 +0000152
153 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
154 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
155 // commutative case, "(A op' B) op (C op' A)"?
156 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
157 Value *DD = A == C ? D : C;
158 // Form "A op' (B op DD)" if it simplifies completely.
159 // Does "B op DD" simplify?
160 if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, DT, MaxRecurse)) {
161 // It does! Return "A op' V" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000162 // If V equals B then "A op' V" is just the LHS. If V equals DD then
163 // "A op' V" is just the RHS.
164 if (V == B || V == DD) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000165 ++NumFactor;
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000166 return V == B ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000167 }
Duncan Sands3421d902010-12-21 13:32:22 +0000168 // Otherwise return "A op' V" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000169 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, DT, MaxRecurse)) {
170 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000171 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000172 }
Duncan Sands3421d902010-12-21 13:32:22 +0000173 }
174 }
175
176 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
177 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
178 // commutative case, "(A op' B) op (B op' D)"?
179 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
180 Value *CC = B == D ? C : D;
181 // Form "(A op CC) op' B" if it simplifies completely..
182 // Does "A op CC" simplify?
183 if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, DT, MaxRecurse)) {
184 // It does! Return "V op' B" if it simplifies or is already available.
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000185 // If V equals A then "V op' B" is just the LHS. If V equals CC then
186 // "V op' B" is just the RHS.
187 if (V == A || V == CC) {
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000188 ++NumFactor;
Duncan Sands1cd05bb2010-12-22 17:15:25 +0000189 return V == A ? LHS : RHS;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000190 }
Duncan Sands3421d902010-12-21 13:32:22 +0000191 // Otherwise return "V op' B" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000192 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, DT, MaxRecurse)) {
193 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000194 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000195 }
Duncan Sands3421d902010-12-21 13:32:22 +0000196 }
197 }
198
199 return 0;
200}
201
202/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
203/// operations. Returns the simpler value, or null if none was found.
Duncan Sands566edb02010-12-21 08:49:00 +0000204static Value *SimplifyAssociativeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
205 const TargetData *TD,
206 const DominatorTree *DT,
207 unsigned MaxRecurse) {
208 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
209
210 // Recursion is always used, so bail out at once if we already hit the limit.
211 if (!MaxRecurse--)
212 return 0;
213
214 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
215 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
216
217 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
218 if (Op0 && Op0->getOpcode() == Opcode) {
219 Value *A = Op0->getOperand(0);
220 Value *B = Op0->getOperand(1);
221 Value *C = RHS;
222
223 // Does "B op C" simplify?
224 if (Value *V = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
225 // It does! Return "A op V" if it simplifies or is already available.
226 // If V equals B then "A op V" is just the LHS.
Duncan Sands3421d902010-12-21 13:32:22 +0000227 if (V == B) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000228 // Otherwise return "A op V" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000229 if (Value *W = SimplifyBinOp(Opcode, A, V, TD, DT, MaxRecurse)) {
230 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000231 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000232 }
Duncan Sands566edb02010-12-21 08:49:00 +0000233 }
234 }
235
236 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
237 if (Op1 && Op1->getOpcode() == Opcode) {
238 Value *A = LHS;
239 Value *B = Op1->getOperand(0);
240 Value *C = Op1->getOperand(1);
241
242 // Does "A op B" simplify?
243 if (Value *V = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse)) {
244 // It does! Return "V op C" if it simplifies or is already available.
245 // If V equals B then "V op C" is just the RHS.
Duncan Sands3421d902010-12-21 13:32:22 +0000246 if (V == B) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000247 // Otherwise return "V op C" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000248 if (Value *W = SimplifyBinOp(Opcode, V, C, TD, DT, MaxRecurse)) {
249 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000250 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000251 }
Duncan Sands566edb02010-12-21 08:49:00 +0000252 }
253 }
254
255 // The remaining transforms require commutativity as well as associativity.
256 if (!Instruction::isCommutative(Opcode))
257 return 0;
258
259 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
260 if (Op0 && Op0->getOpcode() == Opcode) {
261 Value *A = Op0->getOperand(0);
262 Value *B = Op0->getOperand(1);
263 Value *C = RHS;
264
265 // Does "C op A" simplify?
266 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
267 // It does! Return "V op B" if it simplifies or is already available.
268 // If V equals A then "V op B" is just the LHS.
Duncan Sands3421d902010-12-21 13:32:22 +0000269 if (V == A) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000270 // Otherwise return "V op B" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000271 if (Value *W = SimplifyBinOp(Opcode, V, B, TD, DT, MaxRecurse)) {
272 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000273 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000274 }
Duncan Sands566edb02010-12-21 08:49:00 +0000275 }
276 }
277
278 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
279 if (Op1 && Op1->getOpcode() == Opcode) {
280 Value *A = LHS;
281 Value *B = Op1->getOperand(0);
282 Value *C = Op1->getOperand(1);
283
284 // Does "C op A" simplify?
285 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
286 // It does! Return "B op V" if it simplifies or is already available.
287 // If V equals C then "B op V" is just the RHS.
Duncan Sands3421d902010-12-21 13:32:22 +0000288 if (V == C) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000289 // Otherwise return "B op V" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000290 if (Value *W = SimplifyBinOp(Opcode, B, V, TD, DT, MaxRecurse)) {
291 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000292 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000293 }
Duncan Sands566edb02010-12-21 08:49:00 +0000294 }
295 }
296
297 return 0;
298}
299
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000300/// ThreadBinOpOverSelect - In the case of a binary operation with a select
301/// instruction as an operand, try to simplify the binop by seeing whether
302/// evaluating it on both branches of the select results in the same value.
303/// Returns the common value if so, otherwise returns null.
304static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000305 const TargetData *TD,
306 const DominatorTree *DT,
307 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000308 // Recursion is always used, so bail out at once if we already hit the limit.
309 if (!MaxRecurse--)
310 return 0;
311
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000312 SelectInst *SI;
313 if (isa<SelectInst>(LHS)) {
314 SI = cast<SelectInst>(LHS);
315 } else {
316 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
317 SI = cast<SelectInst>(RHS);
318 }
319
320 // Evaluate the BinOp on the true and false branches of the select.
321 Value *TV;
322 Value *FV;
323 if (SI == LHS) {
Duncan Sands18450092010-11-16 12:16:38 +0000324 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
325 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000326 } else {
Duncan Sands18450092010-11-16 12:16:38 +0000327 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
328 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000329 }
330
331 // If they simplified to the same value, then return the common value.
332 // If they both failed to simplify then return null.
333 if (TV == FV)
334 return TV;
335
336 // If one branch simplified to undef, return the other one.
337 if (TV && isa<UndefValue>(TV))
338 return FV;
339 if (FV && isa<UndefValue>(FV))
340 return TV;
341
342 // If applying the operation did not change the true and false select values,
343 // then the result of the binop is the select itself.
344 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
345 return SI;
346
347 // If one branch simplified and the other did not, and the simplified
348 // value is equal to the unsimplified one, return the simplified value.
349 // For example, select (cond, X, X & Z) & Z -> X & Z.
350 if ((FV && !TV) || (TV && !FV)) {
351 // Check that the simplified value has the form "X op Y" where "op" is the
352 // same as the original operation.
353 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
354 if (Simplified && Simplified->getOpcode() == Opcode) {
355 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
356 // We already know that "op" is the same as for the simplified value. See
357 // if the operands match too. If so, return the simplified value.
358 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
359 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
360 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
361 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
362 Simplified->getOperand(1) == UnsimplifiedRHS)
363 return Simplified;
364 if (Simplified->isCommutative() &&
365 Simplified->getOperand(1) == UnsimplifiedLHS &&
366 Simplified->getOperand(0) == UnsimplifiedRHS)
367 return Simplified;
368 }
369 }
370
371 return 0;
372}
373
374/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
375/// try to simplify the comparison by seeing whether both branches of the select
376/// result in the same value. Returns the common value if so, otherwise returns
377/// null.
378static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000379 Value *RHS, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000380 const DominatorTree *DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000381 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000382 // Recursion is always used, so bail out at once if we already hit the limit.
383 if (!MaxRecurse--)
384 return 0;
385
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000386 // Make sure the select is on the LHS.
387 if (!isa<SelectInst>(LHS)) {
388 std::swap(LHS, RHS);
389 Pred = CmpInst::getSwappedPredicate(Pred);
390 }
391 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
392 SelectInst *SI = cast<SelectInst>(LHS);
393
394 // Now that we have "cmp select(cond, TV, FV), RHS", analyse it.
395 // Does "cmp TV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000396 if (Value *TCmp = SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000397 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000398 // It does! Does "cmp FV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000399 if (Value *FCmp = SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000400 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000401 // It does! If they simplified to the same value, then use it as the
402 // result of the original comparison.
403 if (TCmp == FCmp)
404 return TCmp;
405 return 0;
406}
407
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000408/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
409/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
410/// it on the incoming phi values yields the same result for every value. If so
411/// returns the common value, otherwise returns null.
412static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000413 const TargetData *TD, const DominatorTree *DT,
414 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000415 // Recursion is always used, so bail out at once if we already hit the limit.
416 if (!MaxRecurse--)
417 return 0;
418
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000419 PHINode *PI;
420 if (isa<PHINode>(LHS)) {
421 PI = cast<PHINode>(LHS);
Duncan Sands18450092010-11-16 12:16:38 +0000422 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
423 if (!ValueDominatesPHI(RHS, PI, DT))
424 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000425 } else {
426 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
427 PI = cast<PHINode>(RHS);
Duncan Sands18450092010-11-16 12:16:38 +0000428 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
429 if (!ValueDominatesPHI(LHS, PI, DT))
430 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000431 }
432
433 // Evaluate the BinOp on the incoming phi values.
434 Value *CommonValue = 0;
435 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000436 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000437 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000438 if (Incoming == PI) continue;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000439 Value *V = PI == LHS ?
Duncan Sands18450092010-11-16 12:16:38 +0000440 SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
441 SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000442 // If the operation failed to simplify, or simplified to a different value
443 // to previously, then give up.
444 if (!V || (CommonValue && V != CommonValue))
445 return 0;
446 CommonValue = V;
447 }
448
449 return CommonValue;
450}
451
452/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
453/// try to simplify the comparison by seeing whether comparing with all of the
454/// incoming phi values yields the same result every time. If so returns the
455/// common result, otherwise returns null.
456static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000457 const TargetData *TD, const DominatorTree *DT,
458 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000459 // Recursion is always used, so bail out at once if we already hit the limit.
460 if (!MaxRecurse--)
461 return 0;
462
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000463 // Make sure the phi is on the LHS.
464 if (!isa<PHINode>(LHS)) {
465 std::swap(LHS, RHS);
466 Pred = CmpInst::getSwappedPredicate(Pred);
467 }
468 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
469 PHINode *PI = cast<PHINode>(LHS);
470
Duncan Sands18450092010-11-16 12:16:38 +0000471 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
472 if (!ValueDominatesPHI(RHS, PI, DT))
473 return 0;
474
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000475 // Evaluate the BinOp on the incoming phi values.
476 Value *CommonValue = 0;
477 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000478 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000479 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000480 if (Incoming == PI) continue;
Duncan Sands18450092010-11-16 12:16:38 +0000481 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000482 // If the operation failed to simplify, or simplified to a different value
483 // to previously, then give up.
484 if (!V || (CommonValue && V != CommonValue))
485 return 0;
486 CommonValue = V;
487 }
488
489 return CommonValue;
490}
491
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000492/// SimplifyAddInst - Given operands for an Add, see if we can
493/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000494static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
495 const TargetData *TD, const DominatorTree *DT,
496 unsigned MaxRecurse) {
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000497 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
498 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
499 Constant *Ops[] = { CLHS, CRHS };
500 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
501 Ops, 2, TD);
502 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000503
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000504 // Canonicalize the constant to the RHS.
505 std::swap(Op0, Op1);
506 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000507
Duncan Sandsfea3b212010-12-15 14:07:39 +0000508 // X + undef -> undef
509 if (isa<UndefValue>(Op1))
510 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000511
Duncan Sandsfea3b212010-12-15 14:07:39 +0000512 // X + 0 -> X
513 if (match(Op1, m_Zero()))
514 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000515
Duncan Sandsfea3b212010-12-15 14:07:39 +0000516 // X + (Y - X) -> Y
517 // (Y - X) + X -> Y
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000518 // Eg: X + -X -> 0
Duncan Sandsfea3b212010-12-15 14:07:39 +0000519 Value *Y = 0;
520 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
521 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
522 return Y;
523
524 // X + ~X -> -1 since ~X = -X-1
525 if (match(Op0, m_Not(m_Specific(Op1))) ||
526 match(Op1, m_Not(m_Specific(Op0))))
527 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands87689cf2010-11-19 09:20:39 +0000528
Duncan Sands82fdab32010-12-21 14:00:22 +0000529 /// i1 add -> xor.
Duncan Sands75d289e2010-12-21 14:48:48 +0000530 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000531 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
532 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000533
Duncan Sands566edb02010-12-21 08:49:00 +0000534 // Try some generic simplifications for associative operations.
535 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, DT,
536 MaxRecurse))
537 return V;
538
Duncan Sands3421d902010-12-21 13:32:22 +0000539 // Mul distributes over Add. Try some generic simplifications based on this.
540 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
541 TD, DT, MaxRecurse))
542 return V;
543
Duncan Sands87689cf2010-11-19 09:20:39 +0000544 // Threading Add over selects and phi nodes is pointless, so don't bother.
545 // Threading over the select in "A + select(cond, B, C)" means evaluating
546 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
547 // only if B and C are equal. If B and C are equal then (since we assume
548 // that operands have already been simplified) "select(cond, B, C)" should
549 // have been simplified to the common value of B and C already. Analysing
550 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
551 // for threading over phi nodes.
552
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000553 return 0;
554}
555
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000556Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
557 const TargetData *TD, const DominatorTree *DT) {
558 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
559}
560
Duncan Sandsfea3b212010-12-15 14:07:39 +0000561/// SimplifySubInst - Given operands for a Sub, see if we can
562/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000563static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands3421d902010-12-21 13:32:22 +0000564 const TargetData *TD, const DominatorTree *DT,
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000565 unsigned MaxRecurse) {
Duncan Sandsfea3b212010-12-15 14:07:39 +0000566 if (Constant *CLHS = dyn_cast<Constant>(Op0))
567 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
568 Constant *Ops[] = { CLHS, CRHS };
569 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
570 Ops, 2, TD);
571 }
572
573 // X - undef -> undef
574 // undef - X -> undef
575 if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
576 return UndefValue::get(Op0->getType());
577
578 // X - 0 -> X
579 if (match(Op1, m_Zero()))
580 return Op0;
581
582 // X - X -> 0
583 if (Op0 == Op1)
584 return Constant::getNullValue(Op0->getType());
585
586 // (X + Y) - Y -> X
587 // (Y + X) - Y -> X
588 Value *X = 0;
589 if (match(Op0, m_Add(m_Value(X), m_Specific(Op1))) ||
590 match(Op0, m_Add(m_Specific(Op1), m_Value(X))))
591 return X;
592
Duncan Sands82fdab32010-12-21 14:00:22 +0000593 /// i1 sub -> xor.
Duncan Sands75d289e2010-12-21 14:48:48 +0000594 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000595 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
596 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000597
Duncan Sands3421d902010-12-21 13:32:22 +0000598 // Mul distributes over Sub. Try some generic simplifications based on this.
599 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
600 TD, DT, MaxRecurse))
601 return V;
602
Duncan Sandsfea3b212010-12-15 14:07:39 +0000603 // Threading Sub over selects and phi nodes is pointless, so don't bother.
604 // Threading over the select in "A - select(cond, B, C)" means evaluating
605 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
606 // only if B and C are equal. If B and C are equal then (since we assume
607 // that operands have already been simplified) "select(cond, B, C)" should
608 // have been simplified to the common value of B and C already. Analysing
609 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
610 // for threading over phi nodes.
611
612 return 0;
613}
614
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000615Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
616 const TargetData *TD, const DominatorTree *DT) {
617 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
618}
619
Duncan Sands82fdab32010-12-21 14:00:22 +0000620/// SimplifyMulInst - Given operands for a Mul, see if we can
621/// fold the result. If not, this returns null.
622static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
623 const DominatorTree *DT, unsigned MaxRecurse) {
624 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
625 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
626 Constant *Ops[] = { CLHS, CRHS };
627 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
628 Ops, 2, TD);
629 }
630
631 // Canonicalize the constant to the RHS.
632 std::swap(Op0, Op1);
633 }
634
635 // X * undef -> 0
636 if (isa<UndefValue>(Op1))
637 return Constant::getNullValue(Op0->getType());
638
639 // X * 0 -> 0
640 if (match(Op1, m_Zero()))
641 return Op1;
642
643 // X * 1 -> X
644 if (match(Op1, m_One()))
645 return Op0;
646
647 /// i1 mul -> and.
Duncan Sands75d289e2010-12-21 14:48:48 +0000648 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000649 if (Value *V = SimplifyAndInst(Op0, Op1, TD, DT, MaxRecurse-1))
650 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000651
652 // Try some generic simplifications for associative operations.
653 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, DT,
654 MaxRecurse))
655 return V;
656
657 // Mul distributes over Add. Try some generic simplifications based on this.
658 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
659 TD, DT, MaxRecurse))
660 return V;
661
662 // If the operation is with the result of a select instruction, check whether
663 // operating on either branch of the select always yields the same value.
664 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
665 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, DT,
666 MaxRecurse))
667 return V;
668
669 // If the operation is with the result of a phi instruction, check whether
670 // operating on all incoming values of the phi always yields the same value.
671 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
672 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, DT,
673 MaxRecurse))
674 return V;
675
676 return 0;
677}
678
679Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
680 const DominatorTree *DT) {
681 return ::SimplifyMulInst(Op0, Op1, TD, DT, RecursionLimit);
682}
683
Chris Lattnerd06094f2009-11-10 00:55:12 +0000684/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000685/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000686static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000687 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000688 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
689 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
690 Constant *Ops[] = { CLHS, CRHS };
691 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
692 Ops, 2, TD);
693 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000694
Chris Lattnerd06094f2009-11-10 00:55:12 +0000695 // Canonicalize the constant to the RHS.
696 std::swap(Op0, Op1);
697 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000698
Chris Lattnerd06094f2009-11-10 00:55:12 +0000699 // X & undef -> 0
700 if (isa<UndefValue>(Op1))
701 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000702
Chris Lattnerd06094f2009-11-10 00:55:12 +0000703 // X & X = X
704 if (Op0 == Op1)
705 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000706
Duncan Sands2b749872010-11-17 18:52:15 +0000707 // X & 0 = 0
708 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000709 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000710
Duncan Sands2b749872010-11-17 18:52:15 +0000711 // X & -1 = X
712 if (match(Op1, m_AllOnes()))
713 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000714
Chris Lattnerd06094f2009-11-10 00:55:12 +0000715 // A & ~A = ~A & A = 0
Chandler Carruthe89ada92010-11-29 01:41:13 +0000716 Value *A = 0, *B = 0;
Chris Lattner70ce6d02009-11-10 02:04:54 +0000717 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
718 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000719 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000720
Chris Lattnerd06094f2009-11-10 00:55:12 +0000721 // (A | ?) & A = A
722 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
723 (A == Op1 || B == Op1))
724 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000725
Chris Lattnerd06094f2009-11-10 00:55:12 +0000726 // A & (A | ?) = A
727 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
728 (A == Op0 || B == Op0))
729 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000730
Duncan Sands566edb02010-12-21 08:49:00 +0000731 // Try some generic simplifications for associative operations.
732 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, DT,
733 MaxRecurse))
734 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +0000735
Duncan Sands3421d902010-12-21 13:32:22 +0000736 // And distributes over Or. Try some generic simplifications based on this.
737 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
738 TD, DT, MaxRecurse))
739 return V;
740
741 // And distributes over Xor. Try some generic simplifications based on this.
742 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
743 TD, DT, MaxRecurse))
744 return V;
745
746 // Or distributes over And. Try some generic simplifications based on this.
747 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
748 TD, DT, MaxRecurse))
749 return V;
750
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000751 // If the operation is with the result of a select instruction, check whether
752 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000753 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +0000754 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +0000755 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000756 return V;
757
758 // If the operation is with the result of a phi instruction, check whether
759 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000760 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +0000761 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +0000762 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000763 return V;
764
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000765 return 0;
766}
767
Duncan Sands18450092010-11-16 12:16:38 +0000768Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
769 const DominatorTree *DT) {
770 return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000771}
772
Chris Lattnerd06094f2009-11-10 00:55:12 +0000773/// SimplifyOrInst - Given operands for an Or, see if we can
774/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000775static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000776 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000777 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
778 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
779 Constant *Ops[] = { CLHS, CRHS };
780 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
781 Ops, 2, TD);
782 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000783
Chris Lattnerd06094f2009-11-10 00:55:12 +0000784 // Canonicalize the constant to the RHS.
785 std::swap(Op0, Op1);
786 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000787
Chris Lattnerd06094f2009-11-10 00:55:12 +0000788 // X | undef -> -1
789 if (isa<UndefValue>(Op1))
790 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000791
Chris Lattnerd06094f2009-11-10 00:55:12 +0000792 // X | X = X
793 if (Op0 == Op1)
794 return Op0;
795
Duncan Sands2b749872010-11-17 18:52:15 +0000796 // X | 0 = X
797 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000798 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000799
Duncan Sands2b749872010-11-17 18:52:15 +0000800 // X | -1 = -1
801 if (match(Op1, m_AllOnes()))
802 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000803
Chris Lattnerd06094f2009-11-10 00:55:12 +0000804 // A | ~A = ~A | A = -1
Chandler Carruthe89ada92010-11-29 01:41:13 +0000805 Value *A = 0, *B = 0;
Chris Lattner70ce6d02009-11-10 02:04:54 +0000806 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
807 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000808 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000809
Chris Lattnerd06094f2009-11-10 00:55:12 +0000810 // (A & ?) | A = A
811 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
812 (A == Op1 || B == Op1))
813 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000814
Chris Lattnerd06094f2009-11-10 00:55:12 +0000815 // A | (A & ?) = A
816 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
817 (A == Op0 || B == Op0))
818 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000819
Duncan Sands566edb02010-12-21 08:49:00 +0000820 // Try some generic simplifications for associative operations.
821 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, DT,
822 MaxRecurse))
823 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +0000824
Duncan Sands3421d902010-12-21 13:32:22 +0000825 // Or distributes over And. Try some generic simplifications based on this.
826 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And,
827 TD, DT, MaxRecurse))
828 return V;
829
830 // And distributes over Or. Try some generic simplifications based on this.
831 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
832 TD, DT, MaxRecurse))
833 return V;
834
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000835 // If the operation is with the result of a select instruction, check whether
836 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000837 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +0000838 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +0000839 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000840 return V;
841
842 // If the operation is with the result of a phi instruction, check whether
843 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000844 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +0000845 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +0000846 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000847 return V;
848
Chris Lattnerd06094f2009-11-10 00:55:12 +0000849 return 0;
850}
851
Duncan Sands18450092010-11-16 12:16:38 +0000852Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
853 const DominatorTree *DT) {
854 return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000855}
Chris Lattnerd06094f2009-11-10 00:55:12 +0000856
Duncan Sands2b749872010-11-17 18:52:15 +0000857/// SimplifyXorInst - Given operands for a Xor, see if we can
858/// fold the result. If not, this returns null.
859static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
860 const DominatorTree *DT, unsigned MaxRecurse) {
861 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
862 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
863 Constant *Ops[] = { CLHS, CRHS };
864 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
865 Ops, 2, TD);
866 }
867
868 // Canonicalize the constant to the RHS.
869 std::swap(Op0, Op1);
870 }
871
872 // A ^ undef -> undef
873 if (isa<UndefValue>(Op1))
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +0000874 return Op1;
Duncan Sands2b749872010-11-17 18:52:15 +0000875
876 // A ^ 0 = A
877 if (match(Op1, m_Zero()))
878 return Op0;
879
880 // A ^ A = 0
881 if (Op0 == Op1)
882 return Constant::getNullValue(Op0->getType());
883
884 // A ^ ~A = ~A ^ A = -1
Duncan Sands566edb02010-12-21 08:49:00 +0000885 Value *A = 0;
Duncan Sands2b749872010-11-17 18:52:15 +0000886 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
887 (match(Op1, m_Not(m_Value(A))) && A == Op0))
888 return Constant::getAllOnesValue(Op0->getType());
889
Duncan Sands566edb02010-12-21 08:49:00 +0000890 // Try some generic simplifications for associative operations.
891 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, DT,
892 MaxRecurse))
893 return V;
Duncan Sands2b749872010-11-17 18:52:15 +0000894
Duncan Sands3421d902010-12-21 13:32:22 +0000895 // And distributes over Xor. Try some generic simplifications based on this.
896 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
897 TD, DT, MaxRecurse))
898 return V;
899
Duncan Sands87689cf2010-11-19 09:20:39 +0000900 // Threading Xor over selects and phi nodes is pointless, so don't bother.
901 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
902 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
903 // only if B and C are equal. If B and C are equal then (since we assume
904 // that operands have already been simplified) "select(cond, B, C)" should
905 // have been simplified to the common value of B and C already. Analysing
906 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
907 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +0000908
909 return 0;
910}
911
912Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
913 const DominatorTree *DT) {
914 return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
915}
916
Chris Lattner210c5d42009-11-09 23:55:12 +0000917static const Type *GetCompareTy(Value *Op) {
918 return CmpInst::makeCmpResultType(Op->getType());
919}
920
Chris Lattner9dbb4292009-11-09 23:28:39 +0000921/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
922/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000923static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000924 const TargetData *TD, const DominatorTree *DT,
925 unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000926 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +0000927 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +0000928
Chris Lattnerd06094f2009-11-10 00:55:12 +0000929 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +0000930 if (Constant *CRHS = dyn_cast<Constant>(RHS))
931 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Chris Lattnerd06094f2009-11-10 00:55:12 +0000932
933 // If we have a constant, make sure it is on the RHS.
934 std::swap(LHS, RHS);
935 Pred = CmpInst::getSwappedPredicate(Pred);
936 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000937
Chris Lattner210c5d42009-11-09 23:55:12 +0000938 // ITy - This is the return type of the compare we're considering.
939 const Type *ITy = GetCompareTy(LHS);
Duncan Sands12a86f52010-11-14 11:23:23 +0000940
Chris Lattner210c5d42009-11-09 23:55:12 +0000941 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +0000942 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
943 // because X could be 0.
944 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +0000945 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +0000946
Chris Lattner210c5d42009-11-09 23:55:12 +0000947 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
948 // addresses never equal each other! We already know that Op0 != Op1.
Duncan Sands12a86f52010-11-14 11:23:23 +0000949 if ((isa<GlobalValue>(LHS) || isa<AllocaInst>(LHS) ||
Chris Lattner210c5d42009-11-09 23:55:12 +0000950 isa<ConstantPointerNull>(LHS)) &&
Duncan Sands12a86f52010-11-14 11:23:23 +0000951 (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
Chris Lattner210c5d42009-11-09 23:55:12 +0000952 isa<ConstantPointerNull>(RHS)))
953 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +0000954
Chris Lattner210c5d42009-11-09 23:55:12 +0000955 // See if we are doing a comparison with a constant.
956 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
957 // If we have an icmp le or icmp ge instruction, turn it into the
958 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
959 // them being folded in the code below.
960 switch (Pred) {
961 default: break;
962 case ICmpInst::ICMP_ULE:
963 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
964 return ConstantInt::getTrue(CI->getContext());
965 break;
966 case ICmpInst::ICMP_SLE:
967 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
968 return ConstantInt::getTrue(CI->getContext());
969 break;
970 case ICmpInst::ICMP_UGE:
971 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
972 return ConstantInt::getTrue(CI->getContext());
973 break;
974 case ICmpInst::ICMP_SGE:
975 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
976 return ConstantInt::getTrue(CI->getContext());
977 break;
978 }
Chris Lattner210c5d42009-11-09 23:55:12 +0000979 }
Duncan Sands1ac7c992010-11-07 16:12:23 +0000980
981 // If the comparison is with the result of a select instruction, check whether
982 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000983 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
984 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000985 return V;
986
987 // If the comparison is with the result of a phi instruction, check whether
988 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +0000989 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
990 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +0000991 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +0000992
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000993 return 0;
994}
995
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000996Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000997 const TargetData *TD, const DominatorTree *DT) {
998 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000999}
1000
Chris Lattner9dbb4292009-11-09 23:28:39 +00001001/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
1002/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001003static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001004 const TargetData *TD, const DominatorTree *DT,
1005 unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00001006 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1007 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
1008
Chris Lattnerd06094f2009-11-10 00:55:12 +00001009 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00001010 if (Constant *CRHS = dyn_cast<Constant>(RHS))
1011 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Duncan Sands12a86f52010-11-14 11:23:23 +00001012
Chris Lattnerd06094f2009-11-10 00:55:12 +00001013 // If we have a constant, make sure it is on the RHS.
1014 std::swap(LHS, RHS);
1015 Pred = CmpInst::getSwappedPredicate(Pred);
1016 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001017
Chris Lattner210c5d42009-11-09 23:55:12 +00001018 // Fold trivial predicates.
1019 if (Pred == FCmpInst::FCMP_FALSE)
1020 return ConstantInt::get(GetCompareTy(LHS), 0);
1021 if (Pred == FCmpInst::FCMP_TRUE)
1022 return ConstantInt::get(GetCompareTy(LHS), 1);
1023
Chris Lattner210c5d42009-11-09 23:55:12 +00001024 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
1025 return UndefValue::get(GetCompareTy(LHS));
1026
1027 // fcmp x,x -> true/false. Not all compares are foldable.
1028 if (LHS == RHS) {
1029 if (CmpInst::isTrueWhenEqual(Pred))
1030 return ConstantInt::get(GetCompareTy(LHS), 1);
1031 if (CmpInst::isFalseWhenEqual(Pred))
1032 return ConstantInt::get(GetCompareTy(LHS), 0);
1033 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001034
Chris Lattner210c5d42009-11-09 23:55:12 +00001035 // Handle fcmp with constant RHS
1036 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1037 // If the constant is a nan, see if we can fold the comparison based on it.
1038 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1039 if (CFP->getValueAPF().isNaN()) {
1040 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
1041 return ConstantInt::getFalse(CFP->getContext());
1042 assert(FCmpInst::isUnordered(Pred) &&
1043 "Comparison must be either ordered or unordered!");
1044 // True if unordered.
1045 return ConstantInt::getTrue(CFP->getContext());
1046 }
Dan Gohman6b617a72010-02-22 04:06:03 +00001047 // Check whether the constant is an infinity.
1048 if (CFP->getValueAPF().isInfinity()) {
1049 if (CFP->getValueAPF().isNegative()) {
1050 switch (Pred) {
1051 case FCmpInst::FCMP_OLT:
1052 // No value is ordered and less than negative infinity.
1053 return ConstantInt::getFalse(CFP->getContext());
1054 case FCmpInst::FCMP_UGE:
1055 // All values are unordered with or at least negative infinity.
1056 return ConstantInt::getTrue(CFP->getContext());
1057 default:
1058 break;
1059 }
1060 } else {
1061 switch (Pred) {
1062 case FCmpInst::FCMP_OGT:
1063 // No value is ordered and greater than infinity.
1064 return ConstantInt::getFalse(CFP->getContext());
1065 case FCmpInst::FCMP_ULE:
1066 // All values are unordered with and at most infinity.
1067 return ConstantInt::getTrue(CFP->getContext());
1068 default:
1069 break;
1070 }
1071 }
1072 }
Chris Lattner210c5d42009-11-09 23:55:12 +00001073 }
1074 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001075
Duncan Sands92826de2010-11-07 16:46:25 +00001076 // If the comparison is with the result of a select instruction, check whether
1077 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001078 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
1079 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001080 return V;
1081
1082 // If the comparison is with the result of a phi instruction, check whether
1083 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00001084 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1085 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00001086 return V;
Duncan Sands92826de2010-11-07 16:46:25 +00001087
Chris Lattner9dbb4292009-11-09 23:28:39 +00001088 return 0;
1089}
1090
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001091Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001092 const TargetData *TD, const DominatorTree *DT) {
1093 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001094}
1095
Chris Lattner04754262010-04-20 05:32:14 +00001096/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
1097/// the result. If not, this returns null.
1098Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
Duncan Sands18450092010-11-16 12:16:38 +00001099 const TargetData *TD, const DominatorTree *) {
Chris Lattner04754262010-04-20 05:32:14 +00001100 // select true, X, Y -> X
1101 // select false, X, Y -> Y
1102 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
1103 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00001104
Chris Lattner04754262010-04-20 05:32:14 +00001105 // select C, X, X -> X
1106 if (TrueVal == FalseVal)
1107 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00001108
Chris Lattner04754262010-04-20 05:32:14 +00001109 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
1110 return FalseVal;
1111 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
1112 return TrueVal;
1113 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
1114 if (isa<Constant>(TrueVal))
1115 return TrueVal;
1116 return FalseVal;
1117 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001118
Chris Lattner04754262010-04-20 05:32:14 +00001119 return 0;
1120}
1121
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001122/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
1123/// fold the result. If not, this returns null.
1124Value *llvm::SimplifyGEPInst(Value *const *Ops, unsigned NumOps,
Duncan Sands18450092010-11-16 12:16:38 +00001125 const TargetData *TD, const DominatorTree *) {
Duncan Sands85bbff62010-11-22 13:42:49 +00001126 // The type of the GEP pointer operand.
1127 const PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
1128
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001129 // getelementptr P -> P.
1130 if (NumOps == 1)
1131 return Ops[0];
1132
Duncan Sands85bbff62010-11-22 13:42:49 +00001133 if (isa<UndefValue>(Ops[0])) {
1134 // Compute the (pointer) type returned by the GEP instruction.
1135 const Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, &Ops[1],
1136 NumOps-1);
1137 const Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
1138 return UndefValue::get(GEPTy);
1139 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001140
Duncan Sandse60d79f2010-11-21 13:53:09 +00001141 if (NumOps == 2) {
1142 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001143 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
1144 if (C->isZero())
1145 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +00001146 // getelementptr P, N -> P if P points to a type of zero size.
1147 if (TD) {
Duncan Sands85bbff62010-11-22 13:42:49 +00001148 const Type *Ty = PtrTy->getElementType();
Duncan Sandsa63395a2010-11-22 16:32:50 +00001149 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +00001150 return Ops[0];
1151 }
1152 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001153
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001154 // Check to see if this is constant foldable.
1155 for (unsigned i = 0; i != NumOps; ++i)
1156 if (!isa<Constant>(Ops[i]))
1157 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001158
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001159 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]),
1160 (Constant *const*)Ops+1, NumOps-1);
1161}
1162
Duncan Sandsff103412010-11-17 04:30:22 +00001163/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
1164static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
1165 // If all of the PHI's incoming values are the same then replace the PHI node
1166 // with the common value.
1167 Value *CommonValue = 0;
1168 bool HasUndefInput = false;
1169 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1170 Value *Incoming = PN->getIncomingValue(i);
1171 // If the incoming value is the phi node itself, it can safely be skipped.
1172 if (Incoming == PN) continue;
1173 if (isa<UndefValue>(Incoming)) {
1174 // Remember that we saw an undef value, but otherwise ignore them.
1175 HasUndefInput = true;
1176 continue;
1177 }
1178 if (CommonValue && Incoming != CommonValue)
1179 return 0; // Not the same, bail out.
1180 CommonValue = Incoming;
1181 }
1182
1183 // If CommonValue is null then all of the incoming values were either undef or
1184 // equal to the phi node itself.
1185 if (!CommonValue)
1186 return UndefValue::get(PN->getType());
1187
1188 // If we have a PHI node like phi(X, undef, X), where X is defined by some
1189 // instruction, we cannot return X as the result of the PHI node unless it
1190 // dominates the PHI block.
1191 if (HasUndefInput)
1192 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
1193
1194 return CommonValue;
1195}
1196
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001197
Chris Lattnerd06094f2009-11-10 00:55:12 +00001198//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +00001199
Chris Lattnerd06094f2009-11-10 00:55:12 +00001200/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
1201/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001202static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001203 const TargetData *TD, const DominatorTree *DT,
1204 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001205 switch (Opcode) {
Duncan Sandsee9a2e32010-12-20 14:47:04 +00001206 case Instruction::Add: return SimplifyAddInst(LHS, RHS, /* isNSW */ false,
1207 /* isNUW */ false, TD, DT,
1208 MaxRecurse);
1209 case Instruction::Sub: return SimplifySubInst(LHS, RHS, /* isNSW */ false,
1210 /* isNUW */ false, TD, DT,
1211 MaxRecurse);
Duncan Sands82fdab32010-12-21 14:00:22 +00001212 case Instruction::Mul: return SimplifyMulInst(LHS, RHS, TD, DT, MaxRecurse);
1213 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
1214 case Instruction::Or: return SimplifyOrInst(LHS, RHS, TD, DT, MaxRecurse);
1215 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001216 default:
1217 if (Constant *CLHS = dyn_cast<Constant>(LHS))
1218 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
1219 Constant *COps[] = {CLHS, CRHS};
1220 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, 2, TD);
1221 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001222
Duncan Sands566edb02010-12-21 08:49:00 +00001223 // If the operation is associative, try some generic simplifications.
1224 if (Instruction::isAssociative(Opcode))
1225 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, DT,
1226 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>(LHS) || isa<SelectInst>(RHS))
Duncan Sands18450092010-11-16 12:16:38 +00001232 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, 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>(LHS) || isa<PHINode>(RHS))
1239 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001240 return V;
1241
Chris Lattnerd06094f2009-11-10 00:55:12 +00001242 return 0;
1243 }
1244}
Chris Lattner9dbb4292009-11-09 23:28:39 +00001245
Duncan Sands12a86f52010-11-14 11:23:23 +00001246Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001247 const TargetData *TD, const DominatorTree *DT) {
1248 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +00001249}
1250
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001251/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
1252/// fold the result.
1253static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001254 const TargetData *TD, const DominatorTree *DT,
1255 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001256 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sands18450092010-11-16 12:16:38 +00001257 return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
1258 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001259}
1260
1261Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001262 const TargetData *TD, const DominatorTree *DT) {
1263 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001264}
Chris Lattnere3453782009-11-10 01:08:51 +00001265
1266/// SimplifyInstruction - See if we can compute a simplified version of this
1267/// instruction. If not, this returns null.
Duncan Sandseff05812010-11-14 18:36:10 +00001268Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
1269 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +00001270 Value *Result;
1271
Chris Lattnere3453782009-11-10 01:08:51 +00001272 switch (I->getOpcode()) {
1273 default:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001274 Result = ConstantFoldInstruction(I, TD);
1275 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +00001276 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001277 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
1278 cast<BinaryOperator>(I)->hasNoSignedWrap(),
1279 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
1280 TD, DT);
1281 break;
Duncan Sandsfea3b212010-12-15 14:07:39 +00001282 case Instruction::Sub:
1283 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
1284 cast<BinaryOperator>(I)->hasNoSignedWrap(),
1285 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
1286 TD, DT);
1287 break;
Duncan Sands82fdab32010-12-21 14:00:22 +00001288 case Instruction::Mul:
1289 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, DT);
1290 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001291 case Instruction::And:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001292 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
1293 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001294 case Instruction::Or:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001295 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
1296 break;
Duncan Sands2b749872010-11-17 18:52:15 +00001297 case Instruction::Xor:
1298 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
1299 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001300 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001301 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
1302 I->getOperand(0), I->getOperand(1), TD, DT);
1303 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001304 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001305 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
1306 I->getOperand(0), I->getOperand(1), TD, DT);
1307 break;
Chris Lattner04754262010-04-20 05:32:14 +00001308 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001309 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
1310 I->getOperand(2), TD, DT);
1311 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001312 case Instruction::GetElementPtr: {
1313 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Duncan Sandsd261dc62010-11-17 08:35:29 +00001314 Result = SimplifyGEPInst(&Ops[0], Ops.size(), TD, DT);
1315 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001316 }
Duncan Sandscd6636c2010-11-14 13:30:18 +00001317 case Instruction::PHI:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001318 Result = SimplifyPHINode(cast<PHINode>(I), DT);
1319 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001320 }
Duncan Sandsd261dc62010-11-17 08:35:29 +00001321
1322 /// If called on unreachable code, the above logic may report that the
1323 /// instruction simplified to itself. Make life easier for users by
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00001324 /// detecting that case here, returning a safe value instead.
1325 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnere3453782009-11-10 01:08:51 +00001326}
1327
Chris Lattner40d8c282009-11-10 22:26:15 +00001328/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
1329/// delete the From instruction. In addition to a basic RAUW, this does a
1330/// recursive simplification of the newly formed instructions. This catches
1331/// things where one simplification exposes other opportunities. This only
1332/// simplifies and deletes scalar operations, it does not change the CFG.
1333///
1334void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
Duncan Sandseff05812010-11-14 18:36:10 +00001335 const TargetData *TD,
1336 const DominatorTree *DT) {
Chris Lattner40d8c282009-11-10 22:26:15 +00001337 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
Duncan Sands12a86f52010-11-14 11:23:23 +00001338
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001339 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
1340 // we can know if it gets deleted out from under us or replaced in a
1341 // recursive simplification.
Chris Lattner40d8c282009-11-10 22:26:15 +00001342 WeakVH FromHandle(From);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001343 WeakVH ToHandle(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00001344
Chris Lattner40d8c282009-11-10 22:26:15 +00001345 while (!From->use_empty()) {
1346 // Update the instruction to use the new value.
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001347 Use &TheUse = From->use_begin().getUse();
1348 Instruction *User = cast<Instruction>(TheUse.getUser());
1349 TheUse = To;
1350
1351 // Check to see if the instruction can be folded due to the operand
1352 // replacement. For example changing (or X, Y) into (or X, -1) can replace
1353 // the 'or' with -1.
1354 Value *SimplifiedVal;
1355 {
1356 // Sanity check to make sure 'User' doesn't dangle across
1357 // SimplifyInstruction.
1358 AssertingVH<> UserHandle(User);
Duncan Sands12a86f52010-11-14 11:23:23 +00001359
Duncan Sandseff05812010-11-14 18:36:10 +00001360 SimplifiedVal = SimplifyInstruction(User, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001361 if (SimplifiedVal == 0) continue;
Chris Lattner40d8c282009-11-10 22:26:15 +00001362 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001363
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001364 // Recursively simplify this user to the new value.
Duncan Sandseff05812010-11-14 18:36:10 +00001365 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001366 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
1367 To = ToHandle;
Duncan Sands12a86f52010-11-14 11:23:23 +00001368
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001369 assert(ToHandle && "To value deleted by recursive simplification?");
Duncan Sands12a86f52010-11-14 11:23:23 +00001370
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001371 // If the recursive simplification ended up revisiting and deleting
1372 // 'From' then we're done.
1373 if (From == 0)
1374 return;
Chris Lattner40d8c282009-11-10 22:26:15 +00001375 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001376
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001377 // If 'From' has value handles referring to it, do a real RAUW to update them.
1378 From->replaceAllUsesWith(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00001379
Chris Lattner40d8c282009-11-10 22:26:15 +00001380 From->eraseFromParent();
1381}