blob: a720987e52b9c70eba5e4354099aa648bb03925f [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.
162 // If V equals B then "A op' V" is just the LHS.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000163 if (V == B) {
164 ++NumFactor;
165 return LHS;
166 }
Duncan Sands3421d902010-12-21 13:32:22 +0000167 // Otherwise return "A op' V" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000168 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, DT, MaxRecurse)) {
169 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000170 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000171 }
Duncan Sands3421d902010-12-21 13:32:22 +0000172 }
173 }
174
175 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
176 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
177 // commutative case, "(A op' B) op (B op' D)"?
178 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
179 Value *CC = B == D ? C : D;
180 // Form "(A op CC) op' B" if it simplifies completely..
181 // Does "A op CC" simplify?
182 if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, DT, MaxRecurse)) {
183 // It does! Return "V op' B" if it simplifies or is already available.
184 // If V equals A then "V op' B" is just the LHS.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000185 if (V == B) {
186 ++NumFactor;
187 return LHS;
188 }
Duncan Sands3421d902010-12-21 13:32:22 +0000189 // Otherwise return "V op' B" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000190 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, DT, MaxRecurse)) {
191 ++NumFactor;
Duncan Sands3421d902010-12-21 13:32:22 +0000192 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000193 }
Duncan Sands3421d902010-12-21 13:32:22 +0000194 }
195 }
196
197 return 0;
198}
199
200/// SimplifyAssociativeBinOp - Generic simplifications for associative binary
201/// operations. Returns the simpler value, or null if none was found.
Duncan Sands566edb02010-12-21 08:49:00 +0000202static Value *SimplifyAssociativeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
203 const TargetData *TD,
204 const DominatorTree *DT,
205 unsigned MaxRecurse) {
206 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
207
208 // Recursion is always used, so bail out at once if we already hit the limit.
209 if (!MaxRecurse--)
210 return 0;
211
212 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
213 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
214
215 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
216 if (Op0 && Op0->getOpcode() == Opcode) {
217 Value *A = Op0->getOperand(0);
218 Value *B = Op0->getOperand(1);
219 Value *C = RHS;
220
221 // Does "B op C" simplify?
222 if (Value *V = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
223 // It does! Return "A op V" if it simplifies or is already available.
224 // If V equals B then "A op V" is just the LHS.
Duncan Sands3421d902010-12-21 13:32:22 +0000225 if (V == B) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000226 // Otherwise return "A op V" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000227 if (Value *W = SimplifyBinOp(Opcode, A, V, TD, DT, MaxRecurse)) {
228 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000229 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000230 }
Duncan Sands566edb02010-12-21 08:49:00 +0000231 }
232 }
233
234 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
235 if (Op1 && Op1->getOpcode() == Opcode) {
236 Value *A = LHS;
237 Value *B = Op1->getOperand(0);
238 Value *C = Op1->getOperand(1);
239
240 // Does "A op B" simplify?
241 if (Value *V = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse)) {
242 // It does! Return "V op C" if it simplifies or is already available.
243 // If V equals B then "V op C" is just the RHS.
Duncan Sands3421d902010-12-21 13:32:22 +0000244 if (V == B) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000245 // Otherwise return "V op C" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000246 if (Value *W = SimplifyBinOp(Opcode, V, C, TD, DT, MaxRecurse)) {
247 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000248 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000249 }
Duncan Sands566edb02010-12-21 08:49:00 +0000250 }
251 }
252
253 // The remaining transforms require commutativity as well as associativity.
254 if (!Instruction::isCommutative(Opcode))
255 return 0;
256
257 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
258 if (Op0 && Op0->getOpcode() == Opcode) {
259 Value *A = Op0->getOperand(0);
260 Value *B = Op0->getOperand(1);
261 Value *C = RHS;
262
263 // Does "C op A" simplify?
264 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
265 // It does! Return "V op B" if it simplifies or is already available.
266 // If V equals A then "V op B" is just the LHS.
Duncan Sands3421d902010-12-21 13:32:22 +0000267 if (V == A) return LHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000268 // Otherwise return "V op B" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000269 if (Value *W = SimplifyBinOp(Opcode, V, B, TD, DT, MaxRecurse)) {
270 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000271 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000272 }
Duncan Sands566edb02010-12-21 08:49:00 +0000273 }
274 }
275
276 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
277 if (Op1 && Op1->getOpcode() == Opcode) {
278 Value *A = LHS;
279 Value *B = Op1->getOperand(0);
280 Value *C = Op1->getOperand(1);
281
282 // Does "C op A" simplify?
283 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
284 // It does! Return "B op V" if it simplifies or is already available.
285 // If V equals C then "B op V" is just the RHS.
Duncan Sands3421d902010-12-21 13:32:22 +0000286 if (V == C) return RHS;
Duncan Sands566edb02010-12-21 08:49:00 +0000287 // Otherwise return "B op V" if it simplifies.
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000288 if (Value *W = SimplifyBinOp(Opcode, B, V, TD, DT, MaxRecurse)) {
289 ++NumReassoc;
Duncan Sands566edb02010-12-21 08:49:00 +0000290 return W;
Duncan Sandsa3c44a52010-12-22 09:40:51 +0000291 }
Duncan Sands566edb02010-12-21 08:49:00 +0000292 }
293 }
294
295 return 0;
296}
297
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000298/// ThreadBinOpOverSelect - In the case of a binary operation with a select
299/// instruction as an operand, try to simplify the binop by seeing whether
300/// evaluating it on both branches of the select results in the same value.
301/// Returns the common value if so, otherwise returns null.
302static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000303 const TargetData *TD,
304 const DominatorTree *DT,
305 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000306 // Recursion is always used, so bail out at once if we already hit the limit.
307 if (!MaxRecurse--)
308 return 0;
309
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000310 SelectInst *SI;
311 if (isa<SelectInst>(LHS)) {
312 SI = cast<SelectInst>(LHS);
313 } else {
314 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
315 SI = cast<SelectInst>(RHS);
316 }
317
318 // Evaluate the BinOp on the true and false branches of the select.
319 Value *TV;
320 Value *FV;
321 if (SI == LHS) {
Duncan Sands18450092010-11-16 12:16:38 +0000322 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
323 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000324 } else {
Duncan Sands18450092010-11-16 12:16:38 +0000325 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
326 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000327 }
328
329 // If they simplified to the same value, then return the common value.
330 // If they both failed to simplify then return null.
331 if (TV == FV)
332 return TV;
333
334 // If one branch simplified to undef, return the other one.
335 if (TV && isa<UndefValue>(TV))
336 return FV;
337 if (FV && isa<UndefValue>(FV))
338 return TV;
339
340 // If applying the operation did not change the true and false select values,
341 // then the result of the binop is the select itself.
342 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
343 return SI;
344
345 // If one branch simplified and the other did not, and the simplified
346 // value is equal to the unsimplified one, return the simplified value.
347 // For example, select (cond, X, X & Z) & Z -> X & Z.
348 if ((FV && !TV) || (TV && !FV)) {
349 // Check that the simplified value has the form "X op Y" where "op" is the
350 // same as the original operation.
351 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
352 if (Simplified && Simplified->getOpcode() == Opcode) {
353 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
354 // We already know that "op" is the same as for the simplified value. See
355 // if the operands match too. If so, return the simplified value.
356 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
357 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
358 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
359 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
360 Simplified->getOperand(1) == UnsimplifiedRHS)
361 return Simplified;
362 if (Simplified->isCommutative() &&
363 Simplified->getOperand(1) == UnsimplifiedLHS &&
364 Simplified->getOperand(0) == UnsimplifiedRHS)
365 return Simplified;
366 }
367 }
368
369 return 0;
370}
371
372/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
373/// try to simplify the comparison by seeing whether both branches of the select
374/// result in the same value. Returns the common value if so, otherwise returns
375/// null.
376static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000377 Value *RHS, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000378 const DominatorTree *DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000379 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000380 // Recursion is always used, so bail out at once if we already hit the limit.
381 if (!MaxRecurse--)
382 return 0;
383
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000384 // Make sure the select is on the LHS.
385 if (!isa<SelectInst>(LHS)) {
386 std::swap(LHS, RHS);
387 Pred = CmpInst::getSwappedPredicate(Pred);
388 }
389 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
390 SelectInst *SI = cast<SelectInst>(LHS);
391
392 // Now that we have "cmp select(cond, TV, FV), RHS", analyse it.
393 // Does "cmp TV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000394 if (Value *TCmp = SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000395 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000396 // It does! Does "cmp FV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000397 if (Value *FCmp = SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000398 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000399 // It does! If they simplified to the same value, then use it as the
400 // result of the original comparison.
401 if (TCmp == FCmp)
402 return TCmp;
403 return 0;
404}
405
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000406/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
407/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
408/// it on the incoming phi values yields the same result for every value. If so
409/// returns the common value, otherwise returns null.
410static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000411 const TargetData *TD, const DominatorTree *DT,
412 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000413 // Recursion is always used, so bail out at once if we already hit the limit.
414 if (!MaxRecurse--)
415 return 0;
416
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000417 PHINode *PI;
418 if (isa<PHINode>(LHS)) {
419 PI = cast<PHINode>(LHS);
Duncan Sands18450092010-11-16 12:16:38 +0000420 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
421 if (!ValueDominatesPHI(RHS, PI, DT))
422 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000423 } else {
424 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
425 PI = cast<PHINode>(RHS);
Duncan Sands18450092010-11-16 12:16:38 +0000426 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
427 if (!ValueDominatesPHI(LHS, PI, DT))
428 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000429 }
430
431 // Evaluate the BinOp on the incoming phi values.
432 Value *CommonValue = 0;
433 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000434 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000435 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000436 if (Incoming == PI) continue;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000437 Value *V = PI == LHS ?
Duncan Sands18450092010-11-16 12:16:38 +0000438 SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
439 SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000440 // If the operation failed to simplify, or simplified to a different value
441 // to previously, then give up.
442 if (!V || (CommonValue && V != CommonValue))
443 return 0;
444 CommonValue = V;
445 }
446
447 return CommonValue;
448}
449
450/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
451/// try to simplify the comparison by seeing whether comparing with all of the
452/// incoming phi values yields the same result every time. If so returns the
453/// common result, otherwise returns null.
454static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000455 const TargetData *TD, const DominatorTree *DT,
456 unsigned MaxRecurse) {
Duncan Sands0312a932010-12-21 09:09:15 +0000457 // Recursion is always used, so bail out at once if we already hit the limit.
458 if (!MaxRecurse--)
459 return 0;
460
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000461 // Make sure the phi is on the LHS.
462 if (!isa<PHINode>(LHS)) {
463 std::swap(LHS, RHS);
464 Pred = CmpInst::getSwappedPredicate(Pred);
465 }
466 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
467 PHINode *PI = cast<PHINode>(LHS);
468
Duncan Sands18450092010-11-16 12:16:38 +0000469 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
470 if (!ValueDominatesPHI(RHS, PI, DT))
471 return 0;
472
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000473 // Evaluate the BinOp on the incoming phi values.
474 Value *CommonValue = 0;
475 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000476 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000477 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000478 if (Incoming == PI) continue;
Duncan Sands18450092010-11-16 12:16:38 +0000479 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000480 // If the operation failed to simplify, or simplified to a different value
481 // to previously, then give up.
482 if (!V || (CommonValue && V != CommonValue))
483 return 0;
484 CommonValue = V;
485 }
486
487 return CommonValue;
488}
489
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000490/// SimplifyAddInst - Given operands for an Add, see if we can
491/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000492static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
493 const TargetData *TD, const DominatorTree *DT,
494 unsigned MaxRecurse) {
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000495 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
496 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
497 Constant *Ops[] = { CLHS, CRHS };
498 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
499 Ops, 2, TD);
500 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000501
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000502 // Canonicalize the constant to the RHS.
503 std::swap(Op0, Op1);
504 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000505
Duncan Sandsfea3b212010-12-15 14:07:39 +0000506 // X + undef -> undef
507 if (isa<UndefValue>(Op1))
508 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000509
Duncan Sandsfea3b212010-12-15 14:07:39 +0000510 // X + 0 -> X
511 if (match(Op1, m_Zero()))
512 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000513
Duncan Sandsfea3b212010-12-15 14:07:39 +0000514 // X + (Y - X) -> Y
515 // (Y - X) + X -> Y
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000516 // Eg: X + -X -> 0
Duncan Sandsfea3b212010-12-15 14:07:39 +0000517 Value *Y = 0;
518 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
519 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
520 return Y;
521
522 // X + ~X -> -1 since ~X = -X-1
523 if (match(Op0, m_Not(m_Specific(Op1))) ||
524 match(Op1, m_Not(m_Specific(Op0))))
525 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands87689cf2010-11-19 09:20:39 +0000526
Duncan Sands82fdab32010-12-21 14:00:22 +0000527 /// i1 add -> xor.
Duncan Sands75d289e2010-12-21 14:48:48 +0000528 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000529 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
530 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000531
Duncan Sands566edb02010-12-21 08:49:00 +0000532 // Try some generic simplifications for associative operations.
533 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, DT,
534 MaxRecurse))
535 return V;
536
Duncan Sands3421d902010-12-21 13:32:22 +0000537 // Mul distributes over Add. Try some generic simplifications based on this.
538 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
539 TD, DT, MaxRecurse))
540 return V;
541
Duncan Sands87689cf2010-11-19 09:20:39 +0000542 // Threading Add over selects and phi nodes is pointless, so don't bother.
543 // Threading over the select in "A + select(cond, B, C)" means evaluating
544 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
545 // only if B and C are equal. If B and C are equal then (since we assume
546 // that operands have already been simplified) "select(cond, B, C)" should
547 // have been simplified to the common value of B and C already. Analysing
548 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
549 // for threading over phi nodes.
550
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000551 return 0;
552}
553
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000554Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
555 const TargetData *TD, const DominatorTree *DT) {
556 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
557}
558
Duncan Sandsfea3b212010-12-15 14:07:39 +0000559/// SimplifySubInst - Given operands for a Sub, see if we can
560/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000561static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
Duncan Sands3421d902010-12-21 13:32:22 +0000562 const TargetData *TD, const DominatorTree *DT,
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000563 unsigned MaxRecurse) {
Duncan Sandsfea3b212010-12-15 14:07:39 +0000564 if (Constant *CLHS = dyn_cast<Constant>(Op0))
565 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
566 Constant *Ops[] = { CLHS, CRHS };
567 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
568 Ops, 2, TD);
569 }
570
571 // X - undef -> undef
572 // undef - X -> undef
573 if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
574 return UndefValue::get(Op0->getType());
575
576 // X - 0 -> X
577 if (match(Op1, m_Zero()))
578 return Op0;
579
580 // X - X -> 0
581 if (Op0 == Op1)
582 return Constant::getNullValue(Op0->getType());
583
584 // (X + Y) - Y -> X
585 // (Y + X) - Y -> X
586 Value *X = 0;
587 if (match(Op0, m_Add(m_Value(X), m_Specific(Op1))) ||
588 match(Op0, m_Add(m_Specific(Op1), m_Value(X))))
589 return X;
590
Duncan Sands82fdab32010-12-21 14:00:22 +0000591 /// i1 sub -> xor.
Duncan Sands75d289e2010-12-21 14:48:48 +0000592 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000593 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
594 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000595
Duncan Sands3421d902010-12-21 13:32:22 +0000596 // Mul distributes over Sub. Try some generic simplifications based on this.
597 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
598 TD, DT, MaxRecurse))
599 return V;
600
Duncan Sandsfea3b212010-12-15 14:07:39 +0000601 // Threading Sub over selects and phi nodes is pointless, so don't bother.
602 // Threading over the select in "A - select(cond, B, C)" means evaluating
603 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
604 // only if B and C are equal. If B and C are equal then (since we assume
605 // that operands have already been simplified) "select(cond, B, C)" should
606 // have been simplified to the common value of B and C already. Analysing
607 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
608 // for threading over phi nodes.
609
610 return 0;
611}
612
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000613Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
614 const TargetData *TD, const DominatorTree *DT) {
615 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
616}
617
Duncan Sands82fdab32010-12-21 14:00:22 +0000618/// SimplifyMulInst - Given operands for a Mul, see if we can
619/// fold the result. If not, this returns null.
620static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
621 const DominatorTree *DT, unsigned MaxRecurse) {
622 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
623 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
624 Constant *Ops[] = { CLHS, CRHS };
625 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
626 Ops, 2, TD);
627 }
628
629 // Canonicalize the constant to the RHS.
630 std::swap(Op0, Op1);
631 }
632
633 // X * undef -> 0
634 if (isa<UndefValue>(Op1))
635 return Constant::getNullValue(Op0->getType());
636
637 // X * 0 -> 0
638 if (match(Op1, m_Zero()))
639 return Op1;
640
641 // X * 1 -> X
642 if (match(Op1, m_One()))
643 return Op0;
644
645 /// i1 mul -> and.
Duncan Sands75d289e2010-12-21 14:48:48 +0000646 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
Duncan Sands07f30fb2010-12-21 15:03:43 +0000647 if (Value *V = SimplifyAndInst(Op0, Op1, TD, DT, MaxRecurse-1))
648 return V;
Duncan Sands82fdab32010-12-21 14:00:22 +0000649
650 // Try some generic simplifications for associative operations.
651 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, DT,
652 MaxRecurse))
653 return V;
654
655 // Mul distributes over Add. Try some generic simplifications based on this.
656 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
657 TD, DT, MaxRecurse))
658 return V;
659
660 // If the operation is with the result of a select instruction, check whether
661 // operating on either branch of the select always yields the same value.
662 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
663 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, DT,
664 MaxRecurse))
665 return V;
666
667 // If the operation is with the result of a phi instruction, check whether
668 // operating on all incoming values of the phi always yields the same value.
669 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
670 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, DT,
671 MaxRecurse))
672 return V;
673
674 return 0;
675}
676
677Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
678 const DominatorTree *DT) {
679 return ::SimplifyMulInst(Op0, Op1, TD, DT, RecursionLimit);
680}
681
Chris Lattnerd06094f2009-11-10 00:55:12 +0000682/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000683/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000684static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000685 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000686 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
687 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
688 Constant *Ops[] = { CLHS, CRHS };
689 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
690 Ops, 2, TD);
691 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000692
Chris Lattnerd06094f2009-11-10 00:55:12 +0000693 // Canonicalize the constant to the RHS.
694 std::swap(Op0, Op1);
695 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000696
Chris Lattnerd06094f2009-11-10 00:55:12 +0000697 // X & undef -> 0
698 if (isa<UndefValue>(Op1))
699 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000700
Chris Lattnerd06094f2009-11-10 00:55:12 +0000701 // X & X = X
702 if (Op0 == Op1)
703 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000704
Duncan Sands2b749872010-11-17 18:52:15 +0000705 // X & 0 = 0
706 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000707 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000708
Duncan Sands2b749872010-11-17 18:52:15 +0000709 // X & -1 = X
710 if (match(Op1, m_AllOnes()))
711 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000712
Chris Lattnerd06094f2009-11-10 00:55:12 +0000713 // A & ~A = ~A & A = 0
Chandler Carruthe89ada92010-11-29 01:41:13 +0000714 Value *A = 0, *B = 0;
Chris Lattner70ce6d02009-11-10 02:04:54 +0000715 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
716 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000717 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000718
Chris Lattnerd06094f2009-11-10 00:55:12 +0000719 // (A | ?) & A = A
720 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
721 (A == Op1 || B == Op1))
722 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000723
Chris Lattnerd06094f2009-11-10 00:55:12 +0000724 // A & (A | ?) = A
725 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
726 (A == Op0 || B == Op0))
727 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000728
Duncan Sands566edb02010-12-21 08:49:00 +0000729 // Try some generic simplifications for associative operations.
730 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, DT,
731 MaxRecurse))
732 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +0000733
Duncan Sands3421d902010-12-21 13:32:22 +0000734 // And distributes over Or. Try some generic simplifications based on this.
735 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
736 TD, DT, MaxRecurse))
737 return V;
738
739 // And distributes over Xor. Try some generic simplifications based on this.
740 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
741 TD, DT, MaxRecurse))
742 return V;
743
744 // Or distributes over And. Try some generic simplifications based on this.
745 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
746 TD, DT, MaxRecurse))
747 return V;
748
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000749 // If the operation is with the result of a select instruction, check whether
750 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000751 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +0000752 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +0000753 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000754 return V;
755
756 // If the operation is with the result of a phi instruction, check whether
757 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000758 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +0000759 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +0000760 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000761 return V;
762
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000763 return 0;
764}
765
Duncan Sands18450092010-11-16 12:16:38 +0000766Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
767 const DominatorTree *DT) {
768 return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000769}
770
Chris Lattnerd06094f2009-11-10 00:55:12 +0000771/// SimplifyOrInst - Given operands for an Or, see if we can
772/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000773static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000774 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000775 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
776 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
777 Constant *Ops[] = { CLHS, CRHS };
778 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
779 Ops, 2, TD);
780 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000781
Chris Lattnerd06094f2009-11-10 00:55:12 +0000782 // Canonicalize the constant to the RHS.
783 std::swap(Op0, Op1);
784 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000785
Chris Lattnerd06094f2009-11-10 00:55:12 +0000786 // X | undef -> -1
787 if (isa<UndefValue>(Op1))
788 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000789
Chris Lattnerd06094f2009-11-10 00:55:12 +0000790 // X | X = X
791 if (Op0 == Op1)
792 return Op0;
793
Duncan Sands2b749872010-11-17 18:52:15 +0000794 // X | 0 = X
795 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000796 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000797
Duncan Sands2b749872010-11-17 18:52:15 +0000798 // X | -1 = -1
799 if (match(Op1, m_AllOnes()))
800 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000801
Chris Lattnerd06094f2009-11-10 00:55:12 +0000802 // A | ~A = ~A | A = -1
Chandler Carruthe89ada92010-11-29 01:41:13 +0000803 Value *A = 0, *B = 0;
Chris Lattner70ce6d02009-11-10 02:04:54 +0000804 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
805 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000806 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000807
Chris Lattnerd06094f2009-11-10 00:55:12 +0000808 // (A & ?) | A = A
809 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
810 (A == Op1 || B == Op1))
811 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000812
Chris Lattnerd06094f2009-11-10 00:55:12 +0000813 // A | (A & ?) = A
814 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
815 (A == Op0 || B == Op0))
816 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000817
Duncan Sands566edb02010-12-21 08:49:00 +0000818 // Try some generic simplifications for associative operations.
819 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, DT,
820 MaxRecurse))
821 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +0000822
Duncan Sands3421d902010-12-21 13:32:22 +0000823 // Or distributes over And. Try some generic simplifications based on this.
824 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And,
825 TD, DT, MaxRecurse))
826 return V;
827
828 // And distributes over Or. Try some generic simplifications based on this.
829 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
830 TD, DT, MaxRecurse))
831 return V;
832
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000833 // If the operation is with the result of a select instruction, check whether
834 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000835 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +0000836 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +0000837 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000838 return V;
839
840 // If the operation is with the result of a phi instruction, check whether
841 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000842 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
Duncan Sands18450092010-11-16 12:16:38 +0000843 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +0000844 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000845 return V;
846
Chris Lattnerd06094f2009-11-10 00:55:12 +0000847 return 0;
848}
849
Duncan Sands18450092010-11-16 12:16:38 +0000850Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
851 const DominatorTree *DT) {
852 return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000853}
Chris Lattnerd06094f2009-11-10 00:55:12 +0000854
Duncan Sands2b749872010-11-17 18:52:15 +0000855/// SimplifyXorInst - Given operands for a Xor, see if we can
856/// fold the result. If not, this returns null.
857static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
858 const DominatorTree *DT, unsigned MaxRecurse) {
859 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
860 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
861 Constant *Ops[] = { CLHS, CRHS };
862 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
863 Ops, 2, TD);
864 }
865
866 // Canonicalize the constant to the RHS.
867 std::swap(Op0, Op1);
868 }
869
870 // A ^ undef -> undef
871 if (isa<UndefValue>(Op1))
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +0000872 return Op1;
Duncan Sands2b749872010-11-17 18:52:15 +0000873
874 // A ^ 0 = A
875 if (match(Op1, m_Zero()))
876 return Op0;
877
878 // A ^ A = 0
879 if (Op0 == Op1)
880 return Constant::getNullValue(Op0->getType());
881
882 // A ^ ~A = ~A ^ A = -1
Duncan Sands566edb02010-12-21 08:49:00 +0000883 Value *A = 0;
Duncan Sands2b749872010-11-17 18:52:15 +0000884 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
885 (match(Op1, m_Not(m_Value(A))) && A == Op0))
886 return Constant::getAllOnesValue(Op0->getType());
887
Duncan Sands566edb02010-12-21 08:49:00 +0000888 // Try some generic simplifications for associative operations.
889 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, DT,
890 MaxRecurse))
891 return V;
Duncan Sands2b749872010-11-17 18:52:15 +0000892
Duncan Sands3421d902010-12-21 13:32:22 +0000893 // And distributes over Xor. Try some generic simplifications based on this.
894 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
895 TD, DT, MaxRecurse))
896 return V;
897
Duncan Sands87689cf2010-11-19 09:20:39 +0000898 // Threading Xor over selects and phi nodes is pointless, so don't bother.
899 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
900 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
901 // only if B and C are equal. If B and C are equal then (since we assume
902 // that operands have already been simplified) "select(cond, B, C)" should
903 // have been simplified to the common value of B and C already. Analysing
904 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
905 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +0000906
907 return 0;
908}
909
910Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
911 const DominatorTree *DT) {
912 return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
913}
914
Chris Lattner210c5d42009-11-09 23:55:12 +0000915static const Type *GetCompareTy(Value *Op) {
916 return CmpInst::makeCmpResultType(Op->getType());
917}
918
Chris Lattner9dbb4292009-11-09 23:28:39 +0000919/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
920/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000921static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000922 const TargetData *TD, const DominatorTree *DT,
923 unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000924 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +0000925 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +0000926
Chris Lattnerd06094f2009-11-10 00:55:12 +0000927 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +0000928 if (Constant *CRHS = dyn_cast<Constant>(RHS))
929 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Chris Lattnerd06094f2009-11-10 00:55:12 +0000930
931 // If we have a constant, make sure it is on the RHS.
932 std::swap(LHS, RHS);
933 Pred = CmpInst::getSwappedPredicate(Pred);
934 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000935
Chris Lattner210c5d42009-11-09 23:55:12 +0000936 // ITy - This is the return type of the compare we're considering.
937 const Type *ITy = GetCompareTy(LHS);
Duncan Sands12a86f52010-11-14 11:23:23 +0000938
Chris Lattner210c5d42009-11-09 23:55:12 +0000939 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +0000940 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
941 // because X could be 0.
942 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +0000943 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +0000944
Chris Lattner210c5d42009-11-09 23:55:12 +0000945 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
946 // addresses never equal each other! We already know that Op0 != Op1.
Duncan Sands12a86f52010-11-14 11:23:23 +0000947 if ((isa<GlobalValue>(LHS) || isa<AllocaInst>(LHS) ||
Chris Lattner210c5d42009-11-09 23:55:12 +0000948 isa<ConstantPointerNull>(LHS)) &&
Duncan Sands12a86f52010-11-14 11:23:23 +0000949 (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
Chris Lattner210c5d42009-11-09 23:55:12 +0000950 isa<ConstantPointerNull>(RHS)))
951 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +0000952
Chris Lattner210c5d42009-11-09 23:55:12 +0000953 // See if we are doing a comparison with a constant.
954 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
955 // If we have an icmp le or icmp ge instruction, turn it into the
956 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
957 // them being folded in the code below.
958 switch (Pred) {
959 default: break;
960 case ICmpInst::ICMP_ULE:
961 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
962 return ConstantInt::getTrue(CI->getContext());
963 break;
964 case ICmpInst::ICMP_SLE:
965 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
966 return ConstantInt::getTrue(CI->getContext());
967 break;
968 case ICmpInst::ICMP_UGE:
969 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
970 return ConstantInt::getTrue(CI->getContext());
971 break;
972 case ICmpInst::ICMP_SGE:
973 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
974 return ConstantInt::getTrue(CI->getContext());
975 break;
976 }
Chris Lattner210c5d42009-11-09 23:55:12 +0000977 }
Duncan Sands1ac7c992010-11-07 16:12:23 +0000978
979 // If the comparison is with the result of a select instruction, check whether
980 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +0000981 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
982 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000983 return V;
984
985 // If the comparison is with the result of a phi instruction, check whether
986 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +0000987 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
988 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +0000989 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +0000990
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000991 return 0;
992}
993
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000994Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000995 const TargetData *TD, const DominatorTree *DT) {
996 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000997}
998
Chris Lattner9dbb4292009-11-09 23:28:39 +0000999/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
1000/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001001static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001002 const TargetData *TD, const DominatorTree *DT,
1003 unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00001004 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1005 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
1006
Chris Lattnerd06094f2009-11-10 00:55:12 +00001007 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +00001008 if (Constant *CRHS = dyn_cast<Constant>(RHS))
1009 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Duncan Sands12a86f52010-11-14 11:23:23 +00001010
Chris Lattnerd06094f2009-11-10 00:55:12 +00001011 // If we have a constant, make sure it is on the RHS.
1012 std::swap(LHS, RHS);
1013 Pred = CmpInst::getSwappedPredicate(Pred);
1014 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001015
Chris Lattner210c5d42009-11-09 23:55:12 +00001016 // Fold trivial predicates.
1017 if (Pred == FCmpInst::FCMP_FALSE)
1018 return ConstantInt::get(GetCompareTy(LHS), 0);
1019 if (Pred == FCmpInst::FCMP_TRUE)
1020 return ConstantInt::get(GetCompareTy(LHS), 1);
1021
Chris Lattner210c5d42009-11-09 23:55:12 +00001022 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
1023 return UndefValue::get(GetCompareTy(LHS));
1024
1025 // fcmp x,x -> true/false. Not all compares are foldable.
1026 if (LHS == RHS) {
1027 if (CmpInst::isTrueWhenEqual(Pred))
1028 return ConstantInt::get(GetCompareTy(LHS), 1);
1029 if (CmpInst::isFalseWhenEqual(Pred))
1030 return ConstantInt::get(GetCompareTy(LHS), 0);
1031 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001032
Chris Lattner210c5d42009-11-09 23:55:12 +00001033 // Handle fcmp with constant RHS
1034 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1035 // If the constant is a nan, see if we can fold the comparison based on it.
1036 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1037 if (CFP->getValueAPF().isNaN()) {
1038 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
1039 return ConstantInt::getFalse(CFP->getContext());
1040 assert(FCmpInst::isUnordered(Pred) &&
1041 "Comparison must be either ordered or unordered!");
1042 // True if unordered.
1043 return ConstantInt::getTrue(CFP->getContext());
1044 }
Dan Gohman6b617a72010-02-22 04:06:03 +00001045 // Check whether the constant is an infinity.
1046 if (CFP->getValueAPF().isInfinity()) {
1047 if (CFP->getValueAPF().isNegative()) {
1048 switch (Pred) {
1049 case FCmpInst::FCMP_OLT:
1050 // No value is ordered and less than negative infinity.
1051 return ConstantInt::getFalse(CFP->getContext());
1052 case FCmpInst::FCMP_UGE:
1053 // All values are unordered with or at least negative infinity.
1054 return ConstantInt::getTrue(CFP->getContext());
1055 default:
1056 break;
1057 }
1058 } else {
1059 switch (Pred) {
1060 case FCmpInst::FCMP_OGT:
1061 // No value is ordered and greater than infinity.
1062 return ConstantInt::getFalse(CFP->getContext());
1063 case FCmpInst::FCMP_ULE:
1064 // All values are unordered with and at most infinity.
1065 return ConstantInt::getTrue(CFP->getContext());
1066 default:
1067 break;
1068 }
1069 }
1070 }
Chris Lattner210c5d42009-11-09 23:55:12 +00001071 }
1072 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001073
Duncan Sands92826de2010-11-07 16:46:25 +00001074 // If the comparison is with the result of a select instruction, check whether
1075 // comparing with either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001076 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
1077 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001078 return V;
1079
1080 // If the comparison is with the result of a phi instruction, check whether
1081 // doing the compare with each incoming phi value yields a common result.
Duncan Sands0312a932010-12-21 09:09:15 +00001082 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1083 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +00001084 return V;
Duncan Sands92826de2010-11-07 16:46:25 +00001085
Chris Lattner9dbb4292009-11-09 23:28:39 +00001086 return 0;
1087}
1088
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001089Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001090 const TargetData *TD, const DominatorTree *DT) {
1091 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001092}
1093
Chris Lattner04754262010-04-20 05:32:14 +00001094/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
1095/// the result. If not, this returns null.
1096Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
Duncan Sands18450092010-11-16 12:16:38 +00001097 const TargetData *TD, const DominatorTree *) {
Chris Lattner04754262010-04-20 05:32:14 +00001098 // select true, X, Y -> X
1099 // select false, X, Y -> Y
1100 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
1101 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00001102
Chris Lattner04754262010-04-20 05:32:14 +00001103 // select C, X, X -> X
1104 if (TrueVal == FalseVal)
1105 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +00001106
Chris Lattner04754262010-04-20 05:32:14 +00001107 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
1108 return FalseVal;
1109 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
1110 return TrueVal;
1111 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
1112 if (isa<Constant>(TrueVal))
1113 return TrueVal;
1114 return FalseVal;
1115 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001116
Chris Lattner04754262010-04-20 05:32:14 +00001117 return 0;
1118}
1119
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001120/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
1121/// fold the result. If not, this returns null.
1122Value *llvm::SimplifyGEPInst(Value *const *Ops, unsigned NumOps,
Duncan Sands18450092010-11-16 12:16:38 +00001123 const TargetData *TD, const DominatorTree *) {
Duncan Sands85bbff62010-11-22 13:42:49 +00001124 // The type of the GEP pointer operand.
1125 const PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
1126
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001127 // getelementptr P -> P.
1128 if (NumOps == 1)
1129 return Ops[0];
1130
Duncan Sands85bbff62010-11-22 13:42:49 +00001131 if (isa<UndefValue>(Ops[0])) {
1132 // Compute the (pointer) type returned by the GEP instruction.
1133 const Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, &Ops[1],
1134 NumOps-1);
1135 const Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
1136 return UndefValue::get(GEPTy);
1137 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001138
Duncan Sandse60d79f2010-11-21 13:53:09 +00001139 if (NumOps == 2) {
1140 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001141 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
1142 if (C->isZero())
1143 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +00001144 // getelementptr P, N -> P if P points to a type of zero size.
1145 if (TD) {
Duncan Sands85bbff62010-11-22 13:42:49 +00001146 const Type *Ty = PtrTy->getElementType();
Duncan Sandsa63395a2010-11-22 16:32:50 +00001147 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +00001148 return Ops[0];
1149 }
1150 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001151
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001152 // Check to see if this is constant foldable.
1153 for (unsigned i = 0; i != NumOps; ++i)
1154 if (!isa<Constant>(Ops[i]))
1155 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +00001156
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001157 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]),
1158 (Constant *const*)Ops+1, NumOps-1);
1159}
1160
Duncan Sandsff103412010-11-17 04:30:22 +00001161/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
1162static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
1163 // If all of the PHI's incoming values are the same then replace the PHI node
1164 // with the common value.
1165 Value *CommonValue = 0;
1166 bool HasUndefInput = false;
1167 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1168 Value *Incoming = PN->getIncomingValue(i);
1169 // If the incoming value is the phi node itself, it can safely be skipped.
1170 if (Incoming == PN) continue;
1171 if (isa<UndefValue>(Incoming)) {
1172 // Remember that we saw an undef value, but otherwise ignore them.
1173 HasUndefInput = true;
1174 continue;
1175 }
1176 if (CommonValue && Incoming != CommonValue)
1177 return 0; // Not the same, bail out.
1178 CommonValue = Incoming;
1179 }
1180
1181 // If CommonValue is null then all of the incoming values were either undef or
1182 // equal to the phi node itself.
1183 if (!CommonValue)
1184 return UndefValue::get(PN->getType());
1185
1186 // If we have a PHI node like phi(X, undef, X), where X is defined by some
1187 // instruction, we cannot return X as the result of the PHI node unless it
1188 // dominates the PHI block.
1189 if (HasUndefInput)
1190 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
1191
1192 return CommonValue;
1193}
1194
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001195
Chris Lattnerd06094f2009-11-10 00:55:12 +00001196//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +00001197
Chris Lattnerd06094f2009-11-10 00:55:12 +00001198/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
1199/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001200static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001201 const TargetData *TD, const DominatorTree *DT,
1202 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +00001203 switch (Opcode) {
Duncan Sandsee9a2e32010-12-20 14:47:04 +00001204 case Instruction::Add: return SimplifyAddInst(LHS, RHS, /* isNSW */ false,
1205 /* isNUW */ false, TD, DT,
1206 MaxRecurse);
1207 case Instruction::Sub: return SimplifySubInst(LHS, RHS, /* isNSW */ false,
1208 /* isNUW */ false, TD, DT,
1209 MaxRecurse);
Duncan Sands82fdab32010-12-21 14:00:22 +00001210 case Instruction::Mul: return SimplifyMulInst(LHS, RHS, TD, DT, MaxRecurse);
1211 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
1212 case Instruction::Or: return SimplifyOrInst(LHS, RHS, TD, DT, MaxRecurse);
1213 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +00001214 default:
1215 if (Constant *CLHS = dyn_cast<Constant>(LHS))
1216 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
1217 Constant *COps[] = {CLHS, CRHS};
1218 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, 2, TD);
1219 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001220
Duncan Sands566edb02010-12-21 08:49:00 +00001221 // If the operation is associative, try some generic simplifications.
1222 if (Instruction::isAssociative(Opcode))
1223 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, DT,
1224 MaxRecurse))
1225 return V;
1226
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001227 // If the operation is with the result of a select instruction, check whether
1228 // operating on either branch of the select always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001229 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
Duncan Sands18450092010-11-16 12:16:38 +00001230 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
Duncan Sands0312a932010-12-21 09:09:15 +00001231 MaxRecurse))
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001232 return V;
1233
1234 // If the operation is with the result of a phi instruction, check whether
1235 // operating on all incoming values of the phi always yields the same value.
Duncan Sands0312a932010-12-21 09:09:15 +00001236 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1237 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +00001238 return V;
1239
Chris Lattnerd06094f2009-11-10 00:55:12 +00001240 return 0;
1241 }
1242}
Chris Lattner9dbb4292009-11-09 23:28:39 +00001243
Duncan Sands12a86f52010-11-14 11:23:23 +00001244Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001245 const TargetData *TD, const DominatorTree *DT) {
1246 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +00001247}
1248
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001249/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
1250/// fold the result.
1251static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001252 const TargetData *TD, const DominatorTree *DT,
1253 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001254 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sands18450092010-11-16 12:16:38 +00001255 return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
1256 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001257}
1258
1259Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +00001260 const TargetData *TD, const DominatorTree *DT) {
1261 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +00001262}
Chris Lattnere3453782009-11-10 01:08:51 +00001263
1264/// SimplifyInstruction - See if we can compute a simplified version of this
1265/// instruction. If not, this returns null.
Duncan Sandseff05812010-11-14 18:36:10 +00001266Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
1267 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +00001268 Value *Result;
1269
Chris Lattnere3453782009-11-10 01:08:51 +00001270 switch (I->getOpcode()) {
1271 default:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001272 Result = ConstantFoldInstruction(I, TD);
1273 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +00001274 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001275 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
1276 cast<BinaryOperator>(I)->hasNoSignedWrap(),
1277 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
1278 TD, DT);
1279 break;
Duncan Sandsfea3b212010-12-15 14:07:39 +00001280 case Instruction::Sub:
1281 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
1282 cast<BinaryOperator>(I)->hasNoSignedWrap(),
1283 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
1284 TD, DT);
1285 break;
Duncan Sands82fdab32010-12-21 14:00:22 +00001286 case Instruction::Mul:
1287 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, DT);
1288 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001289 case Instruction::And:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001290 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
1291 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001292 case Instruction::Or:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001293 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
1294 break;
Duncan Sands2b749872010-11-17 18:52:15 +00001295 case Instruction::Xor:
1296 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
1297 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001298 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001299 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
1300 I->getOperand(0), I->getOperand(1), TD, DT);
1301 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001302 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001303 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
1304 I->getOperand(0), I->getOperand(1), TD, DT);
1305 break;
Chris Lattner04754262010-04-20 05:32:14 +00001306 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001307 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
1308 I->getOperand(2), TD, DT);
1309 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001310 case Instruction::GetElementPtr: {
1311 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Duncan Sandsd261dc62010-11-17 08:35:29 +00001312 Result = SimplifyGEPInst(&Ops[0], Ops.size(), TD, DT);
1313 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001314 }
Duncan Sandscd6636c2010-11-14 13:30:18 +00001315 case Instruction::PHI:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001316 Result = SimplifyPHINode(cast<PHINode>(I), DT);
1317 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001318 }
Duncan Sandsd261dc62010-11-17 08:35:29 +00001319
1320 /// If called on unreachable code, the above logic may report that the
1321 /// instruction simplified to itself. Make life easier for users by
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00001322 /// detecting that case here, returning a safe value instead.
1323 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnere3453782009-11-10 01:08:51 +00001324}
1325
Chris Lattner40d8c282009-11-10 22:26:15 +00001326/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
1327/// delete the From instruction. In addition to a basic RAUW, this does a
1328/// recursive simplification of the newly formed instructions. This catches
1329/// things where one simplification exposes other opportunities. This only
1330/// simplifies and deletes scalar operations, it does not change the CFG.
1331///
1332void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
Duncan Sandseff05812010-11-14 18:36:10 +00001333 const TargetData *TD,
1334 const DominatorTree *DT) {
Chris Lattner40d8c282009-11-10 22:26:15 +00001335 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
Duncan Sands12a86f52010-11-14 11:23:23 +00001336
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001337 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
1338 // we can know if it gets deleted out from under us or replaced in a
1339 // recursive simplification.
Chris Lattner40d8c282009-11-10 22:26:15 +00001340 WeakVH FromHandle(From);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001341 WeakVH ToHandle(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00001342
Chris Lattner40d8c282009-11-10 22:26:15 +00001343 while (!From->use_empty()) {
1344 // Update the instruction to use the new value.
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001345 Use &TheUse = From->use_begin().getUse();
1346 Instruction *User = cast<Instruction>(TheUse.getUser());
1347 TheUse = To;
1348
1349 // Check to see if the instruction can be folded due to the operand
1350 // replacement. For example changing (or X, Y) into (or X, -1) can replace
1351 // the 'or' with -1.
1352 Value *SimplifiedVal;
1353 {
1354 // Sanity check to make sure 'User' doesn't dangle across
1355 // SimplifyInstruction.
1356 AssertingVH<> UserHandle(User);
Duncan Sands12a86f52010-11-14 11:23:23 +00001357
Duncan Sandseff05812010-11-14 18:36:10 +00001358 SimplifiedVal = SimplifyInstruction(User, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001359 if (SimplifiedVal == 0) continue;
Chris Lattner40d8c282009-11-10 22:26:15 +00001360 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001361
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001362 // Recursively simplify this user to the new value.
Duncan Sandseff05812010-11-14 18:36:10 +00001363 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001364 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
1365 To = ToHandle;
Duncan Sands12a86f52010-11-14 11:23:23 +00001366
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001367 assert(ToHandle && "To value deleted by recursive simplification?");
Duncan Sands12a86f52010-11-14 11:23:23 +00001368
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001369 // If the recursive simplification ended up revisiting and deleting
1370 // 'From' then we're done.
1371 if (From == 0)
1372 return;
Chris Lattner40d8c282009-11-10 22:26:15 +00001373 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001374
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001375 // If 'From' has value handles referring to it, do a real RAUW to update them.
1376 From->replaceAllUsesWith(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00001377
Chris Lattner40d8c282009-11-10 22:26:15 +00001378 From->eraseFromParent();
1379}