1 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements routines for folding instructions into simpler forms
11 // that do not require creating new instructions. This does constant folding
12 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
13 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
14 // ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been
15 // simplified: This is usually true and assuming it simplifies the logic (if
16 // they have not been simplified then results are correct but maybe suboptimal).
18 //===----------------------------------------------------------------------===//
20 #include "llvm/Analysis/InstructionSimplify.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/ConstantFolding.h"
24 #include "llvm/Analysis/MemoryBuiltins.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/IR/ConstantRange.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/GetElementPtrTypeIterator.h"
30 #include "llvm/IR/GlobalAlias.h"
31 #include "llvm/IR/Operator.h"
32 #include "llvm/IR/PatternMatch.h"
33 #include "llvm/IR/ValueHandle.h"
35 using namespace llvm::PatternMatch;
37 #define DEBUG_TYPE "instsimplify"
39 enum { RecursionLimit = 3 };
41 STATISTIC(NumExpand, "Number of expansions");
42 STATISTIC(NumReassoc, "Number of reassociations");
46 const TargetLibraryInfo *TLI;
47 const DominatorTree *DT;
48 AssumptionTracker *AT;
49 const Instruction *CxtI;
51 Query(const DataLayout *DL, const TargetLibraryInfo *tli,
52 const DominatorTree *dt, AssumptionTracker *at = nullptr,
53 const Instruction *cxti = nullptr)
54 : DL(DL), TLI(tli), DT(dt), AT(at), CxtI(cxti) {}
57 static Value *SimplifyAndInst(Value *, Value *, const Query &, unsigned);
58 static Value *SimplifyBinOp(unsigned, Value *, Value *, const Query &,
60 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const Query &,
62 static Value *SimplifyOrInst(Value *, Value *, const Query &, unsigned);
63 static Value *SimplifyXorInst(Value *, Value *, const Query &, unsigned);
64 static Value *SimplifyTruncInst(Value *, Type *, const Query &, unsigned);
66 /// getFalse - For a boolean type, or a vector of boolean type, return false, or
67 /// a vector with every element false, as appropriate for the type.
68 static Constant *getFalse(Type *Ty) {
69 assert(Ty->getScalarType()->isIntegerTy(1) &&
70 "Expected i1 type or a vector of i1!");
71 return Constant::getNullValue(Ty);
74 /// getTrue - For a boolean type, or a vector of boolean type, return true, or
75 /// a vector with every element true, as appropriate for the type.
76 static Constant *getTrue(Type *Ty) {
77 assert(Ty->getScalarType()->isIntegerTy(1) &&
78 "Expected i1 type or a vector of i1!");
79 return Constant::getAllOnesValue(Ty);
82 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
83 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
85 CmpInst *Cmp = dyn_cast<CmpInst>(V);
88 CmpInst::Predicate CPred = Cmp->getPredicate();
89 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
90 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
92 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
96 /// ValueDominatesPHI - Does the given value dominate the specified phi node?
97 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
98 Instruction *I = dyn_cast<Instruction>(V);
100 // Arguments and constants dominate all instructions.
103 // If we are processing instructions (and/or basic blocks) that have not been
104 // fully added to a function, the parent nodes may still be null. Simply
105 // return the conservative answer in these cases.
106 if (!I->getParent() || !P->getParent() || !I->getParent()->getParent())
109 // If we have a DominatorTree then do a precise test.
111 if (!DT->isReachableFromEntry(P->getParent()))
113 if (!DT->isReachableFromEntry(I->getParent()))
115 return DT->dominates(I, P);
118 // Otherwise, if the instruction is in the entry block, and is not an invoke,
119 // then it obviously dominates all phi nodes.
120 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
127 /// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
128 /// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
129 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
130 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
131 /// Returns the simplified value, or null if no simplification was performed.
132 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
133 unsigned OpcToExpand, const Query &Q,
134 unsigned MaxRecurse) {
135 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
136 // Recursion is always used, so bail out at once if we already hit the limit.
140 // Check whether the expression has the form "(A op' B) op C".
141 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
142 if (Op0->getOpcode() == OpcodeToExpand) {
143 // It does! Try turning it into "(A op C) op' (B op C)".
144 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
145 // Do "A op C" and "B op C" both simplify?
146 if (Value *L = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse))
147 if (Value *R = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
148 // They do! Return "L op' R" if it simplifies or is already available.
149 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
150 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
151 && L == B && R == A)) {
155 // Otherwise return "L op' R" if it simplifies.
156 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
163 // Check whether the expression has the form "A op (B op' C)".
164 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
165 if (Op1->getOpcode() == OpcodeToExpand) {
166 // It does! Try turning it into "(A op B) op' (A op C)".
167 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
168 // Do "A op B" and "A op C" both simplify?
169 if (Value *L = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse))
170 if (Value *R = SimplifyBinOp(Opcode, A, C, Q, MaxRecurse)) {
171 // They do! Return "L op' R" if it simplifies or is already available.
172 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
173 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
174 && L == C && R == B)) {
178 // Otherwise return "L op' R" if it simplifies.
179 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse)) {
189 /// SimplifyAssociativeBinOp - Generic simplifications for associative binary
190 /// operations. Returns the simpler value, or null if none was found.
191 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
192 const Query &Q, unsigned MaxRecurse) {
193 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
194 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
196 // Recursion is always used, so bail out at once if we already hit the limit.
200 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
201 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
203 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
204 if (Op0 && Op0->getOpcode() == Opcode) {
205 Value *A = Op0->getOperand(0);
206 Value *B = Op0->getOperand(1);
209 // Does "B op C" simplify?
210 if (Value *V = SimplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
211 // It does! Return "A op V" if it simplifies or is already available.
212 // If V equals B then "A op V" is just the LHS.
213 if (V == B) return LHS;
214 // Otherwise return "A op V" if it simplifies.
215 if (Value *W = SimplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
222 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
223 if (Op1 && Op1->getOpcode() == Opcode) {
225 Value *B = Op1->getOperand(0);
226 Value *C = Op1->getOperand(1);
228 // Does "A op B" simplify?
229 if (Value *V = SimplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
230 // It does! Return "V op C" if it simplifies or is already available.
231 // If V equals B then "V op C" is just the RHS.
232 if (V == B) return RHS;
233 // Otherwise return "V op C" if it simplifies.
234 if (Value *W = SimplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
241 // The remaining transforms require commutativity as well as associativity.
242 if (!Instruction::isCommutative(Opcode))
245 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
246 if (Op0 && Op0->getOpcode() == Opcode) {
247 Value *A = Op0->getOperand(0);
248 Value *B = Op0->getOperand(1);
251 // Does "C op A" simplify?
252 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
253 // It does! Return "V op B" if it simplifies or is already available.
254 // If V equals A then "V op B" is just the LHS.
255 if (V == A) return LHS;
256 // Otherwise return "V op B" if it simplifies.
257 if (Value *W = SimplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
264 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
265 if (Op1 && Op1->getOpcode() == Opcode) {
267 Value *B = Op1->getOperand(0);
268 Value *C = Op1->getOperand(1);
270 // Does "C op A" simplify?
271 if (Value *V = SimplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
272 // It does! Return "B op V" if it simplifies or is already available.
273 // If V equals C then "B op V" is just the RHS.
274 if (V == C) return RHS;
275 // Otherwise return "B op V" if it simplifies.
276 if (Value *W = SimplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
286 /// ThreadBinOpOverSelect - In the case of a binary operation with a select
287 /// instruction as an operand, try to simplify the binop by seeing whether
288 /// evaluating it on both branches of the select results in the same value.
289 /// Returns the common value if so, otherwise returns null.
290 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
291 const Query &Q, unsigned MaxRecurse) {
292 // Recursion is always used, so bail out at once if we already hit the limit.
297 if (isa<SelectInst>(LHS)) {
298 SI = cast<SelectInst>(LHS);
300 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
301 SI = cast<SelectInst>(RHS);
304 // Evaluate the BinOp on the true and false branches of the select.
308 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
309 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
311 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
312 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
315 // If they simplified to the same value, then return the common value.
316 // If they both failed to simplify then return null.
320 // If one branch simplified to undef, return the other one.
321 if (TV && isa<UndefValue>(TV))
323 if (FV && isa<UndefValue>(FV))
326 // If applying the operation did not change the true and false select values,
327 // then the result of the binop is the select itself.
328 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
331 // If one branch simplified and the other did not, and the simplified
332 // value is equal to the unsimplified one, return the simplified value.
333 // For example, select (cond, X, X & Z) & Z -> X & Z.
334 if ((FV && !TV) || (TV && !FV)) {
335 // Check that the simplified value has the form "X op Y" where "op" is the
336 // same as the original operation.
337 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
338 if (Simplified && Simplified->getOpcode() == Opcode) {
339 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
340 // We already know that "op" is the same as for the simplified value. See
341 // if the operands match too. If so, return the simplified value.
342 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
343 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
344 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
345 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
346 Simplified->getOperand(1) == UnsimplifiedRHS)
348 if (Simplified->isCommutative() &&
349 Simplified->getOperand(1) == UnsimplifiedLHS &&
350 Simplified->getOperand(0) == UnsimplifiedRHS)
358 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
359 /// try to simplify the comparison by seeing whether both branches of the select
360 /// result in the same value. Returns the common value if so, otherwise returns
362 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
363 Value *RHS, const Query &Q,
364 unsigned MaxRecurse) {
365 // Recursion is always used, so bail out at once if we already hit the limit.
369 // Make sure the select is on the LHS.
370 if (!isa<SelectInst>(LHS)) {
372 Pred = CmpInst::getSwappedPredicate(Pred);
374 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
375 SelectInst *SI = cast<SelectInst>(LHS);
376 Value *Cond = SI->getCondition();
377 Value *TV = SI->getTrueValue();
378 Value *FV = SI->getFalseValue();
380 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
381 // Does "cmp TV, RHS" simplify?
382 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, Q, MaxRecurse);
384 // It not only simplified, it simplified to the select condition. Replace
386 TCmp = getTrue(Cond->getType());
388 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
389 // condition then we can replace it with 'true'. Otherwise give up.
390 if (!isSameCompare(Cond, Pred, TV, RHS))
392 TCmp = getTrue(Cond->getType());
395 // Does "cmp FV, RHS" simplify?
396 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, Q, MaxRecurse);
398 // It not only simplified, it simplified to the select condition. Replace
400 FCmp = getFalse(Cond->getType());
402 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
403 // condition then we can replace it with 'false'. Otherwise give up.
404 if (!isSameCompare(Cond, Pred, FV, RHS))
406 FCmp = getFalse(Cond->getType());
409 // If both sides simplified to the same value, then use it as the result of
410 // the original comparison.
414 // The remaining cases only make sense if the select condition has the same
415 // type as the result of the comparison, so bail out if this is not so.
416 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
418 // If the false value simplified to false, then the result of the compare
419 // is equal to "Cond && TCmp". This also catches the case when the false
420 // value simplified to false and the true value to true, returning "Cond".
421 if (match(FCmp, m_Zero()))
422 if (Value *V = SimplifyAndInst(Cond, TCmp, Q, MaxRecurse))
424 // If the true value simplified to true, then the result of the compare
425 // is equal to "Cond || FCmp".
426 if (match(TCmp, m_One()))
427 if (Value *V = SimplifyOrInst(Cond, FCmp, Q, MaxRecurse))
429 // Finally, if the false value simplified to true and the true value to
430 // false, then the result of the compare is equal to "!Cond".
431 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
433 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
440 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
441 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
442 /// it on the incoming phi values yields the same result for every value. If so
443 /// returns the common value, otherwise returns null.
444 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
445 const Query &Q, unsigned MaxRecurse) {
446 // Recursion is always used, so bail out at once if we already hit the limit.
451 if (isa<PHINode>(LHS)) {
452 PI = cast<PHINode>(LHS);
453 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
454 if (!ValueDominatesPHI(RHS, PI, Q.DT))
457 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
458 PI = cast<PHINode>(RHS);
459 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
460 if (!ValueDominatesPHI(LHS, PI, Q.DT))
464 // Evaluate the BinOp on the incoming phi values.
465 Value *CommonValue = nullptr;
466 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
467 Value *Incoming = PI->getIncomingValue(i);
468 // If the incoming value is the phi node itself, it can safely be skipped.
469 if (Incoming == PI) continue;
470 Value *V = PI == LHS ?
471 SimplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse) :
472 SimplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
473 // If the operation failed to simplify, or simplified to a different value
474 // to previously, then give up.
475 if (!V || (CommonValue && V != CommonValue))
483 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
484 /// try to simplify the comparison by seeing whether comparing with all of the
485 /// incoming phi values yields the same result every time. If so returns the
486 /// common result, otherwise returns null.
487 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
488 const Query &Q, unsigned MaxRecurse) {
489 // Recursion is always used, so bail out at once if we already hit the limit.
493 // Make sure the phi is on the LHS.
494 if (!isa<PHINode>(LHS)) {
496 Pred = CmpInst::getSwappedPredicate(Pred);
498 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
499 PHINode *PI = cast<PHINode>(LHS);
501 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
502 if (!ValueDominatesPHI(RHS, PI, Q.DT))
505 // Evaluate the BinOp on the incoming phi values.
506 Value *CommonValue = nullptr;
507 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
508 Value *Incoming = PI->getIncomingValue(i);
509 // If the incoming value is the phi node itself, it can safely be skipped.
510 if (Incoming == PI) continue;
511 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, Q, MaxRecurse);
512 // If the operation failed to simplify, or simplified to a different value
513 // to previously, then give up.
514 if (!V || (CommonValue && V != CommonValue))
522 /// SimplifyAddInst - Given operands for an Add, see if we can
523 /// fold the result. If not, this returns null.
524 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
525 const Query &Q, unsigned MaxRecurse) {
526 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
527 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
528 Constant *Ops[] = { CLHS, CRHS };
529 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(), Ops,
533 // Canonicalize the constant to the RHS.
537 // X + undef -> undef
538 if (match(Op1, m_Undef()))
542 if (match(Op1, m_Zero()))
549 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
550 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
553 // X + ~X -> -1 since ~X = -X-1
554 if (match(Op0, m_Not(m_Specific(Op1))) ||
555 match(Op1, m_Not(m_Specific(Op0))))
556 return Constant::getAllOnesValue(Op0->getType());
559 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
560 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
563 // Try some generic simplifications for associative operations.
564 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q,
568 // Threading Add over selects and phi nodes is pointless, so don't bother.
569 // Threading over the select in "A + select(cond, B, C)" means evaluating
570 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
571 // only if B and C are equal. If B and C are equal then (since we assume
572 // that operands have already been simplified) "select(cond, B, C)" should
573 // have been simplified to the common value of B and C already. Analysing
574 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
575 // for threading over phi nodes.
580 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
581 const DataLayout *DL, const TargetLibraryInfo *TLI,
582 const DominatorTree *DT, AssumptionTracker *AT,
583 const Instruction *CxtI) {
584 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW,
585 Query (DL, TLI, DT, AT, CxtI), RecursionLimit);
588 /// \brief Compute the base pointer and cumulative constant offsets for V.
590 /// This strips all constant offsets off of V, leaving it the base pointer, and
591 /// accumulates the total constant offset applied in the returned constant. It
592 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
593 /// no constant offsets applied.
595 /// This is very similar to GetPointerBaseWithConstantOffset except it doesn't
596 /// follow non-inbounds geps. This allows it to remain usable for icmp ult/etc.
598 static Constant *stripAndComputeConstantOffsets(const DataLayout *DL,
600 bool AllowNonInbounds = false) {
601 assert(V->getType()->getScalarType()->isPointerTy());
603 // Without DataLayout, just be conservative for now. Theoretically, more could
604 // be done in this case.
606 return ConstantInt::get(IntegerType::get(V->getContext(), 64), 0);
608 Type *IntPtrTy = DL->getIntPtrType(V->getType())->getScalarType();
609 APInt Offset = APInt::getNullValue(IntPtrTy->getIntegerBitWidth());
611 // Even though we don't look through PHI nodes, we could be called on an
612 // instruction in an unreachable block, which may be on a cycle.
613 SmallPtrSet<Value *, 4> Visited;
616 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
617 if ((!AllowNonInbounds && !GEP->isInBounds()) ||
618 !GEP->accumulateConstantOffset(*DL, Offset))
620 V = GEP->getPointerOperand();
621 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
622 V = cast<Operator>(V)->getOperand(0);
623 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
624 if (GA->mayBeOverridden())
626 V = GA->getAliasee();
630 assert(V->getType()->getScalarType()->isPointerTy() &&
631 "Unexpected operand type!");
632 } while (Visited.insert(V));
634 Constant *OffsetIntPtr = ConstantInt::get(IntPtrTy, Offset);
635 if (V->getType()->isVectorTy())
636 return ConstantVector::getSplat(V->getType()->getVectorNumElements(),
641 /// \brief Compute the constant difference between two pointer values.
642 /// If the difference is not a constant, returns zero.
643 static Constant *computePointerDifference(const DataLayout *DL,
644 Value *LHS, Value *RHS) {
645 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
646 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
648 // If LHS and RHS are not related via constant offsets to the same base
649 // value, there is nothing we can do here.
653 // Otherwise, the difference of LHS - RHS can be computed as:
655 // = (LHSOffset + Base) - (RHSOffset + Base)
656 // = LHSOffset - RHSOffset
657 return ConstantExpr::getSub(LHSOffset, RHSOffset);
660 /// SimplifySubInst - Given operands for a Sub, see if we can
661 /// fold the result. If not, this returns null.
662 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
663 const Query &Q, unsigned MaxRecurse) {
664 if (Constant *CLHS = dyn_cast<Constant>(Op0))
665 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
666 Constant *Ops[] = { CLHS, CRHS };
667 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
671 // X - undef -> undef
672 // undef - X -> undef
673 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
674 return UndefValue::get(Op0->getType());
677 if (match(Op1, m_Zero()))
682 return Constant::getNullValue(Op0->getType());
684 // X - (0 - Y) -> X if the second sub is NUW.
685 // If Y != 0, 0 - Y is a poison value.
686 // If Y == 0, 0 - Y simplifies to 0.
687 if (BinaryOperator::isNeg(Op1)) {
688 if (const auto *BO = dyn_cast<BinaryOperator>(Op1)) {
689 assert(BO->getOpcode() == Instruction::Sub &&
690 "Expected a subtraction operator!");
691 if (BO->hasNoUnsignedWrap())
696 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
697 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
698 Value *X = nullptr, *Y = nullptr, *Z = Op1;
699 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
700 // See if "V === Y - Z" simplifies.
701 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse-1))
702 // It does! Now see if "X + V" simplifies.
703 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse-1)) {
704 // It does, we successfully reassociated!
708 // See if "V === X - Z" simplifies.
709 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
710 // It does! Now see if "Y + V" simplifies.
711 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse-1)) {
712 // It does, we successfully reassociated!
718 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
719 // For example, X - (X + 1) -> -1
721 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
722 // See if "V === X - Y" simplifies.
723 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
724 // It does! Now see if "V - Z" simplifies.
725 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse-1)) {
726 // It does, we successfully reassociated!
730 // See if "V === X - Z" simplifies.
731 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse-1))
732 // It does! Now see if "V - Y" simplifies.
733 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse-1)) {
734 // It does, we successfully reassociated!
740 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
741 // For example, X - (X - Y) -> Y.
743 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
744 // See if "V === Z - X" simplifies.
745 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse-1))
746 // It does! Now see if "V + Y" simplifies.
747 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse-1)) {
748 // It does, we successfully reassociated!
753 // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
754 if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
755 match(Op1, m_Trunc(m_Value(Y))))
756 if (X->getType() == Y->getType())
757 // See if "V === X - Y" simplifies.
758 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse-1))
759 // It does! Now see if "trunc V" simplifies.
760 if (Value *W = SimplifyTruncInst(V, Op0->getType(), Q, MaxRecurse-1))
761 // It does, return the simplified "trunc V".
764 // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
765 if (match(Op0, m_PtrToInt(m_Value(X))) &&
766 match(Op1, m_PtrToInt(m_Value(Y))))
767 if (Constant *Result = computePointerDifference(Q.DL, X, Y))
768 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
771 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
772 if (Value *V = SimplifyXorInst(Op0, Op1, Q, MaxRecurse-1))
775 // Threading Sub over selects and phi nodes is pointless, so don't bother.
776 // Threading over the select in "A - select(cond, B, C)" means evaluating
777 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
778 // only if B and C are equal. If B and C are equal then (since we assume
779 // that operands have already been simplified) "select(cond, B, C)" should
780 // have been simplified to the common value of B and C already. Analysing
781 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
782 // for threading over phi nodes.
787 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
788 const DataLayout *DL, const TargetLibraryInfo *TLI,
789 const DominatorTree *DT, AssumptionTracker *AT,
790 const Instruction *CxtI) {
791 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW,
792 Query (DL, TLI, DT, AT, CxtI), RecursionLimit);
795 /// Given operands for an FAdd, see if we can fold the result. If not, this
797 static Value *SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
798 const Query &Q, unsigned MaxRecurse) {
799 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
800 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
801 Constant *Ops[] = { CLHS, CRHS };
802 return ConstantFoldInstOperands(Instruction::FAdd, CLHS->getType(),
806 // Canonicalize the constant to the RHS.
811 if (match(Op1, m_NegZero()))
814 // fadd X, 0 ==> X, when we know X is not -0
815 if (match(Op1, m_Zero()) &&
816 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
819 // fadd [nnan ninf] X, (fsub [nnan ninf] 0, X) ==> 0
820 // where nnan and ninf have to occur at least once somewhere in this
822 Value *SubOp = nullptr;
823 if (match(Op1, m_FSub(m_AnyZero(), m_Specific(Op0))))
825 else if (match(Op0, m_FSub(m_AnyZero(), m_Specific(Op1))))
828 Instruction *FSub = cast<Instruction>(SubOp);
829 if ((FMF.noNaNs() || FSub->hasNoNaNs()) &&
830 (FMF.noInfs() || FSub->hasNoInfs()))
831 return Constant::getNullValue(Op0->getType());
837 /// Given operands for an FSub, see if we can fold the result. If not, this
839 static Value *SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
840 const Query &Q, unsigned MaxRecurse) {
841 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
842 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
843 Constant *Ops[] = { CLHS, CRHS };
844 return ConstantFoldInstOperands(Instruction::FSub, CLHS->getType(),
850 if (match(Op1, m_Zero()))
853 // fsub X, -0 ==> X, when we know X is not -0
854 if (match(Op1, m_NegZero()) &&
855 (FMF.noSignedZeros() || CannotBeNegativeZero(Op0)))
858 // fsub 0, (fsub -0.0, X) ==> X
860 if (match(Op0, m_AnyZero())) {
861 if (match(Op1, m_FSub(m_NegZero(), m_Value(X))))
863 if (FMF.noSignedZeros() && match(Op1, m_FSub(m_AnyZero(), m_Value(X))))
867 // fsub nnan ninf x, x ==> 0.0
868 if (FMF.noNaNs() && FMF.noInfs() && Op0 == Op1)
869 return Constant::getNullValue(Op0->getType());
874 /// Given the operands for an FMul, see if we can fold the result
875 static Value *SimplifyFMulInst(Value *Op0, Value *Op1,
878 unsigned MaxRecurse) {
879 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
880 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
881 Constant *Ops[] = { CLHS, CRHS };
882 return ConstantFoldInstOperands(Instruction::FMul, CLHS->getType(),
886 // Canonicalize the constant to the RHS.
891 if (match(Op1, m_FPOne()))
894 // fmul nnan nsz X, 0 ==> 0
895 if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op1, m_AnyZero()))
901 /// SimplifyMulInst - Given operands for a Mul, see if we can
902 /// fold the result. If not, this returns null.
903 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const Query &Q,
904 unsigned MaxRecurse) {
905 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
906 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
907 Constant *Ops[] = { CLHS, CRHS };
908 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
912 // Canonicalize the constant to the RHS.
917 if (match(Op1, m_Undef()))
918 return Constant::getNullValue(Op0->getType());
921 if (match(Op1, m_Zero()))
925 if (match(Op1, m_One()))
928 // (X / Y) * Y -> X if the division is exact.
930 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
931 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
935 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
936 if (Value *V = SimplifyAndInst(Op0, Op1, Q, MaxRecurse-1))
939 // Try some generic simplifications for associative operations.
940 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q,
944 // Mul distributes over Add. Try some generic simplifications based on this.
945 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
949 // If the operation is with the result of a select instruction, check whether
950 // operating on either branch of the select always yields the same value.
951 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
952 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q,
956 // If the operation is with the result of a phi instruction, check whether
957 // operating on all incoming values of the phi always yields the same value.
958 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
959 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q,
966 Value *llvm::SimplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
967 const DataLayout *DL, const TargetLibraryInfo *TLI,
968 const DominatorTree *DT, AssumptionTracker *AT,
969 const Instruction *CxtI) {
970 return ::SimplifyFAddInst(Op0, Op1, FMF, Query (DL, TLI, DT, AT, CxtI),
974 Value *llvm::SimplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
975 const DataLayout *DL, const TargetLibraryInfo *TLI,
976 const DominatorTree *DT, AssumptionTracker *AT,
977 const Instruction *CxtI) {
978 return ::SimplifyFSubInst(Op0, Op1, FMF, Query (DL, TLI, DT, AT, CxtI),
982 Value *llvm::SimplifyFMulInst(Value *Op0, Value *Op1,
984 const DataLayout *DL,
985 const TargetLibraryInfo *TLI,
986 const DominatorTree *DT,
987 AssumptionTracker *AT,
988 const Instruction *CxtI) {
989 return ::SimplifyFMulInst(Op0, Op1, FMF, Query (DL, TLI, DT, AT, CxtI),
993 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const DataLayout *DL,
994 const TargetLibraryInfo *TLI,
995 const DominatorTree *DT, AssumptionTracker *AT,
996 const Instruction *CxtI) {
997 return ::SimplifyMulInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1001 /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
1002 /// fold the result. If not, this returns null.
1003 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1004 const Query &Q, unsigned MaxRecurse) {
1005 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1006 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1007 Constant *Ops[] = { C0, C1 };
1008 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
1012 bool isSigned = Opcode == Instruction::SDiv;
1014 // X / undef -> undef
1015 if (match(Op1, m_Undef()))
1019 if (match(Op0, m_Undef()))
1020 return Constant::getNullValue(Op0->getType());
1022 // 0 / X -> 0, we don't need to preserve faults!
1023 if (match(Op0, m_Zero()))
1027 if (match(Op1, m_One()))
1030 if (Op0->getType()->isIntegerTy(1))
1031 // It can't be division by zero, hence it must be division by one.
1036 return ConstantInt::get(Op0->getType(), 1);
1038 // (X * Y) / Y -> X if the multiplication does not overflow.
1039 Value *X = nullptr, *Y = nullptr;
1040 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1041 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
1042 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
1043 // If the Mul knows it does not overflow, then we are good to go.
1044 if ((isSigned && Mul->hasNoSignedWrap()) ||
1045 (!isSigned && Mul->hasNoUnsignedWrap()))
1047 // If X has the form X = A / Y then X * Y cannot overflow.
1048 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1049 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1053 // (X rem Y) / Y -> 0
1054 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1055 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1056 return Constant::getNullValue(Op0->getType());
1058 // If the operation is with the result of a select instruction, check whether
1059 // operating on either branch of the select always yields the same value.
1060 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1061 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1064 // If the operation is with the result of a phi instruction, check whether
1065 // operating on all incoming values of the phi always yields the same value.
1066 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1067 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1073 /// SimplifySDivInst - Given operands for an SDiv, see if we can
1074 /// fold the result. If not, this returns null.
1075 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const Query &Q,
1076 unsigned MaxRecurse) {
1077 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, Q, MaxRecurse))
1083 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
1084 const TargetLibraryInfo *TLI,
1085 const DominatorTree *DT,
1086 AssumptionTracker *AT,
1087 const Instruction *CxtI) {
1088 return ::SimplifySDivInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1092 /// SimplifyUDivInst - Given operands for a UDiv, see if we can
1093 /// fold the result. If not, this returns null.
1094 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const Query &Q,
1095 unsigned MaxRecurse) {
1096 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, Q, MaxRecurse))
1102 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
1103 const TargetLibraryInfo *TLI,
1104 const DominatorTree *DT,
1105 AssumptionTracker *AT,
1106 const Instruction *CxtI) {
1107 return ::SimplifyUDivInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1111 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const Query &Q,
1113 // undef / X -> undef (the undef could be a snan).
1114 if (match(Op0, m_Undef()))
1117 // X / undef -> undef
1118 if (match(Op1, m_Undef()))
1124 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const DataLayout *DL,
1125 const TargetLibraryInfo *TLI,
1126 const DominatorTree *DT,
1127 AssumptionTracker *AT,
1128 const Instruction *CxtI) {
1129 return ::SimplifyFDivInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1133 /// SimplifyRem - Given operands for an SRem or URem, see if we can
1134 /// fold the result. If not, this returns null.
1135 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1136 const Query &Q, unsigned MaxRecurse) {
1137 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1138 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1139 Constant *Ops[] = { C0, C1 };
1140 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
1144 // X % undef -> undef
1145 if (match(Op1, m_Undef()))
1149 if (match(Op0, m_Undef()))
1150 return Constant::getNullValue(Op0->getType());
1152 // 0 % X -> 0, we don't need to preserve faults!
1153 if (match(Op0, m_Zero()))
1156 // X % 0 -> undef, we don't need to preserve faults!
1157 if (match(Op1, m_Zero()))
1158 return UndefValue::get(Op0->getType());
1161 if (match(Op1, m_One()))
1162 return Constant::getNullValue(Op0->getType());
1164 if (Op0->getType()->isIntegerTy(1))
1165 // It can't be remainder by zero, hence it must be remainder by one.
1166 return Constant::getNullValue(Op0->getType());
1170 return Constant::getNullValue(Op0->getType());
1172 // If the operation is with the result of a select instruction, check whether
1173 // operating on either branch of the select always yields the same value.
1174 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1175 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1178 // If the operation is with the result of a phi instruction, check whether
1179 // operating on all incoming values of the phi always yields the same value.
1180 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1181 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1187 /// SimplifySRemInst - Given operands for an SRem, see if we can
1188 /// fold the result. If not, this returns null.
1189 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const Query &Q,
1190 unsigned MaxRecurse) {
1191 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse))
1197 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
1198 const TargetLibraryInfo *TLI,
1199 const DominatorTree *DT,
1200 AssumptionTracker *AT,
1201 const Instruction *CxtI) {
1202 return ::SimplifySRemInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1206 /// SimplifyURemInst - Given operands for a URem, see if we can
1207 /// fold the result. If not, this returns null.
1208 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const Query &Q,
1209 unsigned MaxRecurse) {
1210 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse))
1216 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const DataLayout *DL,
1217 const TargetLibraryInfo *TLI,
1218 const DominatorTree *DT,
1219 AssumptionTracker *AT,
1220 const Instruction *CxtI) {
1221 return ::SimplifyURemInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1225 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const Query &,
1227 // undef % X -> undef (the undef could be a snan).
1228 if (match(Op0, m_Undef()))
1231 // X % undef -> undef
1232 if (match(Op1, m_Undef()))
1238 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const DataLayout *DL,
1239 const TargetLibraryInfo *TLI,
1240 const DominatorTree *DT,
1241 AssumptionTracker *AT,
1242 const Instruction *CxtI) {
1243 return ::SimplifyFRemInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1247 /// isUndefShift - Returns true if a shift by \c Amount always yields undef.
1248 static bool isUndefShift(Value *Amount) {
1249 Constant *C = dyn_cast<Constant>(Amount);
1253 // X shift by undef -> undef because it may shift by the bitwidth.
1254 if (isa<UndefValue>(C))
1257 // Shifting by the bitwidth or more is undefined.
1258 if (ConstantInt *CI = dyn_cast<ConstantInt>(C))
1259 if (CI->getValue().getLimitedValue() >=
1260 CI->getType()->getScalarSizeInBits())
1263 // If all lanes of a vector shift are undefined the whole shift is.
1264 if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
1265 for (unsigned I = 0, E = C->getType()->getVectorNumElements(); I != E; ++I)
1266 if (!isUndefShift(C->getAggregateElement(I)))
1274 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
1275 /// fold the result. If not, this returns null.
1276 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1277 const Query &Q, unsigned MaxRecurse) {
1278 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1279 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1280 Constant *Ops[] = { C0, C1 };
1281 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, Q.DL, Q.TLI);
1285 // 0 shift by X -> 0
1286 if (match(Op0, m_Zero()))
1289 // X shift by 0 -> X
1290 if (match(Op1, m_Zero()))
1293 // Fold undefined shifts.
1294 if (isUndefShift(Op1))
1295 return UndefValue::get(Op0->getType());
1297 // If the operation is with the result of a select instruction, check whether
1298 // operating on either branch of the select always yields the same value.
1299 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1300 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
1303 // If the operation is with the result of a phi instruction, check whether
1304 // operating on all incoming values of the phi always yields the same value.
1305 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1306 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
1312 /// SimplifyShlInst - Given operands for an Shl, see if we can
1313 /// fold the result. If not, this returns null.
1314 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1315 const Query &Q, unsigned MaxRecurse) {
1316 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, Q, MaxRecurse))
1320 if (match(Op0, m_Undef()))
1321 return Constant::getNullValue(Op0->getType());
1323 // (X >> A) << A -> X
1325 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1330 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1331 const DataLayout *DL, const TargetLibraryInfo *TLI,
1332 const DominatorTree *DT, AssumptionTracker *AT,
1333 const Instruction *CxtI) {
1334 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, Query (DL, TLI, DT, AT, CxtI),
1338 /// SimplifyLShrInst - Given operands for an LShr, see if we can
1339 /// fold the result. If not, this returns null.
1340 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1341 const Query &Q, unsigned MaxRecurse) {
1342 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, Q, MaxRecurse))
1347 return Constant::getNullValue(Op0->getType());
1350 if (match(Op0, m_Undef()))
1351 return Constant::getNullValue(Op0->getType());
1353 // (X << A) >> A -> X
1355 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1356 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1362 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1363 const DataLayout *DL,
1364 const TargetLibraryInfo *TLI,
1365 const DominatorTree *DT,
1366 AssumptionTracker *AT,
1367 const Instruction *CxtI) {
1368 return ::SimplifyLShrInst(Op0, Op1, isExact, Query (DL, TLI, DT, AT, CxtI),
1372 /// SimplifyAShrInst - Given operands for an AShr, see if we can
1373 /// fold the result. If not, this returns null.
1374 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1375 const Query &Q, unsigned MaxRecurse) {
1376 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, Q, MaxRecurse))
1381 return Constant::getNullValue(Op0->getType());
1383 // all ones >>a X -> all ones
1384 if (match(Op0, m_AllOnes()))
1387 // undef >>a X -> all ones
1388 if (match(Op0, m_Undef()))
1389 return Constant::getAllOnesValue(Op0->getType());
1391 // (X << A) >> A -> X
1393 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1394 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1397 // Arithmetic shifting an all-sign-bit value is a no-op.
1398 unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AT, Q.CxtI, Q.DT);
1399 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
1405 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1406 const DataLayout *DL,
1407 const TargetLibraryInfo *TLI,
1408 const DominatorTree *DT,
1409 AssumptionTracker *AT,
1410 const Instruction *CxtI) {
1411 return ::SimplifyAShrInst(Op0, Op1, isExact, Query (DL, TLI, DT, AT, CxtI),
1415 /// SimplifyAndInst - Given operands for an And, see if we can
1416 /// fold the result. If not, this returns null.
1417 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const Query &Q,
1418 unsigned MaxRecurse) {
1419 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1420 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1421 Constant *Ops[] = { CLHS, CRHS };
1422 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
1426 // Canonicalize the constant to the RHS.
1427 std::swap(Op0, Op1);
1431 if (match(Op1, m_Undef()))
1432 return Constant::getNullValue(Op0->getType());
1439 if (match(Op1, m_Zero()))
1443 if (match(Op1, m_AllOnes()))
1446 // A & ~A = ~A & A = 0
1447 if (match(Op0, m_Not(m_Specific(Op1))) ||
1448 match(Op1, m_Not(m_Specific(Op0))))
1449 return Constant::getNullValue(Op0->getType());
1452 Value *A = nullptr, *B = nullptr;
1453 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1454 (A == Op1 || B == Op1))
1458 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1459 (A == Op0 || B == Op0))
1462 // A & (-A) = A if A is a power of two or zero.
1463 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1464 match(Op1, m_Neg(m_Specific(Op0)))) {
1465 if (isKnownToBeAPowerOfTwo(Op0, /*OrZero*/true, 0, Q.AT, Q.CxtI, Q.DT))
1467 if (isKnownToBeAPowerOfTwo(Op1, /*OrZero*/true, 0, Q.AT, Q.CxtI, Q.DT))
1471 // Try some generic simplifications for associative operations.
1472 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q,
1476 // And distributes over Or. Try some generic simplifications based on this.
1477 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1481 // And distributes over Xor. Try some generic simplifications based on this.
1482 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1486 // If the operation is with the result of a select instruction, check whether
1487 // operating on either branch of the select always yields the same value.
1488 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1489 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, Q,
1493 // If the operation is with the result of a phi instruction, check whether
1494 // operating on all incoming values of the phi always yields the same value.
1495 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1496 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, Q,
1503 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const DataLayout *DL,
1504 const TargetLibraryInfo *TLI,
1505 const DominatorTree *DT, AssumptionTracker *AT,
1506 const Instruction *CxtI) {
1507 return ::SimplifyAndInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1511 /// SimplifyOrInst - Given operands for an Or, see if we can
1512 /// fold the result. If not, this returns null.
1513 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const Query &Q,
1514 unsigned MaxRecurse) {
1515 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1516 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1517 Constant *Ops[] = { CLHS, CRHS };
1518 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
1522 // Canonicalize the constant to the RHS.
1523 std::swap(Op0, Op1);
1527 if (match(Op1, m_Undef()))
1528 return Constant::getAllOnesValue(Op0->getType());
1535 if (match(Op1, m_Zero()))
1539 if (match(Op1, m_AllOnes()))
1542 // A | ~A = ~A | A = -1
1543 if (match(Op0, m_Not(m_Specific(Op1))) ||
1544 match(Op1, m_Not(m_Specific(Op0))))
1545 return Constant::getAllOnesValue(Op0->getType());
1548 Value *A = nullptr, *B = nullptr;
1549 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1550 (A == Op1 || B == Op1))
1554 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1555 (A == Op0 || B == Op0))
1558 // ~(A & ?) | A = -1
1559 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1560 (A == Op1 || B == Op1))
1561 return Constant::getAllOnesValue(Op1->getType());
1563 // A | ~(A & ?) = -1
1564 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1565 (A == Op0 || B == Op0))
1566 return Constant::getAllOnesValue(Op0->getType());
1568 // Try some generic simplifications for associative operations.
1569 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q,
1573 // Or distributes over And. Try some generic simplifications based on this.
1574 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, Q,
1578 // If the operation is with the result of a select instruction, check whether
1579 // operating on either branch of the select always yields the same value.
1580 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1581 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, Q,
1586 Value *C = nullptr, *D = nullptr;
1587 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
1588 match(Op1, m_And(m_Value(B), m_Value(D)))) {
1589 ConstantInt *C1 = dyn_cast<ConstantInt>(C);
1590 ConstantInt *C2 = dyn_cast<ConstantInt>(D);
1591 if (C1 && C2 && (C1->getValue() == ~C2->getValue())) {
1592 // (A & C1)|(B & C2)
1593 // If we have: ((V + N) & C1) | (V & C2)
1594 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
1595 // replace with V+N.
1597 if ((C2->getValue() & (C2->getValue() + 1)) == 0 && // C2 == 0+1+
1598 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
1599 // Add commutes, try both ways.
1600 if (V1 == B && MaskedValueIsZero(V2, C2->getValue(), Q.DL,
1601 0, Q.AT, Q.CxtI, Q.DT))
1603 if (V2 == B && MaskedValueIsZero(V1, C2->getValue(), Q.DL,
1604 0, Q.AT, Q.CxtI, Q.DT))
1607 // Or commutes, try both ways.
1608 if ((C1->getValue() & (C1->getValue() + 1)) == 0 &&
1609 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
1610 // Add commutes, try both ways.
1611 if (V1 == A && MaskedValueIsZero(V2, C1->getValue(), Q.DL,
1612 0, Q.AT, Q.CxtI, Q.DT))
1614 if (V2 == A && MaskedValueIsZero(V1, C1->getValue(), Q.DL,
1615 0, Q.AT, Q.CxtI, Q.DT))
1621 // If the operation is with the result of a phi instruction, check whether
1622 // operating on all incoming values of the phi always yields the same value.
1623 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1624 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
1630 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const DataLayout *DL,
1631 const TargetLibraryInfo *TLI,
1632 const DominatorTree *DT, AssumptionTracker *AT,
1633 const Instruction *CxtI) {
1634 return ::SimplifyOrInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1638 /// SimplifyXorInst - Given operands for a Xor, see if we can
1639 /// fold the result. If not, this returns null.
1640 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const Query &Q,
1641 unsigned MaxRecurse) {
1642 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1643 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1644 Constant *Ops[] = { CLHS, CRHS };
1645 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
1649 // Canonicalize the constant to the RHS.
1650 std::swap(Op0, Op1);
1653 // A ^ undef -> undef
1654 if (match(Op1, m_Undef()))
1658 if (match(Op1, m_Zero()))
1663 return Constant::getNullValue(Op0->getType());
1665 // A ^ ~A = ~A ^ A = -1
1666 if (match(Op0, m_Not(m_Specific(Op1))) ||
1667 match(Op1, m_Not(m_Specific(Op0))))
1668 return Constant::getAllOnesValue(Op0->getType());
1670 // Try some generic simplifications for associative operations.
1671 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q,
1675 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1676 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1677 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1678 // only if B and C are equal. If B and C are equal then (since we assume
1679 // that operands have already been simplified) "select(cond, B, C)" should
1680 // have been simplified to the common value of B and C already. Analysing
1681 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1682 // for threading over phi nodes.
1687 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const DataLayout *DL,
1688 const TargetLibraryInfo *TLI,
1689 const DominatorTree *DT, AssumptionTracker *AT,
1690 const Instruction *CxtI) {
1691 return ::SimplifyXorInst(Op0, Op1, Query (DL, TLI, DT, AT, CxtI),
1695 static Type *GetCompareTy(Value *Op) {
1696 return CmpInst::makeCmpResultType(Op->getType());
1699 /// ExtractEquivalentCondition - Rummage around inside V looking for something
1700 /// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1701 /// otherwise return null. Helper function for analyzing max/min idioms.
1702 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1703 Value *LHS, Value *RHS) {
1704 SelectInst *SI = dyn_cast<SelectInst>(V);
1707 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1710 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1711 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1713 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1714 LHS == CmpRHS && RHS == CmpLHS)
1719 // A significant optimization not implemented here is assuming that alloca
1720 // addresses are not equal to incoming argument values. They don't *alias*,
1721 // as we say, but that doesn't mean they aren't equal, so we take a
1722 // conservative approach.
1724 // This is inspired in part by C++11 5.10p1:
1725 // "Two pointers of the same type compare equal if and only if they are both
1726 // null, both point to the same function, or both represent the same
1729 // This is pretty permissive.
1731 // It's also partly due to C11 6.5.9p6:
1732 // "Two pointers compare equal if and only if both are null pointers, both are
1733 // pointers to the same object (including a pointer to an object and a
1734 // subobject at its beginning) or function, both are pointers to one past the
1735 // last element of the same array object, or one is a pointer to one past the
1736 // end of one array object and the other is a pointer to the start of a
1737 // different array object that happens to immediately follow the first array
1738 // object in the address space.)
1740 // C11's version is more restrictive, however there's no reason why an argument
1741 // couldn't be a one-past-the-end value for a stack object in the caller and be
1742 // equal to the beginning of a stack object in the callee.
1744 // If the C and C++ standards are ever made sufficiently restrictive in this
1745 // area, it may be possible to update LLVM's semantics accordingly and reinstate
1746 // this optimization.
1747 static Constant *computePointerICmp(const DataLayout *DL,
1748 const TargetLibraryInfo *TLI,
1749 CmpInst::Predicate Pred,
1750 Value *LHS, Value *RHS) {
1751 // First, skip past any trivial no-ops.
1752 LHS = LHS->stripPointerCasts();
1753 RHS = RHS->stripPointerCasts();
1755 // A non-null pointer is not equal to a null pointer.
1756 if (llvm::isKnownNonNull(LHS, TLI) && isa<ConstantPointerNull>(RHS) &&
1757 (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE))
1758 return ConstantInt::get(GetCompareTy(LHS),
1759 !CmpInst::isTrueWhenEqual(Pred));
1761 // We can only fold certain predicates on pointer comparisons.
1766 // Equality comaprisons are easy to fold.
1767 case CmpInst::ICMP_EQ:
1768 case CmpInst::ICMP_NE:
1771 // We can only handle unsigned relational comparisons because 'inbounds' on
1772 // a GEP only protects against unsigned wrapping.
1773 case CmpInst::ICMP_UGT:
1774 case CmpInst::ICMP_UGE:
1775 case CmpInst::ICMP_ULT:
1776 case CmpInst::ICMP_ULE:
1777 // However, we have to switch them to their signed variants to handle
1778 // negative indices from the base pointer.
1779 Pred = ICmpInst::getSignedPredicate(Pred);
1783 // Strip off any constant offsets so that we can reason about them.
1784 // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
1785 // here and compare base addresses like AliasAnalysis does, however there are
1786 // numerous hazards. AliasAnalysis and its utilities rely on special rules
1787 // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
1788 // doesn't need to guarantee pointer inequality when it says NoAlias.
1789 Constant *LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
1790 Constant *RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
1792 // If LHS and RHS are related via constant offsets to the same base
1793 // value, we can replace it with an icmp which just compares the offsets.
1795 return ConstantExpr::getICmp(Pred, LHSOffset, RHSOffset);
1797 // Various optimizations for (in)equality comparisons.
1798 if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
1799 // Different non-empty allocations that exist at the same time have
1800 // different addresses (if the program can tell). Global variables always
1801 // exist, so they always exist during the lifetime of each other and all
1802 // allocas. Two different allocas usually have different addresses...
1804 // However, if there's an @llvm.stackrestore dynamically in between two
1805 // allocas, they may have the same address. It's tempting to reduce the
1806 // scope of the problem by only looking at *static* allocas here. That would
1807 // cover the majority of allocas while significantly reducing the likelihood
1808 // of having an @llvm.stackrestore pop up in the middle. However, it's not
1809 // actually impossible for an @llvm.stackrestore to pop up in the middle of
1810 // an entry block. Also, if we have a block that's not attached to a
1811 // function, we can't tell if it's "static" under the current definition.
1812 // Theoretically, this problem could be fixed by creating a new kind of
1813 // instruction kind specifically for static allocas. Such a new instruction
1814 // could be required to be at the top of the entry block, thus preventing it
1815 // from being subject to a @llvm.stackrestore. Instcombine could even
1816 // convert regular allocas into these special allocas. It'd be nifty.
1817 // However, until then, this problem remains open.
1819 // So, we'll assume that two non-empty allocas have different addresses
1822 // With all that, if the offsets are within the bounds of their allocations
1823 // (and not one-past-the-end! so we can't use inbounds!), and their
1824 // allocations aren't the same, the pointers are not equal.
1826 // Note that it's not necessary to check for LHS being a global variable
1827 // address, due to canonicalization and constant folding.
1828 if (isa<AllocaInst>(LHS) &&
1829 (isa<AllocaInst>(RHS) || isa<GlobalVariable>(RHS))) {
1830 ConstantInt *LHSOffsetCI = dyn_cast<ConstantInt>(LHSOffset);
1831 ConstantInt *RHSOffsetCI = dyn_cast<ConstantInt>(RHSOffset);
1832 uint64_t LHSSize, RHSSize;
1833 if (LHSOffsetCI && RHSOffsetCI &&
1834 getObjectSize(LHS, LHSSize, DL, TLI) &&
1835 getObjectSize(RHS, RHSSize, DL, TLI)) {
1836 const APInt &LHSOffsetValue = LHSOffsetCI->getValue();
1837 const APInt &RHSOffsetValue = RHSOffsetCI->getValue();
1838 if (!LHSOffsetValue.isNegative() &&
1839 !RHSOffsetValue.isNegative() &&
1840 LHSOffsetValue.ult(LHSSize) &&
1841 RHSOffsetValue.ult(RHSSize)) {
1842 return ConstantInt::get(GetCompareTy(LHS),
1843 !CmpInst::isTrueWhenEqual(Pred));
1847 // Repeat the above check but this time without depending on DataLayout
1848 // or being able to compute a precise size.
1849 if (!cast<PointerType>(LHS->getType())->isEmptyTy() &&
1850 !cast<PointerType>(RHS->getType())->isEmptyTy() &&
1851 LHSOffset->isNullValue() &&
1852 RHSOffset->isNullValue())
1853 return ConstantInt::get(GetCompareTy(LHS),
1854 !CmpInst::isTrueWhenEqual(Pred));
1857 // Even if an non-inbounds GEP occurs along the path we can still optimize
1858 // equality comparisons concerning the result. We avoid walking the whole
1859 // chain again by starting where the last calls to
1860 // stripAndComputeConstantOffsets left off and accumulate the offsets.
1861 Constant *LHSNoBound = stripAndComputeConstantOffsets(DL, LHS, true);
1862 Constant *RHSNoBound = stripAndComputeConstantOffsets(DL, RHS, true);
1864 return ConstantExpr::getICmp(Pred,
1865 ConstantExpr::getAdd(LHSOffset, LHSNoBound),
1866 ConstantExpr::getAdd(RHSOffset, RHSNoBound));
1873 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1874 /// fold the result. If not, this returns null.
1875 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1876 const Query &Q, unsigned MaxRecurse) {
1877 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1878 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
1880 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
1881 if (Constant *CRHS = dyn_cast<Constant>(RHS))
1882 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
1884 // If we have a constant, make sure it is on the RHS.
1885 std::swap(LHS, RHS);
1886 Pred = CmpInst::getSwappedPredicate(Pred);
1889 Type *ITy = GetCompareTy(LHS); // The return type.
1890 Type *OpTy = LHS->getType(); // The operand type.
1892 // icmp X, X -> true/false
1893 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1894 // because X could be 0.
1895 if (LHS == RHS || isa<UndefValue>(RHS))
1896 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1898 // Special case logic when the operands have i1 type.
1899 if (OpTy->getScalarType()->isIntegerTy(1)) {
1902 case ICmpInst::ICMP_EQ:
1904 if (match(RHS, m_One()))
1907 case ICmpInst::ICMP_NE:
1909 if (match(RHS, m_Zero()))
1912 case ICmpInst::ICMP_UGT:
1914 if (match(RHS, m_Zero()))
1917 case ICmpInst::ICMP_UGE:
1919 if (match(RHS, m_One()))
1922 case ICmpInst::ICMP_SLT:
1924 if (match(RHS, m_Zero()))
1927 case ICmpInst::ICMP_SLE:
1929 if (match(RHS, m_One()))
1935 // If we are comparing with zero then try hard since this is a common case.
1936 if (match(RHS, m_Zero())) {
1937 bool LHSKnownNonNegative, LHSKnownNegative;
1939 default: llvm_unreachable("Unknown ICmp predicate!");
1940 case ICmpInst::ICMP_ULT:
1941 return getFalse(ITy);
1942 case ICmpInst::ICMP_UGE:
1943 return getTrue(ITy);
1944 case ICmpInst::ICMP_EQ:
1945 case ICmpInst::ICMP_ULE:
1946 if (isKnownNonZero(LHS, Q.DL, 0, Q.AT, Q.CxtI, Q.DT))
1947 return getFalse(ITy);
1949 case ICmpInst::ICMP_NE:
1950 case ICmpInst::ICMP_UGT:
1951 if (isKnownNonZero(LHS, Q.DL, 0, Q.AT, Q.CxtI, Q.DT))
1952 return getTrue(ITy);
1954 case ICmpInst::ICMP_SLT:
1955 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL,
1956 0, Q.AT, Q.CxtI, Q.DT);
1957 if (LHSKnownNegative)
1958 return getTrue(ITy);
1959 if (LHSKnownNonNegative)
1960 return getFalse(ITy);
1962 case ICmpInst::ICMP_SLE:
1963 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL,
1964 0, Q.AT, Q.CxtI, Q.DT);
1965 if (LHSKnownNegative)
1966 return getTrue(ITy);
1967 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL,
1968 0, Q.AT, Q.CxtI, Q.DT))
1969 return getFalse(ITy);
1971 case ICmpInst::ICMP_SGE:
1972 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL,
1973 0, Q.AT, Q.CxtI, Q.DT);
1974 if (LHSKnownNegative)
1975 return getFalse(ITy);
1976 if (LHSKnownNonNegative)
1977 return getTrue(ITy);
1979 case ICmpInst::ICMP_SGT:
1980 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, Q.DL,
1981 0, Q.AT, Q.CxtI, Q.DT);
1982 if (LHSKnownNegative)
1983 return getFalse(ITy);
1984 if (LHSKnownNonNegative && isKnownNonZero(LHS, Q.DL,
1985 0, Q.AT, Q.CxtI, Q.DT))
1986 return getTrue(ITy);
1991 // See if we are doing a comparison with a constant integer.
1992 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1993 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1994 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1995 if (RHS_CR.isEmptySet())
1996 return ConstantInt::getFalse(CI->getContext());
1997 if (RHS_CR.isFullSet())
1998 return ConstantInt::getTrue(CI->getContext());
2000 // Many binary operators with constant RHS have easy to compute constant
2001 // range. Use them to check whether the comparison is a tautology.
2002 unsigned Width = CI->getBitWidth();
2003 APInt Lower = APInt(Width, 0);
2004 APInt Upper = APInt(Width, 0);
2006 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
2007 // 'urem x, CI2' produces [0, CI2).
2008 Upper = CI2->getValue();
2009 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
2010 // 'srem x, CI2' produces (-|CI2|, |CI2|).
2011 Upper = CI2->getValue().abs();
2012 Lower = (-Upper) + 1;
2013 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
2014 // 'udiv CI2, x' produces [0, CI2].
2015 Upper = CI2->getValue() + 1;
2016 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
2017 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
2018 APInt NegOne = APInt::getAllOnesValue(Width);
2020 Upper = NegOne.udiv(CI2->getValue()) + 1;
2021 } else if (match(LHS, m_SDiv(m_ConstantInt(CI2), m_Value()))) {
2022 if (CI2->isMinSignedValue()) {
2023 // 'sdiv INT_MIN, x' produces [INT_MIN, INT_MIN / -2].
2024 Lower = CI2->getValue();
2025 Upper = Lower.lshr(1) + 1;
2027 // 'sdiv CI2, x' produces [-|CI2|, |CI2|].
2028 Upper = CI2->getValue().abs() + 1;
2029 Lower = (-Upper) + 1;
2031 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
2032 APInt IntMin = APInt::getSignedMinValue(Width);
2033 APInt IntMax = APInt::getSignedMaxValue(Width);
2034 APInt Val = CI2->getValue();
2035 if (Val.isAllOnesValue()) {
2036 // 'sdiv x, -1' produces [INT_MIN + 1, INT_MAX]
2037 // where CI2 != -1 and CI2 != 0 and CI2 != 1
2040 } else if (Val.countLeadingZeros() < Width - 1) {
2041 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2]
2042 // where CI2 != -1 and CI2 != 0 and CI2 != 1
2043 Lower = IntMin.sdiv(Val);
2044 Upper = IntMax.sdiv(Val);
2045 if (Lower.sgt(Upper))
2046 std::swap(Lower, Upper);
2048 assert(Upper != Lower && "Upper part of range has wrapped!");
2050 } else if (match(LHS, m_NUWShl(m_ConstantInt(CI2), m_Value()))) {
2051 // 'shl nuw CI2, x' produces [CI2, CI2 << CLZ(CI2)]
2052 Lower = CI2->getValue();
2053 Upper = Lower.shl(Lower.countLeadingZeros()) + 1;
2054 } else if (match(LHS, m_NSWShl(m_ConstantInt(CI2), m_Value()))) {
2055 if (CI2->isNegative()) {
2056 // 'shl nsw CI2, x' produces [CI2 << CLO(CI2)-1, CI2]
2057 unsigned ShiftAmount = CI2->getValue().countLeadingOnes() - 1;
2058 Lower = CI2->getValue().shl(ShiftAmount);
2059 Upper = CI2->getValue() + 1;
2061 // 'shl nsw CI2, x' produces [CI2, CI2 << CLZ(CI2)-1]
2062 unsigned ShiftAmount = CI2->getValue().countLeadingZeros() - 1;
2063 Lower = CI2->getValue();
2064 Upper = CI2->getValue().shl(ShiftAmount) + 1;
2066 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
2067 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
2068 APInt NegOne = APInt::getAllOnesValue(Width);
2069 if (CI2->getValue().ult(Width))
2070 Upper = NegOne.lshr(CI2->getValue()) + 1;
2071 } else if (match(LHS, m_LShr(m_ConstantInt(CI2), m_Value()))) {
2072 // 'lshr CI2, x' produces [CI2 >> (Width-1), CI2].
2073 unsigned ShiftAmount = Width - 1;
2074 if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2075 ShiftAmount = CI2->getValue().countTrailingZeros();
2076 Lower = CI2->getValue().lshr(ShiftAmount);
2077 Upper = CI2->getValue() + 1;
2078 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
2079 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
2080 APInt IntMin = APInt::getSignedMinValue(Width);
2081 APInt IntMax = APInt::getSignedMaxValue(Width);
2082 if (CI2->getValue().ult(Width)) {
2083 Lower = IntMin.ashr(CI2->getValue());
2084 Upper = IntMax.ashr(CI2->getValue()) + 1;
2086 } else if (match(LHS, m_AShr(m_ConstantInt(CI2), m_Value()))) {
2087 unsigned ShiftAmount = Width - 1;
2088 if (!CI2->isZero() && cast<BinaryOperator>(LHS)->isExact())
2089 ShiftAmount = CI2->getValue().countTrailingZeros();
2090 if (CI2->isNegative()) {
2091 // 'ashr CI2, x' produces [CI2, CI2 >> (Width-1)]
2092 Lower = CI2->getValue();
2093 Upper = CI2->getValue().ashr(ShiftAmount) + 1;
2095 // 'ashr CI2, x' produces [CI2 >> (Width-1), CI2]
2096 Lower = CI2->getValue().ashr(ShiftAmount);
2097 Upper = CI2->getValue() + 1;
2099 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
2100 // 'or x, CI2' produces [CI2, UINT_MAX].
2101 Lower = CI2->getValue();
2102 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
2103 // 'and x, CI2' produces [0, CI2].
2104 Upper = CI2->getValue() + 1;
2106 if (Lower != Upper) {
2107 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
2108 if (RHS_CR.contains(LHS_CR))
2109 return ConstantInt::getTrue(RHS->getContext());
2110 if (RHS_CR.inverse().contains(LHS_CR))
2111 return ConstantInt::getFalse(RHS->getContext());
2115 // Compare of cast, for example (zext X) != 0 -> X != 0
2116 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
2117 Instruction *LI = cast<CastInst>(LHS);
2118 Value *SrcOp = LI->getOperand(0);
2119 Type *SrcTy = SrcOp->getType();
2120 Type *DstTy = LI->getType();
2122 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
2123 // if the integer type is the same size as the pointer type.
2124 if (MaxRecurse && Q.DL && isa<PtrToIntInst>(LI) &&
2125 Q.DL->getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
2126 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2127 // Transfer the cast to the constant.
2128 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
2129 ConstantExpr::getIntToPtr(RHSC, SrcTy),
2132 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
2133 if (RI->getOperand(0)->getType() == SrcTy)
2134 // Compare without the cast.
2135 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
2141 if (isa<ZExtInst>(LHS)) {
2142 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
2144 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
2145 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2146 // Compare X and Y. Note that signed predicates become unsigned.
2147 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
2148 SrcOp, RI->getOperand(0), Q,
2152 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
2153 // too. If not, then try to deduce the result of the comparison.
2154 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2155 // Compute the constant that would happen if we truncated to SrcTy then
2156 // reextended to DstTy.
2157 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2158 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
2160 // If the re-extended constant didn't change then this is effectively
2161 // also a case of comparing two zero-extended values.
2162 if (RExt == CI && MaxRecurse)
2163 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
2164 SrcOp, Trunc, Q, MaxRecurse-1))
2167 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
2168 // there. Use this to work out the result of the comparison.
2171 default: llvm_unreachable("Unknown ICmp predicate!");
2173 case ICmpInst::ICMP_EQ:
2174 case ICmpInst::ICMP_UGT:
2175 case ICmpInst::ICMP_UGE:
2176 return ConstantInt::getFalse(CI->getContext());
2178 case ICmpInst::ICMP_NE:
2179 case ICmpInst::ICMP_ULT:
2180 case ICmpInst::ICMP_ULE:
2181 return ConstantInt::getTrue(CI->getContext());
2183 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
2184 // is non-negative then LHS <s RHS.
2185 case ICmpInst::ICMP_SGT:
2186 case ICmpInst::ICMP_SGE:
2187 return CI->getValue().isNegative() ?
2188 ConstantInt::getTrue(CI->getContext()) :
2189 ConstantInt::getFalse(CI->getContext());
2191 case ICmpInst::ICMP_SLT:
2192 case ICmpInst::ICMP_SLE:
2193 return CI->getValue().isNegative() ?
2194 ConstantInt::getFalse(CI->getContext()) :
2195 ConstantInt::getTrue(CI->getContext());
2201 if (isa<SExtInst>(LHS)) {
2202 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
2204 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
2205 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
2206 // Compare X and Y. Note that the predicate does not change.
2207 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
2211 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
2212 // too. If not, then try to deduce the result of the comparison.
2213 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2214 // Compute the constant that would happen if we truncated to SrcTy then
2215 // reextended to DstTy.
2216 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
2217 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
2219 // If the re-extended constant didn't change then this is effectively
2220 // also a case of comparing two sign-extended values.
2221 if (RExt == CI && MaxRecurse)
2222 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse-1))
2225 // Otherwise the upper bits of LHS are all equal, while RHS has varying
2226 // bits there. Use this to work out the result of the comparison.
2229 default: llvm_unreachable("Unknown ICmp predicate!");
2230 case ICmpInst::ICMP_EQ:
2231 return ConstantInt::getFalse(CI->getContext());
2232 case ICmpInst::ICMP_NE:
2233 return ConstantInt::getTrue(CI->getContext());
2235 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
2237 case ICmpInst::ICMP_SGT:
2238 case ICmpInst::ICMP_SGE:
2239 return CI->getValue().isNegative() ?
2240 ConstantInt::getTrue(CI->getContext()) :
2241 ConstantInt::getFalse(CI->getContext());
2242 case ICmpInst::ICMP_SLT:
2243 case ICmpInst::ICMP_SLE:
2244 return CI->getValue().isNegative() ?
2245 ConstantInt::getFalse(CI->getContext()) :
2246 ConstantInt::getTrue(CI->getContext());
2248 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
2250 case ICmpInst::ICMP_UGT:
2251 case ICmpInst::ICMP_UGE:
2252 // Comparison is true iff the LHS <s 0.
2254 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2255 Constant::getNullValue(SrcTy),
2259 case ICmpInst::ICMP_ULT:
2260 case ICmpInst::ICMP_ULE:
2261 // Comparison is true iff the LHS >=s 0.
2263 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2264 Constant::getNullValue(SrcTy),
2274 // If a bit is known to be zero for A and known to be one for B,
2275 // then A and B cannot be equal.
2276 if (ICmpInst::isEquality(Pred)) {
2277 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
2278 uint32_t BitWidth = CI->getBitWidth();
2279 APInt LHSKnownZero(BitWidth, 0);
2280 APInt LHSKnownOne(BitWidth, 0);
2281 computeKnownBits(LHS, LHSKnownZero, LHSKnownOne, Q.DL,
2282 0, Q.AT, Q.CxtI, Q.DT);
2283 APInt RHSKnownZero(BitWidth, 0);
2284 APInt RHSKnownOne(BitWidth, 0);
2285 computeKnownBits(RHS, RHSKnownZero, RHSKnownOne, Q.DL,
2286 0, Q.AT, Q.CxtI, Q.DT);
2287 if (((LHSKnownOne & RHSKnownZero) != 0) ||
2288 ((LHSKnownZero & RHSKnownOne) != 0))
2289 return (Pred == ICmpInst::ICMP_EQ)
2290 ? ConstantInt::getFalse(CI->getContext())
2291 : ConstantInt::getTrue(CI->getContext());
2295 // Special logic for binary operators.
2296 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2297 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2298 if (MaxRecurse && (LBO || RBO)) {
2299 // Analyze the case when either LHS or RHS is an add instruction.
2300 Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
2301 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2302 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2303 if (LBO && LBO->getOpcode() == Instruction::Add) {
2304 A = LBO->getOperand(0); B = LBO->getOperand(1);
2305 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2306 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2307 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2309 if (RBO && RBO->getOpcode() == Instruction::Add) {
2310 C = RBO->getOperand(0); D = RBO->getOperand(1);
2311 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2312 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2313 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2316 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2317 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2318 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2319 Constant::getNullValue(RHS->getType()),
2323 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2324 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2325 if (Value *V = SimplifyICmpInst(Pred,
2326 Constant::getNullValue(LHS->getType()),
2327 C == LHS ? D : C, Q, MaxRecurse-1))
2330 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2331 if (A && C && (A == C || A == D || B == C || B == D) &&
2332 NoLHSWrapProblem && NoRHSWrapProblem) {
2333 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2336 // C + B == C + D -> B == D
2339 } else if (A == D) {
2340 // D + B == C + D -> B == C
2343 } else if (B == C) {
2344 // A + C == C + D -> A == D
2349 // A + D == C + D -> A == C
2353 if (Value *V = SimplifyICmpInst(Pred, Y, Z, Q, MaxRecurse-1))
2358 // 0 - (zext X) pred C
2359 if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
2360 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2361 if (RHSC->getValue().isStrictlyPositive()) {
2362 if (Pred == ICmpInst::ICMP_SLT)
2363 return ConstantInt::getTrue(RHSC->getContext());
2364 if (Pred == ICmpInst::ICMP_SGE)
2365 return ConstantInt::getFalse(RHSC->getContext());
2366 if (Pred == ICmpInst::ICMP_EQ)
2367 return ConstantInt::getFalse(RHSC->getContext());
2368 if (Pred == ICmpInst::ICMP_NE)
2369 return ConstantInt::getTrue(RHSC->getContext());
2371 if (RHSC->getValue().isNonNegative()) {
2372 if (Pred == ICmpInst::ICMP_SLE)
2373 return ConstantInt::getTrue(RHSC->getContext());
2374 if (Pred == ICmpInst::ICMP_SGT)
2375 return ConstantInt::getFalse(RHSC->getContext());
2380 // icmp pred (urem X, Y), Y
2381 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2382 bool KnownNonNegative, KnownNegative;
2386 case ICmpInst::ICMP_SGT:
2387 case ICmpInst::ICMP_SGE:
2388 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL,
2389 0, Q.AT, Q.CxtI, Q.DT);
2390 if (!KnownNonNegative)
2393 case ICmpInst::ICMP_EQ:
2394 case ICmpInst::ICMP_UGT:
2395 case ICmpInst::ICMP_UGE:
2396 return getFalse(ITy);
2397 case ICmpInst::ICMP_SLT:
2398 case ICmpInst::ICMP_SLE:
2399 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, Q.DL,
2400 0, Q.AT, Q.CxtI, Q.DT);
2401 if (!KnownNonNegative)
2404 case ICmpInst::ICMP_NE:
2405 case ICmpInst::ICMP_ULT:
2406 case ICmpInst::ICMP_ULE:
2407 return getTrue(ITy);
2411 // icmp pred X, (urem Y, X)
2412 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2413 bool KnownNonNegative, KnownNegative;
2417 case ICmpInst::ICMP_SGT:
2418 case ICmpInst::ICMP_SGE:
2419 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL,
2420 0, Q.AT, Q.CxtI, Q.DT);
2421 if (!KnownNonNegative)
2424 case ICmpInst::ICMP_NE:
2425 case ICmpInst::ICMP_UGT:
2426 case ICmpInst::ICMP_UGE:
2427 return getTrue(ITy);
2428 case ICmpInst::ICMP_SLT:
2429 case ICmpInst::ICMP_SLE:
2430 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, Q.DL,
2431 0, Q.AT, Q.CxtI, Q.DT);
2432 if (!KnownNonNegative)
2435 case ICmpInst::ICMP_EQ:
2436 case ICmpInst::ICMP_ULT:
2437 case ICmpInst::ICMP_ULE:
2438 return getFalse(ITy);
2443 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2444 // icmp pred (X /u Y), X
2445 if (Pred == ICmpInst::ICMP_UGT)
2446 return getFalse(ITy);
2447 if (Pred == ICmpInst::ICMP_ULE)
2448 return getTrue(ITy);
2455 // where CI2 is a power of 2 and CI isn't
2456 if (auto *CI = dyn_cast<ConstantInt>(RHS)) {
2457 const APInt *CI2Val, *CIVal = &CI->getValue();
2458 if (LBO && match(LBO, m_Shl(m_APInt(CI2Val), m_Value())) &&
2459 CI2Val->isPowerOf2()) {
2460 if (!CIVal->isPowerOf2()) {
2461 // CI2 << X can equal zero in some circumstances,
2462 // this simplification is unsafe if CI is zero.
2464 // We know it is safe if:
2465 // - The shift is nsw, we can't shift out the one bit.
2466 // - The shift is nuw, we can't shift out the one bit.
2469 if (LBO->hasNoSignedWrap() || LBO->hasNoUnsignedWrap() ||
2470 *CI2Val == 1 || !CI->isZero()) {
2471 if (Pred == ICmpInst::ICMP_EQ)
2472 return ConstantInt::getFalse(RHS->getContext());
2473 if (Pred == ICmpInst::ICMP_NE)
2474 return ConstantInt::getTrue(RHS->getContext());
2477 if (CIVal->isSignBit() && *CI2Val == 1) {
2478 if (Pred == ICmpInst::ICMP_UGT)
2479 return ConstantInt::getFalse(RHS->getContext());
2480 if (Pred == ICmpInst::ICMP_ULE)
2481 return ConstantInt::getTrue(RHS->getContext());
2486 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2487 LBO->getOperand(1) == RBO->getOperand(1)) {
2488 switch (LBO->getOpcode()) {
2490 case Instruction::UDiv:
2491 case Instruction::LShr:
2492 if (ICmpInst::isSigned(Pred))
2495 case Instruction::SDiv:
2496 case Instruction::AShr:
2497 if (!LBO->isExact() || !RBO->isExact())
2499 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2500 RBO->getOperand(0), Q, MaxRecurse-1))
2503 case Instruction::Shl: {
2504 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2505 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2508 if (!NSW && ICmpInst::isSigned(Pred))
2510 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2511 RBO->getOperand(0), Q, MaxRecurse-1))
2518 // Simplify comparisons involving max/min.
2520 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2521 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2523 // Signed variants on "max(a,b)>=a -> true".
2524 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2525 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2526 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2527 // We analyze this as smax(A, B) pred A.
2529 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2530 (A == LHS || B == LHS)) {
2531 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2532 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2533 // We analyze this as smax(A, B) swapped-pred A.
2534 P = CmpInst::getSwappedPredicate(Pred);
2535 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2536 (A == RHS || B == RHS)) {
2537 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2538 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2539 // We analyze this as smax(-A, -B) swapped-pred -A.
2540 // Note that we do not need to actually form -A or -B thanks to EqP.
2541 P = CmpInst::getSwappedPredicate(Pred);
2542 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2543 (A == LHS || B == LHS)) {
2544 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2545 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2546 // We analyze this as smax(-A, -B) pred -A.
2547 // Note that we do not need to actually form -A or -B thanks to EqP.
2550 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2551 // Cases correspond to "max(A, B) p A".
2555 case CmpInst::ICMP_EQ:
2556 case CmpInst::ICMP_SLE:
2557 // Equivalent to "A EqP B". This may be the same as the condition tested
2558 // in the max/min; if so, we can just return that.
2559 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2561 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2563 // Otherwise, see if "A EqP B" simplifies.
2565 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2568 case CmpInst::ICMP_NE:
2569 case CmpInst::ICMP_SGT: {
2570 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2571 // Equivalent to "A InvEqP B". This may be the same as the condition
2572 // tested in the max/min; if so, we can just return that.
2573 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2575 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2577 // Otherwise, see if "A InvEqP B" simplifies.
2579 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2583 case CmpInst::ICMP_SGE:
2585 return getTrue(ITy);
2586 case CmpInst::ICMP_SLT:
2588 return getFalse(ITy);
2592 // Unsigned variants on "max(a,b)>=a -> true".
2593 P = CmpInst::BAD_ICMP_PREDICATE;
2594 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2595 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2596 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2597 // We analyze this as umax(A, B) pred A.
2599 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2600 (A == LHS || B == LHS)) {
2601 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2602 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2603 // We analyze this as umax(A, B) swapped-pred A.
2604 P = CmpInst::getSwappedPredicate(Pred);
2605 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2606 (A == RHS || B == RHS)) {
2607 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2608 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2609 // We analyze this as umax(-A, -B) swapped-pred -A.
2610 // Note that we do not need to actually form -A or -B thanks to EqP.
2611 P = CmpInst::getSwappedPredicate(Pred);
2612 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2613 (A == LHS || B == LHS)) {
2614 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2615 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2616 // We analyze this as umax(-A, -B) pred -A.
2617 // Note that we do not need to actually form -A or -B thanks to EqP.
2620 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2621 // Cases correspond to "max(A, B) p A".
2625 case CmpInst::ICMP_EQ:
2626 case CmpInst::ICMP_ULE:
2627 // Equivalent to "A EqP B". This may be the same as the condition tested
2628 // in the max/min; if so, we can just return that.
2629 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2631 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2633 // Otherwise, see if "A EqP B" simplifies.
2635 if (Value *V = SimplifyICmpInst(EqP, A, B, Q, MaxRecurse-1))
2638 case CmpInst::ICMP_NE:
2639 case CmpInst::ICMP_UGT: {
2640 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2641 // Equivalent to "A InvEqP B". This may be the same as the condition
2642 // tested in the max/min; if so, we can just return that.
2643 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2645 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2647 // Otherwise, see if "A InvEqP B" simplifies.
2649 if (Value *V = SimplifyICmpInst(InvEqP, A, B, Q, MaxRecurse-1))
2653 case CmpInst::ICMP_UGE:
2655 return getTrue(ITy);
2656 case CmpInst::ICMP_ULT:
2658 return getFalse(ITy);
2662 // Variants on "max(x,y) >= min(x,z)".
2664 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2665 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2666 (A == C || A == D || B == C || B == D)) {
2667 // max(x, ?) pred min(x, ?).
2668 if (Pred == CmpInst::ICMP_SGE)
2670 return getTrue(ITy);
2671 if (Pred == CmpInst::ICMP_SLT)
2673 return getFalse(ITy);
2674 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2675 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2676 (A == C || A == D || B == C || B == D)) {
2677 // min(x, ?) pred max(x, ?).
2678 if (Pred == CmpInst::ICMP_SLE)
2680 return getTrue(ITy);
2681 if (Pred == CmpInst::ICMP_SGT)
2683 return getFalse(ITy);
2684 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2685 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2686 (A == C || A == D || B == C || B == D)) {
2687 // max(x, ?) pred min(x, ?).
2688 if (Pred == CmpInst::ICMP_UGE)
2690 return getTrue(ITy);
2691 if (Pred == CmpInst::ICMP_ULT)
2693 return getFalse(ITy);
2694 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2695 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2696 (A == C || A == D || B == C || B == D)) {
2697 // min(x, ?) pred max(x, ?).
2698 if (Pred == CmpInst::ICMP_ULE)
2700 return getTrue(ITy);
2701 if (Pred == CmpInst::ICMP_UGT)
2703 return getFalse(ITy);
2706 // Simplify comparisons of related pointers using a powerful, recursive
2707 // GEP-walk when we have target data available..
2708 if (LHS->getType()->isPointerTy())
2709 if (Constant *C = computePointerICmp(Q.DL, Q.TLI, Pred, LHS, RHS))
2712 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2713 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2714 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2715 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2716 (ICmpInst::isEquality(Pred) ||
2717 (GLHS->isInBounds() && GRHS->isInBounds() &&
2718 Pred == ICmpInst::getSignedPredicate(Pred)))) {
2719 // The bases are equal and the indices are constant. Build a constant
2720 // expression GEP with the same indices and a null base pointer to see
2721 // what constant folding can make out of it.
2722 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2723 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2724 Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2726 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2727 Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2728 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2733 // If the comparison is with the result of a select instruction, check whether
2734 // comparing with either branch of the select always yields the same value.
2735 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2736 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
2739 // If the comparison is with the result of a phi instruction, check whether
2740 // doing the compare with each incoming phi value yields a common result.
2741 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2742 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
2748 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2749 const DataLayout *DL,
2750 const TargetLibraryInfo *TLI,
2751 const DominatorTree *DT,
2752 AssumptionTracker *AT,
2753 Instruction *CxtI) {
2754 return ::SimplifyICmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT, AT, CxtI),
2758 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2759 /// fold the result. If not, this returns null.
2760 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2761 const Query &Q, unsigned MaxRecurse) {
2762 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2763 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2765 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2766 if (Constant *CRHS = dyn_cast<Constant>(RHS))
2767 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
2769 // If we have a constant, make sure it is on the RHS.
2770 std::swap(LHS, RHS);
2771 Pred = CmpInst::getSwappedPredicate(Pred);
2774 // Fold trivial predicates.
2775 if (Pred == FCmpInst::FCMP_FALSE)
2776 return ConstantInt::get(GetCompareTy(LHS), 0);
2777 if (Pred == FCmpInst::FCMP_TRUE)
2778 return ConstantInt::get(GetCompareTy(LHS), 1);
2780 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2781 return UndefValue::get(GetCompareTy(LHS));
2783 // fcmp x,x -> true/false. Not all compares are foldable.
2785 if (CmpInst::isTrueWhenEqual(Pred))
2786 return ConstantInt::get(GetCompareTy(LHS), 1);
2787 if (CmpInst::isFalseWhenEqual(Pred))
2788 return ConstantInt::get(GetCompareTy(LHS), 0);
2791 // Handle fcmp with constant RHS
2792 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2793 // If the constant is a nan, see if we can fold the comparison based on it.
2794 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2795 if (CFP->getValueAPF().isNaN()) {
2796 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2797 return ConstantInt::getFalse(CFP->getContext());
2798 assert(FCmpInst::isUnordered(Pred) &&
2799 "Comparison must be either ordered or unordered!");
2800 // True if unordered.
2801 return ConstantInt::getTrue(CFP->getContext());
2803 // Check whether the constant is an infinity.
2804 if (CFP->getValueAPF().isInfinity()) {
2805 if (CFP->getValueAPF().isNegative()) {
2807 case FCmpInst::FCMP_OLT:
2808 // No value is ordered and less than negative infinity.
2809 return ConstantInt::getFalse(CFP->getContext());
2810 case FCmpInst::FCMP_UGE:
2811 // All values are unordered with or at least negative infinity.
2812 return ConstantInt::getTrue(CFP->getContext());
2818 case FCmpInst::FCMP_OGT:
2819 // No value is ordered and greater than infinity.
2820 return ConstantInt::getFalse(CFP->getContext());
2821 case FCmpInst::FCMP_ULE:
2822 // All values are unordered with and at most infinity.
2823 return ConstantInt::getTrue(CFP->getContext());
2832 // If the comparison is with the result of a select instruction, check whether
2833 // comparing with either branch of the select always yields the same value.
2834 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2835 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
2838 // If the comparison is with the result of a phi instruction, check whether
2839 // doing the compare with each incoming phi value yields a common result.
2840 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2841 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
2847 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2848 const DataLayout *DL,
2849 const TargetLibraryInfo *TLI,
2850 const DominatorTree *DT,
2851 AssumptionTracker *AT,
2852 const Instruction *CxtI) {
2853 return ::SimplifyFCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT, AT, CxtI),
2857 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2858 /// the result. If not, this returns null.
2859 static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal,
2860 Value *FalseVal, const Query &Q,
2861 unsigned MaxRecurse) {
2862 // select true, X, Y -> X
2863 // select false, X, Y -> Y
2864 if (Constant *CB = dyn_cast<Constant>(CondVal)) {
2865 if (CB->isAllOnesValue())
2867 if (CB->isNullValue())
2871 // select C, X, X -> X
2872 if (TrueVal == FalseVal)
2875 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2876 if (isa<Constant>(TrueVal))
2880 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2882 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2888 Value *llvm::SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
2889 const DataLayout *DL,
2890 const TargetLibraryInfo *TLI,
2891 const DominatorTree *DT,
2892 AssumptionTracker *AT,
2893 const Instruction *CxtI) {
2894 return ::SimplifySelectInst(Cond, TrueVal, FalseVal,
2895 Query (DL, TLI, DT, AT, CxtI), RecursionLimit);
2898 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2899 /// fold the result. If not, this returns null.
2900 static Value *SimplifyGEPInst(ArrayRef<Value *> Ops, const Query &Q, unsigned) {
2901 // The type of the GEP pointer operand.
2902 PointerType *PtrTy = cast<PointerType>(Ops[0]->getType()->getScalarType());
2903 unsigned AS = PtrTy->getAddressSpace();
2905 // getelementptr P -> P.
2906 if (Ops.size() == 1)
2909 // Compute the (pointer) type returned by the GEP instruction.
2910 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
2911 Type *GEPTy = PointerType::get(LastType, AS);
2912 if (VectorType *VT = dyn_cast<VectorType>(Ops[0]->getType()))
2913 GEPTy = VectorType::get(GEPTy, VT->getNumElements());
2915 if (isa<UndefValue>(Ops[0]))
2916 return UndefValue::get(GEPTy);
2918 if (Ops.size() == 2) {
2919 // getelementptr P, 0 -> P.
2920 if (match(Ops[1], m_Zero()))
2923 Type *Ty = PtrTy->getElementType();
2924 if (Q.DL && Ty->isSized()) {
2927 uint64_t TyAllocSize = Q.DL->getTypeAllocSize(Ty);
2928 // getelementptr P, N -> P if P points to a type of zero size.
2929 if (TyAllocSize == 0)
2932 // The following transforms are only safe if the ptrtoint cast
2933 // doesn't truncate the pointers.
2934 if (Ops[1]->getType()->getScalarSizeInBits() ==
2935 Q.DL->getPointerSizeInBits(AS)) {
2936 auto PtrToIntOrZero = [GEPTy](Value *P) -> Value * {
2937 if (match(P, m_Zero()))
2938 return Constant::getNullValue(GEPTy);
2940 if (match(P, m_PtrToInt(m_Value(Temp))))
2941 if (Temp->getType() == GEPTy)
2946 // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
2947 if (TyAllocSize == 1 &&
2948 match(Ops[1], m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0])))))
2949 if (Value *R = PtrToIntOrZero(P))
2952 // getelementptr V, (ashr (sub P, V), C) -> Q
2953 // if P points to a type of size 1 << C.
2955 m_AShr(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
2956 m_ConstantInt(C))) &&
2957 TyAllocSize == 1ULL << C)
2958 if (Value *R = PtrToIntOrZero(P))
2961 // getelementptr V, (sdiv (sub P, V), C) -> Q
2962 // if P points to a type of size C.
2964 m_SDiv(m_Sub(m_Value(P), m_PtrToInt(m_Specific(Ops[0]))),
2965 m_SpecificInt(TyAllocSize))))
2966 if (Value *R = PtrToIntOrZero(P))
2972 // Check to see if this is constant foldable.
2973 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2974 if (!isa<Constant>(Ops[i]))
2977 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
2980 Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const DataLayout *DL,
2981 const TargetLibraryInfo *TLI,
2982 const DominatorTree *DT, AssumptionTracker *AT,
2983 const Instruction *CxtI) {
2984 return ::SimplifyGEPInst(Ops, Query (DL, TLI, DT, AT, CxtI), RecursionLimit);
2987 /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2988 /// can fold the result. If not, this returns null.
2989 static Value *SimplifyInsertValueInst(Value *Agg, Value *Val,
2990 ArrayRef<unsigned> Idxs, const Query &Q,
2992 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2993 if (Constant *CVal = dyn_cast<Constant>(Val))
2994 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2996 // insertvalue x, undef, n -> x
2997 if (match(Val, m_Undef()))
3000 // insertvalue x, (extractvalue y, n), n
3001 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
3002 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
3003 EV->getIndices() == Idxs) {
3004 // insertvalue undef, (extractvalue y, n), n -> y
3005 if (match(Agg, m_Undef()))
3006 return EV->getAggregateOperand();
3008 // insertvalue y, (extractvalue y, n), n -> y
3009 if (Agg == EV->getAggregateOperand())
3016 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
3017 ArrayRef<unsigned> Idxs,
3018 const DataLayout *DL,
3019 const TargetLibraryInfo *TLI,
3020 const DominatorTree *DT,
3021 AssumptionTracker *AT,
3022 const Instruction *CxtI) {
3023 return ::SimplifyInsertValueInst(Agg, Val, Idxs,
3024 Query (DL, TLI, DT, AT, CxtI),
3028 /// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
3029 static Value *SimplifyPHINode(PHINode *PN, const Query &Q) {
3030 // If all of the PHI's incoming values are the same then replace the PHI node
3031 // with the common value.
3032 Value *CommonValue = nullptr;
3033 bool HasUndefInput = false;
3034 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3035 Value *Incoming = PN->getIncomingValue(i);
3036 // If the incoming value is the phi node itself, it can safely be skipped.
3037 if (Incoming == PN) continue;
3038 if (isa<UndefValue>(Incoming)) {
3039 // Remember that we saw an undef value, but otherwise ignore them.
3040 HasUndefInput = true;
3043 if (CommonValue && Incoming != CommonValue)
3044 return nullptr; // Not the same, bail out.
3045 CommonValue = Incoming;
3048 // If CommonValue is null then all of the incoming values were either undef or
3049 // equal to the phi node itself.
3051 return UndefValue::get(PN->getType());
3053 // If we have a PHI node like phi(X, undef, X), where X is defined by some
3054 // instruction, we cannot return X as the result of the PHI node unless it
3055 // dominates the PHI block.
3057 return ValueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
3062 static Value *SimplifyTruncInst(Value *Op, Type *Ty, const Query &Q, unsigned) {
3063 if (Constant *C = dyn_cast<Constant>(Op))
3064 return ConstantFoldInstOperands(Instruction::Trunc, Ty, C, Q.DL, Q.TLI);
3069 Value *llvm::SimplifyTruncInst(Value *Op, Type *Ty, const DataLayout *DL,
3070 const TargetLibraryInfo *TLI,
3071 const DominatorTree *DT,
3072 AssumptionTracker *AT,
3073 const Instruction *CxtI) {
3074 return ::SimplifyTruncInst(Op, Ty, Query (DL, TLI, DT, AT, CxtI),
3078 //=== Helper functions for higher up the class hierarchy.
3080 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
3081 /// fold the result. If not, this returns null.
3082 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3083 const Query &Q, unsigned MaxRecurse) {
3085 case Instruction::Add:
3086 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3088 case Instruction::FAdd:
3089 return SimplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3091 case Instruction::Sub:
3092 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3094 case Instruction::FSub:
3095 return SimplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3097 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, Q, MaxRecurse);
3098 case Instruction::FMul:
3099 return SimplifyFMulInst (LHS, RHS, FastMathFlags(), Q, MaxRecurse);
3100 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, Q, MaxRecurse);
3101 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, Q, MaxRecurse);
3102 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, Q, MaxRecurse);
3103 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, Q, MaxRecurse);
3104 case Instruction::URem: return SimplifyURemInst(LHS, RHS, Q, MaxRecurse);
3105 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, Q, MaxRecurse);
3106 case Instruction::Shl:
3107 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
3109 case Instruction::LShr:
3110 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
3111 case Instruction::AShr:
3112 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, Q, MaxRecurse);
3113 case Instruction::And: return SimplifyAndInst(LHS, RHS, Q, MaxRecurse);
3114 case Instruction::Or: return SimplifyOrInst (LHS, RHS, Q, MaxRecurse);
3115 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, Q, MaxRecurse);
3117 if (Constant *CLHS = dyn_cast<Constant>(LHS))
3118 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
3119 Constant *COps[] = {CLHS, CRHS};
3120 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, Q.DL,
3124 // If the operation is associative, try some generic simplifications.
3125 if (Instruction::isAssociative(Opcode))
3126 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, Q, MaxRecurse))
3129 // If the operation is with the result of a select instruction check whether
3130 // operating on either branch of the select always yields the same value.
3131 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
3132 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, Q, MaxRecurse))
3135 // If the operation is with the result of a phi instruction, check whether
3136 // operating on all incoming values of the phi always yields the same value.
3137 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
3138 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, Q, MaxRecurse))
3145 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
3146 const DataLayout *DL, const TargetLibraryInfo *TLI,
3147 const DominatorTree *DT, AssumptionTracker *AT,
3148 const Instruction *CxtI) {
3149 return ::SimplifyBinOp(Opcode, LHS, RHS, Query (DL, TLI, DT, AT, CxtI),
3153 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
3154 /// fold the result.
3155 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3156 const Query &Q, unsigned MaxRecurse) {
3157 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
3158 return SimplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
3159 return SimplifyFCmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
3162 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
3163 const DataLayout *DL, const TargetLibraryInfo *TLI,
3164 const DominatorTree *DT, AssumptionTracker *AT,
3165 const Instruction *CxtI) {
3166 return ::SimplifyCmpInst(Predicate, LHS, RHS, Query (DL, TLI, DT, AT, CxtI),
3170 static bool IsIdempotent(Intrinsic::ID ID) {
3172 default: return false;
3174 // Unary idempotent: f(f(x)) = f(x)
3175 case Intrinsic::fabs:
3176 case Intrinsic::floor:
3177 case Intrinsic::ceil:
3178 case Intrinsic::trunc:
3179 case Intrinsic::rint:
3180 case Intrinsic::nearbyint:
3181 case Intrinsic::round:
3186 template <typename IterTy>
3187 static Value *SimplifyIntrinsic(Intrinsic::ID IID, IterTy ArgBegin, IterTy ArgEnd,
3188 const Query &Q, unsigned MaxRecurse) {
3189 // Perform idempotent optimizations
3190 if (!IsIdempotent(IID))
3194 if (std::distance(ArgBegin, ArgEnd) == 1)
3195 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(*ArgBegin))
3196 if (II->getIntrinsicID() == IID)
3202 template <typename IterTy>
3203 static Value *SimplifyCall(Value *V, IterTy ArgBegin, IterTy ArgEnd,
3204 const Query &Q, unsigned MaxRecurse) {
3205 Type *Ty = V->getType();
3206 if (PointerType *PTy = dyn_cast<PointerType>(Ty))
3207 Ty = PTy->getElementType();
3208 FunctionType *FTy = cast<FunctionType>(Ty);
3210 // call undef -> undef
3211 if (isa<UndefValue>(V))
3212 return UndefValue::get(FTy->getReturnType());
3214 Function *F = dyn_cast<Function>(V);
3218 if (unsigned IID = F->getIntrinsicID())
3220 SimplifyIntrinsic((Intrinsic::ID) IID, ArgBegin, ArgEnd, Q, MaxRecurse))
3223 if (!canConstantFoldCallTo(F))
3226 SmallVector<Constant *, 4> ConstantArgs;
3227 ConstantArgs.reserve(ArgEnd - ArgBegin);
3228 for (IterTy I = ArgBegin, E = ArgEnd; I != E; ++I) {
3229 Constant *C = dyn_cast<Constant>(*I);
3232 ConstantArgs.push_back(C);
3235 return ConstantFoldCall(F, ConstantArgs, Q.TLI);
3238 Value *llvm::SimplifyCall(Value *V, User::op_iterator ArgBegin,
3239 User::op_iterator ArgEnd, const DataLayout *DL,
3240 const TargetLibraryInfo *TLI,
3241 const DominatorTree *DT, AssumptionTracker *AT,
3242 const Instruction *CxtI) {
3243 return ::SimplifyCall(V, ArgBegin, ArgEnd, Query(DL, TLI, DT, AT, CxtI),
3247 Value *llvm::SimplifyCall(Value *V, ArrayRef<Value *> Args,
3248 const DataLayout *DL, const TargetLibraryInfo *TLI,
3249 const DominatorTree *DT, AssumptionTracker *AT,
3250 const Instruction *CxtI) {
3251 return ::SimplifyCall(V, Args.begin(), Args.end(),
3252 Query(DL, TLI, DT, AT, CxtI), RecursionLimit);
3255 /// SimplifyInstruction - See if we can compute a simplified version of this
3256 /// instruction. If not, this returns null.
3257 Value *llvm::SimplifyInstruction(Instruction *I, const DataLayout *DL,
3258 const TargetLibraryInfo *TLI,
3259 const DominatorTree *DT,
3260 AssumptionTracker *AT) {
3263 switch (I->getOpcode()) {
3265 Result = ConstantFoldInstruction(I, DL, TLI);
3267 case Instruction::FAdd:
3268 Result = SimplifyFAddInst(I->getOperand(0), I->getOperand(1),
3269 I->getFastMathFlags(), DL, TLI, DT, AT, I);
3271 case Instruction::Add:
3272 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
3273 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3274 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
3275 DL, TLI, DT, AT, I);
3277 case Instruction::FSub:
3278 Result = SimplifyFSubInst(I->getOperand(0), I->getOperand(1),
3279 I->getFastMathFlags(), DL, TLI, DT, AT, I);
3281 case Instruction::Sub:
3282 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
3283 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3284 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
3285 DL, TLI, DT, AT, I);
3287 case Instruction::FMul:
3288 Result = SimplifyFMulInst(I->getOperand(0), I->getOperand(1),
3289 I->getFastMathFlags(), DL, TLI, DT, AT, I);
3291 case Instruction::Mul:
3292 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1),
3293 DL, TLI, DT, AT, I);
3295 case Instruction::SDiv:
3296 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1),
3297 DL, TLI, DT, AT, I);
3299 case Instruction::UDiv:
3300 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1),
3301 DL, TLI, DT, AT, I);
3303 case Instruction::FDiv:
3304 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1),
3305 DL, TLI, DT, AT, I);
3307 case Instruction::SRem:
3308 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1),
3309 DL, TLI, DT, AT, I);
3311 case Instruction::URem:
3312 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1),
3313 DL, TLI, DT, AT, I);
3315 case Instruction::FRem:
3316 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1),
3317 DL, TLI, DT, AT, I);
3319 case Instruction::Shl:
3320 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
3321 cast<BinaryOperator>(I)->hasNoSignedWrap(),
3322 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
3323 DL, TLI, DT, AT, I);
3325 case Instruction::LShr:
3326 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
3327 cast<BinaryOperator>(I)->isExact(),
3328 DL, TLI, DT, AT, I);
3330 case Instruction::AShr:
3331 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
3332 cast<BinaryOperator>(I)->isExact(),
3333 DL, TLI, DT, AT, I);
3335 case Instruction::And:
3336 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1),
3337 DL, TLI, DT, AT, I);
3339 case Instruction::Or:
3340 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), DL, TLI, DT,
3343 case Instruction::Xor:
3344 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1),
3345 DL, TLI, DT, AT, I);
3347 case Instruction::ICmp:
3348 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
3349 I->getOperand(0), I->getOperand(1),
3350 DL, TLI, DT, AT, I);
3352 case Instruction::FCmp:
3353 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
3354 I->getOperand(0), I->getOperand(1),
3355 DL, TLI, DT, AT, I);
3357 case Instruction::Select:
3358 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
3359 I->getOperand(2), DL, TLI, DT, AT, I);
3361 case Instruction::GetElementPtr: {
3362 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
3363 Result = SimplifyGEPInst(Ops, DL, TLI, DT, AT, I);
3366 case Instruction::InsertValue: {
3367 InsertValueInst *IV = cast<InsertValueInst>(I);
3368 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
3369 IV->getInsertedValueOperand(),
3370 IV->getIndices(), DL, TLI, DT, AT, I);
3373 case Instruction::PHI:
3374 Result = SimplifyPHINode(cast<PHINode>(I), Query (DL, TLI, DT, AT, I));
3376 case Instruction::Call: {
3377 CallSite CS(cast<CallInst>(I));
3378 Result = SimplifyCall(CS.getCalledValue(), CS.arg_begin(), CS.arg_end(),
3379 DL, TLI, DT, AT, I);
3382 case Instruction::Trunc:
3383 Result = SimplifyTruncInst(I->getOperand(0), I->getType(), DL, TLI, DT,
3388 /// If called on unreachable code, the above logic may report that the
3389 /// instruction simplified to itself. Make life easier for users by
3390 /// detecting that case here, returning a safe value instead.
3391 return Result == I ? UndefValue::get(I->getType()) : Result;
3394 /// \brief Implementation of recursive simplification through an instructions
3397 /// This is the common implementation of the recursive simplification routines.
3398 /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
3399 /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
3400 /// instructions to process and attempt to simplify it using
3401 /// InstructionSimplify.
3403 /// This routine returns 'true' only when *it* simplifies something. The passed
3404 /// in simplified value does not count toward this.
3405 static bool replaceAndRecursivelySimplifyImpl(Instruction *I, Value *SimpleV,
3406 const DataLayout *DL,
3407 const TargetLibraryInfo *TLI,
3408 const DominatorTree *DT,
3409 AssumptionTracker *AT) {
3410 bool Simplified = false;
3411 SmallSetVector<Instruction *, 8> Worklist;
3413 // If we have an explicit value to collapse to, do that round of the
3414 // simplification loop by hand initially.
3416 for (User *U : I->users())
3418 Worklist.insert(cast<Instruction>(U));
3420 // Replace the instruction with its simplified value.
3421 I->replaceAllUsesWith(SimpleV);
3423 // Gracefully handle edge cases where the instruction is not wired into any
3426 I->eraseFromParent();
3431 // Note that we must test the size on each iteration, the worklist can grow.
3432 for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
3435 // See if this instruction simplifies.
3436 SimpleV = SimplifyInstruction(I, DL, TLI, DT, AT);
3442 // Stash away all the uses of the old instruction so we can check them for
3443 // recursive simplifications after a RAUW. This is cheaper than checking all
3444 // uses of To on the recursive step in most cases.
3445 for (User *U : I->users())
3446 Worklist.insert(cast<Instruction>(U));
3448 // Replace the instruction with its simplified value.
3449 I->replaceAllUsesWith(SimpleV);
3451 // Gracefully handle edge cases where the instruction is not wired into any
3454 I->eraseFromParent();
3459 bool llvm::recursivelySimplifyInstruction(Instruction *I,
3460 const DataLayout *DL,
3461 const TargetLibraryInfo *TLI,
3462 const DominatorTree *DT,
3463 AssumptionTracker *AT) {
3464 return replaceAndRecursivelySimplifyImpl(I, nullptr, DL, TLI, DT, AT);
3467 bool llvm::replaceAndRecursivelySimplify(Instruction *I, Value *SimpleV,
3468 const DataLayout *DL,
3469 const TargetLibraryInfo *TLI,
3470 const DominatorTree *DT,
3471 AssumptionTracker *AT) {
3472 assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
3473 assert(SimpleV && "Must provide a simplified value.");
3474 return replaceAndRecursivelySimplifyImpl(I, SimpleV, DL, TLI, DT, AT);