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 #define DEBUG_TYPE "instsimplify"
21 #include "llvm/Operator.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/InstructionSimplify.h"
24 #include "llvm/Analysis/ConstantFolding.h"
25 #include "llvm/Analysis/Dominators.h"
26 #include "llvm/Analysis/ValueTracking.h"
27 #include "llvm/Support/ConstantRange.h"
28 #include "llvm/Support/PatternMatch.h"
29 #include "llvm/Support/ValueHandle.h"
30 #include "llvm/Target/TargetData.h"
32 using namespace llvm::PatternMatch;
34 enum { RecursionLimit = 3 };
36 STATISTIC(NumExpand, "Number of expansions");
37 STATISTIC(NumFactor , "Number of factorizations");
38 STATISTIC(NumReassoc, "Number of reassociations");
40 static Value *SimplifyAndInst(Value *, Value *, const TargetData *,
41 const DominatorTree *, unsigned);
42 static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
43 const DominatorTree *, unsigned);
44 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
45 const DominatorTree *, unsigned);
46 static Value *SimplifyOrInst(Value *, Value *, const TargetData *,
47 const DominatorTree *, unsigned);
48 static Value *SimplifyXorInst(Value *, Value *, const TargetData *,
49 const DominatorTree *, unsigned);
51 /// getFalse - For a boolean type, or a vector of boolean type, return false, or
52 /// a vector with every element false, as appropriate for the type.
53 static Constant *getFalse(Type *Ty) {
54 assert((Ty->isIntegerTy(1) ||
56 cast<VectorType>(Ty)->getElementType()->isIntegerTy(1))) &&
57 "Expected i1 type or a vector of i1!");
58 return Constant::getNullValue(Ty);
61 /// getTrue - For a boolean type, or a vector of boolean type, return true, or
62 /// a vector with every element true, as appropriate for the type.
63 static Constant *getTrue(Type *Ty) {
64 assert((Ty->isIntegerTy(1) ||
66 cast<VectorType>(Ty)->getElementType()->isIntegerTy(1))) &&
67 "Expected i1 type or a vector of i1!");
68 return Constant::getAllOnesValue(Ty);
71 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
72 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
74 CmpInst *Cmp = dyn_cast<CmpInst>(V);
77 CmpInst::Predicate CPred = Cmp->getPredicate();
78 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
79 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
81 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
85 /// ValueDominatesPHI - Does the given value dominate the specified phi node?
86 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
87 Instruction *I = dyn_cast<Instruction>(V);
89 // Arguments and constants dominate all instructions.
92 // If we have a DominatorTree then do a precise test.
94 return DT->dominates(I, P);
96 // Otherwise, if the instruction is in the entry block, and is not an invoke,
97 // then it obviously dominates all phi nodes.
98 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
105 /// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
106 /// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
107 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
108 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
109 /// Returns the simplified value, or null if no simplification was performed.
110 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
111 unsigned OpcToExpand, const TargetData *TD,
112 const DominatorTree *DT, unsigned MaxRecurse) {
113 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
114 // Recursion is always used, so bail out at once if we already hit the limit.
118 // Check whether the expression has the form "(A op' B) op C".
119 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
120 if (Op0->getOpcode() == OpcodeToExpand) {
121 // It does! Try turning it into "(A op C) op' (B op C)".
122 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
123 // Do "A op C" and "B op C" both simplify?
124 if (Value *L = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse))
125 if (Value *R = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
126 // They do! Return "L op' R" if it simplifies or is already available.
127 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
128 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
129 && L == B && R == A)) {
133 // Otherwise return "L op' R" if it simplifies.
134 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
142 // Check whether the expression has the form "A op (B op' C)".
143 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
144 if (Op1->getOpcode() == OpcodeToExpand) {
145 // It does! Try turning it into "(A op B) op' (A op C)".
146 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
147 // Do "A op B" and "A op C" both simplify?
148 if (Value *L = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse))
149 if (Value *R = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse)) {
150 // They do! Return "L op' R" if it simplifies or is already available.
151 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
152 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
153 && L == C && R == B)) {
157 // Otherwise return "L op' R" if it simplifies.
158 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
169 /// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
170 /// using the operation OpCodeToExtract. For example, when Opcode is Add and
171 /// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
172 /// Returns the simplified value, or null if no simplification was performed.
173 static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
174 unsigned OpcToExtract, const TargetData *TD,
175 const DominatorTree *DT, unsigned MaxRecurse) {
176 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
177 // Recursion is always used, so bail out at once if we already hit the limit.
181 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
182 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
184 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
185 !Op1 || Op1->getOpcode() != OpcodeToExtract)
188 // The expression has the form "(A op' B) op (C op' D)".
189 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
190 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
192 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
193 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
194 // commutative case, "(A op' B) op (C op' A)"?
195 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
196 Value *DD = A == C ? D : C;
197 // Form "A op' (B op DD)" if it simplifies completely.
198 // Does "B op DD" simplify?
199 if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, DT, MaxRecurse)) {
200 // It does! Return "A op' V" if it simplifies or is already available.
201 // If V equals B then "A op' V" is just the LHS. If V equals DD then
202 // "A op' V" is just the RHS.
203 if (V == B || V == DD) {
205 return V == B ? LHS : RHS;
207 // Otherwise return "A op' V" if it simplifies.
208 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, DT, MaxRecurse)) {
215 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
216 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
217 // commutative case, "(A op' B) op (B op' D)"?
218 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
219 Value *CC = B == D ? C : D;
220 // Form "(A op CC) op' B" if it simplifies completely..
221 // Does "A op CC" simplify?
222 if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, DT, MaxRecurse)) {
223 // It does! Return "V op' B" if it simplifies or is already available.
224 // If V equals A then "V op' B" is just the LHS. If V equals CC then
225 // "V op' B" is just the RHS.
226 if (V == A || V == CC) {
228 return V == A ? LHS : RHS;
230 // Otherwise return "V op' B" if it simplifies.
231 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, DT, MaxRecurse)) {
241 /// SimplifyAssociativeBinOp - Generic simplifications for associative binary
242 /// operations. Returns the simpler value, or null if none was found.
243 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
244 const TargetData *TD,
245 const DominatorTree *DT,
246 unsigned MaxRecurse) {
247 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
248 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
250 // Recursion is always used, so bail out at once if we already hit the limit.
254 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
255 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
257 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
258 if (Op0 && Op0->getOpcode() == Opcode) {
259 Value *A = Op0->getOperand(0);
260 Value *B = Op0->getOperand(1);
263 // Does "B op C" simplify?
264 if (Value *V = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
265 // It does! Return "A op V" if it simplifies or is already available.
266 // If V equals B then "A op V" is just the LHS.
267 if (V == B) return LHS;
268 // Otherwise return "A op V" if it simplifies.
269 if (Value *W = SimplifyBinOp(Opcode, A, V, TD, DT, MaxRecurse)) {
276 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
277 if (Op1 && Op1->getOpcode() == Opcode) {
279 Value *B = Op1->getOperand(0);
280 Value *C = Op1->getOperand(1);
282 // Does "A op B" simplify?
283 if (Value *V = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse)) {
284 // It does! Return "V op C" if it simplifies or is already available.
285 // If V equals B then "V op C" is just the RHS.
286 if (V == B) return RHS;
287 // Otherwise return "V op C" if it simplifies.
288 if (Value *W = SimplifyBinOp(Opcode, V, C, TD, DT, MaxRecurse)) {
295 // The remaining transforms require commutativity as well as associativity.
296 if (!Instruction::isCommutative(Opcode))
299 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
300 if (Op0 && Op0->getOpcode() == Opcode) {
301 Value *A = Op0->getOperand(0);
302 Value *B = Op0->getOperand(1);
305 // Does "C op A" simplify?
306 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
307 // It does! Return "V op B" if it simplifies or is already available.
308 // If V equals A then "V op B" is just the LHS.
309 if (V == A) return LHS;
310 // Otherwise return "V op B" if it simplifies.
311 if (Value *W = SimplifyBinOp(Opcode, V, B, TD, DT, MaxRecurse)) {
318 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
319 if (Op1 && Op1->getOpcode() == Opcode) {
321 Value *B = Op1->getOperand(0);
322 Value *C = Op1->getOperand(1);
324 // Does "C op A" simplify?
325 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
326 // It does! Return "B op V" if it simplifies or is already available.
327 // If V equals C then "B op V" is just the RHS.
328 if (V == C) return RHS;
329 // Otherwise return "B op V" if it simplifies.
330 if (Value *W = SimplifyBinOp(Opcode, B, V, TD, DT, MaxRecurse)) {
340 /// ThreadBinOpOverSelect - In the case of a binary operation with a select
341 /// instruction as an operand, try to simplify the binop by seeing whether
342 /// evaluating it on both branches of the select results in the same value.
343 /// Returns the common value if so, otherwise returns null.
344 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
345 const TargetData *TD,
346 const DominatorTree *DT,
347 unsigned MaxRecurse) {
348 // Recursion is always used, so bail out at once if we already hit the limit.
353 if (isa<SelectInst>(LHS)) {
354 SI = cast<SelectInst>(LHS);
356 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
357 SI = cast<SelectInst>(RHS);
360 // Evaluate the BinOp on the true and false branches of the select.
364 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
365 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
367 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
368 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
371 // If they simplified to the same value, then return the common value.
372 // If they both failed to simplify then return null.
376 // If one branch simplified to undef, return the other one.
377 if (TV && isa<UndefValue>(TV))
379 if (FV && isa<UndefValue>(FV))
382 // If applying the operation did not change the true and false select values,
383 // then the result of the binop is the select itself.
384 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
387 // If one branch simplified and the other did not, and the simplified
388 // value is equal to the unsimplified one, return the simplified value.
389 // For example, select (cond, X, X & Z) & Z -> X & Z.
390 if ((FV && !TV) || (TV && !FV)) {
391 // Check that the simplified value has the form "X op Y" where "op" is the
392 // same as the original operation.
393 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
394 if (Simplified && Simplified->getOpcode() == Opcode) {
395 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
396 // We already know that "op" is the same as for the simplified value. See
397 // if the operands match too. If so, return the simplified value.
398 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
399 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
400 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
401 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
402 Simplified->getOperand(1) == UnsimplifiedRHS)
404 if (Simplified->isCommutative() &&
405 Simplified->getOperand(1) == UnsimplifiedLHS &&
406 Simplified->getOperand(0) == UnsimplifiedRHS)
414 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
415 /// try to simplify the comparison by seeing whether both branches of the select
416 /// result in the same value. Returns the common value if so, otherwise returns
418 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
419 Value *RHS, const TargetData *TD,
420 const DominatorTree *DT,
421 unsigned MaxRecurse) {
422 // Recursion is always used, so bail out at once if we already hit the limit.
426 // Make sure the select is on the LHS.
427 if (!isa<SelectInst>(LHS)) {
429 Pred = CmpInst::getSwappedPredicate(Pred);
431 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
432 SelectInst *SI = cast<SelectInst>(LHS);
433 Value *Cond = SI->getCondition();
434 Value *TV = SI->getTrueValue();
435 Value *FV = SI->getFalseValue();
437 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
438 // Does "cmp TV, RHS" simplify?
439 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, TD, DT, MaxRecurse);
441 // It not only simplified, it simplified to the select condition. Replace
443 TCmp = getTrue(Cond->getType());
445 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
446 // condition then we can replace it with 'true'. Otherwise give up.
447 if (!isSameCompare(Cond, Pred, TV, RHS))
449 TCmp = getTrue(Cond->getType());
452 // Does "cmp FV, RHS" simplify?
453 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, TD, DT, MaxRecurse);
455 // It not only simplified, it simplified to the select condition. Replace
457 FCmp = getFalse(Cond->getType());
459 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
460 // condition then we can replace it with 'false'. Otherwise give up.
461 if (!isSameCompare(Cond, Pred, FV, RHS))
463 FCmp = getFalse(Cond->getType());
466 // If both sides simplified to the same value, then use it as the result of
467 // the original comparison.
470 // If the false value simplified to false, then the result of the compare
471 // is equal to "Cond && TCmp". This also catches the case when the false
472 // value simplified to false and the true value to true, returning "Cond".
473 if (match(FCmp, m_Zero()))
474 if (Value *V = SimplifyAndInst(Cond, TCmp, TD, DT, MaxRecurse))
476 // If the true value simplified to true, then the result of the compare
477 // is equal to "Cond || FCmp".
478 if (match(TCmp, m_One()))
479 if (Value *V = SimplifyOrInst(Cond, FCmp, TD, DT, MaxRecurse))
481 // Finally, if the false value simplified to true and the true value to
482 // false, then the result of the compare is equal to "!Cond".
483 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
485 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
492 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
493 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
494 /// it on the incoming phi values yields the same result for every value. If so
495 /// returns the common value, otherwise returns null.
496 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
497 const TargetData *TD, const DominatorTree *DT,
498 unsigned MaxRecurse) {
499 // Recursion is always used, so bail out at once if we already hit the limit.
504 if (isa<PHINode>(LHS)) {
505 PI = cast<PHINode>(LHS);
506 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
507 if (!ValueDominatesPHI(RHS, PI, DT))
510 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
511 PI = cast<PHINode>(RHS);
512 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
513 if (!ValueDominatesPHI(LHS, PI, DT))
517 // Evaluate the BinOp on the incoming phi values.
518 Value *CommonValue = 0;
519 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
520 Value *Incoming = PI->getIncomingValue(i);
521 // If the incoming value is the phi node itself, it can safely be skipped.
522 if (Incoming == PI) continue;
523 Value *V = PI == LHS ?
524 SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
525 SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
526 // If the operation failed to simplify, or simplified to a different value
527 // to previously, then give up.
528 if (!V || (CommonValue && V != CommonValue))
536 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
537 /// try to simplify the comparison by seeing whether comparing with all of the
538 /// incoming phi values yields the same result every time. If so returns the
539 /// common result, otherwise returns null.
540 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
541 const TargetData *TD, const DominatorTree *DT,
542 unsigned MaxRecurse) {
543 // Recursion is always used, so bail out at once if we already hit the limit.
547 // Make sure the phi is on the LHS.
548 if (!isa<PHINode>(LHS)) {
550 Pred = CmpInst::getSwappedPredicate(Pred);
552 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
553 PHINode *PI = cast<PHINode>(LHS);
555 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
556 if (!ValueDominatesPHI(RHS, PI, DT))
559 // Evaluate the BinOp on the incoming phi values.
560 Value *CommonValue = 0;
561 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
562 Value *Incoming = PI->getIncomingValue(i);
563 // If the incoming value is the phi node itself, it can safely be skipped.
564 if (Incoming == PI) continue;
565 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
566 // If the operation failed to simplify, or simplified to a different value
567 // to previously, then give up.
568 if (!V || (CommonValue && V != CommonValue))
576 /// SimplifyAddInst - Given operands for an Add, see if we can
577 /// fold the result. If not, this returns null.
578 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
579 const TargetData *TD, const DominatorTree *DT,
580 unsigned MaxRecurse) {
581 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
582 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
583 Constant *Ops[] = { CLHS, CRHS };
584 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
588 // Canonicalize the constant to the RHS.
592 // X + undef -> undef
593 if (match(Op1, m_Undef()))
597 if (match(Op1, m_Zero()))
604 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
605 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
608 // X + ~X -> -1 since ~X = -X-1
609 if (match(Op0, m_Not(m_Specific(Op1))) ||
610 match(Op1, m_Not(m_Specific(Op0))))
611 return Constant::getAllOnesValue(Op0->getType());
614 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
615 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
618 // Try some generic simplifications for associative operations.
619 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, DT,
623 // Mul distributes over Add. Try some generic simplifications based on this.
624 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
628 // Threading Add over selects and phi nodes is pointless, so don't bother.
629 // Threading over the select in "A + select(cond, B, C)" means evaluating
630 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
631 // only if B and C are equal. If B and C are equal then (since we assume
632 // that operands have already been simplified) "select(cond, B, C)" should
633 // have been simplified to the common value of B and C already. Analysing
634 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
635 // for threading over phi nodes.
640 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
641 const TargetData *TD, const DominatorTree *DT) {
642 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
645 /// SimplifySubInst - Given operands for a Sub, see if we can
646 /// fold the result. If not, this returns null.
647 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
648 const TargetData *TD, const DominatorTree *DT,
649 unsigned MaxRecurse) {
650 if (Constant *CLHS = dyn_cast<Constant>(Op0))
651 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
652 Constant *Ops[] = { CLHS, CRHS };
653 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
657 // X - undef -> undef
658 // undef - X -> undef
659 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
660 return UndefValue::get(Op0->getType());
663 if (match(Op1, m_Zero()))
668 return Constant::getNullValue(Op0->getType());
673 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
674 match(Op0, m_Shl(m_Specific(Op1), m_One())))
677 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
678 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
679 Value *Y = 0, *Z = Op1;
680 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
681 // See if "V === Y - Z" simplifies.
682 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, TD, DT, MaxRecurse-1))
683 // It does! Now see if "X + V" simplifies.
684 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, TD, DT,
686 // It does, we successfully reassociated!
690 // See if "V === X - Z" simplifies.
691 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecurse-1))
692 // It does! Now see if "Y + V" simplifies.
693 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, TD, DT,
695 // It does, we successfully reassociated!
701 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
702 // For example, X - (X + 1) -> -1
704 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
705 // See if "V === X - Y" simplifies.
706 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, TD, DT, MaxRecurse-1))
707 // It does! Now see if "V - Z" simplifies.
708 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, TD, DT,
710 // It does, we successfully reassociated!
714 // See if "V === X - Z" simplifies.
715 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, DT, MaxRecurse-1))
716 // It does! Now see if "V - Y" simplifies.
717 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, TD, DT,
719 // It does, we successfully reassociated!
725 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
726 // For example, X - (X - Y) -> Y.
728 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
729 // See if "V === Z - X" simplifies.
730 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, TD, DT, MaxRecurse-1))
731 // It does! Now see if "V + Y" simplifies.
732 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, TD, DT,
734 // It does, we successfully reassociated!
739 // Mul distributes over Sub. Try some generic simplifications based on this.
740 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
745 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
746 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
749 // Threading Sub over selects and phi nodes is pointless, so don't bother.
750 // Threading over the select in "A - select(cond, B, C)" means evaluating
751 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
752 // only if B and C are equal. If B and C are equal then (since we assume
753 // that operands have already been simplified) "select(cond, B, C)" should
754 // have been simplified to the common value of B and C already. Analysing
755 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
756 // for threading over phi nodes.
761 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
762 const TargetData *TD, const DominatorTree *DT) {
763 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
766 /// SimplifyMulInst - Given operands for a Mul, see if we can
767 /// fold the result. If not, this returns null.
768 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
769 const DominatorTree *DT, unsigned MaxRecurse) {
770 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
771 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
772 Constant *Ops[] = { CLHS, CRHS };
773 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
777 // Canonicalize the constant to the RHS.
782 if (match(Op1, m_Undef()))
783 return Constant::getNullValue(Op0->getType());
786 if (match(Op1, m_Zero()))
790 if (match(Op1, m_One()))
793 // (X / Y) * Y -> X if the division is exact.
794 Value *X = 0, *Y = 0;
795 if ((match(Op0, m_IDiv(m_Value(X), m_Value(Y))) && Y == Op1) || // (X / Y) * Y
796 (match(Op1, m_IDiv(m_Value(X), m_Value(Y))) && Y == Op0)) { // Y * (X / Y)
797 PossiblyExactOperator *Div =
798 cast<PossiblyExactOperator>(Y == Op1 ? Op0 : Op1);
804 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
805 if (Value *V = SimplifyAndInst(Op0, Op1, TD, DT, MaxRecurse-1))
808 // Try some generic simplifications for associative operations.
809 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, DT,
813 // Mul distributes over Add. Try some generic simplifications based on this.
814 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
818 // If the operation is with the result of a select instruction, check whether
819 // operating on either branch of the select always yields the same value.
820 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
821 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, DT,
825 // If the operation is with the result of a phi instruction, check whether
826 // operating on all incoming values of the phi always yields the same value.
827 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
828 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, DT,
835 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
836 const DominatorTree *DT) {
837 return ::SimplifyMulInst(Op0, Op1, TD, DT, RecursionLimit);
840 /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
841 /// fold the result. If not, this returns null.
842 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
843 const TargetData *TD, const DominatorTree *DT,
844 unsigned MaxRecurse) {
845 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
846 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
847 Constant *Ops[] = { C0, C1 };
848 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD);
852 bool isSigned = Opcode == Instruction::SDiv;
854 // X / undef -> undef
855 if (match(Op1, m_Undef()))
859 if (match(Op0, m_Undef()))
860 return Constant::getNullValue(Op0->getType());
862 // 0 / X -> 0, we don't need to preserve faults!
863 if (match(Op0, m_Zero()))
867 if (match(Op1, m_One()))
870 if (Op0->getType()->isIntegerTy(1))
871 // It can't be division by zero, hence it must be division by one.
876 return ConstantInt::get(Op0->getType(), 1);
878 // (X * Y) / Y -> X if the multiplication does not overflow.
879 Value *X = 0, *Y = 0;
880 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
881 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
882 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
883 // If the Mul knows it does not overflow, then we are good to go.
884 if ((isSigned && Mul->hasNoSignedWrap()) ||
885 (!isSigned && Mul->hasNoUnsignedWrap()))
887 // If X has the form X = A / Y then X * Y cannot overflow.
888 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
889 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
893 // (X rem Y) / Y -> 0
894 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
895 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
896 return Constant::getNullValue(Op0->getType());
898 // If the operation is with the result of a select instruction, check whether
899 // operating on either branch of the select always yields the same value.
900 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
901 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
904 // If the operation is with the result of a phi instruction, check whether
905 // operating on all incoming values of the phi always yields the same value.
906 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
907 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
913 /// SimplifySDivInst - Given operands for an SDiv, see if we can
914 /// fold the result. If not, this returns null.
915 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
916 const DominatorTree *DT, unsigned MaxRecurse) {
917 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, TD, DT, MaxRecurse))
923 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
924 const DominatorTree *DT) {
925 return ::SimplifySDivInst(Op0, Op1, TD, DT, RecursionLimit);
928 /// SimplifyUDivInst - Given operands for a UDiv, see if we can
929 /// fold the result. If not, this returns null.
930 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
931 const DominatorTree *DT, unsigned MaxRecurse) {
932 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, TD, DT, MaxRecurse))
938 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
939 const DominatorTree *DT) {
940 return ::SimplifyUDivInst(Op0, Op1, TD, DT, RecursionLimit);
943 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *,
944 const DominatorTree *, unsigned) {
945 // undef / X -> undef (the undef could be a snan).
946 if (match(Op0, m_Undef()))
949 // X / undef -> undef
950 if (match(Op1, m_Undef()))
956 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *TD,
957 const DominatorTree *DT) {
958 return ::SimplifyFDivInst(Op0, Op1, TD, DT, RecursionLimit);
961 /// SimplifyRem - Given operands for an SRem or URem, see if we can
962 /// fold the result. If not, this returns null.
963 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
964 const TargetData *TD, const DominatorTree *DT,
965 unsigned MaxRecurse) {
966 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
967 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
968 Constant *Ops[] = { C0, C1 };
969 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD);
973 // X % undef -> undef
974 if (match(Op1, m_Undef()))
978 if (match(Op0, m_Undef()))
979 return Constant::getNullValue(Op0->getType());
981 // 0 % X -> 0, we don't need to preserve faults!
982 if (match(Op0, m_Zero()))
985 // X % 0 -> undef, we don't need to preserve faults!
986 if (match(Op1, m_Zero()))
987 return UndefValue::get(Op0->getType());
990 if (match(Op1, m_One()))
991 return Constant::getNullValue(Op0->getType());
993 if (Op0->getType()->isIntegerTy(1))
994 // It can't be remainder by zero, hence it must be remainder by one.
995 return Constant::getNullValue(Op0->getType());
999 return Constant::getNullValue(Op0->getType());
1001 // If the operation is with the result of a select instruction, check whether
1002 // operating on either branch of the select always yields the same value.
1003 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1004 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
1007 // If the operation is with the result of a phi instruction, check whether
1008 // operating on all incoming values of the phi always yields the same value.
1009 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1010 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
1016 /// SimplifySRemInst - Given operands for an SRem, see if we can
1017 /// fold the result. If not, this returns null.
1018 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1019 const DominatorTree *DT, unsigned MaxRecurse) {
1020 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, TD, DT, MaxRecurse))
1026 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1027 const DominatorTree *DT) {
1028 return ::SimplifySRemInst(Op0, Op1, TD, DT, RecursionLimit);
1031 /// SimplifyURemInst - Given operands for a URem, see if we can
1032 /// fold the result. If not, this returns null.
1033 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
1034 const DominatorTree *DT, unsigned MaxRecurse) {
1035 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, TD, DT, MaxRecurse))
1041 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
1042 const DominatorTree *DT) {
1043 return ::SimplifyURemInst(Op0, Op1, TD, DT, RecursionLimit);
1046 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *,
1047 const DominatorTree *, unsigned) {
1048 // undef % X -> undef (the undef could be a snan).
1049 if (match(Op0, m_Undef()))
1052 // X % undef -> undef
1053 if (match(Op1, m_Undef()))
1059 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1060 const DominatorTree *DT) {
1061 return ::SimplifyFRemInst(Op0, Op1, TD, DT, RecursionLimit);
1064 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
1065 /// fold the result. If not, this returns null.
1066 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1067 const TargetData *TD, const DominatorTree *DT,
1068 unsigned MaxRecurse) {
1069 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1070 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1071 Constant *Ops[] = { C0, C1 };
1072 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD);
1076 // 0 shift by X -> 0
1077 if (match(Op0, m_Zero()))
1080 // X shift by 0 -> X
1081 if (match(Op1, m_Zero()))
1084 // X shift by undef -> undef because it may shift by the bitwidth.
1085 if (match(Op1, m_Undef()))
1088 // Shifting by the bitwidth or more is undefined.
1089 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1090 if (CI->getValue().getLimitedValue() >=
1091 Op0->getType()->getScalarSizeInBits())
1092 return UndefValue::get(Op0->getType());
1094 // If the operation is with the result of a select instruction, check whether
1095 // operating on either branch of the select always yields the same value.
1096 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1097 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, DT, MaxRecurse))
1100 // If the operation is with the result of a phi instruction, check whether
1101 // operating on all incoming values of the phi always yields the same value.
1102 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1103 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, DT, MaxRecurse))
1109 /// SimplifyShlInst - Given operands for an Shl, see if we can
1110 /// fold the result. If not, this returns null.
1111 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1112 const TargetData *TD, const DominatorTree *DT,
1113 unsigned MaxRecurse) {
1114 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, TD, DT, MaxRecurse))
1118 if (match(Op0, m_Undef()))
1119 return Constant::getNullValue(Op0->getType());
1121 // (X >> A) << A -> X
1123 if (match(Op0, m_Shr(m_Value(X), m_Specific(Op1))) &&
1124 cast<PossiblyExactOperator>(Op0)->isExact())
1129 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1130 const TargetData *TD, const DominatorTree *DT) {
1131 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
1134 /// SimplifyLShrInst - Given operands for an LShr, see if we can
1135 /// fold the result. If not, this returns null.
1136 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1137 const TargetData *TD, const DominatorTree *DT,
1138 unsigned MaxRecurse) {
1139 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, TD, DT, MaxRecurse))
1143 if (match(Op0, m_Undef()))
1144 return Constant::getNullValue(Op0->getType());
1146 // (X << A) >> A -> X
1148 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1149 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1155 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1156 const TargetData *TD, const DominatorTree *DT) {
1157 return ::SimplifyLShrInst(Op0, Op1, isExact, TD, DT, RecursionLimit);
1160 /// SimplifyAShrInst - Given operands for an AShr, see if we can
1161 /// fold the result. If not, this returns null.
1162 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1163 const TargetData *TD, const DominatorTree *DT,
1164 unsigned MaxRecurse) {
1165 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, TD, DT, MaxRecurse))
1168 // all ones >>a X -> all ones
1169 if (match(Op0, m_AllOnes()))
1172 // undef >>a X -> all ones
1173 if (match(Op0, m_Undef()))
1174 return Constant::getAllOnesValue(Op0->getType());
1176 // (X << A) >> A -> X
1178 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1179 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1185 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1186 const TargetData *TD, const DominatorTree *DT) {
1187 return ::SimplifyAShrInst(Op0, Op1, isExact, TD, DT, RecursionLimit);
1190 /// SimplifyAndInst - Given operands for an And, see if we can
1191 /// fold the result. If not, this returns null.
1192 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1193 const DominatorTree *DT, unsigned MaxRecurse) {
1194 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1195 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1196 Constant *Ops[] = { CLHS, CRHS };
1197 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
1201 // Canonicalize the constant to the RHS.
1202 std::swap(Op0, Op1);
1206 if (match(Op1, m_Undef()))
1207 return Constant::getNullValue(Op0->getType());
1214 if (match(Op1, m_Zero()))
1218 if (match(Op1, m_AllOnes()))
1221 // A & ~A = ~A & A = 0
1222 if (match(Op0, m_Not(m_Specific(Op1))) ||
1223 match(Op1, m_Not(m_Specific(Op0))))
1224 return Constant::getNullValue(Op0->getType());
1227 Value *A = 0, *B = 0;
1228 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1229 (A == Op1 || B == Op1))
1233 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1234 (A == Op0 || B == Op0))
1237 // A & (-A) = A if A is a power of two or zero.
1238 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1239 match(Op1, m_Neg(m_Specific(Op0)))) {
1240 if (isPowerOfTwo(Op0, TD, /*OrZero*/true))
1242 if (isPowerOfTwo(Op1, TD, /*OrZero*/true))
1246 // Try some generic simplifications for associative operations.
1247 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, DT,
1251 // And distributes over Or. Try some generic simplifications based on this.
1252 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1253 TD, DT, MaxRecurse))
1256 // And distributes over Xor. Try some generic simplifications based on this.
1257 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1258 TD, DT, MaxRecurse))
1261 // Or distributes over And. Try some generic simplifications based on this.
1262 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1263 TD, DT, MaxRecurse))
1266 // If the operation is with the result of a select instruction, check whether
1267 // operating on either branch of the select always yields the same value.
1268 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1269 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
1273 // If the operation is with the result of a phi instruction, check whether
1274 // operating on all incoming values of the phi always yields the same value.
1275 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1276 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
1283 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1284 const DominatorTree *DT) {
1285 return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
1288 /// SimplifyOrInst - Given operands for an Or, see if we can
1289 /// fold the result. If not, this returns null.
1290 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1291 const DominatorTree *DT, unsigned MaxRecurse) {
1292 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1293 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1294 Constant *Ops[] = { CLHS, CRHS };
1295 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
1299 // Canonicalize the constant to the RHS.
1300 std::swap(Op0, Op1);
1304 if (match(Op1, m_Undef()))
1305 return Constant::getAllOnesValue(Op0->getType());
1312 if (match(Op1, m_Zero()))
1316 if (match(Op1, m_AllOnes()))
1319 // A | ~A = ~A | A = -1
1320 if (match(Op0, m_Not(m_Specific(Op1))) ||
1321 match(Op1, m_Not(m_Specific(Op0))))
1322 return Constant::getAllOnesValue(Op0->getType());
1325 Value *A = 0, *B = 0;
1326 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1327 (A == Op1 || B == Op1))
1331 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1332 (A == Op0 || B == Op0))
1335 // ~(A & ?) | A = -1
1336 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1337 (A == Op1 || B == Op1))
1338 return Constant::getAllOnesValue(Op1->getType());
1340 // A | ~(A & ?) = -1
1341 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1342 (A == Op0 || B == Op0))
1343 return Constant::getAllOnesValue(Op0->getType());
1345 // Try some generic simplifications for associative operations.
1346 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, DT,
1350 // Or distributes over And. Try some generic simplifications based on this.
1351 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1352 TD, DT, MaxRecurse))
1355 // And distributes over Or. Try some generic simplifications based on this.
1356 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1357 TD, DT, MaxRecurse))
1360 // If the operation is with the result of a select instruction, check whether
1361 // operating on either branch of the select always yields the same value.
1362 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1363 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
1367 // If the operation is with the result of a phi instruction, check whether
1368 // operating on all incoming values of the phi always yields the same value.
1369 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1370 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
1377 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1378 const DominatorTree *DT) {
1379 return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
1382 /// SimplifyXorInst - Given operands for a Xor, see if we can
1383 /// fold the result. If not, this returns null.
1384 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1385 const DominatorTree *DT, unsigned MaxRecurse) {
1386 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1387 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1388 Constant *Ops[] = { CLHS, CRHS };
1389 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
1393 // Canonicalize the constant to the RHS.
1394 std::swap(Op0, Op1);
1397 // A ^ undef -> undef
1398 if (match(Op1, m_Undef()))
1402 if (match(Op1, m_Zero()))
1407 return Constant::getNullValue(Op0->getType());
1409 // A ^ ~A = ~A ^ A = -1
1410 if (match(Op0, m_Not(m_Specific(Op1))) ||
1411 match(Op1, m_Not(m_Specific(Op0))))
1412 return Constant::getAllOnesValue(Op0->getType());
1414 // Try some generic simplifications for associative operations.
1415 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, DT,
1419 // And distributes over Xor. Try some generic simplifications based on this.
1420 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1421 TD, DT, MaxRecurse))
1424 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1425 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1426 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1427 // only if B and C are equal. If B and C are equal then (since we assume
1428 // that operands have already been simplified) "select(cond, B, C)" should
1429 // have been simplified to the common value of B and C already. Analysing
1430 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1431 // for threading over phi nodes.
1436 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1437 const DominatorTree *DT) {
1438 return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
1441 static Type *GetCompareTy(Value *Op) {
1442 return CmpInst::makeCmpResultType(Op->getType());
1445 /// ExtractEquivalentCondition - Rummage around inside V looking for something
1446 /// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1447 /// otherwise return null. Helper function for analyzing max/min idioms.
1448 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1449 Value *LHS, Value *RHS) {
1450 SelectInst *SI = dyn_cast<SelectInst>(V);
1453 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1456 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1457 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1459 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1460 LHS == CmpRHS && RHS == CmpLHS)
1465 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1466 /// fold the result. If not, this returns null.
1467 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1468 const TargetData *TD, const DominatorTree *DT,
1469 unsigned MaxRecurse) {
1470 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1471 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
1473 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
1474 if (Constant *CRHS = dyn_cast<Constant>(RHS))
1475 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
1477 // If we have a constant, make sure it is on the RHS.
1478 std::swap(LHS, RHS);
1479 Pred = CmpInst::getSwappedPredicate(Pred);
1482 Type *ITy = GetCompareTy(LHS); // The return type.
1483 Type *OpTy = LHS->getType(); // The operand type.
1485 // icmp X, X -> true/false
1486 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1487 // because X could be 0.
1488 if (LHS == RHS || isa<UndefValue>(RHS))
1489 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1491 // Special case logic when the operands have i1 type.
1492 if (OpTy->isIntegerTy(1) || (OpTy->isVectorTy() &&
1493 cast<VectorType>(OpTy)->getElementType()->isIntegerTy(1))) {
1496 case ICmpInst::ICMP_EQ:
1498 if (match(RHS, m_One()))
1501 case ICmpInst::ICMP_NE:
1503 if (match(RHS, m_Zero()))
1506 case ICmpInst::ICMP_UGT:
1508 if (match(RHS, m_Zero()))
1511 case ICmpInst::ICMP_UGE:
1513 if (match(RHS, m_One()))
1516 case ICmpInst::ICMP_SLT:
1518 if (match(RHS, m_Zero()))
1521 case ICmpInst::ICMP_SLE:
1523 if (match(RHS, m_One()))
1529 // icmp <alloca*>, <global/alloca*/null> - Different stack variables have
1530 // different addresses, and what's more the address of a stack variable is
1531 // never null or equal to the address of a global. Note that generalizing
1532 // to the case where LHS is a global variable address or null is pointless,
1533 // since if both LHS and RHS are constants then we already constant folded
1534 // the compare, and if only one of them is then we moved it to RHS already.
1535 if (isa<AllocaInst>(LHS) && (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
1536 isa<ConstantPointerNull>(RHS)))
1537 // We already know that LHS != RHS.
1538 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1540 // If we are comparing with zero then try hard since this is a common case.
1541 if (match(RHS, m_Zero())) {
1542 bool LHSKnownNonNegative, LHSKnownNegative;
1545 assert(false && "Unknown ICmp predicate!");
1546 case ICmpInst::ICMP_ULT:
1547 return getFalse(ITy);
1548 case ICmpInst::ICMP_UGE:
1549 return getTrue(ITy);
1550 case ICmpInst::ICMP_EQ:
1551 case ICmpInst::ICMP_ULE:
1552 if (isKnownNonZero(LHS, TD))
1553 return getFalse(ITy);
1555 case ICmpInst::ICMP_NE:
1556 case ICmpInst::ICMP_UGT:
1557 if (isKnownNonZero(LHS, TD))
1558 return getTrue(ITy);
1560 case ICmpInst::ICMP_SLT:
1561 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1562 if (LHSKnownNegative)
1563 return getTrue(ITy);
1564 if (LHSKnownNonNegative)
1565 return getFalse(ITy);
1567 case ICmpInst::ICMP_SLE:
1568 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1569 if (LHSKnownNegative)
1570 return getTrue(ITy);
1571 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1572 return getFalse(ITy);
1574 case ICmpInst::ICMP_SGE:
1575 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1576 if (LHSKnownNegative)
1577 return getFalse(ITy);
1578 if (LHSKnownNonNegative)
1579 return getTrue(ITy);
1581 case ICmpInst::ICMP_SGT:
1582 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1583 if (LHSKnownNegative)
1584 return getFalse(ITy);
1585 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1586 return getTrue(ITy);
1591 // See if we are doing a comparison with a constant integer.
1592 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1593 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1594 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1595 if (RHS_CR.isEmptySet())
1596 return ConstantInt::getFalse(CI->getContext());
1597 if (RHS_CR.isFullSet())
1598 return ConstantInt::getTrue(CI->getContext());
1600 // Many binary operators with constant RHS have easy to compute constant
1601 // range. Use them to check whether the comparison is a tautology.
1602 uint32_t Width = CI->getBitWidth();
1603 APInt Lower = APInt(Width, 0);
1604 APInt Upper = APInt(Width, 0);
1606 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1607 // 'urem x, CI2' produces [0, CI2).
1608 Upper = CI2->getValue();
1609 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1610 // 'srem x, CI2' produces (-|CI2|, |CI2|).
1611 Upper = CI2->getValue().abs();
1612 Lower = (-Upper) + 1;
1613 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
1614 // 'udiv CI2, x' produces [0, CI2].
1615 Upper = CI2->getValue() + 1;
1616 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1617 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1618 APInt NegOne = APInt::getAllOnesValue(Width);
1620 Upper = NegOne.udiv(CI2->getValue()) + 1;
1621 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1622 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1623 APInt IntMin = APInt::getSignedMinValue(Width);
1624 APInt IntMax = APInt::getSignedMaxValue(Width);
1625 APInt Val = CI2->getValue().abs();
1626 if (!Val.isMinValue()) {
1627 Lower = IntMin.sdiv(Val);
1628 Upper = IntMax.sdiv(Val) + 1;
1630 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1631 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1632 APInt NegOne = APInt::getAllOnesValue(Width);
1633 if (CI2->getValue().ult(Width))
1634 Upper = NegOne.lshr(CI2->getValue()) + 1;
1635 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1636 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1637 APInt IntMin = APInt::getSignedMinValue(Width);
1638 APInt IntMax = APInt::getSignedMaxValue(Width);
1639 if (CI2->getValue().ult(Width)) {
1640 Lower = IntMin.ashr(CI2->getValue());
1641 Upper = IntMax.ashr(CI2->getValue()) + 1;
1643 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1644 // 'or x, CI2' produces [CI2, UINT_MAX].
1645 Lower = CI2->getValue();
1646 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1647 // 'and x, CI2' produces [0, CI2].
1648 Upper = CI2->getValue() + 1;
1650 if (Lower != Upper) {
1651 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1652 if (RHS_CR.contains(LHS_CR))
1653 return ConstantInt::getTrue(RHS->getContext());
1654 if (RHS_CR.inverse().contains(LHS_CR))
1655 return ConstantInt::getFalse(RHS->getContext());
1659 // Compare of cast, for example (zext X) != 0 -> X != 0
1660 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1661 Instruction *LI = cast<CastInst>(LHS);
1662 Value *SrcOp = LI->getOperand(0);
1663 Type *SrcTy = SrcOp->getType();
1664 Type *DstTy = LI->getType();
1666 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1667 // if the integer type is the same size as the pointer type.
1668 if (MaxRecurse && TD && isa<PtrToIntInst>(LI) &&
1669 TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
1670 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1671 // Transfer the cast to the constant.
1672 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1673 ConstantExpr::getIntToPtr(RHSC, SrcTy),
1674 TD, DT, MaxRecurse-1))
1676 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1677 if (RI->getOperand(0)->getType() == SrcTy)
1678 // Compare without the cast.
1679 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1680 TD, DT, MaxRecurse-1))
1685 if (isa<ZExtInst>(LHS)) {
1686 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1688 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1689 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1690 // Compare X and Y. Note that signed predicates become unsigned.
1691 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1692 SrcOp, RI->getOperand(0), TD, DT,
1696 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1697 // too. If not, then try to deduce the result of the comparison.
1698 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1699 // Compute the constant that would happen if we truncated to SrcTy then
1700 // reextended to DstTy.
1701 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1702 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1704 // If the re-extended constant didn't change then this is effectively
1705 // also a case of comparing two zero-extended values.
1706 if (RExt == CI && MaxRecurse)
1707 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1708 SrcOp, Trunc, TD, DT, MaxRecurse-1))
1711 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1712 // there. Use this to work out the result of the comparison.
1716 assert(false && "Unknown ICmp predicate!");
1718 case ICmpInst::ICMP_EQ:
1719 case ICmpInst::ICMP_UGT:
1720 case ICmpInst::ICMP_UGE:
1721 return ConstantInt::getFalse(CI->getContext());
1723 case ICmpInst::ICMP_NE:
1724 case ICmpInst::ICMP_ULT:
1725 case ICmpInst::ICMP_ULE:
1726 return ConstantInt::getTrue(CI->getContext());
1728 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
1729 // is non-negative then LHS <s RHS.
1730 case ICmpInst::ICMP_SGT:
1731 case ICmpInst::ICMP_SGE:
1732 return CI->getValue().isNegative() ?
1733 ConstantInt::getTrue(CI->getContext()) :
1734 ConstantInt::getFalse(CI->getContext());
1736 case ICmpInst::ICMP_SLT:
1737 case ICmpInst::ICMP_SLE:
1738 return CI->getValue().isNegative() ?
1739 ConstantInt::getFalse(CI->getContext()) :
1740 ConstantInt::getTrue(CI->getContext());
1746 if (isa<SExtInst>(LHS)) {
1747 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1749 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1750 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1751 // Compare X and Y. Note that the predicate does not change.
1752 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1753 TD, DT, MaxRecurse-1))
1756 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1757 // too. If not, then try to deduce the result of the comparison.
1758 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1759 // Compute the constant that would happen if we truncated to SrcTy then
1760 // reextended to DstTy.
1761 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1762 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1764 // If the re-extended constant didn't change then this is effectively
1765 // also a case of comparing two sign-extended values.
1766 if (RExt == CI && MaxRecurse)
1767 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, TD, DT,
1771 // Otherwise the upper bits of LHS are all equal, while RHS has varying
1772 // bits there. Use this to work out the result of the comparison.
1776 assert(false && "Unknown ICmp predicate!");
1777 case ICmpInst::ICMP_EQ:
1778 return ConstantInt::getFalse(CI->getContext());
1779 case ICmpInst::ICMP_NE:
1780 return ConstantInt::getTrue(CI->getContext());
1782 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
1784 case ICmpInst::ICMP_SGT:
1785 case ICmpInst::ICMP_SGE:
1786 return CI->getValue().isNegative() ?
1787 ConstantInt::getTrue(CI->getContext()) :
1788 ConstantInt::getFalse(CI->getContext());
1789 case ICmpInst::ICMP_SLT:
1790 case ICmpInst::ICMP_SLE:
1791 return CI->getValue().isNegative() ?
1792 ConstantInt::getFalse(CI->getContext()) :
1793 ConstantInt::getTrue(CI->getContext());
1795 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
1797 case ICmpInst::ICMP_UGT:
1798 case ICmpInst::ICMP_UGE:
1799 // Comparison is true iff the LHS <s 0.
1801 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
1802 Constant::getNullValue(SrcTy),
1803 TD, DT, MaxRecurse-1))
1806 case ICmpInst::ICMP_ULT:
1807 case ICmpInst::ICMP_ULE:
1808 // Comparison is true iff the LHS >=s 0.
1810 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
1811 Constant::getNullValue(SrcTy),
1812 TD, DT, MaxRecurse-1))
1821 // Special logic for binary operators.
1822 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
1823 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
1824 if (MaxRecurse && (LBO || RBO)) {
1825 // Analyze the case when either LHS or RHS is an add instruction.
1826 Value *A = 0, *B = 0, *C = 0, *D = 0;
1827 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
1828 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
1829 if (LBO && LBO->getOpcode() == Instruction::Add) {
1830 A = LBO->getOperand(0); B = LBO->getOperand(1);
1831 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
1832 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
1833 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
1835 if (RBO && RBO->getOpcode() == Instruction::Add) {
1836 C = RBO->getOperand(0); D = RBO->getOperand(1);
1837 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
1838 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
1839 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
1842 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
1843 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
1844 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
1845 Constant::getNullValue(RHS->getType()),
1846 TD, DT, MaxRecurse-1))
1849 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
1850 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
1851 if (Value *V = SimplifyICmpInst(Pred,
1852 Constant::getNullValue(LHS->getType()),
1853 C == LHS ? D : C, TD, DT, MaxRecurse-1))
1856 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
1857 if (A && C && (A == C || A == D || B == C || B == D) &&
1858 NoLHSWrapProblem && NoRHSWrapProblem) {
1859 // Determine Y and Z in the form icmp (X+Y), (X+Z).
1860 Value *Y = (A == C || A == D) ? B : A;
1861 Value *Z = (C == A || C == B) ? D : C;
1862 if (Value *V = SimplifyICmpInst(Pred, Y, Z, TD, DT, MaxRecurse-1))
1867 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
1868 bool KnownNonNegative, KnownNegative;
1872 case ICmpInst::ICMP_SGT:
1873 case ICmpInst::ICMP_SGE:
1874 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1875 if (!KnownNonNegative)
1878 case ICmpInst::ICMP_EQ:
1879 case ICmpInst::ICMP_UGT:
1880 case ICmpInst::ICMP_UGE:
1881 return getFalse(ITy);
1882 case ICmpInst::ICMP_SLT:
1883 case ICmpInst::ICMP_SLE:
1884 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
1885 if (!KnownNonNegative)
1888 case ICmpInst::ICMP_NE:
1889 case ICmpInst::ICMP_ULT:
1890 case ICmpInst::ICMP_ULE:
1891 return getTrue(ITy);
1894 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
1895 bool KnownNonNegative, KnownNegative;
1899 case ICmpInst::ICMP_SGT:
1900 case ICmpInst::ICMP_SGE:
1901 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1902 if (!KnownNonNegative)
1905 case ICmpInst::ICMP_NE:
1906 case ICmpInst::ICMP_UGT:
1907 case ICmpInst::ICMP_UGE:
1908 return getTrue(ITy);
1909 case ICmpInst::ICMP_SLT:
1910 case ICmpInst::ICMP_SLE:
1911 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
1912 if (!KnownNonNegative)
1915 case ICmpInst::ICMP_EQ:
1916 case ICmpInst::ICMP_ULT:
1917 case ICmpInst::ICMP_ULE:
1918 return getFalse(ITy);
1923 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
1924 // icmp pred (X /u Y), X
1925 if (Pred == ICmpInst::ICMP_UGT)
1926 return getFalse(ITy);
1927 if (Pred == ICmpInst::ICMP_ULE)
1928 return getTrue(ITy);
1931 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
1932 LBO->getOperand(1) == RBO->getOperand(1)) {
1933 switch (LBO->getOpcode()) {
1935 case Instruction::UDiv:
1936 case Instruction::LShr:
1937 if (ICmpInst::isSigned(Pred))
1940 case Instruction::SDiv:
1941 case Instruction::AShr:
1942 if (!LBO->isExact() || !RBO->isExact())
1944 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
1945 RBO->getOperand(0), TD, DT, MaxRecurse-1))
1948 case Instruction::Shl: {
1949 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
1950 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
1953 if (!NSW && ICmpInst::isSigned(Pred))
1955 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
1956 RBO->getOperand(0), TD, DT, MaxRecurse-1))
1963 // Simplify comparisons involving max/min.
1965 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
1966 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
1968 // Signed variants on "max(a,b)>=a -> true".
1969 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
1970 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
1971 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
1972 // We analyze this as smax(A, B) pred A.
1974 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
1975 (A == LHS || B == LHS)) {
1976 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
1977 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
1978 // We analyze this as smax(A, B) swapped-pred A.
1979 P = CmpInst::getSwappedPredicate(Pred);
1980 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
1981 (A == RHS || B == RHS)) {
1982 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
1983 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
1984 // We analyze this as smax(-A, -B) swapped-pred -A.
1985 // Note that we do not need to actually form -A or -B thanks to EqP.
1986 P = CmpInst::getSwappedPredicate(Pred);
1987 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
1988 (A == LHS || B == LHS)) {
1989 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
1990 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
1991 // We analyze this as smax(-A, -B) pred -A.
1992 // Note that we do not need to actually form -A or -B thanks to EqP.
1995 if (P != CmpInst::BAD_ICMP_PREDICATE) {
1996 // Cases correspond to "max(A, B) p A".
2000 case CmpInst::ICMP_EQ:
2001 case CmpInst::ICMP_SLE:
2002 // Equivalent to "A EqP B". This may be the same as the condition tested
2003 // in the max/min; if so, we can just return that.
2004 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2006 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2008 // Otherwise, see if "A EqP B" simplifies.
2010 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, DT, MaxRecurse-1))
2013 case CmpInst::ICMP_NE:
2014 case CmpInst::ICMP_SGT: {
2015 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2016 // Equivalent to "A InvEqP B". This may be the same as the condition
2017 // tested in the max/min; if so, we can just return that.
2018 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2020 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2022 // Otherwise, see if "A InvEqP B" simplifies.
2024 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, DT, MaxRecurse-1))
2028 case CmpInst::ICMP_SGE:
2030 return getTrue(ITy);
2031 case CmpInst::ICMP_SLT:
2033 return getFalse(ITy);
2037 // Unsigned variants on "max(a,b)>=a -> true".
2038 P = CmpInst::BAD_ICMP_PREDICATE;
2039 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2040 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2041 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2042 // We analyze this as umax(A, B) pred A.
2044 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2045 (A == LHS || B == LHS)) {
2046 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2047 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2048 // We analyze this as umax(A, B) swapped-pred A.
2049 P = CmpInst::getSwappedPredicate(Pred);
2050 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2051 (A == RHS || B == RHS)) {
2052 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2053 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2054 // We analyze this as umax(-A, -B) swapped-pred -A.
2055 // Note that we do not need to actually form -A or -B thanks to EqP.
2056 P = CmpInst::getSwappedPredicate(Pred);
2057 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2058 (A == LHS || B == LHS)) {
2059 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2060 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2061 // We analyze this as umax(-A, -B) pred -A.
2062 // Note that we do not need to actually form -A or -B thanks to EqP.
2065 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2066 // Cases correspond to "max(A, B) p A".
2070 case CmpInst::ICMP_EQ:
2071 case CmpInst::ICMP_ULE:
2072 // Equivalent to "A EqP B". This may be the same as the condition tested
2073 // in the max/min; if so, we can just return that.
2074 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2076 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2078 // Otherwise, see if "A EqP B" simplifies.
2080 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, DT, MaxRecurse-1))
2083 case CmpInst::ICMP_NE:
2084 case CmpInst::ICMP_UGT: {
2085 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2086 // Equivalent to "A InvEqP B". This may be the same as the condition
2087 // tested in the max/min; if so, we can just return that.
2088 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2090 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2092 // Otherwise, see if "A InvEqP B" simplifies.
2094 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, DT, MaxRecurse-1))
2098 case CmpInst::ICMP_UGE:
2100 return getTrue(ITy);
2101 case CmpInst::ICMP_ULT:
2103 return getFalse(ITy);
2107 // Variants on "max(x,y) >= min(x,z)".
2109 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2110 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2111 (A == C || A == D || B == C || B == D)) {
2112 // max(x, ?) pred min(x, ?).
2113 if (Pred == CmpInst::ICMP_SGE)
2115 return getTrue(ITy);
2116 if (Pred == CmpInst::ICMP_SLT)
2118 return getFalse(ITy);
2119 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2120 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2121 (A == C || A == D || B == C || B == D)) {
2122 // min(x, ?) pred max(x, ?).
2123 if (Pred == CmpInst::ICMP_SLE)
2125 return getTrue(ITy);
2126 if (Pred == CmpInst::ICMP_SGT)
2128 return getFalse(ITy);
2129 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2130 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2131 (A == C || A == D || B == C || B == D)) {
2132 // max(x, ?) pred min(x, ?).
2133 if (Pred == CmpInst::ICMP_UGE)
2135 return getTrue(ITy);
2136 if (Pred == CmpInst::ICMP_ULT)
2138 return getFalse(ITy);
2139 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2140 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2141 (A == C || A == D || B == C || B == D)) {
2142 // min(x, ?) pred max(x, ?).
2143 if (Pred == CmpInst::ICMP_ULE)
2145 return getTrue(ITy);
2146 if (Pred == CmpInst::ICMP_UGT)
2148 return getFalse(ITy);
2151 // If the comparison is with the result of a select instruction, check whether
2152 // comparing with either branch of the select always yields the same value.
2153 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2154 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
2157 // If the comparison is with the result of a phi instruction, check whether
2158 // doing the compare with each incoming phi value yields a common result.
2159 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2160 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
2166 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2167 const TargetData *TD, const DominatorTree *DT) {
2168 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
2171 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2172 /// fold the result. If not, this returns null.
2173 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2174 const TargetData *TD, const DominatorTree *DT,
2175 unsigned MaxRecurse) {
2176 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2177 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2179 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2180 if (Constant *CRHS = dyn_cast<Constant>(RHS))
2181 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
2183 // If we have a constant, make sure it is on the RHS.
2184 std::swap(LHS, RHS);
2185 Pred = CmpInst::getSwappedPredicate(Pred);
2188 // Fold trivial predicates.
2189 if (Pred == FCmpInst::FCMP_FALSE)
2190 return ConstantInt::get(GetCompareTy(LHS), 0);
2191 if (Pred == FCmpInst::FCMP_TRUE)
2192 return ConstantInt::get(GetCompareTy(LHS), 1);
2194 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2195 return UndefValue::get(GetCompareTy(LHS));
2197 // fcmp x,x -> true/false. Not all compares are foldable.
2199 if (CmpInst::isTrueWhenEqual(Pred))
2200 return ConstantInt::get(GetCompareTy(LHS), 1);
2201 if (CmpInst::isFalseWhenEqual(Pred))
2202 return ConstantInt::get(GetCompareTy(LHS), 0);
2205 // Handle fcmp with constant RHS
2206 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2207 // If the constant is a nan, see if we can fold the comparison based on it.
2208 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2209 if (CFP->getValueAPF().isNaN()) {
2210 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2211 return ConstantInt::getFalse(CFP->getContext());
2212 assert(FCmpInst::isUnordered(Pred) &&
2213 "Comparison must be either ordered or unordered!");
2214 // True if unordered.
2215 return ConstantInt::getTrue(CFP->getContext());
2217 // Check whether the constant is an infinity.
2218 if (CFP->getValueAPF().isInfinity()) {
2219 if (CFP->getValueAPF().isNegative()) {
2221 case FCmpInst::FCMP_OLT:
2222 // No value is ordered and less than negative infinity.
2223 return ConstantInt::getFalse(CFP->getContext());
2224 case FCmpInst::FCMP_UGE:
2225 // All values are unordered with or at least negative infinity.
2226 return ConstantInt::getTrue(CFP->getContext());
2232 case FCmpInst::FCMP_OGT:
2233 // No value is ordered and greater than infinity.
2234 return ConstantInt::getFalse(CFP->getContext());
2235 case FCmpInst::FCMP_ULE:
2236 // All values are unordered with and at most infinity.
2237 return ConstantInt::getTrue(CFP->getContext());
2246 // If the comparison is with the result of a select instruction, check whether
2247 // comparing with either branch of the select always yields the same value.
2248 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2249 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
2252 // If the comparison is with the result of a phi instruction, check whether
2253 // doing the compare with each incoming phi value yields a common result.
2254 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2255 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
2261 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2262 const TargetData *TD, const DominatorTree *DT) {
2263 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
2266 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2267 /// the result. If not, this returns null.
2268 Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
2269 const TargetData *TD, const DominatorTree *) {
2270 // select true, X, Y -> X
2271 // select false, X, Y -> Y
2272 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2273 return CB->getZExtValue() ? TrueVal : FalseVal;
2275 // select C, X, X -> X
2276 if (TrueVal == FalseVal)
2279 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2280 if (isa<Constant>(TrueVal))
2284 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2286 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2292 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2293 /// fold the result. If not, this returns null.
2294 Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops,
2295 const TargetData *TD, const DominatorTree *) {
2296 // The type of the GEP pointer operand.
2297 PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
2299 // getelementptr P -> P.
2300 if (Ops.size() == 1)
2303 if (isa<UndefValue>(Ops[0])) {
2304 // Compute the (pointer) type returned by the GEP instruction.
2305 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
2306 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
2307 return UndefValue::get(GEPTy);
2310 if (Ops.size() == 2) {
2311 // getelementptr P, 0 -> P.
2312 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2315 // getelementptr P, N -> P if P points to a type of zero size.
2317 Type *Ty = PtrTy->getElementType();
2318 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
2323 // Check to see if this is constant foldable.
2324 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2325 if (!isa<Constant>(Ops[i]))
2328 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
2331 /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2332 /// can fold the result. If not, this returns null.
2333 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2334 ArrayRef<unsigned> Idxs,
2336 const DominatorTree *) {
2337 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2338 if (Constant *CVal = dyn_cast<Constant>(Val))
2339 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2341 // insertvalue x, undef, n -> x
2342 if (match(Val, m_Undef()))
2345 // insertvalue x, (extractvalue y, n), n
2346 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
2347 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2348 EV->getIndices() == Idxs) {
2349 // insertvalue undef, (extractvalue y, n), n -> y
2350 if (match(Agg, m_Undef()))
2351 return EV->getAggregateOperand();
2353 // insertvalue y, (extractvalue y, n), n -> y
2354 if (Agg == EV->getAggregateOperand())
2361 /// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
2362 static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
2363 // If all of the PHI's incoming values are the same then replace the PHI node
2364 // with the common value.
2365 Value *CommonValue = 0;
2366 bool HasUndefInput = false;
2367 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2368 Value *Incoming = PN->getIncomingValue(i);
2369 // If the incoming value is the phi node itself, it can safely be skipped.
2370 if (Incoming == PN) continue;
2371 if (isa<UndefValue>(Incoming)) {
2372 // Remember that we saw an undef value, but otherwise ignore them.
2373 HasUndefInput = true;
2376 if (CommonValue && Incoming != CommonValue)
2377 return 0; // Not the same, bail out.
2378 CommonValue = Incoming;
2381 // If CommonValue is null then all of the incoming values were either undef or
2382 // equal to the phi node itself.
2384 return UndefValue::get(PN->getType());
2386 // If we have a PHI node like phi(X, undef, X), where X is defined by some
2387 // instruction, we cannot return X as the result of the PHI node unless it
2388 // dominates the PHI block.
2390 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
2396 //=== Helper functions for higher up the class hierarchy.
2398 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2399 /// fold the result. If not, this returns null.
2400 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2401 const TargetData *TD, const DominatorTree *DT,
2402 unsigned MaxRecurse) {
2404 case Instruction::Add:
2405 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2406 TD, DT, MaxRecurse);
2407 case Instruction::Sub:
2408 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2409 TD, DT, MaxRecurse);
2410 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, TD, DT, MaxRecurse);
2411 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, TD, DT, MaxRecurse);
2412 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, TD, DT, MaxRecurse);
2413 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, TD, DT, MaxRecurse);
2414 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, TD, DT, MaxRecurse);
2415 case Instruction::URem: return SimplifyURemInst(LHS, RHS, TD, DT, MaxRecurse);
2416 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, TD, DT, MaxRecurse);
2417 case Instruction::Shl:
2418 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2419 TD, DT, MaxRecurse);
2420 case Instruction::LShr:
2421 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, TD, DT, MaxRecurse);
2422 case Instruction::AShr:
2423 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, TD, DT, MaxRecurse);
2424 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
2425 case Instruction::Or: return SimplifyOrInst (LHS, RHS, TD, DT, MaxRecurse);
2426 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecurse);
2428 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2429 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2430 Constant *COps[] = {CLHS, CRHS};
2431 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, TD);
2434 // If the operation is associative, try some generic simplifications.
2435 if (Instruction::isAssociative(Opcode))
2436 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, DT,
2440 // If the operation is with the result of a select instruction, check whether
2441 // operating on either branch of the select always yields the same value.
2442 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2443 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
2447 // If the operation is with the result of a phi instruction, check whether
2448 // operating on all incoming values of the phi always yields the same value.
2449 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2450 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse))
2457 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2458 const TargetData *TD, const DominatorTree *DT) {
2459 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
2462 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2463 /// fold the result.
2464 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2465 const TargetData *TD, const DominatorTree *DT,
2466 unsigned MaxRecurse) {
2467 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
2468 return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
2469 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
2472 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2473 const TargetData *TD, const DominatorTree *DT) {
2474 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
2477 static Value *SimplifyCallInst(CallInst *CI) {
2478 // call undef -> undef
2479 if (isa<UndefValue>(CI->getCalledValue()))
2480 return UndefValue::get(CI->getType());
2485 /// SimplifyInstruction - See if we can compute a simplified version of this
2486 /// instruction. If not, this returns null.
2487 Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
2488 const DominatorTree *DT) {
2491 switch (I->getOpcode()) {
2493 Result = ConstantFoldInstruction(I, TD);
2495 case Instruction::Add:
2496 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2497 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2498 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2501 case Instruction::Sub:
2502 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2503 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2504 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2507 case Instruction::Mul:
2508 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, DT);
2510 case Instruction::SDiv:
2511 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2513 case Instruction::UDiv:
2514 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2516 case Instruction::FDiv:
2517 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, DT);
2519 case Instruction::SRem:
2520 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2522 case Instruction::URem:
2523 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2525 case Instruction::FRem:
2526 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, DT);
2528 case Instruction::Shl:
2529 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2530 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2531 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2534 case Instruction::LShr:
2535 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2536 cast<BinaryOperator>(I)->isExact(),
2539 case Instruction::AShr:
2540 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2541 cast<BinaryOperator>(I)->isExact(),
2544 case Instruction::And:
2545 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
2547 case Instruction::Or:
2548 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
2550 case Instruction::Xor:
2551 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
2553 case Instruction::ICmp:
2554 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
2555 I->getOperand(0), I->getOperand(1), TD, DT);
2557 case Instruction::FCmp:
2558 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
2559 I->getOperand(0), I->getOperand(1), TD, DT);
2561 case Instruction::Select:
2562 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
2563 I->getOperand(2), TD, DT);
2565 case Instruction::GetElementPtr: {
2566 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
2567 Result = SimplifyGEPInst(Ops, TD, DT);
2570 case Instruction::InsertValue: {
2571 InsertValueInst *IV = cast<InsertValueInst>(I);
2572 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
2573 IV->getInsertedValueOperand(),
2574 IV->getIndices(), TD, DT);
2577 case Instruction::PHI:
2578 Result = SimplifyPHINode(cast<PHINode>(I), DT);
2580 case Instruction::Call:
2581 Result = SimplifyCallInst(cast<CallInst>(I));
2585 /// If called on unreachable code, the above logic may report that the
2586 /// instruction simplified to itself. Make life easier for users by
2587 /// detecting that case here, returning a safe value instead.
2588 return Result == I ? UndefValue::get(I->getType()) : Result;
2591 /// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
2592 /// delete the From instruction. In addition to a basic RAUW, this does a
2593 /// recursive simplification of the newly formed instructions. This catches
2594 /// things where one simplification exposes other opportunities. This only
2595 /// simplifies and deletes scalar operations, it does not change the CFG.
2597 void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
2598 const TargetData *TD,
2599 const DominatorTree *DT) {
2600 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
2602 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
2603 // we can know if it gets deleted out from under us or replaced in a
2604 // recursive simplification.
2605 WeakVH FromHandle(From);
2606 WeakVH ToHandle(To);
2608 while (!From->use_empty()) {
2609 // Update the instruction to use the new value.
2610 Use &TheUse = From->use_begin().getUse();
2611 Instruction *User = cast<Instruction>(TheUse.getUser());
2614 // Check to see if the instruction can be folded due to the operand
2615 // replacement. For example changing (or X, Y) into (or X, -1) can replace
2616 // the 'or' with -1.
2617 Value *SimplifiedVal;
2619 // Sanity check to make sure 'User' doesn't dangle across
2620 // SimplifyInstruction.
2621 AssertingVH<> UserHandle(User);
2623 SimplifiedVal = SimplifyInstruction(User, TD, DT);
2624 if (SimplifiedVal == 0) continue;
2627 // Recursively simplify this user to the new value.
2628 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
2629 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
2632 assert(ToHandle && "To value deleted by recursive simplification?");
2634 // If the recursive simplification ended up revisiting and deleting
2635 // 'From' then we're done.
2640 // If 'From' has value handles referring to it, do a real RAUW to update them.
2641 From->replaceAllUsesWith(To);
2643 From->eraseFromParent();