1 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements routines for folding instructions into simpler forms
11 // 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
14 // ("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).
18 //===----------------------------------------------------------------------===//
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/Analysis/ConstantFolding.h"
22 #include "llvm/Analysis/Dominators.h"
23 #include "llvm/Support/PatternMatch.h"
24 #include "llvm/Support/ValueHandle.h"
25 #include "llvm/Target/TargetData.h"
27 using namespace llvm::PatternMatch;
29 #define RecursionLimit 3
31 static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
32 const DominatorTree *, unsigned);
33 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
34 const DominatorTree *, unsigned);
36 /// ValueDominatesPHI - Does the given value dominate the specified phi node?
37 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
38 Instruction *I = dyn_cast<Instruction>(V);
40 // Arguments and constants dominate all instructions.
43 // If we have a DominatorTree then do a precise test.
45 return DT->dominates(I, P);
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() &&
56 // SimplifyAssociativeBinOp - Generic simplifications for associative binary
57 // operations. Returns the simpler value, or null if none was found.
58 static Value *SimplifyAssociativeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
60 const DominatorTree *DT,
61 unsigned MaxRecurse) {
62 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
64 // Recursion is always used, so bail out at once if we already hit the limit.
68 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
69 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
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);
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.
83 // Otherwise return "A op V" if it simplifies.
84 if (Value *W = SimplifyBinOp(Opcode, A, V, TD, DT, MaxRecurse))
89 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
90 if (Op1 && Op1->getOpcode() == Opcode) {
92 Value *B = Op1->getOperand(0);
93 Value *C = Op1->getOperand(1);
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.
101 // Otherwise return "V op C" if it simplifies.
102 if (Value *W = SimplifyBinOp(Opcode, V, C, TD, DT, MaxRecurse))
107 // The remaining transforms require commutativity as well as associativity.
108 if (!Instruction::isCommutative(Opcode))
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);
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.
123 // Otherwise return "V op B" if it simplifies.
124 if (Value *W = SimplifyBinOp(Opcode, V, B, TD, DT, MaxRecurse))
129 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
130 if (Op1 && Op1->getOpcode() == Opcode) {
132 Value *B = Op1->getOperand(0);
133 Value *C = Op1->getOperand(1);
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.
141 // Otherwise return "B op V" if it simplifies.
142 if (Value *W = SimplifyBinOp(Opcode, B, V, TD, DT, MaxRecurse))
150 /// 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.
154 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
155 const TargetData *TD,
156 const DominatorTree *DT,
157 unsigned MaxRecurse) {
158 // Recursion is always used, so bail out at once if we already hit the limit.
163 if (isa<SelectInst>(LHS)) {
164 SI = cast<SelectInst>(LHS);
166 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
167 SI = cast<SelectInst>(RHS);
170 // Evaluate the BinOp on the true and false branches of the select.
174 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
175 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
177 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
178 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
181 // If they simplified to the same value, then return the common value.
182 // If they both failed to simplify then return null.
186 // If one branch simplified to undef, return the other one.
187 if (TV && isa<UndefValue>(TV))
189 if (FV && isa<UndefValue>(FV))
192 // If applying the operation did not change the true and false select values,
193 // then the result of the binop is the select itself.
194 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
197 // If one branch simplified and the other did not, and the simplified
198 // value is equal to the unsimplified one, return the simplified value.
199 // For example, select (cond, X, X & Z) & Z -> X & Z.
200 if ((FV && !TV) || (TV && !FV)) {
201 // Check that the simplified value has the form "X op Y" where "op" is the
202 // same as the original operation.
203 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
204 if (Simplified && Simplified->getOpcode() == Opcode) {
205 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
206 // We already know that "op" is the same as for the simplified value. See
207 // if the operands match too. If so, return the simplified value.
208 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
209 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
210 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
211 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
212 Simplified->getOperand(1) == UnsimplifiedRHS)
214 if (Simplified->isCommutative() &&
215 Simplified->getOperand(1) == UnsimplifiedLHS &&
216 Simplified->getOperand(0) == UnsimplifiedRHS)
224 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
225 /// try to simplify the comparison by seeing whether both branches of the select
226 /// result in the same value. Returns the common value if so, otherwise returns
228 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
229 Value *RHS, const TargetData *TD,
230 const DominatorTree *DT,
231 unsigned MaxRecurse) {
232 // Recursion is always used, so bail out at once if we already hit the limit.
236 // Make sure the select is on the LHS.
237 if (!isa<SelectInst>(LHS)) {
239 Pred = CmpInst::getSwappedPredicate(Pred);
241 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
242 SelectInst *SI = cast<SelectInst>(LHS);
244 // Now that we have "cmp select(cond, TV, FV), RHS", analyse it.
245 // Does "cmp TV, RHS" simplify?
246 if (Value *TCmp = SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, DT,
248 // It does! Does "cmp FV, RHS" simplify?
249 if (Value *FCmp = SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD, DT,
251 // It does! If they simplified to the same value, then use it as the
252 // result of the original comparison.
258 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
259 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
260 /// it on the incoming phi values yields the same result for every value. If so
261 /// returns the common value, otherwise returns null.
262 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
263 const TargetData *TD, const DominatorTree *DT,
264 unsigned MaxRecurse) {
265 // Recursion is always used, so bail out at once if we already hit the limit.
270 if (isa<PHINode>(LHS)) {
271 PI = cast<PHINode>(LHS);
272 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
273 if (!ValueDominatesPHI(RHS, PI, DT))
276 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
277 PI = cast<PHINode>(RHS);
278 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
279 if (!ValueDominatesPHI(LHS, PI, DT))
283 // Evaluate the BinOp on the incoming phi values.
284 Value *CommonValue = 0;
285 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
286 Value *Incoming = PI->getIncomingValue(i);
287 // If the incoming value is the phi node itself, it can safely be skipped.
288 if (Incoming == PI) continue;
289 Value *V = PI == LHS ?
290 SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
291 SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
292 // If the operation failed to simplify, or simplified to a different value
293 // to previously, then give up.
294 if (!V || (CommonValue && V != CommonValue))
302 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
303 /// try to simplify the comparison by seeing whether comparing with all of the
304 /// incoming phi values yields the same result every time. If so returns the
305 /// common result, otherwise returns null.
306 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
307 const TargetData *TD, const DominatorTree *DT,
308 unsigned MaxRecurse) {
309 // Recursion is always used, so bail out at once if we already hit the limit.
313 // Make sure the phi is on the LHS.
314 if (!isa<PHINode>(LHS)) {
316 Pred = CmpInst::getSwappedPredicate(Pred);
318 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
319 PHINode *PI = cast<PHINode>(LHS);
321 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
322 if (!ValueDominatesPHI(RHS, PI, DT))
325 // Evaluate the BinOp on the incoming phi values.
326 Value *CommonValue = 0;
327 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
328 Value *Incoming = PI->getIncomingValue(i);
329 // If the incoming value is the phi node itself, it can safely be skipped.
330 if (Incoming == PI) continue;
331 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
332 // If the operation failed to simplify, or simplified to a different value
333 // to previously, then give up.
334 if (!V || (CommonValue && V != CommonValue))
342 /// SimplifyAddInst - Given operands for an Add, see if we can
343 /// fold the result. If not, this returns null.
344 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
345 const TargetData *TD, const DominatorTree *DT,
346 unsigned MaxRecurse) {
347 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
348 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
349 Constant *Ops[] = { CLHS, CRHS };
350 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
354 // Canonicalize the constant to the RHS.
358 // X + undef -> undef
359 if (isa<UndefValue>(Op1))
363 if (match(Op1, m_Zero()))
370 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
371 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
374 // X + ~X -> -1 since ~X = -X-1
375 if (match(Op0, m_Not(m_Specific(Op1))) ||
376 match(Op1, m_Not(m_Specific(Op0))))
377 return Constant::getAllOnesValue(Op0->getType());
379 // Try some generic simplifications for associative operations.
380 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, DT,
384 // Threading Add over selects and phi nodes is pointless, so don't bother.
385 // Threading over the select in "A + select(cond, B, C)" means evaluating
386 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
387 // only if B and C are equal. If B and C are equal then (since we assume
388 // that operands have already been simplified) "select(cond, B, C)" should
389 // have been simplified to the common value of B and C already. Analysing
390 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
391 // for threading over phi nodes.
396 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
397 const TargetData *TD, const DominatorTree *DT) {
398 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
401 /// SimplifySubInst - Given operands for a Sub, see if we can
402 /// fold the result. If not, this returns null.
403 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
404 const TargetData *TD, const DominatorTree *,
405 unsigned MaxRecurse) {
406 if (Constant *CLHS = dyn_cast<Constant>(Op0))
407 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
408 Constant *Ops[] = { CLHS, CRHS };
409 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
413 // X - undef -> undef
414 // undef - X -> undef
415 if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
416 return UndefValue::get(Op0->getType());
419 if (match(Op1, m_Zero()))
424 return Constant::getNullValue(Op0->getType());
429 if (match(Op0, m_Add(m_Value(X), m_Specific(Op1))) ||
430 match(Op0, m_Add(m_Specific(Op1), m_Value(X))))
433 // Threading Sub over selects and phi nodes is pointless, so don't bother.
434 // Threading over the select in "A - select(cond, B, C)" means evaluating
435 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
436 // only if B and C are equal. If B and C are equal then (since we assume
437 // that operands have already been simplified) "select(cond, B, C)" should
438 // have been simplified to the common value of B and C already. Analysing
439 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
440 // for threading over phi nodes.
445 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
446 const TargetData *TD, const DominatorTree *DT) {
447 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
450 /// SimplifyAndInst - Given operands for an And, see if we can
451 /// fold the result. If not, this returns null.
452 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
453 const DominatorTree *DT, unsigned MaxRecurse) {
454 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
455 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
456 Constant *Ops[] = { CLHS, CRHS };
457 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
461 // Canonicalize the constant to the RHS.
466 if (isa<UndefValue>(Op1))
467 return Constant::getNullValue(Op0->getType());
474 if (match(Op1, m_Zero()))
478 if (match(Op1, m_AllOnes()))
481 // A & ~A = ~A & A = 0
482 Value *A = 0, *B = 0;
483 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
484 (match(Op1, m_Not(m_Value(A))) && A == Op0))
485 return Constant::getNullValue(Op0->getType());
488 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
489 (A == Op1 || B == Op1))
493 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
494 (A == Op0 || B == Op0))
497 // Try some generic simplifications for associative operations.
498 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, DT,
502 // If the operation is with the result of a select instruction, check whether
503 // operating on either branch of the select always yields the same value.
504 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
505 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
509 // If the operation is with the result of a phi instruction, check whether
510 // operating on all incoming values of the phi always yields the same value.
511 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
512 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
519 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
520 const DominatorTree *DT) {
521 return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
524 /// SimplifyOrInst - Given operands for an Or, see if we can
525 /// fold the result. If not, this returns null.
526 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
527 const DominatorTree *DT, unsigned MaxRecurse) {
528 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
529 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
530 Constant *Ops[] = { CLHS, CRHS };
531 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
535 // Canonicalize the constant to the RHS.
540 if (isa<UndefValue>(Op1))
541 return Constant::getAllOnesValue(Op0->getType());
548 if (match(Op1, m_Zero()))
552 if (match(Op1, m_AllOnes()))
555 // A | ~A = ~A | A = -1
556 Value *A = 0, *B = 0;
557 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
558 (match(Op1, m_Not(m_Value(A))) && A == Op0))
559 return Constant::getAllOnesValue(Op0->getType());
562 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
563 (A == Op1 || B == Op1))
567 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
568 (A == Op0 || B == Op0))
571 // Try some generic simplifications for associative operations.
572 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, DT,
576 // If the operation is with the result of a select instruction, check whether
577 // operating on either branch of the select always yields the same value.
578 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
579 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
583 // If the operation is with the result of a phi instruction, check whether
584 // operating on all incoming values of the phi always yields the same value.
585 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
586 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
593 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
594 const DominatorTree *DT) {
595 return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
598 /// SimplifyXorInst - Given operands for a Xor, see if we can
599 /// fold the result. If not, this returns null.
600 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
601 const DominatorTree *DT, unsigned MaxRecurse) {
602 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
603 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
604 Constant *Ops[] = { CLHS, CRHS };
605 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
609 // Canonicalize the constant to the RHS.
613 // A ^ undef -> undef
614 if (isa<UndefValue>(Op1))
618 if (match(Op1, m_Zero()))
623 return Constant::getNullValue(Op0->getType());
625 // A ^ ~A = ~A ^ A = -1
627 if ((match(Op0, m_Not(m_Value(A))) && A == Op1) ||
628 (match(Op1, m_Not(m_Value(A))) && A == Op0))
629 return Constant::getAllOnesValue(Op0->getType());
631 // Try some generic simplifications for associative operations.
632 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, DT,
636 // Threading Xor over selects and phi nodes is pointless, so don't bother.
637 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
638 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
639 // only if B and C are equal. If B and C are equal then (since we assume
640 // that operands have already been simplified) "select(cond, B, C)" should
641 // have been simplified to the common value of B and C already. Analysing
642 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
643 // for threading over phi nodes.
648 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
649 const DominatorTree *DT) {
650 return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
653 static const Type *GetCompareTy(Value *Op) {
654 return CmpInst::makeCmpResultType(Op->getType());
657 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
658 /// fold the result. If not, this returns null.
659 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
660 const TargetData *TD, const DominatorTree *DT,
661 unsigned MaxRecurse) {
662 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
663 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
665 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
666 if (Constant *CRHS = dyn_cast<Constant>(RHS))
667 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
669 // If we have a constant, make sure it is on the RHS.
671 Pred = CmpInst::getSwappedPredicate(Pred);
674 // ITy - This is the return type of the compare we're considering.
675 const Type *ITy = GetCompareTy(LHS);
677 // icmp X, X -> true/false
678 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
679 // because X could be 0.
680 if (LHS == RHS || isa<UndefValue>(RHS))
681 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
683 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
684 // addresses never equal each other! We already know that Op0 != Op1.
685 if ((isa<GlobalValue>(LHS) || isa<AllocaInst>(LHS) ||
686 isa<ConstantPointerNull>(LHS)) &&
687 (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
688 isa<ConstantPointerNull>(RHS)))
689 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
691 // See if we are doing a comparison with a constant.
692 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
693 // If we have an icmp le or icmp ge instruction, turn it into the
694 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
695 // them being folded in the code below.
698 case ICmpInst::ICMP_ULE:
699 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
700 return ConstantInt::getTrue(CI->getContext());
702 case ICmpInst::ICMP_SLE:
703 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
704 return ConstantInt::getTrue(CI->getContext());
706 case ICmpInst::ICMP_UGE:
707 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
708 return ConstantInt::getTrue(CI->getContext());
710 case ICmpInst::ICMP_SGE:
711 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
712 return ConstantInt::getTrue(CI->getContext());
717 // If the comparison is with the result of a select instruction, check whether
718 // comparing with either branch of the select always yields the same value.
719 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
720 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
723 // If the comparison is with the result of a phi instruction, check whether
724 // doing the compare with each incoming phi value yields a common result.
725 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
726 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
732 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
733 const TargetData *TD, const DominatorTree *DT) {
734 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
737 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
738 /// fold the result. If not, this returns null.
739 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
740 const TargetData *TD, const DominatorTree *DT,
741 unsigned MaxRecurse) {
742 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
743 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
745 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
746 if (Constant *CRHS = dyn_cast<Constant>(RHS))
747 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
749 // If we have a constant, make sure it is on the RHS.
751 Pred = CmpInst::getSwappedPredicate(Pred);
754 // Fold trivial predicates.
755 if (Pred == FCmpInst::FCMP_FALSE)
756 return ConstantInt::get(GetCompareTy(LHS), 0);
757 if (Pred == FCmpInst::FCMP_TRUE)
758 return ConstantInt::get(GetCompareTy(LHS), 1);
760 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
761 return UndefValue::get(GetCompareTy(LHS));
763 // fcmp x,x -> true/false. Not all compares are foldable.
765 if (CmpInst::isTrueWhenEqual(Pred))
766 return ConstantInt::get(GetCompareTy(LHS), 1);
767 if (CmpInst::isFalseWhenEqual(Pred))
768 return ConstantInt::get(GetCompareTy(LHS), 0);
771 // Handle fcmp with constant RHS
772 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
773 // If the constant is a nan, see if we can fold the comparison based on it.
774 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
775 if (CFP->getValueAPF().isNaN()) {
776 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
777 return ConstantInt::getFalse(CFP->getContext());
778 assert(FCmpInst::isUnordered(Pred) &&
779 "Comparison must be either ordered or unordered!");
780 // True if unordered.
781 return ConstantInt::getTrue(CFP->getContext());
783 // Check whether the constant is an infinity.
784 if (CFP->getValueAPF().isInfinity()) {
785 if (CFP->getValueAPF().isNegative()) {
787 case FCmpInst::FCMP_OLT:
788 // No value is ordered and less than negative infinity.
789 return ConstantInt::getFalse(CFP->getContext());
790 case FCmpInst::FCMP_UGE:
791 // All values are unordered with or at least negative infinity.
792 return ConstantInt::getTrue(CFP->getContext());
798 case FCmpInst::FCMP_OGT:
799 // No value is ordered and greater than infinity.
800 return ConstantInt::getFalse(CFP->getContext());
801 case FCmpInst::FCMP_ULE:
802 // All values are unordered with and at most infinity.
803 return ConstantInt::getTrue(CFP->getContext());
812 // If the comparison is with the result of a select instruction, check whether
813 // comparing with either branch of the select always yields the same value.
814 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
815 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
818 // If the comparison is with the result of a phi instruction, check whether
819 // doing the compare with each incoming phi value yields a common result.
820 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
821 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
827 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
828 const TargetData *TD, const DominatorTree *DT) {
829 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
832 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
833 /// the result. If not, this returns null.
834 Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
835 const TargetData *TD, const DominatorTree *) {
836 // select true, X, Y -> X
837 // select false, X, Y -> Y
838 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
839 return CB->getZExtValue() ? TrueVal : FalseVal;
841 // select C, X, X -> X
842 if (TrueVal == FalseVal)
845 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
847 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
849 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
850 if (isa<Constant>(TrueVal))
858 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
859 /// fold the result. If not, this returns null.
860 Value *llvm::SimplifyGEPInst(Value *const *Ops, unsigned NumOps,
861 const TargetData *TD, const DominatorTree *) {
862 // The type of the GEP pointer operand.
863 const PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
865 // getelementptr P -> P.
869 if (isa<UndefValue>(Ops[0])) {
870 // Compute the (pointer) type returned by the GEP instruction.
871 const Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, &Ops[1],
873 const Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
874 return UndefValue::get(GEPTy);
878 // getelementptr P, 0 -> P.
879 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
882 // getelementptr P, N -> P if P points to a type of zero size.
884 const Type *Ty = PtrTy->getElementType();
885 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
890 // Check to see if this is constant foldable.
891 for (unsigned i = 0; i != NumOps; ++i)
892 if (!isa<Constant>(Ops[i]))
895 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]),
896 (Constant *const*)Ops+1, NumOps-1);
899 /// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
900 static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
901 // If all of the PHI's incoming values are the same then replace the PHI node
902 // with the common value.
903 Value *CommonValue = 0;
904 bool HasUndefInput = false;
905 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
906 Value *Incoming = PN->getIncomingValue(i);
907 // If the incoming value is the phi node itself, it can safely be skipped.
908 if (Incoming == PN) continue;
909 if (isa<UndefValue>(Incoming)) {
910 // Remember that we saw an undef value, but otherwise ignore them.
911 HasUndefInput = true;
914 if (CommonValue && Incoming != CommonValue)
915 return 0; // Not the same, bail out.
916 CommonValue = Incoming;
919 // If CommonValue is null then all of the incoming values were either undef or
920 // equal to the phi node itself.
922 return UndefValue::get(PN->getType());
924 // If we have a PHI node like phi(X, undef, X), where X is defined by some
925 // instruction, we cannot return X as the result of the PHI node unless it
926 // dominates the PHI block.
928 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
934 //=== Helper functions for higher up the class hierarchy.
936 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
937 /// fold the result. If not, this returns null.
938 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
939 const TargetData *TD, const DominatorTree *DT,
940 unsigned MaxRecurse) {
942 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
943 case Instruction::Or: return SimplifyOrInst(LHS, RHS, TD, DT, MaxRecurse);
944 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecurse);
945 case Instruction::Add: return SimplifyAddInst(LHS, RHS, /* isNSW */ false,
946 /* isNUW */ false, TD, DT,
948 case Instruction::Sub: return SimplifySubInst(LHS, RHS, /* isNSW */ false,
949 /* isNUW */ false, TD, DT,
952 if (Constant *CLHS = dyn_cast<Constant>(LHS))
953 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
954 Constant *COps[] = {CLHS, CRHS};
955 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, 2, TD);
958 // If the operation is associative, try some generic simplifications.
959 if (Instruction::isAssociative(Opcode))
960 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, DT,
964 // If the operation is with the result of a select instruction, check whether
965 // operating on either branch of the select always yields the same value.
966 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
967 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
971 // If the operation is with the result of a phi instruction, check whether
972 // operating on all incoming values of the phi always yields the same value.
973 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
974 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse))
981 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
982 const TargetData *TD, const DominatorTree *DT) {
983 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
986 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
988 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
989 const TargetData *TD, const DominatorTree *DT,
990 unsigned MaxRecurse) {
991 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
992 return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
993 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
996 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
997 const TargetData *TD, const DominatorTree *DT) {
998 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
1001 /// SimplifyInstruction - See if we can compute a simplified version of this
1002 /// instruction. If not, this returns null.
1003 Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
1004 const DominatorTree *DT) {
1007 switch (I->getOpcode()) {
1009 Result = ConstantFoldInstruction(I, TD);
1011 case Instruction::Add:
1012 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
1013 cast<BinaryOperator>(I)->hasNoSignedWrap(),
1014 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
1017 case Instruction::Sub:
1018 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
1019 cast<BinaryOperator>(I)->hasNoSignedWrap(),
1020 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
1023 case Instruction::And:
1024 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
1026 case Instruction::Or:
1027 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
1029 case Instruction::Xor:
1030 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
1032 case Instruction::ICmp:
1033 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
1034 I->getOperand(0), I->getOperand(1), TD, DT);
1036 case Instruction::FCmp:
1037 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
1038 I->getOperand(0), I->getOperand(1), TD, DT);
1040 case Instruction::Select:
1041 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
1042 I->getOperand(2), TD, DT);
1044 case Instruction::GetElementPtr: {
1045 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
1046 Result = SimplifyGEPInst(&Ops[0], Ops.size(), TD, DT);
1049 case Instruction::PHI:
1050 Result = SimplifyPHINode(cast<PHINode>(I), DT);
1054 /// If called on unreachable code, the above logic may report that the
1055 /// instruction simplified to itself. Make life easier for users by
1056 /// detecting that case here, returning a safe value instead.
1057 return Result == I ? UndefValue::get(I->getType()) : Result;
1060 /// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
1061 /// delete the From instruction. In addition to a basic RAUW, this does a
1062 /// recursive simplification of the newly formed instructions. This catches
1063 /// things where one simplification exposes other opportunities. This only
1064 /// simplifies and deletes scalar operations, it does not change the CFG.
1066 void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
1067 const TargetData *TD,
1068 const DominatorTree *DT) {
1069 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
1071 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
1072 // we can know if it gets deleted out from under us or replaced in a
1073 // recursive simplification.
1074 WeakVH FromHandle(From);
1075 WeakVH ToHandle(To);
1077 while (!From->use_empty()) {
1078 // Update the instruction to use the new value.
1079 Use &TheUse = From->use_begin().getUse();
1080 Instruction *User = cast<Instruction>(TheUse.getUser());
1083 // Check to see if the instruction can be folded due to the operand
1084 // replacement. For example changing (or X, Y) into (or X, -1) can replace
1085 // the 'or' with -1.
1086 Value *SimplifiedVal;
1088 // Sanity check to make sure 'User' doesn't dangle across
1089 // SimplifyInstruction.
1090 AssertingVH<> UserHandle(User);
1092 SimplifiedVal = SimplifyInstruction(User, TD, DT);
1093 if (SimplifiedVal == 0) continue;
1096 // Recursively simplify this user to the new value.
1097 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
1098 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
1101 assert(ToHandle && "To value deleted by recursive simplification?");
1103 // If the recursive simplification ended up revisiting and deleting
1104 // 'From' then we're done.
1109 // If 'From' has value handles referring to it, do a real RAUW to update them.
1110 From->replaceAllUsesWith(To);
1112 From->eraseFromParent();