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/GlobalAlias.h"
22 #include "llvm/Operator.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/ADT/SetVector.h"
25 #include "llvm/Analysis/InstructionSimplify.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Analysis/ConstantFolding.h"
28 #include "llvm/Analysis/Dominators.h"
29 #include "llvm/Analysis/ValueTracking.h"
30 #include "llvm/Support/ConstantRange.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/Support/PatternMatch.h"
33 #include "llvm/Support/ValueHandle.h"
34 #include "llvm/Target/TargetData.h"
36 using namespace llvm::PatternMatch;
38 enum { RecursionLimit = 3 };
40 STATISTIC(NumExpand, "Number of expansions");
41 STATISTIC(NumFactor , "Number of factorizations");
42 STATISTIC(NumReassoc, "Number of reassociations");
46 const TargetLibraryInfo *TLI;
47 const DominatorTree *DT;
49 Query(const TargetData *td, const TargetLibraryInfo *tli,
50 const DominatorTree *dt) : TD(td), TLI(tli), DT(dt) {}
53 static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
54 static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
56 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
58 static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
59 static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
60 static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
62 /// getFalse - For a boolean type, or a vector of boolean type, return false, or
63 /// a vector with every element false, as appropriate for the type.
64 static Constant *getFalse(Type *Ty) {
65 assert(Ty->getScalarType()->isIntegerTy(1) &&
66 "Expected i1 type or a vector of i1!");
67 return Constant::getNullValue(Ty);
70 /// getTrue - For a boolean type, or a vector of boolean type, return true, or
71 /// a vector with every element true, as appropriate for the type.
72 static Constant *getTrue(Type *Ty) {
73 assert(Ty->getScalarType()->isIntegerTy(1) &&
74 "Expected i1 type or a vector of i1!");
75 return Constant::getAllOnesValue(Ty);
78 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
79 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
81 CmpInst *Cmp = dyn_cast<CmpInst>(V);
84 CmpInst::Predicate CPred = Cmp->getPredicate();
85 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
86 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
88 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
92 /// ValueDominatesPHI - Does the given value dominate the specified phi node?
93 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
94 Instruction *I = dyn_cast<Instruction>(V);
96 // Arguments and constants dominate all instructions.
99 // If we are processing instructions (and/or basic blocks) that have not been
100 // fully added to a function, the parent nodes may still be null. Simply
101 // return the conservative answer in these cases.
102 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
105 // If we have a DominatorTree then do a precise test.
107 if (!DT->isReachableFromEntry(P->getParent()))
109 if (!DT->isReachableFromEntry(I->getParent()))
111 return DT->dominates(I, P);
114 // Otherwise, if the instruction is in the entry block, and is not an invoke,
115 // then it obviously dominates all phi nodes.
116 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
123 /// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
124 /// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
125 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
126 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
127 /// Returns the simplified value, or null if no simplification was performed.
128 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
129 unsigned OpcToExpand, const Query &Q,
130 unsigned MaxRecurse) {
131 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
132 // Recursion is always used, so bail out at once if we already hit the limit.
136 // Check whether the expression has the form "(A op' B) op C".
137 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
138 if (Op0->getOpcode() == OpcodeToExpand) {
139 // It does! Try turning it into "(A op C) op' (B op C)".
140 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
141 // Do "A op C" and "B op C" both simplify?
142 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
143 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
144 // They do! Return "L op' R" if it simplifies or is already available.
145 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
146 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
147 && L == B && R == A)) {
151 // Otherwise return "L op' R" if it simplifies.
152 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
159 // Check whether the expression has the form "A op (B op' C)".
160 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
161 if (Op1->getOpcode() == OpcodeToExpand) {
162 // It does! Try turning it into "(A op B) op' (A op C)".
163 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
164 // Do "A op B" and "A op C" both simplify?
165 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
166 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
167 // They do! Return "L op' R" if it simplifies or is already available.
168 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
169 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
170 && L == C && R == B)) {
174 // Otherwise return "L op' R" if it simplifies.
175 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
185 /// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
186 /// using the operation OpCodeToExtract. For example, when Opcode is Add and
187 /// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
188 /// Returns the simplified value, or null if no simplification was performed.
189 static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
190 unsigned OpcToExtract, const Query &Q,
191 unsigned MaxRecurse) {
192 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
193 // Recursion is always used, so bail out at once if we already hit the limit.
197 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
198 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
200 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
201 !Op1 || Op1->getOpcode() != OpcodeToExtract)
204 // The expression has the form "(A op' B) op (C op' D)".
205 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
206 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
208 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
209 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
210 // commutative case, "(A op' B) op (C op' A)"?
211 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
212 Value *DD = A == C ? D : C;
213 // Form "A op' (B op DD)" if it simplifies completely.
214 // Does "B op DD" simplify?
215 if (Value *V = SimplifyBinOp(Opcode, B, DD, Q, MaxRecurse)) {
216 // It does! Return "A op' V" if it simplifies or is already available.
217 // If V equals B then "A op' V" is just the LHS. If V equals DD then
218 // "A op' V" is just the RHS.
219 if (V == B || V == DD) {
221 return V == B ? LHS : RHS;
223 // Otherwise return "A op' V" if it simplifies.
224 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, Q, MaxRecurse)) {
231 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
232 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
233 // commutative case, "(A op' B) op (B op' D)"?
234 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
235 Value *CC = B == D ? C : D;
236 // Form "(A op CC) op' B" if it simplifies completely..
237 // Does "A op CC" simplify?
238 if (Value *V = SimplifyBinOp(Opcode, A, CC, Q, MaxRecurse)) {
239 // It does! Return "V op' B" if it simplifies or is already available.
240 // If V equals A then "V op' B" is just the LHS. If V equals CC then
241 // "V op' B" is just the RHS.
242 if (V == A || V == CC) {
244 return V == A ? LHS : RHS;
246 // Otherwise return "V op' B" if it simplifies.
247 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, Q, MaxRecurse)) {
257 /// SimplifyAssociativeBinOp - Generic simplifications for associative binary
258 /// operations. Returns the simpler value, or null if none was found.
259 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
260 const Query &Q, unsigned MaxRecurse) {
261 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
262 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
264 // Recursion is always used, so bail out at once if we already hit the limit.
268 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
269 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
271 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
272 if (Op0 && Op0->getOpcode() == Opcode) {
273 Value *A = Op0->getOperand(0);
274 Value *B = Op0->getOperand(1);
277 // Does "B op C" simplify?
278 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
279 // It does! Return "A op V" if it simplifies or is already available.
280 // If V equals B then "A op V" is just the LHS.
281 if (V == B) return LHS;
282 // Otherwise return "A op V" if it simplifies.
283 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
290 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
291 if (Op1 && Op1->getOpcode() == Opcode) {
293 Value *B = Op1->getOperand(0);
294 Value *C = Op1->getOperand(1);
296 // Does "A op B" simplify?
297 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
298 // It does! Return "V op C" if it simplifies or is already available.
299 // If V equals B then "V op C" is just the RHS.
300 if (V == B) return RHS;
301 // Otherwise return "V op C" if it simplifies.
302 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
309 // The remaining transforms require commutativity as well as associativity.
310 if (!Instruction::isCommutative(Opcode))
313 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
314 if (Op0 && Op0->getOpcode() == Opcode) {
315 Value *A = Op0->getOperand(0);
316 Value *B = Op0->getOperand(1);
319 // Does "C op A" simplify?
320 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
321 // It does! Return "V op B" if it simplifies or is already available.
322 // If V equals A then "V op B" is just the LHS.
323 if (V == A) return LHS;
324 // Otherwise return "V op B" if it simplifies.
325 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
332 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
333 if (Op1 && Op1->getOpcode() == Opcode) {
335 Value *B = Op1->getOperand(0);
336 Value *C = Op1->getOperand(1);
338 // Does "C op A" simplify?
339 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
340 // It does! Return "B op V" if it simplifies or is already available.
341 // If V equals C then "B op V" is just the RHS.
342 if (V == C) return RHS;
343 // Otherwise return "B op V" if it simplifies.
344 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
354 /// ThreadBinOpOverSelect - In the case of a binary operation with a select
355 /// instruction as an operand, try to simplify the binop by seeing whether
356 /// evaluating it on both branches of the select results in the same value.
357 /// Returns the common value if so, otherwise returns null.
358 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
359 const Query &Q, unsigned MaxRecurse) {
360 // Recursion is always used, so bail out at once if we already hit the limit.
365 if (isa<SelectInst>(LHS)) {
366 SI = cast<SelectInst>(LHS);
368 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
369 SI = cast<SelectInst>(RHS);
372 // Evaluate the BinOp on the true and false branches of the select.
376 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
377 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
379 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
380 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
383 // If they simplified to the same value, then return the common value.
384 // If they both failed to simplify then return null.
388 // If one branch simplified to undef, return the other one.
389 if (TV && isa<UndefValue>(TV))
391 if (FV && isa<UndefValue>(FV))
394 // If applying the operation did not change the true and false select values,
395 // then the result of the binop is the select itself.
396 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
399 // If one branch simplified and the other did not, and the simplified
400 // value is equal to the unsimplified one, return the simplified value.
401 // For example, select (cond, X, X & Z) & Z -> X & Z.
402 if ((FV && !TV) || (TV && !FV)) {
403 // Check that the simplified value has the form "X op Y" where "op" is the
404 // same as the original operation.
405 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
406 if (Simplified && Simplified->getOpcode() == Opcode) {
407 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
408 // We already know that "op" is the same as for the simplified value. See
409 // if the operands match too. If so, return the simplified value.
410 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
411 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
412 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
413 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
414 Simplified->getOperand(1) == UnsimplifiedRHS)
416 if (Simplified->isCommutative() &&
417 Simplified->getOperand(1) == UnsimplifiedLHS &&
418 Simplified->getOperand(0) == UnsimplifiedRHS)
426 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
427 /// try to simplify the comparison by seeing whether both branches of the select
428 /// result in the same value. Returns the common value if so, otherwise returns
430 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
431 Value *RHS, const Query &Q,
432 unsigned MaxRecurse) {
433 // Recursion is always used, so bail out at once if we already hit the limit.
437 // Make sure the select is on the LHS.
438 if (!isa<SelectInst>(LHS)) {
440 Pred = CmpInst::getSwappedPredicate(Pred);
442 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
443 SelectInst *SI = cast<SelectInst>(LHS);
444 Value *Cond = SI->getCondition();
445 Value *TV = SI->getTrueValue();
446 Value *FV = SI->getFalseValue();
448 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
449 // Does "cmp TV, RHS" simplify?
450 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
452 // It not only simplified, it simplified to the select condition. Replace
454 TCmp = getTrue(Cond->getType());
456 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
457 // condition then we can replace it with 'true'. Otherwise give up.
458 if (!isSameCompare(Cond, Pred, TV, RHS))
460 TCmp = getTrue(Cond->getType());
463 // Does "cmp FV, RHS" simplify?
464 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
466 // It not only simplified, it simplified to the select condition. Replace
468 FCmp = getFalse(Cond->getType());
470 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
471 // condition then we can replace it with 'false'. Otherwise give up.
472 if (!isSameCompare(Cond, Pred, FV, RHS))
474 FCmp = getFalse(Cond->getType());
477 // If both sides simplified to the same value, then use it as the result of
478 // the original comparison.
482 // The remaining cases only make sense if the select condition has the same
483 // type as the result of the comparison, so bail out if this is not so.
484 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
486 // If the false value simplified to false, then the result of the compare
487 // is equal to "Cond && TCmp". This also catches the case when the false
488 // value simplified to false and the true value to true, returning "Cond".
489 if (match(FCmp, m_Zero()))
490 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
492 // If the true value simplified to true, then the result of the compare
493 // is equal to "Cond || FCmp".
494 if (match(TCmp, m_One()))
495 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
497 // Finally, if the false value simplified to true and the true value to
498 // false, then the result of the compare is equal to "!Cond".
499 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
501 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
508 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
509 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
510 /// it on the incoming phi values yields the same result for every value. If so
511 /// returns the common value, otherwise returns null.
512 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
513 const Query &Q, unsigned MaxRecurse) {
514 // Recursion is always used, so bail out at once if we already hit the limit.
519 if (isa<PHINode>(LHS)) {
520 PI = cast<PHINode>(LHS);
521 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
522 if (!ValueDominatesPHI(RHS, PI, Q.DT))
525 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
526 PI = cast<PHINode>(RHS);
527 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
528 if (!ValueDominatesPHI(LHS, PI, Q.DT))
532 // Evaluate the BinOp on the incoming phi values.
533 Value *CommonValue = 0;
534 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
535 Value *Incoming = PI->getIncomingValue(i);
536 // If the incoming value is the phi node itself, it can safely be skipped.
537 if (Incoming == PI) continue;
538 Value *V = PI == LHS ?
539 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
540 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
541 // If the operation failed to simplify, or simplified to a different value
542 // to previously, then give up.
543 if (!V || (CommonValue && V != CommonValue))
551 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
552 /// try to simplify the comparison by seeing whether comparing with all of the
553 /// incoming phi values yields the same result every time. If so returns the
554 /// common result, otherwise returns null.
555 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
556 const Query &Q, unsigned MaxRecurse) {
557 // Recursion is always used, so bail out at once if we already hit the limit.
561 // Make sure the phi is on the LHS.
562 if (!isa<PHINode>(LHS)) {
564 Pred = CmpInst::getSwappedPredicate(Pred);
566 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
567 PHINode *PI = cast<PHINode>(LHS);
569 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
570 if (!ValueDominatesPHI(RHS, PI, Q.DT))
573 // Evaluate the BinOp on the incoming phi values.
574 Value *CommonValue = 0;
575 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
576 Value *Incoming = PI->getIncomingValue(i);
577 // If the incoming value is the phi node itself, it can safely be skipped.
578 if (Incoming == PI) continue;
579 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
580 // If the operation failed to simplify, or simplified to a different value
581 // to previously, then give up.
582 if (!V || (CommonValue && V != CommonValue))
590 /// SimplifyAddInst - Given operands for an Add, see if we can
591 /// fold the result. If not, this returns null.
592 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
593 const Query &Q, unsigned MaxRecurse) {
594 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
595 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
596 Constant *Ops[] = { CLHS, CRHS };
597 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(), Ops,
601 // Canonicalize the constant to the RHS.
605 // X + undef -> undef
606 if (match(Op1, m_Undef()))
610 if (match(Op1, m_Zero()))
617 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
618 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
621 // X + ~X -> -1 since ~X = -X-1
622 if (match(Op0, m_Not(m_Specific(Op1))) ||
623 match(Op1, m_Not(m_Specific(Op0))))
624 return Constant::getAllOnesValue(Op0->getType());
627 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
628 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
631 // Try some generic simplifications for associative operations.
632 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
636 // Mul distributes over Add. Try some generic simplifications based on this.
637 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
641 // Threading Add over selects and phi nodes is pointless, so don't bother.
642 // Threading over the select in "A + select(cond, B, C)" means evaluating
643 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
644 // only if B and C are equal. If B and C are equal then (since we assume
645 // that operands have already been simplified) "select(cond, B, C)" should
646 // have been simplified to the common value of B and C already. Analysing
647 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
648 // for threading over phi nodes.
653 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
654 const TargetData *TD, const TargetLibraryInfo *TLI,
655 const DominatorTree *DT) {
656 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
660 /// \brief Accumulate the constant integer offset a GEP represents.
662 /// Given a getelementptr instruction/constantexpr, accumulate the constant
663 /// offset from the base pointer into the provided APInt 'Offset'. Returns true
664 /// if the GEP has all-constant indices. Returns false if any non-constant
665 /// index is encountered leaving the 'Offset' in an undefined state. The
666 /// 'Offset' APInt must be the bitwidth of the target's pointer size.
667 static bool accumulateGEPOffset(const TargetData &TD, GEPOperator *GEP,
669 unsigned IntPtrWidth = TD.getPointerSizeInBits();
670 assert(IntPtrWidth == Offset.getBitWidth());
672 gep_type_iterator GTI = gep_type_begin(GEP);
673 for (User::op_iterator I = GEP->op_begin() + 1, E = GEP->op_end(); I != E;
675 ConstantInt *OpC = dyn_cast<ConstantInt>(*I);
676 if (!OpC) return false;
677 if (OpC->isZero()) continue;
679 // Handle a struct index, which adds its field offset to the pointer.
680 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
681 unsigned ElementIdx = OpC->getZExtValue();
682 const StructLayout *SL = TD.getStructLayout(STy);
683 Offset += APInt(IntPtrWidth, SL->getElementOffset(ElementIdx));
687 APInt TypeSize(IntPtrWidth, TD.getTypeAllocSize(GTI.getIndexedType()));
688 Offset += OpC->getValue().sextOrTrunc(IntPtrWidth) * TypeSize;
693 /// \brief Compute the base pointer and cumulative constant offsets for V.
695 /// This strips all constant offsets off of V, leaving it the base pointer, and
696 /// accumulates the total constant offset applied in the returned constant. It
697 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
698 /// no constant offsets applied.
699 static Constant *stripAndComputeConstantOffsets(const TargetData &TD,
701 if (!V->getType()->isPointerTy())
704 unsigned IntPtrWidth = TD.getPointerSizeInBits();
705 APInt Offset = APInt::getNullValue(IntPtrWidth);
707 // Even though we don't look through PHI nodes, we could be called on an
708 // instruction in an unreachable block, which may be on a cycle.
709 SmallPtrSet<Value *, 4> Visited;
712 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
713 if (!GEP->isInBounds() || !accumulateGEPOffset(TD, GEP, Offset))
715 V = GEP->getPointerOperand();
716 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
717 V = cast<Operator>(V)->getOperand(0);
718 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
719 if (GA->mayBeOverridden())
721 V = GA->getAliasee();
725 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
726 } while (Visited.insert(V));
728 Type *IntPtrTy = TD.getIntPtrType(V->getContext());
729 return ConstantInt::get(IntPtrTy, Offset);
732 /// \brief Compute the constant difference between two pointer values.
733 /// If the difference is not a constant, returns zero.
734 static Constant *computePointerDifference(const TargetData &TD,
735 Value *LHS, Value *RHS) {
736 Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
739 Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
743 // If LHS and RHS are not related via constant offsets to the same base
744 // value, there is nothing we can do here.
748 // Otherwise, the difference of LHS - RHS can be computed as:
750 // = (LHSOffset + Base) - (RHSOffset + Base)
751 // = LHSOffset - RHSOffset
752 return ConstantExpr::getSub(LHSOffset, RHSOffset);
755 /// SimplifySubInst - Given operands for a Sub, see if we can
756 /// fold the result. If not, this returns null.
757 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
758 const Query &Q, unsigned MaxRecurse) {
759 if (Constant *CLHS = dyn_cast<Constant>(Op0))
760 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
761 Constant *Ops[] = { CLHS, CRHS };
762 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
766 // X - undef -> undef
767 // undef - X -> undef
768 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
769 return UndefValue::get(Op0->getType());
772 if (match(Op1, m_Zero()))
777 return Constant::getNullValue(Op0->getType());
782 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
783 match(Op0, m_Shl(m_Specific(Op1), m_One())))
786 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
787 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
788 Value *Y = 0, *Z = Op1;
789 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
790 // See if "V === Y - Z" simplifies.
791 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
792 // It does! Now see if "X + V" simplifies.
793 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
794 // It does, we successfully reassociated!
798 // See if "V === X - Z" simplifies.
799 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
800 // It does! Now see if "Y + V" simplifies.
801 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
802 // It does, we successfully reassociated!
808 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
809 // For example, X - (X + 1) -> -1
811 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
812 // See if "V === X - Y" simplifies.
813 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
814 // It does! Now see if "V - Z" simplifies.
815 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
816 // It does, we successfully reassociated!
820 // See if "V === X - Z" simplifies.
821 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
822 // It does! Now see if "V - Y" simplifies.
823 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
824 // It does, we successfully reassociated!
830 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
831 // For example, X - (X - Y) -> Y.
833 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
834 // See if "V === Z - X" simplifies.
835 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
836 // It does! Now see if "V + Y" simplifies.
837 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
838 // It does, we successfully reassociated!
843 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
844 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
845 match(Op1, m_Trunc(m_Value(Y))))
846 if (X->getType() == Y->getType())
847 // See if "V === X - Y" simplifies.
848 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
849 // It does! Now see if "trunc V" simplifies.
850 if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
851 // It does, return the simplified "trunc V".
854 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
855 if (Q.TD && match(Op0, m_PtrToInt(m_Value(X))) &&
856 match(Op1, m_PtrToInt(m_Value(Y))))
857 if (Constant *Result = computePointerDifference(*Q.TD, X, Y))
858 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
860 // Mul distributes over Sub. Try some generic simplifications based on this.
861 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
866 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
867 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
870 // Threading Sub over selects and phi nodes is pointless, so don't bother.
871 // Threading over the select in "A - select(cond, B, C)" means evaluating
872 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
873 // only if B and C are equal. If B and C are equal then (since we assume
874 // that operands have already been simplified) "select(cond, B, C)" should
875 // have been simplified to the common value of B and C already. Analysing
876 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
877 // for threading over phi nodes.
882 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
883 const TargetData *TD, const TargetLibraryInfo *TLI,
884 const DominatorTree *DT) {
885 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
889 /// SimplifyMulInst - Given operands for a Mul, see if we can
890 /// fold the result. If not, this returns null.
891 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
892 unsigned MaxRecurse) {
893 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
894 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
895 Constant *Ops[] = { CLHS, CRHS };
896 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
900 // Canonicalize the constant to the RHS.
905 if (match(Op1, m_Undef()))
906 return Constant::getNullValue(Op0->getType());
909 if (match(Op1, m_Zero()))
913 if (match(Op1, m_One()))
916 // (X / Y) * Y -> X if the division is exact.
918 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
919 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
923 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
924 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
927 // Try some generic simplifications for associative operations.
928 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
932 // Mul distributes over Add. Try some generic simplifications based on this.
933 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
937 // If the operation is with the result of a select instruction, check whether
938 // operating on either branch of the select always yields the same value.
939 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
940 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
944 // If the operation is with the result of a phi instruction, check whether
945 // operating on all incoming values of the phi always yields the same value.
946 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
947 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
954 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
955 const TargetLibraryInfo *TLI,
956 const DominatorTree *DT) {
957 return ::SimplifyMulInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
960 /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
961 /// fold the result. If not, this returns null.
962 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
963 const Query &Q, unsigned MaxRecurse) {
964 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
965 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
966 Constant *Ops[] = { C0, C1 };
967 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
971 bool isSigned = Opcode == Instruction::SDiv;
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()))
986 if (match(Op1, m_One()))
989 if (Op0->getType()->isIntegerTy(1))
990 // It can't be division by zero, hence it must be division by one.
995 return ConstantInt::get(Op0->getType(), 1);
997 // (X * Y) / Y -> X if the multiplication does not overflow.
998 Value *X = 0, *Y = 0;
999 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1000 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
1001 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
1002 // If the Mul knows it does not overflow, then we are good to go.
1003 if ((isSigned && Mul->hasNoSignedWrap()) ||
1004 (!isSigned && Mul->hasNoUnsignedWrap()))
1006 // If X has the form X = A / Y then X * Y cannot overflow.
1007 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1008 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1012 // (X rem Y) / Y -> 0
1013 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1014 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1015 return Constant::getNullValue(Op0->getType());
1017 // If the operation is with the result of a select instruction, check whether
1018 // operating on either branch of the select always yields the same value.
1019 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1020 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1023 // If the operation is with the result of a phi instruction, check whether
1024 // operating on all incoming values of the phi always yields the same value.
1025 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1026 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1032 /// SimplifySDivInst - Given operands for an SDiv, see if we can
1033 /// fold the result. If not, this returns null.
1034 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1035 unsigned MaxRecurse) {
1036 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
1042 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
1043 const TargetLibraryInfo *TLI,
1044 const DominatorTree *DT) {
1045 return ::SimplifySDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1048 /// SimplifyUDivInst - Given operands for a UDiv, see if we can
1049 /// fold the result. If not, this returns null.
1050 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1051 unsigned MaxRecurse) {
1052 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
1058 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
1059 const TargetLibraryInfo *TLI,
1060 const DominatorTree *DT) {
1061 return ::SimplifyUDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1064 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q,
1066 // undef / X -> undef (the undef could be a snan).
1067 if (match(Op0, m_Undef()))
1070 // X / undef -> undef
1071 if (match(Op1, m_Undef()))
1077 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *TD,
1078 const TargetLibraryInfo *TLI,
1079 const DominatorTree *DT) {
1080 return ::SimplifyFDivInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1083 /// SimplifyRem - Given operands for an SRem or URem, see if we can
1084 /// fold the result. If not, this returns null.
1085 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1086 const Query &Q, unsigned MaxRecurse) {
1087 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1088 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1089 Constant *Ops[] = { C0, C1 };
1090 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
1094 // X % undef -> undef
1095 if (match(Op1, m_Undef()))
1099 if (match(Op0, m_Undef()))
1100 return Constant::getNullValue(Op0->getType());
1102 // 0 % X -> 0, we don't need to preserve faults!
1103 if (match(Op0, m_Zero()))
1106 // X % 0 -> undef, we don't need to preserve faults!
1107 if (match(Op1, m_Zero()))
1108 return UndefValue::get(Op0->getType());
1111 if (match(Op1, m_One()))
1112 return Constant::getNullValue(Op0->getType());
1114 if (Op0->getType()->isIntegerTy(1))
1115 // It can't be remainder by zero, hence it must be remainder by one.
1116 return Constant::getNullValue(Op0->getType());
1120 return Constant::getNullValue(Op0->getType());
1122 // If the operation is with the result of a select instruction, check whether
1123 // operating on either branch of the select always yields the same value.
1124 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1125 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1128 // If the operation is with the result of a phi instruction, check whether
1129 // operating on all incoming values of the phi always yields the same value.
1130 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1131 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1137 /// SimplifySRemInst - Given operands for an SRem, see if we can
1138 /// fold the result. If not, this returns null.
1139 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1140 unsigned MaxRecurse) {
1141 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
1147 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1148 const TargetLibraryInfo *TLI,
1149 const DominatorTree *DT) {
1150 return ::SimplifySRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1153 /// SimplifyURemInst - Given operands for a URem, see if we can
1154 /// fold the result. If not, this returns null.
1155 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
1156 unsigned MaxRecurse) {
1157 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
1163 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
1164 const TargetLibraryInfo *TLI,
1165 const DominatorTree *DT) {
1166 return ::SimplifyURemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1169 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &,
1171 // undef % X -> undef (the undef could be a snan).
1172 if (match(Op0, m_Undef()))
1175 // X % undef -> undef
1176 if (match(Op1, m_Undef()))
1182 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1183 const TargetLibraryInfo *TLI,
1184 const DominatorTree *DT) {
1185 return ::SimplifyFRemInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1188 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
1189 /// fold the result. If not, this returns null.
1190 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1191 const Query &Q, unsigned MaxRecurse) {
1192 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1193 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1194 Constant *Ops[] = { C0, C1 };
1195 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.TD, Q.TLI);
1199 // 0 shift by X -> 0
1200 if (match(Op0, m_Zero()))
1203 // X shift by 0 -> X
1204 if (match(Op1, m_Zero()))
1207 // X shift by undef -> undef because it may shift by the bitwidth.
1208 if (match(Op1, m_Undef()))
1211 // Shifting by the bitwidth or more is undefined.
1212 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1213 if (CI->getValue().getLimitedValue() >=
1214 Op0->getType()->getScalarSizeInBits())
1215 return UndefValue::get(Op0->getType());
1217 // If the operation is with the result of a select instruction, check whether
1218 // operating on either branch of the select always yields the same value.
1219 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1220 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1223 // If the operation is with the result of a phi instruction, check whether
1224 // operating on all incoming values of the phi always yields the same value.
1225 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1226 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1232 /// SimplifyShlInst - Given operands for an Shl, see if we can
1233 /// fold the result. If not, this returns null.
1234 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1235 const Query &Q, unsigned MaxRecurse) {
1236 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
1240 if (match(Op0, m_Undef()))
1241 return Constant::getNullValue(Op0->getType());
1243 // (X >> A) << A -> X
1245 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1250 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1251 const TargetData *TD, const TargetLibraryInfo *TLI,
1252 const DominatorTree *DT) {
1253 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (TD, TLI, DT),
1257 /// SimplifyLShrInst - Given operands for an LShr, see if we can
1258 /// fold the result. If not, this returns null.
1259 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1260 const Query &Q, unsigned MaxRecurse) {
1261 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse))
1265 if (match(Op0, m_Undef()))
1266 return Constant::getNullValue(Op0->getType());
1268 // (X << A) >> A -> X
1270 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1271 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1277 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1278 const TargetData *TD,
1279 const TargetLibraryInfo *TLI,
1280 const DominatorTree *DT) {
1281 return ::SimplifyLShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
1285 /// SimplifyAShrInst - Given operands for an AShr, see if we can
1286 /// fold the result. If not, this returns null.
1287 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1288 const Query &Q, unsigned MaxRecurse) {
1289 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse))
1292 // all ones >>a X -> all ones
1293 if (match(Op0, m_AllOnes()))
1296 // undef >>a X -> all ones
1297 if (match(Op0, m_Undef()))
1298 return Constant::getAllOnesValue(Op0->getType());
1300 // (X << A) >> A -> X
1302 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1303 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1309 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1310 const TargetData *TD,
1311 const TargetLibraryInfo *TLI,
1312 const DominatorTree *DT) {
1313 return ::SimplifyAShrInst(Op0, Op1, isExact, Query (TD, TLI, DT),
1317 /// SimplifyAndInst - Given operands for an And, see if we can
1318 /// fold the result. If not, this returns null.
1319 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
1320 unsigned MaxRecurse) {
1321 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1322 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1323 Constant *Ops[] = { CLHS, CRHS };
1324 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
1328 // Canonicalize the constant to the RHS.
1329 std::swap(Op0, Op1);
1333 if (match(Op1, m_Undef()))
1334 return Constant::getNullValue(Op0->getType());
1341 if (match(Op1, m_Zero()))
1345 if (match(Op1, m_AllOnes()))
1348 // A & ~A = ~A & A = 0
1349 if (match(Op0, m_Not(m_Specific(Op1))) ||
1350 match(Op1, m_Not(m_Specific(Op0))))
1351 return Constant::getNullValue(Op0->getType());
1354 Value *A = 0, *B = 0;
1355 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1356 (A == Op1 || B == Op1))
1360 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1361 (A == Op0 || B == Op0))
1364 // A & (-A) = A if A is a power of two or zero.
1365 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1366 match(Op1, m_Neg(m_Specific(Op0)))) {
1367 if (isPowerOfTwo(Op0, Q.TD, /*OrZero*/true))
1369 if (isPowerOfTwo(Op1, Q.TD, /*OrZero*/true))
1373 // Try some generic simplifications for associative operations.
1374 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1378 // And distributes over Or. Try some generic simplifications based on this.
1379 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1383 // And distributes over Xor. Try some generic simplifications based on this.
1384 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1388 // Or distributes over And. Try some generic simplifications based on this.
1389 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1393 // If the operation is with the result of a select instruction, check whether
1394 // operating on either branch of the select always yields the same value.
1395 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1396 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1400 // If the operation is with the result of a phi instruction, check whether
1401 // operating on all incoming values of the phi always yields the same value.
1402 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1403 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
1410 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1411 const TargetLibraryInfo *TLI,
1412 const DominatorTree *DT) {
1413 return ::SimplifyAndInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1416 /// SimplifyOrInst - Given operands for an Or, see if we can
1417 /// fold the result. If not, this returns null.
1418 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1419 unsigned MaxRecurse) {
1420 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1421 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1422 Constant *Ops[] = { CLHS, CRHS };
1423 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
1427 // Canonicalize the constant to the RHS.
1428 std::swap(Op0, Op1);
1432 if (match(Op1, m_Undef()))
1433 return Constant::getAllOnesValue(Op0->getType());
1440 if (match(Op1, m_Zero()))
1444 if (match(Op1, m_AllOnes()))
1447 // A | ~A = ~A | A = -1
1448 if (match(Op0, m_Not(m_Specific(Op1))) ||
1449 match(Op1, m_Not(m_Specific(Op0))))
1450 return Constant::getAllOnesValue(Op0->getType());
1453 Value *A = 0, *B = 0;
1454 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1455 (A == Op1 || B == Op1))
1459 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1460 (A == Op0 || B == Op0))
1463 // ~(A & ?) | A = -1
1464 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1465 (A == Op1 || B == Op1))
1466 return Constant::getAllOnesValue(Op1->getType());
1468 // A | ~(A & ?) = -1
1469 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1470 (A == Op0 || B == Op0))
1471 return Constant::getAllOnesValue(Op0->getType());
1473 // Try some generic simplifications for associative operations.
1474 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1478 // Or distributes over And. Try some generic simplifications based on this.
1479 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1483 // And distributes over Or. Try some generic simplifications based on this.
1484 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1488 // If the operation is with the result of a select instruction, check whether
1489 // operating on either branch of the select always yields the same value.
1490 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1491 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
1495 // If the operation is with the result of a phi instruction, check whether
1496 // operating on all incoming values of the phi always yields the same value.
1497 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1498 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
1504 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1505 const TargetLibraryInfo *TLI,
1506 const DominatorTree *DT) {
1507 return ::SimplifyOrInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1510 /// SimplifyXorInst - Given operands for a Xor, see if we can
1511 /// fold the result. If not, this returns null.
1512 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1513 unsigned MaxRecurse) {
1514 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1515 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1516 Constant *Ops[] = { CLHS, CRHS };
1517 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
1521 // Canonicalize the constant to the RHS.
1522 std::swap(Op0, Op1);
1525 // A ^ undef -> undef
1526 if (match(Op1, m_Undef()))
1530 if (match(Op1, m_Zero()))
1535 return Constant::getNullValue(Op0->getType());
1537 // A ^ ~A = ~A ^ A = -1
1538 if (match(Op0, m_Not(m_Specific(Op1))) ||
1539 match(Op1, m_Not(m_Specific(Op0))))
1540 return Constant::getAllOnesValue(Op0->getType());
1542 // Try some generic simplifications for associative operations.
1543 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1547 // And distributes over Xor. Try some generic simplifications based on this.
1548 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1552 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1553 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1554 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1555 // only if B and C are equal. If B and C are equal then (since we assume
1556 // that operands have already been simplified) "select(cond, B, C)" should
1557 // have been simplified to the common value of B and C already. Analysing
1558 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1559 // for threading over phi nodes.
1564 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1565 const TargetLibraryInfo *TLI,
1566 const DominatorTree *DT) {
1567 return ::SimplifyXorInst(Op0, Op1, Query (TD, TLI, DT), RecursionLimit);
1570 static Type *GetCompareTy(Value *Op) {
1571 return CmpInst::makeCmpResultType(Op->getType());
1574 /// ExtractEquivalentCondition - Rummage around inside V looking for something
1575 /// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1576 /// otherwise return null. Helper function for analyzing max/min idioms.
1577 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1578 Value *LHS, Value *RHS) {
1579 SelectInst *SI = dyn_cast<SelectInst>(V);
1582 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1585 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1586 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1588 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1589 LHS == CmpRHS && RHS == CmpLHS)
1594 static Constant *computePointerICmp(const TargetData &TD,
1595 CmpInst::Predicate Pred,
1596 Value *LHS, Value *RHS) {
1597 // We can only fold certain predicates on pointer comparisons.
1602 // Equality comaprisons are easy to fold.
1603 case CmpInst::ICMP_EQ:
1604 case CmpInst::ICMP_NE:
1607 // We can only handle unsigned relational comparisons because 'inbounds' on
1608 // a GEP only protects against unsigned wrapping.
1609 case CmpInst::ICMP_UGT:
1610 case CmpInst::ICMP_UGE:
1611 case CmpInst::ICMP_ULT:
1612 case CmpInst::ICMP_ULE:
1613 // However, we have to switch them to their signed variants to handle
1614 // negative indices from the base pointer.
1615 Pred = ICmpInst::getSignedPredicate(Pred);
1619 Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
1622 Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
1626 // If LHS and RHS are not related via constant offsets to the same base
1627 // value, there is nothing we can do here.
1631 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
1634 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1635 /// fold the result. If not, this returns null.
1636 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1637 const Query &Q, unsigned MaxRecurse) {
1638 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1639 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
1641 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
1642 if (Constant *CRHS = dyn_cast<Constant>(RHS))
1643 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI);
1645 // If we have a constant, make sure it is on the RHS.
1646 std::swap(LHS, RHS);
1647 Pred = CmpInst::getSwappedPredicate(Pred);
1650 Type *ITy = GetCompareTy(LHS); // The return type.
1651 Type *OpTy = LHS->getType(); // The operand type.
1653 // icmp X, X -> true/false
1654 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1655 // because X could be 0.
1656 if (LHS == RHS || isa<UndefValue>(RHS))
1657 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1659 // Special case logic when the operands have i1 type.
1660 if (OpTy->getScalarType()->isIntegerTy(1)) {
1663 case ICmpInst::ICMP_EQ:
1665 if (match(RHS, m_One()))
1668 case ICmpInst::ICMP_NE:
1670 if (match(RHS, m_Zero()))
1673 case ICmpInst::ICMP_UGT:
1675 if (match(RHS, m_Zero()))
1678 case ICmpInst::ICMP_UGE:
1680 if (match(RHS, m_One()))
1683 case ICmpInst::ICMP_SLT:
1685 if (match(RHS, m_Zero()))
1688 case ICmpInst::ICMP_SLE:
1690 if (match(RHS, m_One()))
1696 // icmp <object*>, <object*/null> - Different identified objects have
1697 // different addresses (unless null), and what's more the address of an
1698 // identified local is never equal to another argument (again, barring null).
1699 // Note that generalizing to the case where LHS is a global variable address
1700 // or null is pointless, since if both LHS and RHS are constants then we
1701 // already constant folded the compare, and if only one of them is then we
1702 // moved it to RHS already.
1703 Value *LHSPtr = LHS->stripPointerCasts();
1704 Value *RHSPtr = RHS->stripPointerCasts();
1705 if (LHSPtr == RHSPtr)
1706 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1708 // Be more aggressive about stripping pointer adjustments when checking a
1709 // comparison of an alloca address to another object. We can rip off all
1710 // inbounds GEP operations, even if they are variable.
1711 LHSPtr = LHSPtr->stripInBoundsOffsets();
1712 if (llvm::isIdentifiedObject(LHSPtr)) {
1713 RHSPtr = RHSPtr->stripInBoundsOffsets();
1714 if (llvm::isKnownNonNull(LHSPtr) || llvm::isKnownNonNull(RHSPtr)) {
1715 // If both sides are different identified objects, they aren't equal
1716 // unless they're null.
1717 if (LHSPtr != RHSPtr && llvm::isIdentifiedObject(RHSPtr) &&
1718 Pred == CmpInst::ICMP_EQ)
1719 return ConstantInt::get(ITy, false);
1721 // A local identified object (alloca or noalias call) can't equal any
1722 // incoming argument, unless they're both null.
1723 if (isa<Instruction>(LHSPtr) && isa<Argument>(RHSPtr) &&
1724 Pred == CmpInst::ICMP_EQ)
1725 return ConstantInt::get(ITy, false);
1728 // Assume that the constant null is on the right.
1729 if (llvm::isKnownNonNull(LHSPtr) && isa<ConstantPointerNull>(RHSPtr)) {
1730 if (Pred == CmpInst::ICMP_EQ)
1731 return ConstantInt::get(ITy, false);
1732 else if (Pred == CmpInst::ICMP_NE)
1733 return ConstantInt::get(ITy, true);
1735 } else if (isa<Argument>(LHSPtr)) {
1736 RHSPtr = RHSPtr->stripInBoundsOffsets();
1737 // An alloca can't be equal to an argument.
1738 if (isa<AllocaInst>(RHSPtr)) {
1739 if (Pred == CmpInst::ICMP_EQ)
1740 return ConstantInt::get(ITy, false);
1741 else if (Pred == CmpInst::ICMP_NE)
1742 return ConstantInt::get(ITy, true);
1746 // If we are comparing with zero then try hard since this is a common case.
1747 if (match(RHS, m_Zero())) {
1748 bool LHSKnownNonNegative, LHSKnownNegative;
1750 default: llvm_unreachable("Unknown ICmp predicate!");
1751 case ICmpInst::ICMP_ULT:
1752 return getFalse(ITy);
1753 case ICmpInst::ICMP_UGE:
1754 return getTrue(ITy);
1755 case ICmpInst::ICMP_EQ:
1756 case ICmpInst::ICMP_ULE:
1757 if (isKnownNonZero(LHS, Q.TD))
1758 return getFalse(ITy);
1760 case ICmpInst::ICMP_NE:
1761 case ICmpInst::ICMP_UGT:
1762 if (isKnownNonZero(LHS, Q.TD))
1763 return getTrue(ITy);
1765 case ICmpInst::ICMP_SLT:
1766 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
1767 if (LHSKnownNegative)
1768 return getTrue(ITy);
1769 if (LHSKnownNonNegative)
1770 return getFalse(ITy);
1772 case ICmpInst::ICMP_SLE:
1773 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
1774 if (LHSKnownNegative)
1775 return getTrue(ITy);
1776 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
1777 return getFalse(ITy);
1779 case ICmpInst::ICMP_SGE:
1780 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
1781 if (LHSKnownNegative)
1782 return getFalse(ITy);
1783 if (LHSKnownNonNegative)
1784 return getTrue(ITy);
1786 case ICmpInst::ICMP_SGT:
1787 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.TD);
1788 if (LHSKnownNegative)
1789 return getFalse(ITy);
1790 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.TD))
1791 return getTrue(ITy);
1796 // See if we are doing a comparison with a constant integer.
1797 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1798 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1799 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1800 if (RHS_CR.isEmptySet())
1801 return ConstantInt::getFalse(CI->getContext());
1802 if (RHS_CR.isFullSet())
1803 return ConstantInt::getTrue(CI->getContext());
1805 // Many binary operators with constant RHS have easy to compute constant
1806 // range. Use them to check whether the comparison is a tautology.
1807 uint32_t Width = CI->getBitWidth();
1808 APInt Lower = APInt(Width, 0);
1809 APInt Upper = APInt(Width, 0);
1811 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1812 // 'urem x, CI2' produces [0, CI2).
1813 Upper = CI2->getValue();
1814 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1815 // 'srem x, CI2' produces (-|CI2|, |CI2|).
1816 Upper = CI2->getValue().abs();
1817 Lower = (-Upper) + 1;
1818 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
1819 // 'udiv CI2, x' produces [0, CI2].
1820 Upper = CI2->getValue() + 1;
1821 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1822 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1823 APInt NegOne = APInt::getAllOnesValue(Width);
1825 Upper = NegOne.udiv(CI2->getValue()) + 1;
1826 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1827 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1828 APInt IntMin = APInt::getSignedMinValue(Width);
1829 APInt IntMax = APInt::getSignedMaxValue(Width);
1830 APInt Val = CI2->getValue().abs();
1831 if (!Val.isMinValue()) {
1832 Lower = IntMin.sdiv(Val);
1833 Upper = IntMax.sdiv(Val) + 1;
1835 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1836 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1837 APInt NegOne = APInt::getAllOnesValue(Width);
1838 if (CI2->getValue().ult(Width))
1839 Upper = NegOne.lshr(CI2->getValue()) + 1;
1840 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1841 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1842 APInt IntMin = APInt::getSignedMinValue(Width);
1843 APInt IntMax = APInt::getSignedMaxValue(Width);
1844 if (CI2->getValue().ult(Width)) {
1845 Lower = IntMin.ashr(CI2->getValue());
1846 Upper = IntMax.ashr(CI2->getValue()) + 1;
1848 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1849 // 'or x, CI2' produces [CI2, UINT_MAX].
1850 Lower = CI2->getValue();
1851 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1852 // 'and x, CI2' produces [0, CI2].
1853 Upper = CI2->getValue() + 1;
1855 if (Lower != Upper) {
1856 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1857 if (RHS_CR.contains(LHS_CR))
1858 return ConstantInt::getTrue(RHS->getContext());
1859 if (RHS_CR.inverse().contains(LHS_CR))
1860 return ConstantInt::getFalse(RHS->getContext());
1864 // Compare of cast, for example (zext X) != 0 -> X != 0
1865 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1866 Instruction *LI = cast<CastInst>(LHS);
1867 Value *SrcOp = LI->getOperand(0);
1868 Type *SrcTy = SrcOp->getType();
1869 Type *DstTy = LI->getType();
1871 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1872 // if the integer type is the same size as the pointer type.
1873 if (MaxRecurse && Q.TD && isa<PtrToIntInst>(LI) &&
1874 Q.TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
1875 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1876 // Transfer the cast to the constant.
1877 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1878 ConstantExpr::getIntToPtr(RHSC, SrcTy),
1881 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1882 if (RI->getOperand(0)->getType() == SrcTy)
1883 // Compare without the cast.
1884 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1890 if (isa<ZExtInst>(LHS)) {
1891 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1893 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1894 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1895 // Compare X and Y. Note that signed predicates become unsigned.
1896 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1897 SrcOp, RI->getOperand(0), Q,
1901 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1902 // too. If not, then try to deduce the result of the comparison.
1903 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1904 // Compute the constant that would happen if we truncated to SrcTy then
1905 // reextended to DstTy.
1906 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1907 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1909 // If the re-extended constant didn't change then this is effectively
1910 // also a case of comparing two zero-extended values.
1911 if (RExt == CI && MaxRecurse)
1912 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1913 SrcOp, Trunc, Q, MaxRecurse-1))
1916 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1917 // there. Use this to work out the result of the comparison.
1920 default: llvm_unreachable("Unknown ICmp predicate!");
1922 case ICmpInst::ICMP_EQ:
1923 case ICmpInst::ICMP_UGT:
1924 case ICmpInst::ICMP_UGE:
1925 return ConstantInt::getFalse(CI->getContext());
1927 case ICmpInst::ICMP_NE:
1928 case ICmpInst::ICMP_ULT:
1929 case ICmpInst::ICMP_ULE:
1930 return ConstantInt::getTrue(CI->getContext());
1932 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
1933 // is non-negative then LHS <s RHS.
1934 case ICmpInst::ICMP_SGT:
1935 case ICmpInst::ICMP_SGE:
1936 return CI->getValue().isNegative() ?
1937 ConstantInt::getTrue(CI->getContext()) :
1938 ConstantInt::getFalse(CI->getContext());
1940 case ICmpInst::ICMP_SLT:
1941 case ICmpInst::ICMP_SLE:
1942 return CI->getValue().isNegative() ?
1943 ConstantInt::getFalse(CI->getContext()) :
1944 ConstantInt::getTrue(CI->getContext());
1950 if (isa<SExtInst>(LHS)) {
1951 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1953 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1954 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1955 // Compare X and Y. Note that the predicate does not change.
1956 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1960 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1961 // too. If not, then try to deduce the result of the comparison.
1962 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1963 // Compute the constant that would happen if we truncated to SrcTy then
1964 // reextended to DstTy.
1965 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1966 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1968 // If the re-extended constant didn't change then this is effectively
1969 // also a case of comparing two sign-extended values.
1970 if (RExt == CI && MaxRecurse)
1971 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
1974 // Otherwise the upper bits of LHS are all equal, while RHS has varying
1975 // bits there. Use this to work out the result of the comparison.
1978 default: llvm_unreachable("Unknown ICmp predicate!");
1979 case ICmpInst::ICMP_EQ:
1980 return ConstantInt::getFalse(CI->getContext());
1981 case ICmpInst::ICMP_NE:
1982 return ConstantInt::getTrue(CI->getContext());
1984 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
1986 case ICmpInst::ICMP_SGT:
1987 case ICmpInst::ICMP_SGE:
1988 return CI->getValue().isNegative() ?
1989 ConstantInt::getTrue(CI->getContext()) :
1990 ConstantInt::getFalse(CI->getContext());
1991 case ICmpInst::ICMP_SLT:
1992 case ICmpInst::ICMP_SLE:
1993 return CI->getValue().isNegative() ?
1994 ConstantInt::getFalse(CI->getContext()) :
1995 ConstantInt::getTrue(CI->getContext());
1997 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
1999 case ICmpInst::ICMP_UGT:
2000 case ICmpInst::ICMP_UGE:
2001 // Comparison is true iff the LHS <s 0.
2003 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2004 Constant::getNullValue(SrcTy),
2008 case ICmpInst::ICMP_ULT:
2009 case ICmpInst::ICMP_ULE:
2010 // Comparison is true iff the LHS >=s 0.
2012 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2013 Constant::getNullValue(SrcTy),
2023 // Special logic for binary operators.
2024 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2025 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2026 if (MaxRecurse && (LBO || RBO)) {
2027 // Analyze the case when either LHS or RHS is an add instruction.
2028 Value *A = 0, *B = 0, *C = 0, *D = 0;
2029 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2030 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2031 if (LBO && LBO->getOpcode() == Instruction::Add) {
2032 A = LBO->getOperand(0); B = LBO->getOperand(1);
2033 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2034 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2035 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2037 if (RBO && RBO->getOpcode() == Instruction::Add) {
2038 C = RBO->getOperand(0); D = RBO->getOperand(1);
2039 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2040 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2041 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2044 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2045 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2046 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2047 Constant::getNullValue(RHS->getType()),
2051 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2052 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2053 if (Value *V = SimplifyICmpInst(Pred,
2054 Constant::getNullValue(LHS->getType()),
2055 C == LHS ? D : C, Q, MaxRecurse-1))
2058 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2059 if (A && C && (A == C || A == D || B == C || B == D) &&
2060 NoLHSWrapProblem && NoRHSWrapProblem) {
2061 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2062 Value *Y = (A == C || A == D) ? B : A;
2063 Value *Z = (C == A || C == B) ? D : C;
2064 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
2069 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2070 bool KnownNonNegative, KnownNegative;
2074 case ICmpInst::ICMP_SGT:
2075 case ICmpInst::ICMP_SGE:
2076 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
2077 if (!KnownNonNegative)
2080 case ICmpInst::ICMP_EQ:
2081 case ICmpInst::ICMP_UGT:
2082 case ICmpInst::ICMP_UGE:
2083 return getFalse(ITy);
2084 case ICmpInst::ICMP_SLT:
2085 case ICmpInst::ICMP_SLE:
2086 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.TD);
2087 if (!KnownNonNegative)
2090 case ICmpInst::ICMP_NE:
2091 case ICmpInst::ICMP_ULT:
2092 case ICmpInst::ICMP_ULE:
2093 return getTrue(ITy);
2096 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2097 bool KnownNonNegative, KnownNegative;
2101 case ICmpInst::ICMP_SGT:
2102 case ICmpInst::ICMP_SGE:
2103 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
2104 if (!KnownNonNegative)
2107 case ICmpInst::ICMP_NE:
2108 case ICmpInst::ICMP_UGT:
2109 case ICmpInst::ICMP_UGE:
2110 return getTrue(ITy);
2111 case ICmpInst::ICMP_SLT:
2112 case ICmpInst::ICMP_SLE:
2113 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.TD);
2114 if (!KnownNonNegative)
2117 case ICmpInst::ICMP_EQ:
2118 case ICmpInst::ICMP_ULT:
2119 case ICmpInst::ICMP_ULE:
2120 return getFalse(ITy);
2125 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2126 // icmp pred (X /u Y), X
2127 if (Pred == ICmpInst::ICMP_UGT)
2128 return getFalse(ITy);
2129 if (Pred == ICmpInst::ICMP_ULE)
2130 return getTrue(ITy);
2133 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2134 LBO->getOperand(1) == RBO->getOperand(1)) {
2135 switch (LBO->getOpcode()) {
2137 case Instruction::UDiv:
2138 case Instruction::LShr:
2139 if (ICmpInst::isSigned(Pred))
2142 case Instruction::SDiv:
2143 case Instruction::AShr:
2144 if (!LBO->isExact() || !RBO->isExact())
2146 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2147 RBO->getOperand(0), Q, MaxRecurse-1))
2150 case Instruction::Shl: {
2151 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2152 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2155 if (!NSW && ICmpInst::isSigned(Pred))
2157 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2158 RBO->getOperand(0), Q, MaxRecurse-1))
2165 // Simplify comparisons involving max/min.
2167 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2168 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2170 // Signed variants on "max(a,b)>=a -> true".
2171 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2172 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2173 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2174 // We analyze this as smax(A, B) pred A.
2176 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2177 (A == LHS || B == LHS)) {
2178 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2179 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2180 // We analyze this as smax(A, B) swapped-pred A.
2181 P = CmpInst::getSwappedPredicate(Pred);
2182 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2183 (A == RHS || B == RHS)) {
2184 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2185 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2186 // We analyze this as smax(-A, -B) swapped-pred -A.
2187 // Note that we do not need to actually form -A or -B thanks to EqP.
2188 P = CmpInst::getSwappedPredicate(Pred);
2189 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2190 (A == LHS || B == LHS)) {
2191 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2192 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2193 // We analyze this as smax(-A, -B) pred -A.
2194 // Note that we do not need to actually form -A or -B thanks to EqP.
2197 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2198 // Cases correspond to "max(A, B) p A".
2202 case CmpInst::ICMP_EQ:
2203 case CmpInst::ICMP_SLE:
2204 // Equivalent to "A EqP B". This may be the same as the condition tested
2205 // in the max/min; if so, we can just return that.
2206 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2208 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2210 // Otherwise, see if "A EqP B" simplifies.
2212 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2215 case CmpInst::ICMP_NE:
2216 case CmpInst::ICMP_SGT: {
2217 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2218 // Equivalent to "A InvEqP B". This may be the same as the condition
2219 // tested in the max/min; if so, we can just return that.
2220 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2222 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2224 // Otherwise, see if "A InvEqP B" simplifies.
2226 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2230 case CmpInst::ICMP_SGE:
2232 return getTrue(ITy);
2233 case CmpInst::ICMP_SLT:
2235 return getFalse(ITy);
2239 // Unsigned variants on "max(a,b)>=a -> true".
2240 P = CmpInst::BAD_ICMP_PREDICATE;
2241 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2242 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2243 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2244 // We analyze this as umax(A, B) pred A.
2246 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2247 (A == LHS || B == LHS)) {
2248 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2249 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2250 // We analyze this as umax(A, B) swapped-pred A.
2251 P = CmpInst::getSwappedPredicate(Pred);
2252 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2253 (A == RHS || B == RHS)) {
2254 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2255 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2256 // We analyze this as umax(-A, -B) swapped-pred -A.
2257 // Note that we do not need to actually form -A or -B thanks to EqP.
2258 P = CmpInst::getSwappedPredicate(Pred);
2259 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2260 (A == LHS || B == LHS)) {
2261 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2262 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2263 // We analyze this as umax(-A, -B) pred -A.
2264 // Note that we do not need to actually form -A or -B thanks to EqP.
2267 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2268 // Cases correspond to "max(A, B) p A".
2272 case CmpInst::ICMP_EQ:
2273 case CmpInst::ICMP_ULE:
2274 // Equivalent to "A EqP B". This may be the same as the condition tested
2275 // in the max/min; if so, we can just return that.
2276 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2278 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2280 // Otherwise, see if "A EqP B" simplifies.
2282 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2285 case CmpInst::ICMP_NE:
2286 case CmpInst::ICMP_UGT: {
2287 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2288 // Equivalent to "A InvEqP B". This may be the same as the condition
2289 // tested in the max/min; if so, we can just return that.
2290 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2292 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2294 // Otherwise, see if "A InvEqP B" simplifies.
2296 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2300 case CmpInst::ICMP_UGE:
2302 return getTrue(ITy);
2303 case CmpInst::ICMP_ULT:
2305 return getFalse(ITy);
2309 // Variants on "max(x,y) >= min(x,z)".
2311 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2312 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2313 (A == C || A == D || B == C || B == D)) {
2314 // max(x, ?) pred min(x, ?).
2315 if (Pred == CmpInst::ICMP_SGE)
2317 return getTrue(ITy);
2318 if (Pred == CmpInst::ICMP_SLT)
2320 return getFalse(ITy);
2321 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2322 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2323 (A == C || A == D || B == C || B == D)) {
2324 // min(x, ?) pred max(x, ?).
2325 if (Pred == CmpInst::ICMP_SLE)
2327 return getTrue(ITy);
2328 if (Pred == CmpInst::ICMP_SGT)
2330 return getFalse(ITy);
2331 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2332 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2333 (A == C || A == D || B == C || B == D)) {
2334 // max(x, ?) pred min(x, ?).
2335 if (Pred == CmpInst::ICMP_UGE)
2337 return getTrue(ITy);
2338 if (Pred == CmpInst::ICMP_ULT)
2340 return getFalse(ITy);
2341 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2342 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2343 (A == C || A == D || B == C || B == D)) {
2344 // min(x, ?) pred max(x, ?).
2345 if (Pred == CmpInst::ICMP_ULE)
2347 return getTrue(ITy);
2348 if (Pred == CmpInst::ICMP_UGT)
2350 return getFalse(ITy);
2353 // Simplify comparisons of related pointers using a powerful, recursive
2354 // GEP-walk when we have target data available..
2355 if (Q.TD && LHS->getType()->isPointerTy() && RHS->getType()->isPointerTy())
2356 if (Constant *C = computePointerICmp(*Q.TD, Pred, LHS, RHS))
2359 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2360 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2361 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2362 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2363 (ICmpInst::isEquality(Pred) ||
2364 (GLHS->isInBounds() && GRHS->isInBounds() &&
2365 Pred == ICmpInst::getSignedPredicate(Pred)))) {
2366 // The bases are equal and the indices are constant. Build a constant
2367 // expression GEP with the same indices and a null base pointer to see
2368 // what constant folding can make out of it.
2369 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2370 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2371 Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2373 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2374 Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2375 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2380 // If the comparison is with the result of a select instruction, check whether
2381 // comparing with either branch of the select always yields the same value.
2382 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2383 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
2386 // If the comparison is with the result of a phi instruction, check whether
2387 // doing the compare with each incoming phi value yields a common result.
2388 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2389 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
2395 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2396 const TargetData *TD,
2397 const TargetLibraryInfo *TLI,
2398 const DominatorTree *DT) {
2399 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2403 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2404 /// fold the result. If not, this returns null.
2405 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2406 const Query &Q, unsigned MaxRecurse) {
2407 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2408 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2410 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2411 if (Constant *CRHS = dyn_cast<Constant>(RHS))
2412 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.TD, Q.TLI);
2414 // If we have a constant, make sure it is on the RHS.
2415 std::swap(LHS, RHS);
2416 Pred = CmpInst::getSwappedPredicate(Pred);
2419 // Fold trivial predicates.
2420 if (Pred == FCmpInst::FCMP_FALSE)
2421 return ConstantInt::get(GetCompareTy(LHS), 0);
2422 if (Pred == FCmpInst::FCMP_TRUE)
2423 return ConstantInt::get(GetCompareTy(LHS), 1);
2425 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2426 return UndefValue::get(GetCompareTy(LHS));
2428 // fcmp x,x -> true/false. Not all compares are foldable.
2430 if (CmpInst::isTrueWhenEqual(Pred))
2431 return ConstantInt::get(GetCompareTy(LHS), 1);
2432 if (CmpInst::isFalseWhenEqual(Pred))
2433 return ConstantInt::get(GetCompareTy(LHS), 0);
2436 // Handle fcmp with constant RHS
2437 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2438 // If the constant is a nan, see if we can fold the comparison based on it.
2439 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2440 if (CFP->getValueAPF().isNaN()) {
2441 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2442 return ConstantInt::getFalse(CFP->getContext());
2443 assert(FCmpInst::isUnordered(Pred) &&
2444 "Comparison must be either ordered or unordered!");
2445 // True if unordered.
2446 return ConstantInt::getTrue(CFP->getContext());
2448 // Check whether the constant is an infinity.
2449 if (CFP->getValueAPF().isInfinity()) {
2450 if (CFP->getValueAPF().isNegative()) {
2452 case FCmpInst::FCMP_OLT:
2453 // No value is ordered and less than negative infinity.
2454 return ConstantInt::getFalse(CFP->getContext());
2455 case FCmpInst::FCMP_UGE:
2456 // All values are unordered with or at least negative infinity.
2457 return ConstantInt::getTrue(CFP->getContext());
2463 case FCmpInst::FCMP_OGT:
2464 // No value is ordered and greater than infinity.
2465 return ConstantInt::getFalse(CFP->getContext());
2466 case FCmpInst::FCMP_ULE:
2467 // All values are unordered with and at most infinity.
2468 return ConstantInt::getTrue(CFP->getContext());
2477 // If the comparison is with the result of a select instruction, check whether
2478 // comparing with either branch of the select always yields the same value.
2479 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2480 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
2483 // If the comparison is with the result of a phi instruction, check whether
2484 // doing the compare with each incoming phi value yields a common result.
2485 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2486 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
2492 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2493 const TargetData *TD,
2494 const TargetLibraryInfo *TLI,
2495 const DominatorTree *DT) {
2496 return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2500 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2501 /// the result. If not, this returns null.
2502 static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
2503 Value *FalseVal, const Query &Q,
2504 unsigned MaxRecurse) {
2505 // select true, X, Y -> X
2506 // select false, X, Y -> Y
2507 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2508 return CB->getZExtValue() ? TrueVal : FalseVal;
2510 // select C, X, X -> X
2511 if (TrueVal == FalseVal)
2514 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2515 if (isa<Constant>(TrueVal))
2519 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2521 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2527 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
2528 const TargetData *TD,
2529 const TargetLibraryInfo *TLI,
2530 const DominatorTree *DT) {
2531 return ::SimplifySelectInst(Cond, TrueVal, FalseVal, Query (TD, TLI, DT),
2535 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2536 /// fold the result. If not, this returns null.
2537 static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) {
2538 // The type of the GEP pointer operand.
2539 PointerType *PtrTy = dyn_cast<PointerType>(Ops[0]->getType());
2540 // The GEP pointer operand is not a pointer, it's a vector of pointers.
2544 // getelementptr P -> P.
2545 if (Ops.size() == 1)
2548 if (isa<UndefValue>(Ops[0])) {
2549 // Compute the (pointer) type returned by the GEP instruction.
2550 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
2551 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
2552 return UndefValue::get(GEPTy);
2555 if (Ops.size() == 2) {
2556 // getelementptr P, 0 -> P.
2557 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2560 // getelementptr P, N -> P if P points to a type of zero size.
2562 Type *Ty = PtrTy->getElementType();
2563 if (Ty->isSized() && Q.TD->getTypeAllocSize(Ty) == 0)
2568 // Check to see if this is constant foldable.
2569 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2570 if (!isa<Constant>(Ops[i]))
2573 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
2576 Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const TargetData *TD,
2577 const TargetLibraryInfo *TLI,
2578 const DominatorTree *DT) {
2579 return ::SimplifyGEPInst(Ops, Query (TD, TLI, DT), RecursionLimit);
2582 /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2583 /// can fold the result. If not, this returns null.
2584 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
2585 ArrayRef<unsigned> Idxs, const Query &Q,
2587 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2588 if (Constant *CVal = dyn_cast<Constant>(Val))
2589 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2591 // insertvalue x, undef, n -> x
2592 if (match(Val, m_Undef()))
2595 // insertvalue x, (extractvalue y, n), n
2596 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
2597 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2598 EV->getIndices() == Idxs) {
2599 // insertvalue undef, (extractvalue y, n), n -> y
2600 if (match(Agg, m_Undef()))
2601 return EV->getAggregateOperand();
2603 // insertvalue y, (extractvalue y, n), n -> y
2604 if (Agg == EV->getAggregateOperand())
2611 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2612 ArrayRef<unsigned> Idxs,
2613 const TargetData *TD,
2614 const TargetLibraryInfo *TLI,
2615 const DominatorTree *DT) {
2616 return ::SimplifyInsertValueInst(Agg, Val, Idxs, Query (TD, TLI, DT),
2620 /// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
2621 static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
2622 // If all of the PHI's incoming values are the same then replace the PHI node
2623 // with the common value.
2624 Value *CommonValue = 0;
2625 bool HasUndefInput = false;
2626 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2627 Value *Incoming = PN->getIncomingValue(i);
2628 // If the incoming value is the phi node itself, it can safely be skipped.
2629 if (Incoming == PN) continue;
2630 if (isa<UndefValue>(Incoming)) {
2631 // Remember that we saw an undef value, but otherwise ignore them.
2632 HasUndefInput = true;
2635 if (CommonValue && Incoming != CommonValue)
2636 return 0; // Not the same, bail out.
2637 CommonValue = Incoming;
2640 // If CommonValue is null then all of the incoming values were either undef or
2641 // equal to the phi node itself.
2643 return UndefValue::get(PN->getType());
2645 // If we have a PHI node like phi(X, undef, X), where X is defined by some
2646 // instruction, we cannot return X as the result of the PHI node unless it
2647 // dominates the PHI block.
2649 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : 0;
2654 static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
2655 if (Constant *C = dyn_cast<Constant>(Op))
2656 return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.TD, Q.TLI);
2661 Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const TargetData *TD,
2662 const TargetLibraryInfo *TLI,
2663 const DominatorTree *DT) {
2664 return ::SimplifyTruncInst(Op, Ty, Query (TD, TLI, DT), RecursionLimit);
2667 //=== Helper functions for higher up the class hierarchy.
2669 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2670 /// fold the result. If not, this returns null.
2671 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2672 const Query &Q, unsigned MaxRecurse) {
2674 case Instruction::Add:
2675 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2677 case Instruction::Sub:
2678 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2680 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
2681 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
2682 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
2683 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse);
2684 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
2685 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
2686 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse);
2687 case Instruction::Shl:
2688 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2690 case Instruction::LShr:
2691 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
2692 case Instruction::AShr:
2693 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
2694 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
2695 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
2696 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
2698 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2699 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2700 Constant *COps[] = {CLHS, CRHS};
2701 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.TD,
2705 // If the operation is associative, try some generic simplifications.
2706 if (Instruction::isAssociative(Opcode))
2707 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
2710 // If the operation is with the result of a select instruction check whether
2711 // operating on either branch of the select always yields the same value.
2712 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2713 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
2716 // If the operation is with the result of a phi instruction, check whether
2717 // operating on all incoming values of the phi always yields the same value.
2718 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2719 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
2726 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2727 const TargetData *TD, const TargetLibraryInfo *TLI,
2728 const DominatorTree *DT) {
2729 return ::SimplifyBinOp(Opcode, LHS, RHS, Query (TD, TLI, DT), RecursionLimit);
2732 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2733 /// fold the result.
2734 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2735 const Query &Q, unsigned MaxRecurse) {
2736 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
2737 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
2738 return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
2741 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2742 const TargetData *TD, const TargetLibraryInfo *TLI,
2743 const DominatorTree *DT) {
2744 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (TD, TLI, DT),
2748 static Value *SimplifyCallInst(CallInst *CI, const Query &) {
2749 // call undef -> undef
2750 if (isa<UndefValue>(CI->getCalledValue()))
2751 return UndefValue::get(CI->getType());
2756 /// SimplifyInstruction - See if we can compute a simplified version of this
2757 /// instruction. If not, this returns null.
2758 Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
2759 const TargetLibraryInfo *TLI,
2760 const DominatorTree *DT) {
2763 switch (I->getOpcode()) {
2765 Result = ConstantFoldInstruction(I, TD, TLI);
2767 case Instruction::Add:
2768 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2769 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2770 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2773 case Instruction::Sub:
2774 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2775 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2776 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2779 case Instruction::Mul:
2780 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2782 case Instruction::SDiv:
2783 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2785 case Instruction::UDiv:
2786 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2788 case Instruction::FDiv:
2789 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2791 case Instruction::SRem:
2792 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2794 case Instruction::URem:
2795 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2797 case Instruction::FRem:
2798 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2800 case Instruction::Shl:
2801 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2802 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2803 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2806 case Instruction::LShr:
2807 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2808 cast<BinaryOperator>(I)->isExact(),
2811 case Instruction::AShr:
2812 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2813 cast<BinaryOperator>(I)->isExact(),
2816 case Instruction::And:
2817 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2819 case Instruction::Or:
2820 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2822 case Instruction::Xor:
2823 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2825 case Instruction::ICmp:
2826 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
2827 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2829 case Instruction::FCmp:
2830 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
2831 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2833 case Instruction::Select:
2834 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
2835 I->getOperand(2), TD, TLI, DT);
2837 case Instruction::GetElementPtr: {
2838 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
2839 Result = SimplifyGEPInst(Ops, TD, TLI, DT);
2842 case Instruction::InsertValue: {
2843 InsertValueInst *IV = cast<InsertValueInst>(I);
2844 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
2845 IV->getInsertedValueOperand(),
2846 IV->getIndices(), TD, TLI, DT);
2849 case Instruction::PHI:
2850 Result = SimplifyPHINode(cast<PHINode>(I), Query (TD, TLI, DT));
2852 case Instruction::Call:
2853 Result = SimplifyCallInst(cast<CallInst>(I), Query (TD, TLI, DT));
2855 case Instruction::Trunc:
2856 Result = SimplifyTruncInst(I->getOperand(0), I->getType(), TD, TLI, DT);
2860 /// If called on unreachable code, the above logic may report that the
2861 /// instruction simplified to itself. Make life easier for users by
2862 /// detecting that case here, returning a safe value instead.
2863 return Result == I ? UndefValue::get(I->getType()) : Result;
2866 /// \brief Implementation of recursive simplification through an instructions
2869 /// This is the common implementation of the recursive simplification routines.
2870 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
2871 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
2872 /// instructions to process and attempt to simplify it using
2873 /// InstructionSimplify.
2875 /// This routine returns 'true' only when *it* simplifies something. The passed
2876 /// in simplified value does not count toward this.
2877 static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
2878 const TargetData *TD,
2879 const TargetLibraryInfo *TLI,
2880 const DominatorTree *DT) {
2881 bool Simplified = false;
2882 SmallSetVector<Instruction *, 8> Worklist;
2884 // If we have an explicit value to collapse to, do that round of the
2885 // simplification loop by hand initially.
2887 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
2890 Worklist.insert(cast<Instruction>(*UI));
2892 // Replace the instruction with its simplified value.
2893 I->replaceAllUsesWith(SimpleV);
2895 // Gracefully handle edge cases where the instruction is not wired into any
2898 I->eraseFromParent();
2903 // Note that we must test the size on each iteration, the worklist can grow.
2904 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
2907 // See if this instruction simplifies.
2908 SimpleV = SimplifyInstruction(I, TD, TLI, DT);
2914 // Stash away all the uses of the old instruction so we can check them for
2915 // recursive simplifications after a RAUW. This is cheaper than checking all
2916 // uses of To on the recursive step in most cases.
2917 for (Value::use_iterator UI = I->use_begin(), UE = I->use_end(); UI != UE;
2919 Worklist.insert(cast<Instruction>(*UI));
2921 // Replace the instruction with its simplified value.
2922 I->replaceAllUsesWith(SimpleV);
2924 // Gracefully handle edge cases where the instruction is not wired into any
2927 I->eraseFromParent();
2932 bool llvm::recursivelySimplifyInstruction(Instruction *I,
2933 const TargetData *TD,
2934 const TargetLibraryInfo *TLI,
2935 const DominatorTree *DT) {
2936 return replaceAndRecursivelySimplifyImpl(I, 0, TD, TLI, DT);
2939 bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
2940 const TargetData *TD,
2941 const TargetLibraryInfo *TLI,
2942 const DominatorTree *DT) {
2943 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
2944 assert(SimpleV && "Must provide a simplified value.");
2945 return replaceAndRecursivelySimplifyImpl(I, SimpleV, TD, TLI, DT);