blob: c81d3defef9fea47f987288bf503f48f782a137c [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
20#include "llvm/Analysis/InstructionSimplify.h"
21#include "llvm/Analysis/ConstantFolding.h"
Duncan Sands18450092010-11-16 12:16:38 +000022#include "llvm/Analysis/Dominators.h"
Chris Lattnerd06094f2009-11-10 00:55:12 +000023#include "llvm/Support/PatternMatch.h"
Duncan Sands18450092010-11-16 12:16:38 +000024#include "llvm/Support/ValueHandle.h"
Duncan Sandse60d79f2010-11-21 13:53:09 +000025#include "llvm/Target/TargetData.h"
Chris Lattner9f3c25a2009-11-09 22:57:59 +000026using namespace llvm;
Chris Lattnerd06094f2009-11-10 00:55:12 +000027using namespace llvm::PatternMatch;
Chris Lattner9f3c25a2009-11-09 22:57:59 +000028
Duncan Sands18450092010-11-16 12:16:38 +000029#define RecursionLimit 3
Duncan Sandsa74a58c2010-11-10 18:23:01 +000030
31static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
Duncan Sands18450092010-11-16 12:16:38 +000032 const DominatorTree *, unsigned);
Duncan Sandsa74a58c2010-11-10 18:23:01 +000033static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
Duncan Sands18450092010-11-16 12:16:38 +000034 const DominatorTree *, unsigned);
35
36/// ValueDominatesPHI - Does the given value dominate the specified phi node?
37static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
38 Instruction *I = dyn_cast<Instruction>(V);
39 if (!I)
40 // Arguments and constants dominate all instructions.
41 return true;
42
43 // If we have a DominatorTree then do a precise test.
44 if (DT)
45 return DT->dominates(I, P);
46
47 // Otherwise, if the instruction is in the entry block, and is not an invoke,
48 // then it obviously dominates all phi nodes.
49 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
50 !isa<InvokeInst>(I))
51 return true;
52
53 return false;
54}
Duncan Sandsa74a58c2010-11-10 18:23:01 +000055
Duncan Sands566edb02010-12-21 08:49:00 +000056// SimplifyAssociativeBinOp - Generic simplifications for associative binary
57// operations. Returns the simpler value, or null if none was found.
58static Value *SimplifyAssociativeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
59 const TargetData *TD,
60 const DominatorTree *DT,
61 unsigned MaxRecurse) {
62 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
63
64 // Recursion is always used, so bail out at once if we already hit the limit.
65 if (!MaxRecurse--)
66 return 0;
67
68 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
69 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
70
71 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
72 if (Op0 && Op0->getOpcode() == Opcode) {
73 Value *A = Op0->getOperand(0);
74 Value *B = Op0->getOperand(1);
75 Value *C = RHS;
76
77 // Does "B op C" simplify?
78 if (Value *V = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
79 // It does! Return "A op V" if it simplifies or is already available.
80 // If V equals B then "A op V" is just the LHS.
81 if (V == B)
82 return LHS;
83 // Otherwise return "A op V" if it simplifies.
84 if (Value *W = SimplifyBinOp(Opcode, A, V, TD, DT, MaxRecurse))
85 return W;
86 }
87 }
88
89 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
90 if (Op1 && Op1->getOpcode() == Opcode) {
91 Value *A = LHS;
92 Value *B = Op1->getOperand(0);
93 Value *C = Op1->getOperand(1);
94
95 // Does "A op B" simplify?
96 if (Value *V = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse)) {
97 // It does! Return "V op C" if it simplifies or is already available.
98 // If V equals B then "V op C" is just the RHS.
99 if (V == B)
100 return RHS;
101 // Otherwise return "V op C" if it simplifies.
102 if (Value *W = SimplifyBinOp(Opcode, V, C, TD, DT, MaxRecurse))
103 return W;
104 }
105 }
106
107 // The remaining transforms require commutativity as well as associativity.
108 if (!Instruction::isCommutative(Opcode))
109 return 0;
110
111 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
112 if (Op0 && Op0->getOpcode() == Opcode) {
113 Value *A = Op0->getOperand(0);
114 Value *B = Op0->getOperand(1);
115 Value *C = RHS;
116
117 // Does "C op A" simplify?
118 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
119 // It does! Return "V op B" if it simplifies or is already available.
120 // If V equals A then "V op B" is just the LHS.
121 if (V == A)
122 return LHS;
123 // Otherwise return "V op B" if it simplifies.
124 if (Value *W = SimplifyBinOp(Opcode, V, B, TD, DT, MaxRecurse))
125 return W;
126 }
127 }
128
129 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
130 if (Op1 && Op1->getOpcode() == Opcode) {
131 Value *A = LHS;
132 Value *B = Op1->getOperand(0);
133 Value *C = Op1->getOperand(1);
134
135 // Does "C op A" simplify?
136 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
137 // It does! Return "B op V" if it simplifies or is already available.
138 // If V equals C then "B op V" is just the RHS.
139 if (V == C)
140 return RHS;
141 // Otherwise return "B op V" if it simplifies.
142 if (Value *W = SimplifyBinOp(Opcode, B, V, TD, DT, MaxRecurse))
143 return W;
144 }
145 }
146
147 return 0;
148}
149
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000150/// ThreadBinOpOverSelect - In the case of a binary operation with a select
151/// instruction as an operand, try to simplify the binop by seeing whether
152/// evaluating it on both branches of the select results in the same value.
153/// Returns the common value if so, otherwise returns null.
154static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000155 const TargetData *TD,
156 const DominatorTree *DT,
157 unsigned MaxRecurse) {
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000158 SelectInst *SI;
159 if (isa<SelectInst>(LHS)) {
160 SI = cast<SelectInst>(LHS);
161 } else {
162 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
163 SI = cast<SelectInst>(RHS);
164 }
165
166 // Evaluate the BinOp on the true and false branches of the select.
167 Value *TV;
168 Value *FV;
169 if (SI == LHS) {
Duncan Sands18450092010-11-16 12:16:38 +0000170 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
171 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000172 } else {
Duncan Sands18450092010-11-16 12:16:38 +0000173 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
174 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000175 }
176
177 // If they simplified to the same value, then return the common value.
178 // If they both failed to simplify then return null.
179 if (TV == FV)
180 return TV;
181
182 // If one branch simplified to undef, return the other one.
183 if (TV && isa<UndefValue>(TV))
184 return FV;
185 if (FV && isa<UndefValue>(FV))
186 return TV;
187
188 // If applying the operation did not change the true and false select values,
189 // then the result of the binop is the select itself.
190 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
191 return SI;
192
193 // If one branch simplified and the other did not, and the simplified
194 // value is equal to the unsimplified one, return the simplified value.
195 // For example, select (cond, X, X & Z) & Z -> X & Z.
196 if ((FV && !TV) || (TV && !FV)) {
197 // Check that the simplified value has the form "X op Y" where "op" is the
198 // same as the original operation.
199 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
200 if (Simplified && Simplified->getOpcode() == Opcode) {
201 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
202 // We already know that "op" is the same as for the simplified value. See
203 // if the operands match too. If so, return the simplified value.
204 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
205 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
206 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
207 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
208 Simplified->getOperand(1) == UnsimplifiedRHS)
209 return Simplified;
210 if (Simplified->isCommutative() &&
211 Simplified->getOperand(1) == UnsimplifiedLHS &&
212 Simplified->getOperand(0) == UnsimplifiedRHS)
213 return Simplified;
214 }
215 }
216
217 return 0;
218}
219
220/// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
221/// try to simplify the comparison by seeing whether both branches of the select
222/// result in the same value. Returns the common value if so, otherwise returns
223/// null.
224static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000225 Value *RHS, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000226 const DominatorTree *DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000227 unsigned MaxRecurse) {
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000228 // Make sure the select is on the LHS.
229 if (!isa<SelectInst>(LHS)) {
230 std::swap(LHS, RHS);
231 Pred = CmpInst::getSwappedPredicate(Pred);
232 }
233 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
234 SelectInst *SI = cast<SelectInst>(LHS);
235
236 // Now that we have "cmp select(cond, TV, FV), RHS", analyse it.
237 // Does "cmp TV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000238 if (Value *TCmp = SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000239 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000240 // It does! Does "cmp FV, RHS" simplify?
Duncan Sands18450092010-11-16 12:16:38 +0000241 if (Value *FCmp = SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000242 MaxRecurse))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000243 // It does! If they simplified to the same value, then use it as the
244 // result of the original comparison.
245 if (TCmp == FCmp)
246 return TCmp;
247 return 0;
248}
249
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000250/// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
251/// is a PHI instruction, try to simplify the binop by seeing whether evaluating
252/// it on the incoming phi values yields the same result for every value. If so
253/// returns the common value, otherwise returns null.
254static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000255 const TargetData *TD, const DominatorTree *DT,
256 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000257 PHINode *PI;
258 if (isa<PHINode>(LHS)) {
259 PI = cast<PHINode>(LHS);
Duncan Sands18450092010-11-16 12:16:38 +0000260 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
261 if (!ValueDominatesPHI(RHS, PI, DT))
262 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000263 } else {
264 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
265 PI = cast<PHINode>(RHS);
Duncan Sands18450092010-11-16 12:16:38 +0000266 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
267 if (!ValueDominatesPHI(LHS, PI, DT))
268 return 0;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000269 }
270
271 // Evaluate the BinOp on the incoming phi values.
272 Value *CommonValue = 0;
273 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000274 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000275 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000276 if (Incoming == PI) continue;
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000277 Value *V = PI == LHS ?
Duncan Sands18450092010-11-16 12:16:38 +0000278 SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
279 SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000280 // If the operation failed to simplify, or simplified to a different value
281 // to previously, then give up.
282 if (!V || (CommonValue && V != CommonValue))
283 return 0;
284 CommonValue = V;
285 }
286
287 return CommonValue;
288}
289
290/// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
291/// try to simplify the comparison by seeing whether comparing with all of the
292/// incoming phi values yields the same result every time. If so returns the
293/// common result, otherwise returns null.
294static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000295 const TargetData *TD, const DominatorTree *DT,
296 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000297 // Make sure the phi is on the LHS.
298 if (!isa<PHINode>(LHS)) {
299 std::swap(LHS, RHS);
300 Pred = CmpInst::getSwappedPredicate(Pred);
301 }
302 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
303 PHINode *PI = cast<PHINode>(LHS);
304
Duncan Sands18450092010-11-16 12:16:38 +0000305 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
306 if (!ValueDominatesPHI(RHS, PI, DT))
307 return 0;
308
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000309 // Evaluate the BinOp on the incoming phi values.
310 Value *CommonValue = 0;
311 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
Duncan Sands55200892010-11-15 17:52:45 +0000312 Value *Incoming = PI->getIncomingValue(i);
Duncan Sandsff103412010-11-17 04:30:22 +0000313 // If the incoming value is the phi node itself, it can safely be skipped.
Duncan Sands55200892010-11-15 17:52:45 +0000314 if (Incoming == PI) continue;
Duncan Sands18450092010-11-16 12:16:38 +0000315 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000316 // If the operation failed to simplify, or simplified to a different value
317 // to previously, then give up.
318 if (!V || (CommonValue && V != CommonValue))
319 return 0;
320 CommonValue = V;
321 }
322
323 return CommonValue;
324}
325
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000326/// SimplifyAddInst - Given operands for an Add, see if we can
327/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000328static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
329 const TargetData *TD, const DominatorTree *DT,
330 unsigned MaxRecurse) {
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000331 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
332 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
333 Constant *Ops[] = { CLHS, CRHS };
334 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
335 Ops, 2, TD);
336 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000337
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000338 // Canonicalize the constant to the RHS.
339 std::swap(Op0, Op1);
340 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000341
Duncan Sandsfea3b212010-12-15 14:07:39 +0000342 // X + undef -> undef
343 if (isa<UndefValue>(Op1))
344 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000345
Duncan Sandsfea3b212010-12-15 14:07:39 +0000346 // X + 0 -> X
347 if (match(Op1, m_Zero()))
348 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000349
Duncan Sandsfea3b212010-12-15 14:07:39 +0000350 // X + (Y - X) -> Y
351 // (Y - X) + X -> Y
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000352 // Eg: X + -X -> 0
Duncan Sandsfea3b212010-12-15 14:07:39 +0000353 Value *Y = 0;
354 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
355 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
356 return Y;
357
358 // X + ~X -> -1 since ~X = -X-1
359 if (match(Op0, m_Not(m_Specific(Op1))) ||
360 match(Op1, m_Not(m_Specific(Op0))))
361 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands87689cf2010-11-19 09:20:39 +0000362
Duncan Sands566edb02010-12-21 08:49:00 +0000363 // Try some generic simplifications for associative operations.
364 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, DT,
365 MaxRecurse))
366 return V;
367
Duncan Sands87689cf2010-11-19 09:20:39 +0000368 // Threading Add over selects and phi nodes is pointless, so don't bother.
369 // Threading over the select in "A + select(cond, B, C)" means evaluating
370 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
371 // only if B and C are equal. If B and C are equal then (since we assume
372 // that operands have already been simplified) "select(cond, B, C)" should
373 // have been simplified to the common value of B and C already. Analysing
374 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
375 // for threading over phi nodes.
376
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000377 return 0;
378}
379
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000380Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
381 const TargetData *TD, const DominatorTree *DT) {
382 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
383}
384
Duncan Sandsfea3b212010-12-15 14:07:39 +0000385/// SimplifySubInst - Given operands for a Sub, see if we can
386/// fold the result. If not, this returns null.
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000387static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
388 const TargetData *TD, const DominatorTree *,
389 unsigned MaxRecurse) {
Duncan Sandsfea3b212010-12-15 14:07:39 +0000390 if (Constant *CLHS = dyn_cast<Constant>(Op0))
391 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
392 Constant *Ops[] = { CLHS, CRHS };
393 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
394 Ops, 2, TD);
395 }
396
397 // X - undef -> undef
398 // undef - X -> undef
399 if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
400 return UndefValue::get(Op0->getType());
401
402 // X - 0 -> X
403 if (match(Op1, m_Zero()))
404 return Op0;
405
406 // X - X -> 0
407 if (Op0 == Op1)
408 return Constant::getNullValue(Op0->getType());
409
410 // (X + Y) - Y -> X
411 // (Y + X) - Y -> X
412 Value *X = 0;
413 if (match(Op0, m_Add(m_Value(X), m_Specific(Op1))) ||
414 match(Op0, m_Add(m_Specific(Op1), m_Value(X))))
415 return X;
416
417 // Threading Sub over selects and phi nodes is pointless, so don't bother.
418 // Threading over the select in "A - select(cond, B, C)" means evaluating
419 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
420 // only if B and C are equal. If B and C are equal then (since we assume
421 // that operands have already been simplified) "select(cond, B, C)" should
422 // have been simplified to the common value of B and C already. Analysing
423 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
424 // for threading over phi nodes.
425
426 return 0;
427}
428
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000429Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
430 const TargetData *TD, const DominatorTree *DT) {
431 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
432}
433
Chris Lattnerd06094f2009-11-10 00:55:12 +0000434/// SimplifyAndInst - Given operands for an And, see if we can
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000435/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000436static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000437 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000438 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
439 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
440 Constant *Ops[] = { CLHS, CRHS };
441 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
442 Ops, 2, TD);
443 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000444
Chris Lattnerd06094f2009-11-10 00:55:12 +0000445 // Canonicalize the constant to the RHS.
446 std::swap(Op0, Op1);
447 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000448
Chris Lattnerd06094f2009-11-10 00:55:12 +0000449 // X & undef -> 0
450 if (isa<UndefValue>(Op1))
451 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000452
Chris Lattnerd06094f2009-11-10 00:55:12 +0000453 // X & X = X
454 if (Op0 == Op1)
455 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000456
Duncan Sands2b749872010-11-17 18:52:15 +0000457 // X & 0 = 0
458 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000459 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000460
Duncan Sands2b749872010-11-17 18:52:15 +0000461 // X & -1 = X
462 if (match(Op1, m_AllOnes()))
463 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000464
Chris Lattnerd06094f2009-11-10 00:55:12 +0000465 // A & ~A = ~A & A = 0
Chandler Carruthe89ada92010-11-29 01:41:13 +0000466 Value *A = 0, *B = 0;
Chris Lattner70ce6d02009-11-10 02:04:54 +0000467 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
468 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000469 return Constant::getNullValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000470
Chris Lattnerd06094f2009-11-10 00:55:12 +0000471 // (A | ?) & A = A
472 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
473 (A == Op1 || B == Op1))
474 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000475
Chris Lattnerd06094f2009-11-10 00:55:12 +0000476 // A & (A | ?) = A
477 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
478 (A == Op0 || B == Op0))
479 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000480
Duncan Sands566edb02010-12-21 08:49:00 +0000481 // Try some generic simplifications for associative operations.
482 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, DT,
483 MaxRecurse))
484 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +0000485
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000486 // If the operation is with the result of a select instruction, check whether
487 // operating on either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000488 if (MaxRecurse && (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)))
Duncan Sands18450092010-11-16 12:16:38 +0000489 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000490 MaxRecurse-1))
491 return V;
492
493 // If the operation is with the result of a phi instruction, check whether
494 // operating on all incoming values of the phi always yields the same value.
495 if (MaxRecurse && (isa<PHINode>(Op0) || isa<PHINode>(Op1)))
Duncan Sands18450092010-11-16 12:16:38 +0000496 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000497 MaxRecurse-1))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000498 return V;
499
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000500 return 0;
501}
502
Duncan Sands18450092010-11-16 12:16:38 +0000503Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
504 const DominatorTree *DT) {
505 return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000506}
507
Chris Lattnerd06094f2009-11-10 00:55:12 +0000508/// SimplifyOrInst - Given operands for an Or, see if we can
509/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000510static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
Duncan Sands18450092010-11-16 12:16:38 +0000511 const DominatorTree *DT, unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000512 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
513 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
514 Constant *Ops[] = { CLHS, CRHS };
515 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
516 Ops, 2, TD);
517 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000518
Chris Lattnerd06094f2009-11-10 00:55:12 +0000519 // Canonicalize the constant to the RHS.
520 std::swap(Op0, Op1);
521 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000522
Chris Lattnerd06094f2009-11-10 00:55:12 +0000523 // X | undef -> -1
524 if (isa<UndefValue>(Op1))
525 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000526
Chris Lattnerd06094f2009-11-10 00:55:12 +0000527 // X | X = X
528 if (Op0 == Op1)
529 return Op0;
530
Duncan Sands2b749872010-11-17 18:52:15 +0000531 // X | 0 = X
532 if (match(Op1, m_Zero()))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000533 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000534
Duncan Sands2b749872010-11-17 18:52:15 +0000535 // X | -1 = -1
536 if (match(Op1, m_AllOnes()))
537 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000538
Chris Lattnerd06094f2009-11-10 00:55:12 +0000539 // A | ~A = ~A | A = -1
Chandler Carruthe89ada92010-11-29 01:41:13 +0000540 Value *A = 0, *B = 0;
Chris Lattner70ce6d02009-11-10 02:04:54 +0000541 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
542 (match(Op1, m_Not(m_Value(A))) && A == Op0))
Chris Lattnerd06094f2009-11-10 00:55:12 +0000543 return Constant::getAllOnesValue(Op0->getType());
Duncan Sands12a86f52010-11-14 11:23:23 +0000544
Chris Lattnerd06094f2009-11-10 00:55:12 +0000545 // (A & ?) | A = A
546 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
547 (A == Op1 || B == Op1))
548 return Op1;
Duncan Sands12a86f52010-11-14 11:23:23 +0000549
Chris Lattnerd06094f2009-11-10 00:55:12 +0000550 // A | (A & ?) = A
551 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
552 (A == Op0 || B == Op0))
553 return Op0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000554
Duncan Sands566edb02010-12-21 08:49:00 +0000555 // Try some generic simplifications for associative operations.
556 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, DT,
557 MaxRecurse))
558 return V;
Benjamin Kramer6844c8e2010-09-10 22:39:55 +0000559
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000560 // If the operation is with the result of a select instruction, check whether
561 // operating on either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000562 if (MaxRecurse && (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)))
Duncan Sands18450092010-11-16 12:16:38 +0000563 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000564 MaxRecurse-1))
565 return V;
566
567 // If the operation is with the result of a phi instruction, check whether
568 // operating on all incoming values of the phi always yields the same value.
569 if (MaxRecurse && (isa<PHINode>(Op0) || isa<PHINode>(Op1)))
Duncan Sands18450092010-11-16 12:16:38 +0000570 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000571 MaxRecurse-1))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000572 return V;
573
Chris Lattnerd06094f2009-11-10 00:55:12 +0000574 return 0;
575}
576
Duncan Sands18450092010-11-16 12:16:38 +0000577Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
578 const DominatorTree *DT) {
579 return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000580}
Chris Lattnerd06094f2009-11-10 00:55:12 +0000581
Duncan Sands2b749872010-11-17 18:52:15 +0000582/// SimplifyXorInst - Given operands for a Xor, see if we can
583/// fold the result. If not, this returns null.
584static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
585 const DominatorTree *DT, unsigned MaxRecurse) {
586 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
587 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
588 Constant *Ops[] = { CLHS, CRHS };
589 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
590 Ops, 2, TD);
591 }
592
593 // Canonicalize the constant to the RHS.
594 std::swap(Op0, Op1);
595 }
596
597 // A ^ undef -> undef
598 if (isa<UndefValue>(Op1))
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +0000599 return Op1;
Duncan Sands2b749872010-11-17 18:52:15 +0000600
601 // A ^ 0 = A
602 if (match(Op1, m_Zero()))
603 return Op0;
604
605 // A ^ A = 0
606 if (Op0 == Op1)
607 return Constant::getNullValue(Op0->getType());
608
609 // A ^ ~A = ~A ^ A = -1
Duncan Sands566edb02010-12-21 08:49:00 +0000610 Value *A = 0;
Duncan Sands2b749872010-11-17 18:52:15 +0000611 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
612 (match(Op1, m_Not(m_Value(A))) && A == Op0))
613 return Constant::getAllOnesValue(Op0->getType());
614
Duncan Sands566edb02010-12-21 08:49:00 +0000615 // Try some generic simplifications for associative operations.
616 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, DT,
617 MaxRecurse))
618 return V;
Duncan Sands2b749872010-11-17 18:52:15 +0000619
Duncan Sands87689cf2010-11-19 09:20:39 +0000620 // Threading Xor over selects and phi nodes is pointless, so don't bother.
621 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
622 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
623 // only if B and C are equal. If B and C are equal then (since we assume
624 // that operands have already been simplified) "select(cond, B, C)" should
625 // have been simplified to the common value of B and C already. Analysing
626 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
627 // for threading over phi nodes.
Duncan Sands2b749872010-11-17 18:52:15 +0000628
629 return 0;
630}
631
632Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
633 const DominatorTree *DT) {
634 return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
635}
636
Chris Lattner210c5d42009-11-09 23:55:12 +0000637static const Type *GetCompareTy(Value *Op) {
638 return CmpInst::makeCmpResultType(Op->getType());
639}
640
Chris Lattner9dbb4292009-11-09 23:28:39 +0000641/// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
642/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000643static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000644 const TargetData *TD, const DominatorTree *DT,
645 unsigned MaxRecurse) {
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000646 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
Chris Lattner9dbb4292009-11-09 23:28:39 +0000647 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
Duncan Sands12a86f52010-11-14 11:23:23 +0000648
Chris Lattnerd06094f2009-11-10 00:55:12 +0000649 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner8f73dea2009-11-09 23:06:58 +0000650 if (Constant *CRHS = dyn_cast<Constant>(RHS))
651 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Chris Lattnerd06094f2009-11-10 00:55:12 +0000652
653 // If we have a constant, make sure it is on the RHS.
654 std::swap(LHS, RHS);
655 Pred = CmpInst::getSwappedPredicate(Pred);
656 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000657
Chris Lattner210c5d42009-11-09 23:55:12 +0000658 // ITy - This is the return type of the compare we're considering.
659 const Type *ITy = GetCompareTy(LHS);
Duncan Sands12a86f52010-11-14 11:23:23 +0000660
Chris Lattner210c5d42009-11-09 23:55:12 +0000661 // icmp X, X -> true/false
Chris Lattnerc8e14b32010-03-03 19:46:03 +0000662 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
663 // because X could be 0.
664 if (LHS == RHS || isa<UndefValue>(RHS))
Chris Lattner210c5d42009-11-09 23:55:12 +0000665 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +0000666
Chris Lattner210c5d42009-11-09 23:55:12 +0000667 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
668 // addresses never equal each other! We already know that Op0 != Op1.
Duncan Sands12a86f52010-11-14 11:23:23 +0000669 if ((isa<GlobalValue>(LHS) || isa<AllocaInst>(LHS) ||
Chris Lattner210c5d42009-11-09 23:55:12 +0000670 isa<ConstantPointerNull>(LHS)) &&
Duncan Sands12a86f52010-11-14 11:23:23 +0000671 (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
Chris Lattner210c5d42009-11-09 23:55:12 +0000672 isa<ConstantPointerNull>(RHS)))
673 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
Duncan Sands12a86f52010-11-14 11:23:23 +0000674
Chris Lattner210c5d42009-11-09 23:55:12 +0000675 // See if we are doing a comparison with a constant.
676 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
677 // If we have an icmp le or icmp ge instruction, turn it into the
678 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
679 // them being folded in the code below.
680 switch (Pred) {
681 default: break;
682 case ICmpInst::ICMP_ULE:
683 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
684 return ConstantInt::getTrue(CI->getContext());
685 break;
686 case ICmpInst::ICMP_SLE:
687 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
688 return ConstantInt::getTrue(CI->getContext());
689 break;
690 case ICmpInst::ICMP_UGE:
691 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
692 return ConstantInt::getTrue(CI->getContext());
693 break;
694 case ICmpInst::ICMP_SGE:
695 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
696 return ConstantInt::getTrue(CI->getContext());
697 break;
698 }
Chris Lattner210c5d42009-11-09 23:55:12 +0000699 }
Duncan Sands1ac7c992010-11-07 16:12:23 +0000700
701 // If the comparison is with the result of a select instruction, check whether
702 // comparing with either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000703 if (MaxRecurse && (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000704 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000705 return V;
706
707 // If the comparison is with the result of a phi instruction, check whether
708 // doing the compare with each incoming phi value yields a common result.
709 if (MaxRecurse && (isa<PHINode>(LHS) || isa<PHINode>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000710 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +0000711 return V;
Duncan Sands1ac7c992010-11-07 16:12:23 +0000712
Chris Lattner9f3c25a2009-11-09 22:57:59 +0000713 return 0;
714}
715
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000716Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000717 const TargetData *TD, const DominatorTree *DT) {
718 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000719}
720
Chris Lattner9dbb4292009-11-09 23:28:39 +0000721/// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
722/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000723static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000724 const TargetData *TD, const DominatorTree *DT,
725 unsigned MaxRecurse) {
Chris Lattner9dbb4292009-11-09 23:28:39 +0000726 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
727 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
728
Chris Lattnerd06094f2009-11-10 00:55:12 +0000729 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
Chris Lattner9dbb4292009-11-09 23:28:39 +0000730 if (Constant *CRHS = dyn_cast<Constant>(RHS))
731 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
Duncan Sands12a86f52010-11-14 11:23:23 +0000732
Chris Lattnerd06094f2009-11-10 00:55:12 +0000733 // If we have a constant, make sure it is on the RHS.
734 std::swap(LHS, RHS);
735 Pred = CmpInst::getSwappedPredicate(Pred);
736 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000737
Chris Lattner210c5d42009-11-09 23:55:12 +0000738 // Fold trivial predicates.
739 if (Pred == FCmpInst::FCMP_FALSE)
740 return ConstantInt::get(GetCompareTy(LHS), 0);
741 if (Pred == FCmpInst::FCMP_TRUE)
742 return ConstantInt::get(GetCompareTy(LHS), 1);
743
Chris Lattner210c5d42009-11-09 23:55:12 +0000744 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
745 return UndefValue::get(GetCompareTy(LHS));
746
747 // fcmp x,x -> true/false. Not all compares are foldable.
748 if (LHS == RHS) {
749 if (CmpInst::isTrueWhenEqual(Pred))
750 return ConstantInt::get(GetCompareTy(LHS), 1);
751 if (CmpInst::isFalseWhenEqual(Pred))
752 return ConstantInt::get(GetCompareTy(LHS), 0);
753 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000754
Chris Lattner210c5d42009-11-09 23:55:12 +0000755 // Handle fcmp with constant RHS
756 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
757 // If the constant is a nan, see if we can fold the comparison based on it.
758 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
759 if (CFP->getValueAPF().isNaN()) {
760 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
761 return ConstantInt::getFalse(CFP->getContext());
762 assert(FCmpInst::isUnordered(Pred) &&
763 "Comparison must be either ordered or unordered!");
764 // True if unordered.
765 return ConstantInt::getTrue(CFP->getContext());
766 }
Dan Gohman6b617a72010-02-22 04:06:03 +0000767 // Check whether the constant is an infinity.
768 if (CFP->getValueAPF().isInfinity()) {
769 if (CFP->getValueAPF().isNegative()) {
770 switch (Pred) {
771 case FCmpInst::FCMP_OLT:
772 // No value is ordered and less than negative infinity.
773 return ConstantInt::getFalse(CFP->getContext());
774 case FCmpInst::FCMP_UGE:
775 // All values are unordered with or at least negative infinity.
776 return ConstantInt::getTrue(CFP->getContext());
777 default:
778 break;
779 }
780 } else {
781 switch (Pred) {
782 case FCmpInst::FCMP_OGT:
783 // No value is ordered and greater than infinity.
784 return ConstantInt::getFalse(CFP->getContext());
785 case FCmpInst::FCMP_ULE:
786 // All values are unordered with and at most infinity.
787 return ConstantInt::getTrue(CFP->getContext());
788 default:
789 break;
790 }
791 }
792 }
Chris Lattner210c5d42009-11-09 23:55:12 +0000793 }
794 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000795
Duncan Sands92826de2010-11-07 16:46:25 +0000796 // If the comparison is with the result of a select instruction, check whether
797 // comparing with either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000798 if (MaxRecurse && (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000799 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000800 return V;
801
802 // If the comparison is with the result of a phi instruction, check whether
803 // doing the compare with each incoming phi value yields a common result.
804 if (MaxRecurse && (isa<PHINode>(LHS) || isa<PHINode>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000805 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sands3bbb0cc2010-11-09 17:25:51 +0000806 return V;
Duncan Sands92826de2010-11-07 16:46:25 +0000807
Chris Lattner9dbb4292009-11-09 23:28:39 +0000808 return 0;
809}
810
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000811Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000812 const TargetData *TD, const DominatorTree *DT) {
813 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000814}
815
Chris Lattner04754262010-04-20 05:32:14 +0000816/// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
817/// the result. If not, this returns null.
818Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
Duncan Sands18450092010-11-16 12:16:38 +0000819 const TargetData *TD, const DominatorTree *) {
Chris Lattner04754262010-04-20 05:32:14 +0000820 // select true, X, Y -> X
821 // select false, X, Y -> Y
822 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
823 return CB->getZExtValue() ? TrueVal : FalseVal;
Duncan Sands12a86f52010-11-14 11:23:23 +0000824
Chris Lattner04754262010-04-20 05:32:14 +0000825 // select C, X, X -> X
826 if (TrueVal == FalseVal)
827 return TrueVal;
Duncan Sands12a86f52010-11-14 11:23:23 +0000828
Chris Lattner04754262010-04-20 05:32:14 +0000829 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
830 return FalseVal;
831 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
832 return TrueVal;
833 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
834 if (isa<Constant>(TrueVal))
835 return TrueVal;
836 return FalseVal;
837 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000838
Chris Lattner04754262010-04-20 05:32:14 +0000839 return 0;
840}
841
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000842/// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
843/// fold the result. If not, this returns null.
844Value *llvm::SimplifyGEPInst(Value *const *Ops, unsigned NumOps,
Duncan Sands18450092010-11-16 12:16:38 +0000845 const TargetData *TD, const DominatorTree *) {
Duncan Sands85bbff62010-11-22 13:42:49 +0000846 // The type of the GEP pointer operand.
847 const PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
848
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000849 // getelementptr P -> P.
850 if (NumOps == 1)
851 return Ops[0];
852
Duncan Sands85bbff62010-11-22 13:42:49 +0000853 if (isa<UndefValue>(Ops[0])) {
854 // Compute the (pointer) type returned by the GEP instruction.
855 const Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, &Ops[1],
856 NumOps-1);
857 const Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
858 return UndefValue::get(GEPTy);
859 }
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000860
Duncan Sandse60d79f2010-11-21 13:53:09 +0000861 if (NumOps == 2) {
862 // getelementptr P, 0 -> P.
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000863 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
864 if (C->isZero())
865 return Ops[0];
Duncan Sandse60d79f2010-11-21 13:53:09 +0000866 // getelementptr P, N -> P if P points to a type of zero size.
867 if (TD) {
Duncan Sands85bbff62010-11-22 13:42:49 +0000868 const Type *Ty = PtrTy->getElementType();
Duncan Sandsa63395a2010-11-22 16:32:50 +0000869 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
Duncan Sandse60d79f2010-11-21 13:53:09 +0000870 return Ops[0];
871 }
872 }
Duncan Sands12a86f52010-11-14 11:23:23 +0000873
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000874 // Check to see if this is constant foldable.
875 for (unsigned i = 0; i != NumOps; ++i)
876 if (!isa<Constant>(Ops[i]))
877 return 0;
Duncan Sands12a86f52010-11-14 11:23:23 +0000878
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000879 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]),
880 (Constant *const*)Ops+1, NumOps-1);
881}
882
Duncan Sandsff103412010-11-17 04:30:22 +0000883/// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
884static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
885 // If all of the PHI's incoming values are the same then replace the PHI node
886 // with the common value.
887 Value *CommonValue = 0;
888 bool HasUndefInput = false;
889 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
890 Value *Incoming = PN->getIncomingValue(i);
891 // If the incoming value is the phi node itself, it can safely be skipped.
892 if (Incoming == PN) continue;
893 if (isa<UndefValue>(Incoming)) {
894 // Remember that we saw an undef value, but otherwise ignore them.
895 HasUndefInput = true;
896 continue;
897 }
898 if (CommonValue && Incoming != CommonValue)
899 return 0; // Not the same, bail out.
900 CommonValue = Incoming;
901 }
902
903 // If CommonValue is null then all of the incoming values were either undef or
904 // equal to the phi node itself.
905 if (!CommonValue)
906 return UndefValue::get(PN->getType());
907
908 // If we have a PHI node like phi(X, undef, X), where X is defined by some
909 // instruction, we cannot return X as the result of the PHI node unless it
910 // dominates the PHI block.
911 if (HasUndefInput)
912 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
913
914 return CommonValue;
915}
916
Chris Lattnerc514c1f2009-11-27 00:29:05 +0000917
Chris Lattnerd06094f2009-11-10 00:55:12 +0000918//=== Helper functions for higher up the class hierarchy.
Chris Lattner9dbb4292009-11-09 23:28:39 +0000919
Chris Lattnerd06094f2009-11-10 00:55:12 +0000920/// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
921/// fold the result. If not, this returns null.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000922static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000923 const TargetData *TD, const DominatorTree *DT,
924 unsigned MaxRecurse) {
Chris Lattnerd06094f2009-11-10 00:55:12 +0000925 switch (Opcode) {
Duncan Sands18450092010-11-16 12:16:38 +0000926 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
927 case Instruction::Or: return SimplifyOrInst(LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsee9a2e32010-12-20 14:47:04 +0000928 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecurse);
929 case Instruction::Add: return SimplifyAddInst(LHS, RHS, /* isNSW */ false,
930 /* isNUW */ false, TD, DT,
931 MaxRecurse);
932 case Instruction::Sub: return SimplifySubInst(LHS, RHS, /* isNSW */ false,
933 /* isNUW */ false, TD, DT,
934 MaxRecurse);
Chris Lattnerd06094f2009-11-10 00:55:12 +0000935 default:
936 if (Constant *CLHS = dyn_cast<Constant>(LHS))
937 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
938 Constant *COps[] = {CLHS, CRHS};
939 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, 2, TD);
940 }
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000941
Duncan Sands566edb02010-12-21 08:49:00 +0000942 // If the operation is associative, try some generic simplifications.
943 if (Instruction::isAssociative(Opcode))
944 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, DT,
945 MaxRecurse))
946 return V;
947
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000948 // If the operation is with the result of a select instruction, check whether
949 // operating on either branch of the select always yields the same value.
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000950 if (MaxRecurse && (isa<SelectInst>(LHS) || isa<SelectInst>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000951 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
952 MaxRecurse-1))
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000953 return V;
954
955 // If the operation is with the result of a phi instruction, check whether
956 // operating on all incoming values of the phi always yields the same value.
957 if (MaxRecurse && (isa<PHINode>(LHS) || isa<PHINode>(RHS)))
Duncan Sands18450092010-11-16 12:16:38 +0000958 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse-1))
Duncan Sandsb2cbdc32010-11-10 13:00:08 +0000959 return V;
960
Chris Lattnerd06094f2009-11-10 00:55:12 +0000961 return 0;
962 }
963}
Chris Lattner9dbb4292009-11-09 23:28:39 +0000964
Duncan Sands12a86f52010-11-14 11:23:23 +0000965Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000966 const TargetData *TD, const DominatorTree *DT) {
967 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
Chris Lattner9dbb4292009-11-09 23:28:39 +0000968}
969
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000970/// SimplifyCmpInst - Given operands for a CmpInst, see if we can
971/// fold the result.
972static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000973 const TargetData *TD, const DominatorTree *DT,
974 unsigned MaxRecurse) {
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000975 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
Duncan Sands18450092010-11-16 12:16:38 +0000976 return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
977 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000978}
979
980Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
Duncan Sands18450092010-11-16 12:16:38 +0000981 const TargetData *TD, const DominatorTree *DT) {
982 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
Duncan Sandsa74a58c2010-11-10 18:23:01 +0000983}
Chris Lattnere3453782009-11-10 01:08:51 +0000984
985/// SimplifyInstruction - See if we can compute a simplified version of this
986/// instruction. If not, this returns null.
Duncan Sandseff05812010-11-14 18:36:10 +0000987Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
988 const DominatorTree *DT) {
Duncan Sandsd261dc62010-11-17 08:35:29 +0000989 Value *Result;
990
Chris Lattnere3453782009-11-10 01:08:51 +0000991 switch (I->getOpcode()) {
992 default:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000993 Result = ConstantFoldInstruction(I, TD);
994 break;
Chris Lattner8aee8ef2009-11-27 17:42:22 +0000995 case Instruction::Add:
Duncan Sandsd261dc62010-11-17 08:35:29 +0000996 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
997 cast<BinaryOperator>(I)->hasNoSignedWrap(),
998 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
999 TD, DT);
1000 break;
Duncan Sandsfea3b212010-12-15 14:07:39 +00001001 case Instruction::Sub:
1002 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
1003 cast<BinaryOperator>(I)->hasNoSignedWrap(),
1004 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
1005 TD, DT);
1006 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001007 case Instruction::And:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001008 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
1009 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001010 case Instruction::Or:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001011 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
1012 break;
Duncan Sands2b749872010-11-17 18:52:15 +00001013 case Instruction::Xor:
1014 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
1015 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001016 case Instruction::ICmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001017 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
1018 I->getOperand(0), I->getOperand(1), TD, DT);
1019 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001020 case Instruction::FCmp:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001021 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
1022 I->getOperand(0), I->getOperand(1), TD, DT);
1023 break;
Chris Lattner04754262010-04-20 05:32:14 +00001024 case Instruction::Select:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001025 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
1026 I->getOperand(2), TD, DT);
1027 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001028 case Instruction::GetElementPtr: {
1029 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
Duncan Sandsd261dc62010-11-17 08:35:29 +00001030 Result = SimplifyGEPInst(&Ops[0], Ops.size(), TD, DT);
1031 break;
Chris Lattnerc514c1f2009-11-27 00:29:05 +00001032 }
Duncan Sandscd6636c2010-11-14 13:30:18 +00001033 case Instruction::PHI:
Duncan Sandsd261dc62010-11-17 08:35:29 +00001034 Result = SimplifyPHINode(cast<PHINode>(I), DT);
1035 break;
Chris Lattnere3453782009-11-10 01:08:51 +00001036 }
Duncan Sandsd261dc62010-11-17 08:35:29 +00001037
1038 /// If called on unreachable code, the above logic may report that the
1039 /// instruction simplified to itself. Make life easier for users by
Duncan Sandsf8b1a5e2010-12-15 11:02:22 +00001040 /// detecting that case here, returning a safe value instead.
1041 return Result == I ? UndefValue::get(I->getType()) : Result;
Chris Lattnere3453782009-11-10 01:08:51 +00001042}
1043
Chris Lattner40d8c282009-11-10 22:26:15 +00001044/// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
1045/// delete the From instruction. In addition to a basic RAUW, this does a
1046/// recursive simplification of the newly formed instructions. This catches
1047/// things where one simplification exposes other opportunities. This only
1048/// simplifies and deletes scalar operations, it does not change the CFG.
1049///
1050void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
Duncan Sandseff05812010-11-14 18:36:10 +00001051 const TargetData *TD,
1052 const DominatorTree *DT) {
Chris Lattner40d8c282009-11-10 22:26:15 +00001053 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
Duncan Sands12a86f52010-11-14 11:23:23 +00001054
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001055 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
1056 // we can know if it gets deleted out from under us or replaced in a
1057 // recursive simplification.
Chris Lattner40d8c282009-11-10 22:26:15 +00001058 WeakVH FromHandle(From);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001059 WeakVH ToHandle(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00001060
Chris Lattner40d8c282009-11-10 22:26:15 +00001061 while (!From->use_empty()) {
1062 // Update the instruction to use the new value.
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001063 Use &TheUse = From->use_begin().getUse();
1064 Instruction *User = cast<Instruction>(TheUse.getUser());
1065 TheUse = To;
1066
1067 // Check to see if the instruction can be folded due to the operand
1068 // replacement. For example changing (or X, Y) into (or X, -1) can replace
1069 // the 'or' with -1.
1070 Value *SimplifiedVal;
1071 {
1072 // Sanity check to make sure 'User' doesn't dangle across
1073 // SimplifyInstruction.
1074 AssertingVH<> UserHandle(User);
Duncan Sands12a86f52010-11-14 11:23:23 +00001075
Duncan Sandseff05812010-11-14 18:36:10 +00001076 SimplifiedVal = SimplifyInstruction(User, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001077 if (SimplifiedVal == 0) continue;
Chris Lattner40d8c282009-11-10 22:26:15 +00001078 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001079
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001080 // Recursively simplify this user to the new value.
Duncan Sandseff05812010-11-14 18:36:10 +00001081 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001082 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
1083 To = ToHandle;
Duncan Sands12a86f52010-11-14 11:23:23 +00001084
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001085 assert(ToHandle && "To value deleted by recursive simplification?");
Duncan Sands12a86f52010-11-14 11:23:23 +00001086
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001087 // If the recursive simplification ended up revisiting and deleting
1088 // 'From' then we're done.
1089 if (From == 0)
1090 return;
Chris Lattner40d8c282009-11-10 22:26:15 +00001091 }
Duncan Sands12a86f52010-11-14 11:23:23 +00001092
Chris Lattnerd2bfe542010-07-15 06:36:08 +00001093 // If 'From' has value handles referring to it, do a real RAUW to update them.
1094 From->replaceAllUsesWith(To);
Duncan Sands12a86f52010-11-14 11:23:23 +00001095
Chris Lattner40d8c282009-11-10 22:26:15 +00001096 From->eraseFromParent();
1097}