1 //===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements routines for folding instructions into simpler forms
11 // that do not require creating new instructions. This does constant folding
12 // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
13 // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
14 // ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been
15 // simplified: This is usually true and assuming it simplifies the logic (if
16 // they have not been simplified then results are correct but maybe suboptimal).
18 //===----------------------------------------------------------------------===//
20 #define DEBUG_TYPE "instsimplify"
21 #include "llvm/GlobalAlias.h"
22 #include "llvm/Operator.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/InstructionSimplify.h"
25 #include "llvm/Analysis/AliasAnalysis.h"
26 #include "llvm/Analysis/ConstantFolding.h"
27 #include "llvm/Analysis/Dominators.h"
28 #include "llvm/Analysis/ValueTracking.h"
29 #include "llvm/Support/ConstantRange.h"
30 #include "llvm/Support/GetElementPtrTypeIterator.h"
31 #include "llvm/Support/PatternMatch.h"
32 #include "llvm/Support/ValueHandle.h"
33 #include "llvm/Target/TargetData.h"
35 using namespace llvm::PatternMatch;
37 enum { RecursionLimit = 3 };
39 STATISTIC(NumExpand, "Number of expansions");
40 STATISTIC(NumFactor , "Number of factorizations");
41 STATISTIC(NumReassoc, "Number of reassociations");
43 static Value *SimplifyAndInst(Value *, Value *, const TargetData *,
44 const TargetLibraryInfo *, const DominatorTree *,
46 static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
47 const TargetLibraryInfo *, const DominatorTree *,
49 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
50 const TargetLibraryInfo *, const DominatorTree *,
52 static Value *SimplifyOrInst(Value *, Value *, const TargetData *,
53 const TargetLibraryInfo *, const DominatorTree *,
55 static Value *SimplifyXorInst(Value *, Value *, const TargetData *,
56 const TargetLibraryInfo *, const DominatorTree *,
59 /// getFalse - For a boolean type, or a vector of boolean type, return false, or
60 /// a vector with every element false, as appropriate for the type.
61 static Constant *getFalse(Type *Ty) {
62 assert(Ty->getScalarType()->isIntegerTy(1) &&
63 "Expected i1 type or a vector of i1!");
64 return Constant::getNullValue(Ty);
67 /// getTrue - For a boolean type, or a vector of boolean type, return true, or
68 /// a vector with every element true, as appropriate for the type.
69 static Constant *getTrue(Type *Ty) {
70 assert(Ty->getScalarType()->isIntegerTy(1) &&
71 "Expected i1 type or a vector of i1!");
72 return Constant::getAllOnesValue(Ty);
75 /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
76 static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
78 CmpInst *Cmp = dyn_cast<CmpInst>(V);
81 CmpInst::Predicate CPred = Cmp->getPredicate();
82 Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
83 if (CPred == Pred && CLHS == LHS && CRHS == RHS)
85 return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
89 /// ValueDominatesPHI - Does the given value dominate the specified phi node?
90 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
91 Instruction *I = dyn_cast<Instruction>(V);
93 // Arguments and constants dominate all instructions.
96 // If we have a DominatorTree then do a precise test.
98 return !DT->isReachableFromEntry(P->getParent()) ||
99 !DT->isReachableFromEntry(I->getParent()) || DT->dominates(I, P);
101 // Otherwise, if the instruction is in the entry block, and is not an invoke,
102 // then it obviously dominates all phi nodes.
103 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
110 /// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
111 /// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
112 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
113 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
114 /// Returns the simplified value, or null if no simplification was performed.
115 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
116 unsigned OpcToExpand, const TargetData *TD,
117 const TargetLibraryInfo *TLI, const DominatorTree *DT,
118 unsigned MaxRecurse) {
119 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
120 // Recursion is always used, so bail out at once if we already hit the limit.
124 // Check whether the expression has the form "(A op' B) op C".
125 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
126 if (Op0->getOpcode() == OpcodeToExpand) {
127 // It does! Try turning it into "(A op C) op' (B op C)".
128 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
129 // Do "A op C" and "B op C" both simplify?
130 if (Value *L = SimplifyBinOp(Opcode, A, C, TD, TLI, DT, MaxRecurse))
131 if (Value *R = SimplifyBinOp(Opcode, B, C, TD, TLI, DT, MaxRecurse)) {
132 // They do! Return "L op' R" if it simplifies or is already available.
133 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
134 if ((L == A && R == B) || (Instruction::isCommutative(OpcodeToExpand)
135 && L == B && R == A)) {
139 // Otherwise return "L op' R" if it simplifies.
140 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, TLI, DT,
148 // Check whether the expression has the form "A op (B op' C)".
149 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
150 if (Op1->getOpcode() == OpcodeToExpand) {
151 // It does! Try turning it into "(A op B) op' (A op C)".
152 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
153 // Do "A op B" and "A op C" both simplify?
154 if (Value *L = SimplifyBinOp(Opcode, A, B, TD, TLI, DT, MaxRecurse))
155 if (Value *R = SimplifyBinOp(Opcode, A, C, TD, TLI, DT, MaxRecurse)) {
156 // They do! Return "L op' R" if it simplifies or is already available.
157 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
158 if ((L == B && R == C) || (Instruction::isCommutative(OpcodeToExpand)
159 && L == C && R == B)) {
163 // Otherwise return "L op' R" if it simplifies.
164 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, TLI, DT,
175 /// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
176 /// using the operation OpCodeToExtract. For example, when Opcode is Add and
177 /// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
178 /// Returns the simplified value, or null if no simplification was performed.
179 static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
180 unsigned OpcToExtract, const TargetData *TD,
181 const TargetLibraryInfo *TLI,
182 const DominatorTree *DT,
183 unsigned MaxRecurse) {
184 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
185 // Recursion is always used, so bail out at once if we already hit the limit.
189 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
190 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
192 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
193 !Op1 || Op1->getOpcode() != OpcodeToExtract)
196 // The expression has the form "(A op' B) op (C op' D)".
197 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
198 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
200 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
201 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
202 // commutative case, "(A op' B) op (C op' A)"?
203 if (A == C || (Instruction::isCommutative(OpcodeToExtract) && A == D)) {
204 Value *DD = A == C ? D : C;
205 // Form "A op' (B op DD)" if it simplifies completely.
206 // Does "B op DD" simplify?
207 if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, TLI, DT, MaxRecurse)) {
208 // It does! Return "A op' V" if it simplifies or is already available.
209 // If V equals B then "A op' V" is just the LHS. If V equals DD then
210 // "A op' V" is just the RHS.
211 if (V == B || V == DD) {
213 return V == B ? LHS : RHS;
215 // Otherwise return "A op' V" if it simplifies.
216 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, TLI, DT,
224 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
225 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
226 // commutative case, "(A op' B) op (B op' D)"?
227 if (B == D || (Instruction::isCommutative(OpcodeToExtract) && B == C)) {
228 Value *CC = B == D ? C : D;
229 // Form "(A op CC) op' B" if it simplifies completely..
230 // Does "A op CC" simplify?
231 if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, TLI, DT, MaxRecurse)) {
232 // It does! Return "V op' B" if it simplifies or is already available.
233 // If V equals A then "V op' B" is just the LHS. If V equals CC then
234 // "V op' B" is just the RHS.
235 if (V == A || V == CC) {
237 return V == A ? LHS : RHS;
239 // Otherwise return "V op' B" if it simplifies.
240 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, TLI, DT,
251 /// SimplifyAssociativeBinOp - Generic simplifications for associative binary
252 /// operations. Returns the simpler value, or null if none was found.
253 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
254 const TargetData *TD,
255 const TargetLibraryInfo *TLI,
256 const DominatorTree *DT,
257 unsigned MaxRecurse) {
258 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
259 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
261 // Recursion is always used, so bail out at once if we already hit the limit.
265 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
266 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
268 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
269 if (Op0 && Op0->getOpcode() == Opcode) {
270 Value *A = Op0->getOperand(0);
271 Value *B = Op0->getOperand(1);
274 // Does "B op C" simplify?
275 if (Value *V = SimplifyBinOp(Opcode, B, C, TD, TLI, DT, MaxRecurse)) {
276 // It does! Return "A op V" if it simplifies or is already available.
277 // If V equals B then "A op V" is just the LHS.
278 if (V == B) return LHS;
279 // Otherwise return "A op V" if it simplifies.
280 if (Value *W = SimplifyBinOp(Opcode, A, V, TD, TLI, DT, MaxRecurse)) {
287 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
288 if (Op1 && Op1->getOpcode() == Opcode) {
290 Value *B = Op1->getOperand(0);
291 Value *C = Op1->getOperand(1);
293 // Does "A op B" simplify?
294 if (Value *V = SimplifyBinOp(Opcode, A, B, TD, TLI, DT, MaxRecurse)) {
295 // It does! Return "V op C" if it simplifies or is already available.
296 // If V equals B then "V op C" is just the RHS.
297 if (V == B) return RHS;
298 // Otherwise return "V op C" if it simplifies.
299 if (Value *W = SimplifyBinOp(Opcode, V, C, TD, TLI, DT, MaxRecurse)) {
306 // The remaining transforms require commutativity as well as associativity.
307 if (!Instruction::isCommutative(Opcode))
310 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
311 if (Op0 && Op0->getOpcode() == Opcode) {
312 Value *A = Op0->getOperand(0);
313 Value *B = Op0->getOperand(1);
316 // Does "C op A" simplify?
317 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, TLI, DT, MaxRecurse)) {
318 // It does! Return "V op B" if it simplifies or is already available.
319 // If V equals A then "V op B" is just the LHS.
320 if (V == A) return LHS;
321 // Otherwise return "V op B" if it simplifies.
322 if (Value *W = SimplifyBinOp(Opcode, V, B, TD, TLI, DT, MaxRecurse)) {
329 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
330 if (Op1 && Op1->getOpcode() == Opcode) {
332 Value *B = Op1->getOperand(0);
333 Value *C = Op1->getOperand(1);
335 // Does "C op A" simplify?
336 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, TLI, DT, MaxRecurse)) {
337 // It does! Return "B op V" if it simplifies or is already available.
338 // If V equals C then "B op V" is just the RHS.
339 if (V == C) return RHS;
340 // Otherwise return "B op V" if it simplifies.
341 if (Value *W = SimplifyBinOp(Opcode, B, V, TD, TLI, DT, MaxRecurse)) {
351 /// ThreadBinOpOverSelect - In the case of a binary operation with a select
352 /// instruction as an operand, try to simplify the binop by seeing whether
353 /// evaluating it on both branches of the select results in the same value.
354 /// Returns the common value if so, otherwise returns null.
355 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
356 const TargetData *TD,
357 const TargetLibraryInfo *TLI,
358 const DominatorTree *DT,
359 unsigned MaxRecurse) {
360 // Recursion is always used, so bail out at once if we already hit the limit.
365 if (isa<SelectInst>(LHS)) {
366 SI = cast<SelectInst>(LHS);
368 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
369 SI = cast<SelectInst>(RHS);
372 // Evaluate the BinOp on the true and false branches of the select.
376 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, TLI, DT, MaxRecurse);
377 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, TLI, DT, MaxRecurse);
379 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, TLI, DT, MaxRecurse);
380 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, TLI, DT, MaxRecurse);
383 // If they simplified to the same value, then return the common value.
384 // If they both failed to simplify then return null.
388 // If one branch simplified to undef, return the other one.
389 if (TV && isa<UndefValue>(TV))
391 if (FV && isa<UndefValue>(FV))
394 // If applying the operation did not change the true and false select values,
395 // then the result of the binop is the select itself.
396 if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
399 // If one branch simplified and the other did not, and the simplified
400 // value is equal to the unsimplified one, return the simplified value.
401 // For example, select (cond, X, X & Z) & Z -> X & Z.
402 if ((FV && !TV) || (TV && !FV)) {
403 // Check that the simplified value has the form "X op Y" where "op" is the
404 // same as the original operation.
405 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
406 if (Simplified && Simplified->getOpcode() == Opcode) {
407 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
408 // We already know that "op" is the same as for the simplified value. See
409 // if the operands match too. If so, return the simplified value.
410 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
411 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
412 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
413 if (Simplified->getOperand(0) == UnsimplifiedLHS &&
414 Simplified->getOperand(1) == UnsimplifiedRHS)
416 if (Simplified->isCommutative() &&
417 Simplified->getOperand(1) == UnsimplifiedLHS &&
418 Simplified->getOperand(0) == UnsimplifiedRHS)
426 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
427 /// try to simplify the comparison by seeing whether both branches of the select
428 /// result in the same value. Returns the common value if so, otherwise returns
430 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
431 Value *RHS, const TargetData *TD,
432 const TargetLibraryInfo *TLI,
433 const DominatorTree *DT,
434 unsigned MaxRecurse) {
435 // Recursion is always used, so bail out at once if we already hit the limit.
439 // Make sure the select is on the LHS.
440 if (!isa<SelectInst>(LHS)) {
442 Pred = CmpInst::getSwappedPredicate(Pred);
444 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
445 SelectInst *SI = cast<SelectInst>(LHS);
446 Value *Cond = SI->getCondition();
447 Value *TV = SI->getTrueValue();
448 Value *FV = SI->getFalseValue();
450 // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
451 // Does "cmp TV, RHS" simplify?
452 Value *TCmp = SimplifyCmpInst(Pred, TV, RHS, TD, TLI, DT, MaxRecurse);
454 // It not only simplified, it simplified to the select condition. Replace
456 TCmp = getTrue(Cond->getType());
458 // It didn't simplify. However if "cmp TV, RHS" is equal to the select
459 // condition then we can replace it with 'true'. Otherwise give up.
460 if (!isSameCompare(Cond, Pred, TV, RHS))
462 TCmp = getTrue(Cond->getType());
465 // Does "cmp FV, RHS" simplify?
466 Value *FCmp = SimplifyCmpInst(Pred, FV, RHS, TD, TLI, DT, MaxRecurse);
468 // It not only simplified, it simplified to the select condition. Replace
470 FCmp = getFalse(Cond->getType());
472 // It didn't simplify. However if "cmp FV, RHS" is equal to the select
473 // condition then we can replace it with 'false'. Otherwise give up.
474 if (!isSameCompare(Cond, Pred, FV, RHS))
476 FCmp = getFalse(Cond->getType());
479 // If both sides simplified to the same value, then use it as the result of
480 // the original comparison.
484 // The remaining cases only make sense if the select condition has the same
485 // type as the result of the comparison, so bail out if this is not so.
486 if (Cond->getType()->isVectorTy() != RHS->getType()->isVectorTy())
488 // If the false value simplified to false, then the result of the compare
489 // is equal to "Cond && TCmp". This also catches the case when the false
490 // value simplified to false and the true value to true, returning "Cond".
491 if (match(FCmp, m_Zero()))
492 if (Value *V = SimplifyAndInst(Cond, TCmp, TD, TLI, DT, MaxRecurse))
494 // If the true value simplified to true, then the result of the compare
495 // is equal to "Cond || FCmp".
496 if (match(TCmp, m_One()))
497 if (Value *V = SimplifyOrInst(Cond, FCmp, TD, TLI, DT, MaxRecurse))
499 // Finally, if the false value simplified to true and the true value to
500 // false, then the result of the compare is equal to "!Cond".
501 if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
503 SimplifyXorInst(Cond, Constant::getAllOnesValue(Cond->getType()),
504 TD, TLI, DT, MaxRecurse))
510 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
511 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
512 /// it on the incoming phi values yields the same result for every value. If so
513 /// returns the common value, otherwise returns null.
514 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
515 const TargetData *TD,
516 const TargetLibraryInfo *TLI,
517 const DominatorTree *DT,
518 unsigned MaxRecurse) {
519 // Recursion is always used, so bail out at once if we already hit the limit.
524 if (isa<PHINode>(LHS)) {
525 PI = cast<PHINode>(LHS);
526 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
527 if (!ValueDominatesPHI(RHS, PI, DT))
530 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
531 PI = cast<PHINode>(RHS);
532 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
533 if (!ValueDominatesPHI(LHS, PI, DT))
537 // Evaluate the BinOp on the incoming phi values.
538 Value *CommonValue = 0;
539 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
540 Value *Incoming = PI->getIncomingValue(i);
541 // If the incoming value is the phi node itself, it can safely be skipped.
542 if (Incoming == PI) continue;
543 Value *V = PI == LHS ?
544 SimplifyBinOp(Opcode, Incoming, RHS, TD, TLI, DT, MaxRecurse) :
545 SimplifyBinOp(Opcode, LHS, Incoming, TD, TLI, DT, MaxRecurse);
546 // If the operation failed to simplify, or simplified to a different value
547 // to previously, then give up.
548 if (!V || (CommonValue && V != CommonValue))
556 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
557 /// try to simplify the comparison by seeing whether comparing with all of the
558 /// incoming phi values yields the same result every time. If so returns the
559 /// common result, otherwise returns null.
560 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
561 const TargetData *TD,
562 const TargetLibraryInfo *TLI,
563 const DominatorTree *DT,
564 unsigned MaxRecurse) {
565 // Recursion is always used, so bail out at once if we already hit the limit.
569 // Make sure the phi is on the LHS.
570 if (!isa<PHINode>(LHS)) {
572 Pred = CmpInst::getSwappedPredicate(Pred);
574 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
575 PHINode *PI = cast<PHINode>(LHS);
577 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
578 if (!ValueDominatesPHI(RHS, PI, DT))
581 // Evaluate the BinOp on the incoming phi values.
582 Value *CommonValue = 0;
583 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
584 Value *Incoming = PI->getIncomingValue(i);
585 // If the incoming value is the phi node itself, it can safely be skipped.
586 if (Incoming == PI) continue;
587 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, TLI, DT, MaxRecurse);
588 // If the operation failed to simplify, or simplified to a different value
589 // to previously, then give up.
590 if (!V || (CommonValue && V != CommonValue))
598 /// SimplifyAddInst - Given operands for an Add, see if we can
599 /// fold the result. If not, this returns null.
600 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
601 const TargetData *TD,
602 const TargetLibraryInfo *TLI,
603 const DominatorTree *DT,
604 unsigned MaxRecurse) {
605 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
606 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
607 Constant *Ops[] = { CLHS, CRHS };
608 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
612 // Canonicalize the constant to the RHS.
616 // X + undef -> undef
617 if (match(Op1, m_Undef()))
621 if (match(Op1, m_Zero()))
628 if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
629 match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
632 // X + ~X -> -1 since ~X = -X-1
633 if (match(Op0, m_Not(m_Specific(Op1))) ||
634 match(Op1, m_Not(m_Specific(Op0))))
635 return Constant::getAllOnesValue(Op0->getType());
638 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
639 if (Value *V = SimplifyXorInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
642 // Try some generic simplifications for associative operations.
643 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, TLI, DT,
647 // Mul distributes over Add. Try some generic simplifications based on this.
648 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
649 TD, TLI, DT, MaxRecurse))
652 // Threading Add over selects and phi nodes is pointless, so don't bother.
653 // Threading over the select in "A + select(cond, B, C)" means evaluating
654 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
655 // only if B and C are equal. If B and C are equal then (since we assume
656 // that operands have already been simplified) "select(cond, B, C)" should
657 // have been simplified to the common value of B and C already. Analysing
658 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
659 // for threading over phi nodes.
664 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
665 const TargetData *TD, const TargetLibraryInfo *TLI,
666 const DominatorTree *DT) {
667 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
670 /// \brief Compute the constant integer offset a GEP represents.
672 /// Given a getelementptr instruction/constantexpr, form a constant expression
673 /// which computes the offset from the base pointer (without adding in the base
675 static Constant *computeGEPOffset(const TargetData &TD, GEPOperator *GEP) {
676 Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
677 Constant *Result = Constant::getNullValue(IntPtrTy);
679 // If the GEP is inbounds, we know that none of the addressing operations will
680 // overflow in an unsigned sense.
681 bool IsInBounds = GEP->isInBounds();
683 // Build a mask for high order bits.
684 unsigned IntPtrWidth = TD.getPointerSizeInBits();
685 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
687 gep_type_iterator GTI = gep_type_begin(GEP);
688 for (User::op_iterator I = GEP->op_begin() + 1, E = GEP->op_end(); I != E;
690 ConstantInt *OpC = dyn_cast<ConstantInt>(*I);
692 if (OpC->isZero()) continue;
694 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
696 // Handle a struct index, which adds its field offset to the pointer.
697 if (StructType *STy = dyn_cast<StructType>(*GTI)) {
698 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
701 Result = ConstantExpr::getAdd(Result, ConstantInt::get(IntPtrTy, Size));
705 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
706 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
707 Scale = ConstantExpr::getMul(OC, Scale, IsInBounds/*NUW*/);
708 Result = ConstantExpr::getAdd(Result, Scale);
713 /// \brief Compute the base pointer and cumulative constant offsets for V.
715 /// This strips all constant offsets off of V, leaving it the base pointer, and
716 /// accumulates the total constant offset applied in the returned constant. It
717 /// returns 0 if V is not a pointer, and returns the constant '0' if there are
718 /// no constant offsets applied.
719 static Constant *stripAndComputeConstantOffsets(const TargetData &TD,
721 if (!V->getType()->isPointerTy())
724 Type *IntPtrTy = TD.getIntPtrType(V->getContext());
725 Constant *Result = Constant::getNullValue(IntPtrTy);
727 // Even though we don't look through PHI nodes, we could be called on an
728 // instruction in an unreachable block, which may be on a cycle.
729 SmallPtrSet<Value *, 4> Visited;
732 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
733 Constant *Offset = computeGEPOffset(TD, GEP);
736 Result = ConstantExpr::getAdd(Result, Offset);
737 V = GEP->getPointerOperand();
738 } else if (Operator::getOpcode(V) == Instruction::BitCast) {
739 V = cast<Operator>(V)->getOperand(0);
740 } else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
741 if (GA->mayBeOverridden())
743 V = GA->getAliasee();
747 assert(V->getType()->isPointerTy() && "Unexpected operand type!");
748 } while (Visited.insert(V));
753 /// \brief Compute the constant difference between two pointer values.
754 /// If the difference is not a constant, returns zero.
755 static Constant *computePointerDifference(const TargetData &TD,
756 Value *LHS, Value *RHS) {
757 Constant *LHSOffset = stripAndComputeConstantOffsets(TD, LHS);
760 Constant *RHSOffset = stripAndComputeConstantOffsets(TD, RHS);
764 // If LHS and RHS are not related via constant offsets to the same base
765 // value, there is nothing we can do here.
769 // Otherwise, the difference of LHS - RHS can be computed as:
771 // = (LHSOffset + Base) - (RHSOffset + Base)
772 // = LHSOffset - RHSOffset
773 return ConstantExpr::getSub(LHSOffset, RHSOffset);
776 /// SimplifySubInst - Given operands for a Sub, see if we can
777 /// fold the result. If not, this returns null.
778 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
779 const TargetData *TD,
780 const TargetLibraryInfo *TLI,
781 const DominatorTree *DT,
782 unsigned MaxRecurse) {
783 if (Constant *CLHS = dyn_cast<Constant>(Op0))
784 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
785 Constant *Ops[] = { CLHS, CRHS };
786 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
790 // X - undef -> undef
791 // undef - X -> undef
792 if (match(Op0, m_Undef()) || match(Op1, m_Undef()))
793 return UndefValue::get(Op0->getType());
796 if (match(Op1, m_Zero()))
801 return Constant::getNullValue(Op0->getType());
806 if (match(Op0, m_Mul(m_Specific(Op1), m_ConstantInt<2>())) ||
807 match(Op0, m_Shl(m_Specific(Op1), m_One())))
811 Value *LHSOp, *RHSOp;
812 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
813 match(Op1, m_PtrToInt(m_Value(RHSOp))))
814 if (Constant *Result = computePointerDifference(*TD, LHSOp, RHSOp))
815 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
817 // trunc(p)-trunc(q) -> trunc(p-q)
818 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
819 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
820 if (Constant *Result = computePointerDifference(*TD, LHSOp, RHSOp))
821 return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
824 // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
825 // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
826 Value *Y = 0, *Z = Op1;
827 if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
828 // See if "V === Y - Z" simplifies.
829 if (Value *V = SimplifyBinOp(Instruction::Sub, Y, Z, TD, TLI, DT, MaxRecurse-1))
830 // It does! Now see if "X + V" simplifies.
831 if (Value *W = SimplifyBinOp(Instruction::Add, X, V, TD, TLI, DT,
833 // It does, we successfully reassociated!
837 // See if "V === X - Z" simplifies.
838 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, TLI, DT, MaxRecurse-1))
839 // It does! Now see if "Y + V" simplifies.
840 if (Value *W = SimplifyBinOp(Instruction::Add, Y, V, TD, TLI, DT,
842 // It does, we successfully reassociated!
848 // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
849 // For example, X - (X + 1) -> -1
851 if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
852 // See if "V === X - Y" simplifies.
853 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Y, TD, TLI, DT, MaxRecurse-1))
854 // It does! Now see if "V - Z" simplifies.
855 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Z, TD, TLI, DT,
857 // It does, we successfully reassociated!
861 // See if "V === X - Z" simplifies.
862 if (Value *V = SimplifyBinOp(Instruction::Sub, X, Z, TD, TLI, DT, MaxRecurse-1))
863 // It does! Now see if "V - Y" simplifies.
864 if (Value *W = SimplifyBinOp(Instruction::Sub, V, Y, TD, TLI, DT,
866 // It does, we successfully reassociated!
872 // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
873 // For example, X - (X - Y) -> Y.
875 if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
876 // See if "V === Z - X" simplifies.
877 if (Value *V = SimplifyBinOp(Instruction::Sub, Z, X, TD, TLI, DT, MaxRecurse-1))
878 // It does! Now see if "V + Y" simplifies.
879 if (Value *W = SimplifyBinOp(Instruction::Add, V, Y, TD, TLI, DT,
881 // It does, we successfully reassociated!
886 // Mul distributes over Sub. Try some generic simplifications based on this.
887 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
888 TD, TLI, DT, MaxRecurse))
892 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
893 if (Value *V = SimplifyXorInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
896 // Threading Sub over selects and phi nodes is pointless, so don't bother.
897 // Threading over the select in "A - select(cond, B, C)" means evaluating
898 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
899 // only if B and C are equal. If B and C are equal then (since we assume
900 // that operands have already been simplified) "select(cond, B, C)" should
901 // have been simplified to the common value of B and C already. Analysing
902 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
903 // for threading over phi nodes.
908 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
909 const TargetData *TD,
910 const TargetLibraryInfo *TLI,
911 const DominatorTree *DT) {
912 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
915 /// SimplifyMulInst - Given operands for a Mul, see if we can
916 /// fold the result. If not, this returns null.
917 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
918 const TargetLibraryInfo *TLI,
919 const DominatorTree *DT, unsigned MaxRecurse) {
920 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
921 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
922 Constant *Ops[] = { CLHS, CRHS };
923 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
927 // Canonicalize the constant to the RHS.
932 if (match(Op1, m_Undef()))
933 return Constant::getNullValue(Op0->getType());
936 if (match(Op1, m_Zero()))
940 if (match(Op1, m_One()))
943 // (X / Y) * Y -> X if the division is exact.
945 if (match(Op0, m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
946 match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0))))) // Y * (X / Y)
950 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
951 if (Value *V = SimplifyAndInst(Op0, Op1, TD, TLI, DT, MaxRecurse-1))
954 // Try some generic simplifications for associative operations.
955 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, TLI, DT,
959 // Mul distributes over Add. Try some generic simplifications based on this.
960 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
961 TD, TLI, DT, MaxRecurse))
964 // If the operation is with the result of a select instruction, check whether
965 // operating on either branch of the select always yields the same value.
966 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
967 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, TLI, DT,
971 // If the operation is with the result of a phi instruction, check whether
972 // operating on all incoming values of the phi always yields the same value.
973 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
974 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, TLI, DT,
981 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
982 const TargetLibraryInfo *TLI,
983 const DominatorTree *DT) {
984 return ::SimplifyMulInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
987 /// SimplifyDiv - Given operands for an SDiv or UDiv, see if we can
988 /// fold the result. If not, this returns null.
989 static Value *SimplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
990 const TargetData *TD, const TargetLibraryInfo *TLI,
991 const DominatorTree *DT, unsigned MaxRecurse) {
992 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
993 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
994 Constant *Ops[] = { C0, C1 };
995 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
999 bool isSigned = Opcode == Instruction::SDiv;
1001 // X / undef -> undef
1002 if (match(Op1, m_Undef()))
1006 if (match(Op0, m_Undef()))
1007 return Constant::getNullValue(Op0->getType());
1009 // 0 / X -> 0, we don't need to preserve faults!
1010 if (match(Op0, m_Zero()))
1014 if (match(Op1, m_One()))
1017 if (Op0->getType()->isIntegerTy(1))
1018 // It can't be division by zero, hence it must be division by one.
1023 return ConstantInt::get(Op0->getType(), 1);
1025 // (X * Y) / Y -> X if the multiplication does not overflow.
1026 Value *X = 0, *Y = 0;
1027 if (match(Op0, m_Mul(m_Value(X), m_Value(Y))) && (X == Op1 || Y == Op1)) {
1028 if (Y != Op1) std::swap(X, Y); // Ensure expression is (X * Y) / Y, Y = Op1
1029 OverflowingBinaryOperator *Mul = cast<OverflowingBinaryOperator>(Op0);
1030 // If the Mul knows it does not overflow, then we are good to go.
1031 if ((isSigned && Mul->hasNoSignedWrap()) ||
1032 (!isSigned && Mul->hasNoUnsignedWrap()))
1034 // If X has the form X = A / Y then X * Y cannot overflow.
1035 if (BinaryOperator *Div = dyn_cast<BinaryOperator>(X))
1036 if (Div->getOpcode() == Opcode && Div->getOperand(1) == Y)
1040 // (X rem Y) / Y -> 0
1041 if ((isSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
1042 (!isSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
1043 return Constant::getNullValue(Op0->getType());
1045 // If the operation is with the result of a select instruction, check whether
1046 // operating on either branch of the select always yields the same value.
1047 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1048 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT,
1052 // If the operation is with the result of a phi instruction, check whether
1053 // operating on all incoming values of the phi always yields the same value.
1054 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1055 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT,
1062 /// SimplifySDivInst - Given operands for an SDiv, see if we can
1063 /// fold the result. If not, this returns null.
1064 static Value *SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
1065 const TargetLibraryInfo *TLI,
1066 const DominatorTree *DT, unsigned MaxRecurse) {
1067 if (Value *V = SimplifyDiv(Instruction::SDiv, Op0, Op1, TD, TLI, DT,
1074 Value *llvm::SimplifySDivInst(Value *Op0, Value *Op1, const TargetData *TD,
1075 const TargetLibraryInfo *TLI,
1076 const DominatorTree *DT) {
1077 return ::SimplifySDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1080 /// SimplifyUDivInst - Given operands for a UDiv, see if we can
1081 /// fold the result. If not, this returns null.
1082 static Value *SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
1083 const TargetLibraryInfo *TLI,
1084 const DominatorTree *DT, unsigned MaxRecurse) {
1085 if (Value *V = SimplifyDiv(Instruction::UDiv, Op0, Op1, TD, TLI, DT,
1092 Value *llvm::SimplifyUDivInst(Value *Op0, Value *Op1, const TargetData *TD,
1093 const TargetLibraryInfo *TLI,
1094 const DominatorTree *DT) {
1095 return ::SimplifyUDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1098 static Value *SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *,
1099 const TargetLibraryInfo *,
1100 const DominatorTree *, unsigned) {
1101 // undef / X -> undef (the undef could be a snan).
1102 if (match(Op0, m_Undef()))
1105 // X / undef -> undef
1106 if (match(Op1, m_Undef()))
1112 Value *llvm::SimplifyFDivInst(Value *Op0, Value *Op1, const TargetData *TD,
1113 const TargetLibraryInfo *TLI,
1114 const DominatorTree *DT) {
1115 return ::SimplifyFDivInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1118 /// SimplifyRem - Given operands for an SRem or URem, see if we can
1119 /// fold the result. If not, this returns null.
1120 static Value *SimplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
1121 const TargetData *TD, const TargetLibraryInfo *TLI,
1122 const DominatorTree *DT, unsigned MaxRecurse) {
1123 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1124 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1125 Constant *Ops[] = { C0, C1 };
1126 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
1130 // X % undef -> undef
1131 if (match(Op1, m_Undef()))
1135 if (match(Op0, m_Undef()))
1136 return Constant::getNullValue(Op0->getType());
1138 // 0 % X -> 0, we don't need to preserve faults!
1139 if (match(Op0, m_Zero()))
1142 // X % 0 -> undef, we don't need to preserve faults!
1143 if (match(Op1, m_Zero()))
1144 return UndefValue::get(Op0->getType());
1147 if (match(Op1, m_One()))
1148 return Constant::getNullValue(Op0->getType());
1150 if (Op0->getType()->isIntegerTy(1))
1151 // It can't be remainder by zero, hence it must be remainder by one.
1152 return Constant::getNullValue(Op0->getType());
1156 return Constant::getNullValue(Op0->getType());
1158 // If the operation is with the result of a select instruction, check whether
1159 // operating on either branch of the select always yields the same value.
1160 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1161 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
1164 // If the operation is with the result of a phi instruction, check whether
1165 // operating on all incoming values of the phi always yields the same value.
1166 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1167 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
1173 /// SimplifySRemInst - Given operands for an SRem, see if we can
1174 /// fold the result. If not, this returns null.
1175 static Value *SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1176 const TargetLibraryInfo *TLI,
1177 const DominatorTree *DT,
1178 unsigned MaxRecurse) {
1179 if (Value *V = SimplifyRem(Instruction::SRem, Op0, Op1, TD, TLI, DT, MaxRecurse))
1185 Value *llvm::SimplifySRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1186 const TargetLibraryInfo *TLI,
1187 const DominatorTree *DT) {
1188 return ::SimplifySRemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1191 /// SimplifyURemInst - Given operands for a URem, see if we can
1192 /// fold the result. If not, this returns null.
1193 static Value *SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
1194 const TargetLibraryInfo *TLI,
1195 const DominatorTree *DT,
1196 unsigned MaxRecurse) {
1197 if (Value *V = SimplifyRem(Instruction::URem, Op0, Op1, TD, TLI, DT, MaxRecurse))
1203 Value *llvm::SimplifyURemInst(Value *Op0, Value *Op1, const TargetData *TD,
1204 const TargetLibraryInfo *TLI,
1205 const DominatorTree *DT) {
1206 return ::SimplifyURemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1209 static Value *SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *,
1210 const TargetLibraryInfo *,
1211 const DominatorTree *,
1213 // undef % X -> undef (the undef could be a snan).
1214 if (match(Op0, m_Undef()))
1217 // X % undef -> undef
1218 if (match(Op1, m_Undef()))
1224 Value *llvm::SimplifyFRemInst(Value *Op0, Value *Op1, const TargetData *TD,
1225 const TargetLibraryInfo *TLI,
1226 const DominatorTree *DT) {
1227 return ::SimplifyFRemInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1230 /// SimplifyShift - Given operands for an Shl, LShr or AShr, see if we can
1231 /// fold the result. If not, this returns null.
1232 static Value *SimplifyShift(unsigned Opcode, Value *Op0, Value *Op1,
1233 const TargetData *TD, const TargetLibraryInfo *TLI,
1234 const DominatorTree *DT, unsigned MaxRecurse) {
1235 if (Constant *C0 = dyn_cast<Constant>(Op0)) {
1236 if (Constant *C1 = dyn_cast<Constant>(Op1)) {
1237 Constant *Ops[] = { C0, C1 };
1238 return ConstantFoldInstOperands(Opcode, C0->getType(), Ops, TD, TLI);
1242 // 0 shift by X -> 0
1243 if (match(Op0, m_Zero()))
1246 // X shift by 0 -> X
1247 if (match(Op1, m_Zero()))
1250 // X shift by undef -> undef because it may shift by the bitwidth.
1251 if (match(Op1, m_Undef()))
1254 // Shifting by the bitwidth or more is undefined.
1255 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1))
1256 if (CI->getValue().getLimitedValue() >=
1257 Op0->getType()->getScalarSizeInBits())
1258 return UndefValue::get(Op0->getType());
1260 // If the operation is with the result of a select instruction, check whether
1261 // operating on either branch of the select always yields the same value.
1262 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1263 if (Value *V = ThreadBinOpOverSelect(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
1266 // If the operation is with the result of a phi instruction, check whether
1267 // operating on all incoming values of the phi always yields the same value.
1268 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1269 if (Value *V = ThreadBinOpOverPHI(Opcode, Op0, Op1, TD, TLI, DT, MaxRecurse))
1275 /// SimplifyShlInst - Given operands for an Shl, see if we can
1276 /// fold the result. If not, this returns null.
1277 static Value *SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1278 const TargetData *TD,
1279 const TargetLibraryInfo *TLI,
1280 const DominatorTree *DT, unsigned MaxRecurse) {
1281 if (Value *V = SimplifyShift(Instruction::Shl, Op0, Op1, TD, TLI, DT, MaxRecurse))
1285 if (match(Op0, m_Undef()))
1286 return Constant::getNullValue(Op0->getType());
1288 // (X >> A) << A -> X
1290 if (match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
1295 Value *llvm::SimplifyShlInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
1296 const TargetData *TD, const TargetLibraryInfo *TLI,
1297 const DominatorTree *DT) {
1298 return ::SimplifyShlInst(Op0, Op1, isNSW, isNUW, TD, TLI, DT, RecursionLimit);
1301 /// SimplifyLShrInst - Given operands for an LShr, see if we can
1302 /// fold the result. If not, this returns null.
1303 static Value *SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1304 const TargetData *TD,
1305 const TargetLibraryInfo *TLI,
1306 const DominatorTree *DT,
1307 unsigned MaxRecurse) {
1308 if (Value *V = SimplifyShift(Instruction::LShr, Op0, Op1, TD, TLI, DT, MaxRecurse))
1312 if (match(Op0, m_Undef()))
1313 return Constant::getNullValue(Op0->getType());
1315 // (X << A) >> A -> X
1317 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1318 cast<OverflowingBinaryOperator>(Op0)->hasNoUnsignedWrap())
1324 Value *llvm::SimplifyLShrInst(Value *Op0, Value *Op1, bool isExact,
1325 const TargetData *TD,
1326 const TargetLibraryInfo *TLI,
1327 const DominatorTree *DT) {
1328 return ::SimplifyLShrInst(Op0, Op1, isExact, TD, TLI, DT, RecursionLimit);
1331 /// SimplifyAShrInst - Given operands for an AShr, see if we can
1332 /// fold the result. If not, this returns null.
1333 static Value *SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1334 const TargetData *TD,
1335 const TargetLibraryInfo *TLI,
1336 const DominatorTree *DT,
1337 unsigned MaxRecurse) {
1338 if (Value *V = SimplifyShift(Instruction::AShr, Op0, Op1, TD, TLI, DT, MaxRecurse))
1341 // all ones >>a X -> all ones
1342 if (match(Op0, m_AllOnes()))
1345 // undef >>a X -> all ones
1346 if (match(Op0, m_Undef()))
1347 return Constant::getAllOnesValue(Op0->getType());
1349 // (X << A) >> A -> X
1351 if (match(Op0, m_Shl(m_Value(X), m_Specific(Op1))) &&
1352 cast<OverflowingBinaryOperator>(Op0)->hasNoSignedWrap())
1358 Value *llvm::SimplifyAShrInst(Value *Op0, Value *Op1, bool isExact,
1359 const TargetData *TD,
1360 const TargetLibraryInfo *TLI,
1361 const DominatorTree *DT) {
1362 return ::SimplifyAShrInst(Op0, Op1, isExact, TD, TLI, DT, RecursionLimit);
1365 /// SimplifyAndInst - Given operands for an And, see if we can
1366 /// fold the result. If not, this returns null.
1367 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1368 const TargetLibraryInfo *TLI,
1369 const DominatorTree *DT,
1370 unsigned MaxRecurse) {
1371 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1372 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1373 Constant *Ops[] = { CLHS, CRHS };
1374 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
1378 // Canonicalize the constant to the RHS.
1379 std::swap(Op0, Op1);
1383 if (match(Op1, m_Undef()))
1384 return Constant::getNullValue(Op0->getType());
1391 if (match(Op1, m_Zero()))
1395 if (match(Op1, m_AllOnes()))
1398 // A & ~A = ~A & A = 0
1399 if (match(Op0, m_Not(m_Specific(Op1))) ||
1400 match(Op1, m_Not(m_Specific(Op0))))
1401 return Constant::getNullValue(Op0->getType());
1404 Value *A = 0, *B = 0;
1405 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
1406 (A == Op1 || B == Op1))
1410 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
1411 (A == Op0 || B == Op0))
1414 // A & (-A) = A if A is a power of two or zero.
1415 if (match(Op0, m_Neg(m_Specific(Op1))) ||
1416 match(Op1, m_Neg(m_Specific(Op0)))) {
1417 if (isPowerOfTwo(Op0, TD, /*OrZero*/true))
1419 if (isPowerOfTwo(Op1, TD, /*OrZero*/true))
1423 // Try some generic simplifications for associative operations.
1424 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, TLI,
1428 // And distributes over Or. Try some generic simplifications based on this.
1429 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1430 TD, TLI, DT, MaxRecurse))
1433 // And distributes over Xor. Try some generic simplifications based on this.
1434 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
1435 TD, TLI, DT, MaxRecurse))
1438 // Or distributes over And. Try some generic simplifications based on this.
1439 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
1440 TD, TLI, DT, MaxRecurse))
1443 // If the operation is with the result of a select instruction, check whether
1444 // operating on either branch of the select always yields the same value.
1445 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1446 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, TLI,
1450 // If the operation is with the result of a phi instruction, check whether
1451 // operating on all incoming values of the phi always yields the same value.
1452 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1453 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, TLI, DT,
1460 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
1461 const TargetLibraryInfo *TLI,
1462 const DominatorTree *DT) {
1463 return ::SimplifyAndInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1466 /// SimplifyOrInst - Given operands for an Or, see if we can
1467 /// fold the result. If not, this returns null.
1468 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1469 const TargetLibraryInfo *TLI,
1470 const DominatorTree *DT, unsigned MaxRecurse) {
1471 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1472 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1473 Constant *Ops[] = { CLHS, CRHS };
1474 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
1478 // Canonicalize the constant to the RHS.
1479 std::swap(Op0, Op1);
1483 if (match(Op1, m_Undef()))
1484 return Constant::getAllOnesValue(Op0->getType());
1491 if (match(Op1, m_Zero()))
1495 if (match(Op1, m_AllOnes()))
1498 // A | ~A = ~A | A = -1
1499 if (match(Op0, m_Not(m_Specific(Op1))) ||
1500 match(Op1, m_Not(m_Specific(Op0))))
1501 return Constant::getAllOnesValue(Op0->getType());
1504 Value *A = 0, *B = 0;
1505 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
1506 (A == Op1 || B == Op1))
1510 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
1511 (A == Op0 || B == Op0))
1514 // ~(A & ?) | A = -1
1515 if (match(Op0, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1516 (A == Op1 || B == Op1))
1517 return Constant::getAllOnesValue(Op1->getType());
1519 // A | ~(A & ?) = -1
1520 if (match(Op1, m_Not(m_And(m_Value(A), m_Value(B)))) &&
1521 (A == Op0 || B == Op0))
1522 return Constant::getAllOnesValue(Op0->getType());
1524 // Try some generic simplifications for associative operations.
1525 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, TLI,
1529 // Or distributes over And. Try some generic simplifications based on this.
1530 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And, TD,
1531 TLI, DT, MaxRecurse))
1534 // And distributes over Or. Try some generic simplifications based on this.
1535 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
1536 TD, TLI, DT, MaxRecurse))
1539 // If the operation is with the result of a select instruction, check whether
1540 // operating on either branch of the select always yields the same value.
1541 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
1542 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, TLI, DT,
1546 // If the operation is with the result of a phi instruction, check whether
1547 // operating on all incoming values of the phi always yields the same value.
1548 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
1549 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, TLI, DT,
1556 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
1557 const TargetLibraryInfo *TLI,
1558 const DominatorTree *DT) {
1559 return ::SimplifyOrInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1562 /// SimplifyXorInst - Given operands for a Xor, see if we can
1563 /// fold the result. If not, this returns null.
1564 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1565 const TargetLibraryInfo *TLI,
1566 const DominatorTree *DT, unsigned MaxRecurse) {
1567 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
1568 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
1569 Constant *Ops[] = { CLHS, CRHS };
1570 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
1574 // Canonicalize the constant to the RHS.
1575 std::swap(Op0, Op1);
1578 // A ^ undef -> undef
1579 if (match(Op1, m_Undef()))
1583 if (match(Op1, m_Zero()))
1588 return Constant::getNullValue(Op0->getType());
1590 // A ^ ~A = ~A ^ A = -1
1591 if (match(Op0, m_Not(m_Specific(Op1))) ||
1592 match(Op1, m_Not(m_Specific(Op0))))
1593 return Constant::getAllOnesValue(Op0->getType());
1595 // Try some generic simplifications for associative operations.
1596 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, TLI,
1600 // And distributes over Xor. Try some generic simplifications based on this.
1601 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
1602 TD, TLI, DT, MaxRecurse))
1605 // Threading Xor over selects and phi nodes is pointless, so don't bother.
1606 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
1607 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
1608 // only if B and C are equal. If B and C are equal then (since we assume
1609 // that operands have already been simplified) "select(cond, B, C)" should
1610 // have been simplified to the common value of B and C already. Analysing
1611 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
1612 // for threading over phi nodes.
1617 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
1618 const TargetLibraryInfo *TLI,
1619 const DominatorTree *DT) {
1620 return ::SimplifyXorInst(Op0, Op1, TD, TLI, DT, RecursionLimit);
1623 static Type *GetCompareTy(Value *Op) {
1624 return CmpInst::makeCmpResultType(Op->getType());
1627 /// ExtractEquivalentCondition - Rummage around inside V looking for something
1628 /// equivalent to the comparison "LHS Pred RHS". Return such a value if found,
1629 /// otherwise return null. Helper function for analyzing max/min idioms.
1630 static Value *ExtractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
1631 Value *LHS, Value *RHS) {
1632 SelectInst *SI = dyn_cast<SelectInst>(V);
1635 CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
1638 Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
1639 if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
1641 if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
1642 LHS == CmpRHS && RHS == CmpLHS)
1648 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
1649 /// fold the result. If not, this returns null.
1650 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1651 const TargetData *TD,
1652 const TargetLibraryInfo *TLI,
1653 const DominatorTree *DT,
1654 unsigned MaxRecurse) {
1655 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1656 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
1658 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
1659 if (Constant *CRHS = dyn_cast<Constant>(RHS))
1660 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD, TLI);
1662 // If we have a constant, make sure it is on the RHS.
1663 std::swap(LHS, RHS);
1664 Pred = CmpInst::getSwappedPredicate(Pred);
1667 Type *ITy = GetCompareTy(LHS); // The return type.
1668 Type *OpTy = LHS->getType(); // The operand type.
1670 // icmp X, X -> true/false
1671 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1672 // because X could be 0.
1673 if (LHS == RHS || isa<UndefValue>(RHS))
1674 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1676 // Special case logic when the operands have i1 type.
1677 if (OpTy->getScalarType()->isIntegerTy(1)) {
1680 case ICmpInst::ICMP_EQ:
1682 if (match(RHS, m_One()))
1685 case ICmpInst::ICMP_NE:
1687 if (match(RHS, m_Zero()))
1690 case ICmpInst::ICMP_UGT:
1692 if (match(RHS, m_Zero()))
1695 case ICmpInst::ICMP_UGE:
1697 if (match(RHS, m_One()))
1700 case ICmpInst::ICMP_SLT:
1702 if (match(RHS, m_Zero()))
1705 case ICmpInst::ICMP_SLE:
1707 if (match(RHS, m_One()))
1713 // icmp <object*>, <object*/null> - Different identified objects have
1714 // different addresses (unless null), and what's more the address of an
1715 // identified local is never equal to another argument (again, barring null).
1716 // Note that generalizing to the case where LHS is a global variable address
1717 // or null is pointless, since if both LHS and RHS are constants then we
1718 // already constant folded the compare, and if only one of them is then we
1719 // moved it to RHS already.
1720 Value *LHSPtr = LHS->stripPointerCasts();
1721 Value *RHSPtr = RHS->stripPointerCasts();
1722 if (LHSPtr == RHSPtr)
1723 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1725 // Be more aggressive about stripping pointer adjustments when checking a
1726 // comparison of an alloca address to another object. We can rip off all
1727 // inbounds GEP operations, even if they are variable.
1728 LHSPtr = LHSPtr->stripInBoundsOffsets();
1729 if (llvm::isIdentifiedObject(LHSPtr)) {
1730 RHSPtr = RHSPtr->stripInBoundsOffsets();
1731 if (llvm::isKnownNonNull(LHSPtr) || llvm::isKnownNonNull(RHSPtr)) {
1732 // If both sides are different identified objects, they aren't equal
1733 // unless they're null.
1734 if (LHSPtr != RHSPtr && llvm::isIdentifiedObject(RHSPtr) &&
1735 Pred == CmpInst::ICMP_EQ)
1736 return ConstantInt::get(ITy, false);
1738 // A local identified object (alloca or noalias call) can't equal any
1739 // incoming argument, unless they're both null.
1740 if (isa<Instruction>(LHSPtr) && isa<Argument>(RHSPtr) &&
1741 Pred == CmpInst::ICMP_EQ)
1742 return ConstantInt::get(ITy, false);
1745 // Assume that the constant null is on the right.
1746 if (llvm::isKnownNonNull(LHSPtr) && isa<ConstantPointerNull>(RHSPtr)) {
1747 if (Pred == CmpInst::ICMP_EQ)
1748 return ConstantInt::get(ITy, false);
1749 else if (Pred == CmpInst::ICMP_NE)
1750 return ConstantInt::get(ITy, true);
1752 } else if (isa<Argument>(LHSPtr)) {
1753 RHSPtr = RHSPtr->stripInBoundsOffsets();
1754 // An alloca can't be equal to an argument.
1755 if (isa<AllocaInst>(RHSPtr)) {
1756 if (Pred == CmpInst::ICMP_EQ)
1757 return ConstantInt::get(ITy, false);
1758 else if (Pred == CmpInst::ICMP_NE)
1759 return ConstantInt::get(ITy, true);
1763 // If we are comparing with zero then try hard since this is a common case.
1764 if (match(RHS, m_Zero())) {
1765 bool LHSKnownNonNegative, LHSKnownNegative;
1767 default: llvm_unreachable("Unknown ICmp predicate!");
1768 case ICmpInst::ICMP_ULT:
1769 return getFalse(ITy);
1770 case ICmpInst::ICMP_UGE:
1771 return getTrue(ITy);
1772 case ICmpInst::ICMP_EQ:
1773 case ICmpInst::ICMP_ULE:
1774 if (isKnownNonZero(LHS, TD))
1775 return getFalse(ITy);
1777 case ICmpInst::ICMP_NE:
1778 case ICmpInst::ICMP_UGT:
1779 if (isKnownNonZero(LHS, TD))
1780 return getTrue(ITy);
1782 case ICmpInst::ICMP_SLT:
1783 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1784 if (LHSKnownNegative)
1785 return getTrue(ITy);
1786 if (LHSKnownNonNegative)
1787 return getFalse(ITy);
1789 case ICmpInst::ICMP_SLE:
1790 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1791 if (LHSKnownNegative)
1792 return getTrue(ITy);
1793 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1794 return getFalse(ITy);
1796 case ICmpInst::ICMP_SGE:
1797 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1798 if (LHSKnownNegative)
1799 return getFalse(ITy);
1800 if (LHSKnownNonNegative)
1801 return getTrue(ITy);
1803 case ICmpInst::ICMP_SGT:
1804 ComputeSignBit(LHS, LHSKnownNonNegative, LHSKnownNegative, TD);
1805 if (LHSKnownNegative)
1806 return getFalse(ITy);
1807 if (LHSKnownNonNegative && isKnownNonZero(LHS, TD))
1808 return getTrue(ITy);
1813 // See if we are doing a comparison with a constant integer.
1814 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1815 // Rule out tautological comparisons (eg., ult 0 or uge 0).
1816 ConstantRange RHS_CR = ICmpInst::makeConstantRange(Pred, CI->getValue());
1817 if (RHS_CR.isEmptySet())
1818 return ConstantInt::getFalse(CI->getContext());
1819 if (RHS_CR.isFullSet())
1820 return ConstantInt::getTrue(CI->getContext());
1822 // Many binary operators with constant RHS have easy to compute constant
1823 // range. Use them to check whether the comparison is a tautology.
1824 uint32_t Width = CI->getBitWidth();
1825 APInt Lower = APInt(Width, 0);
1826 APInt Upper = APInt(Width, 0);
1828 if (match(LHS, m_URem(m_Value(), m_ConstantInt(CI2)))) {
1829 // 'urem x, CI2' produces [0, CI2).
1830 Upper = CI2->getValue();
1831 } else if (match(LHS, m_SRem(m_Value(), m_ConstantInt(CI2)))) {
1832 // 'srem x, CI2' produces (-|CI2|, |CI2|).
1833 Upper = CI2->getValue().abs();
1834 Lower = (-Upper) + 1;
1835 } else if (match(LHS, m_UDiv(m_ConstantInt(CI2), m_Value()))) {
1836 // 'udiv CI2, x' produces [0, CI2].
1837 Upper = CI2->getValue() + 1;
1838 } else if (match(LHS, m_UDiv(m_Value(), m_ConstantInt(CI2)))) {
1839 // 'udiv x, CI2' produces [0, UINT_MAX / CI2].
1840 APInt NegOne = APInt::getAllOnesValue(Width);
1842 Upper = NegOne.udiv(CI2->getValue()) + 1;
1843 } else if (match(LHS, m_SDiv(m_Value(), m_ConstantInt(CI2)))) {
1844 // 'sdiv x, CI2' produces [INT_MIN / CI2, INT_MAX / CI2].
1845 APInt IntMin = APInt::getSignedMinValue(Width);
1846 APInt IntMax = APInt::getSignedMaxValue(Width);
1847 APInt Val = CI2->getValue().abs();
1848 if (!Val.isMinValue()) {
1849 Lower = IntMin.sdiv(Val);
1850 Upper = IntMax.sdiv(Val) + 1;
1852 } else if (match(LHS, m_LShr(m_Value(), m_ConstantInt(CI2)))) {
1853 // 'lshr x, CI2' produces [0, UINT_MAX >> CI2].
1854 APInt NegOne = APInt::getAllOnesValue(Width);
1855 if (CI2->getValue().ult(Width))
1856 Upper = NegOne.lshr(CI2->getValue()) + 1;
1857 } else if (match(LHS, m_AShr(m_Value(), m_ConstantInt(CI2)))) {
1858 // 'ashr x, CI2' produces [INT_MIN >> CI2, INT_MAX >> CI2].
1859 APInt IntMin = APInt::getSignedMinValue(Width);
1860 APInt IntMax = APInt::getSignedMaxValue(Width);
1861 if (CI2->getValue().ult(Width)) {
1862 Lower = IntMin.ashr(CI2->getValue());
1863 Upper = IntMax.ashr(CI2->getValue()) + 1;
1865 } else if (match(LHS, m_Or(m_Value(), m_ConstantInt(CI2)))) {
1866 // 'or x, CI2' produces [CI2, UINT_MAX].
1867 Lower = CI2->getValue();
1868 } else if (match(LHS, m_And(m_Value(), m_ConstantInt(CI2)))) {
1869 // 'and x, CI2' produces [0, CI2].
1870 Upper = CI2->getValue() + 1;
1872 if (Lower != Upper) {
1873 ConstantRange LHS_CR = ConstantRange(Lower, Upper);
1874 if (RHS_CR.contains(LHS_CR))
1875 return ConstantInt::getTrue(RHS->getContext());
1876 if (RHS_CR.inverse().contains(LHS_CR))
1877 return ConstantInt::getFalse(RHS->getContext());
1881 // Compare of cast, for example (zext X) != 0 -> X != 0
1882 if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
1883 Instruction *LI = cast<CastInst>(LHS);
1884 Value *SrcOp = LI->getOperand(0);
1885 Type *SrcTy = SrcOp->getType();
1886 Type *DstTy = LI->getType();
1888 // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
1889 // if the integer type is the same size as the pointer type.
1890 if (MaxRecurse && TD && isa<PtrToIntInst>(LI) &&
1891 TD->getPointerSizeInBits() == DstTy->getPrimitiveSizeInBits()) {
1892 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1893 // Transfer the cast to the constant.
1894 if (Value *V = SimplifyICmpInst(Pred, SrcOp,
1895 ConstantExpr::getIntToPtr(RHSC, SrcTy),
1896 TD, TLI, DT, MaxRecurse-1))
1898 } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
1899 if (RI->getOperand(0)->getType() == SrcTy)
1900 // Compare without the cast.
1901 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1902 TD, TLI, DT, MaxRecurse-1))
1907 if (isa<ZExtInst>(LHS)) {
1908 // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
1910 if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
1911 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1912 // Compare X and Y. Note that signed predicates become unsigned.
1913 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1914 SrcOp, RI->getOperand(0), TD, TLI, DT,
1918 // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
1919 // too. If not, then try to deduce the result of the comparison.
1920 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1921 // Compute the constant that would happen if we truncated to SrcTy then
1922 // reextended to DstTy.
1923 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1924 Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
1926 // If the re-extended constant didn't change then this is effectively
1927 // also a case of comparing two zero-extended values.
1928 if (RExt == CI && MaxRecurse)
1929 if (Value *V = SimplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
1930 SrcOp, Trunc, TD, TLI, DT, MaxRecurse-1))
1933 // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
1934 // there. Use this to work out the result of the comparison.
1937 default: llvm_unreachable("Unknown ICmp predicate!");
1939 case ICmpInst::ICMP_EQ:
1940 case ICmpInst::ICMP_UGT:
1941 case ICmpInst::ICMP_UGE:
1942 return ConstantInt::getFalse(CI->getContext());
1944 case ICmpInst::ICMP_NE:
1945 case ICmpInst::ICMP_ULT:
1946 case ICmpInst::ICMP_ULE:
1947 return ConstantInt::getTrue(CI->getContext());
1949 // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
1950 // is non-negative then LHS <s RHS.
1951 case ICmpInst::ICMP_SGT:
1952 case ICmpInst::ICMP_SGE:
1953 return CI->getValue().isNegative() ?
1954 ConstantInt::getTrue(CI->getContext()) :
1955 ConstantInt::getFalse(CI->getContext());
1957 case ICmpInst::ICMP_SLT:
1958 case ICmpInst::ICMP_SLE:
1959 return CI->getValue().isNegative() ?
1960 ConstantInt::getFalse(CI->getContext()) :
1961 ConstantInt::getTrue(CI->getContext());
1967 if (isa<SExtInst>(LHS)) {
1968 // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
1970 if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
1971 if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
1972 // Compare X and Y. Note that the predicate does not change.
1973 if (Value *V = SimplifyICmpInst(Pred, SrcOp, RI->getOperand(0),
1974 TD, TLI, DT, MaxRecurse-1))
1977 // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
1978 // too. If not, then try to deduce the result of the comparison.
1979 else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1980 // Compute the constant that would happen if we truncated to SrcTy then
1981 // reextended to DstTy.
1982 Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
1983 Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
1985 // If the re-extended constant didn't change then this is effectively
1986 // also a case of comparing two sign-extended values.
1987 if (RExt == CI && MaxRecurse)
1988 if (Value *V = SimplifyICmpInst(Pred, SrcOp, Trunc, TD, TLI, DT,
1992 // Otherwise the upper bits of LHS are all equal, while RHS has varying
1993 // bits there. Use this to work out the result of the comparison.
1996 default: llvm_unreachable("Unknown ICmp predicate!");
1997 case ICmpInst::ICMP_EQ:
1998 return ConstantInt::getFalse(CI->getContext());
1999 case ICmpInst::ICMP_NE:
2000 return ConstantInt::getTrue(CI->getContext());
2002 // If RHS is non-negative then LHS <s RHS. If RHS is negative then
2004 case ICmpInst::ICMP_SGT:
2005 case ICmpInst::ICMP_SGE:
2006 return CI->getValue().isNegative() ?
2007 ConstantInt::getTrue(CI->getContext()) :
2008 ConstantInt::getFalse(CI->getContext());
2009 case ICmpInst::ICMP_SLT:
2010 case ICmpInst::ICMP_SLE:
2011 return CI->getValue().isNegative() ?
2012 ConstantInt::getFalse(CI->getContext()) :
2013 ConstantInt::getTrue(CI->getContext());
2015 // If LHS is non-negative then LHS <u RHS. If LHS is negative then
2017 case ICmpInst::ICMP_UGT:
2018 case ICmpInst::ICMP_UGE:
2019 // Comparison is true iff the LHS <s 0.
2021 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
2022 Constant::getNullValue(SrcTy),
2023 TD, TLI, DT, MaxRecurse-1))
2026 case ICmpInst::ICMP_ULT:
2027 case ICmpInst::ICMP_ULE:
2028 // Comparison is true iff the LHS >=s 0.
2030 if (Value *V = SimplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
2031 Constant::getNullValue(SrcTy),
2032 TD, TLI, DT, MaxRecurse-1))
2041 // Special logic for binary operators.
2042 BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
2043 BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
2044 if (MaxRecurse && (LBO || RBO)) {
2045 // Analyze the case when either LHS or RHS is an add instruction.
2046 Value *A = 0, *B = 0, *C = 0, *D = 0;
2047 // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
2048 bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
2049 if (LBO && LBO->getOpcode() == Instruction::Add) {
2050 A = LBO->getOperand(0); B = LBO->getOperand(1);
2051 NoLHSWrapProblem = ICmpInst::isEquality(Pred) ||
2052 (CmpInst::isUnsigned(Pred) && LBO->hasNoUnsignedWrap()) ||
2053 (CmpInst::isSigned(Pred) && LBO->hasNoSignedWrap());
2055 if (RBO && RBO->getOpcode() == Instruction::Add) {
2056 C = RBO->getOperand(0); D = RBO->getOperand(1);
2057 NoRHSWrapProblem = ICmpInst::isEquality(Pred) ||
2058 (CmpInst::isUnsigned(Pred) && RBO->hasNoUnsignedWrap()) ||
2059 (CmpInst::isSigned(Pred) && RBO->hasNoSignedWrap());
2062 // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
2063 if ((A == RHS || B == RHS) && NoLHSWrapProblem)
2064 if (Value *V = SimplifyICmpInst(Pred, A == RHS ? B : A,
2065 Constant::getNullValue(RHS->getType()),
2066 TD, TLI, DT, MaxRecurse-1))
2069 // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
2070 if ((C == LHS || D == LHS) && NoRHSWrapProblem)
2071 if (Value *V = SimplifyICmpInst(Pred,
2072 Constant::getNullValue(LHS->getType()),
2073 C == LHS ? D : C, TD, TLI, DT, MaxRecurse-1))
2076 // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
2077 if (A && C && (A == C || A == D || B == C || B == D) &&
2078 NoLHSWrapProblem && NoRHSWrapProblem) {
2079 // Determine Y and Z in the form icmp (X+Y), (X+Z).
2080 Value *Y = (A == C || A == D) ? B : A;
2081 Value *Z = (C == A || C == B) ? D : C;
2082 if (Value *V = SimplifyICmpInst(Pred, Y, Z, TD, TLI, DT, MaxRecurse-1))
2087 if (LBO && match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
2088 bool KnownNonNegative, KnownNegative;
2092 case ICmpInst::ICMP_SGT:
2093 case ICmpInst::ICMP_SGE:
2094 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
2095 if (!KnownNonNegative)
2098 case ICmpInst::ICMP_EQ:
2099 case ICmpInst::ICMP_UGT:
2100 case ICmpInst::ICMP_UGE:
2101 return getFalse(ITy);
2102 case ICmpInst::ICMP_SLT:
2103 case ICmpInst::ICMP_SLE:
2104 ComputeSignBit(LHS, KnownNonNegative, KnownNegative, TD);
2105 if (!KnownNonNegative)
2108 case ICmpInst::ICMP_NE:
2109 case ICmpInst::ICMP_ULT:
2110 case ICmpInst::ICMP_ULE:
2111 return getTrue(ITy);
2114 if (RBO && match(RBO, m_URem(m_Value(), m_Specific(LHS)))) {
2115 bool KnownNonNegative, KnownNegative;
2119 case ICmpInst::ICMP_SGT:
2120 case ICmpInst::ICMP_SGE:
2121 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
2122 if (!KnownNonNegative)
2125 case ICmpInst::ICMP_NE:
2126 case ICmpInst::ICMP_UGT:
2127 case ICmpInst::ICMP_UGE:
2128 return getTrue(ITy);
2129 case ICmpInst::ICMP_SLT:
2130 case ICmpInst::ICMP_SLE:
2131 ComputeSignBit(RHS, KnownNonNegative, KnownNegative, TD);
2132 if (!KnownNonNegative)
2135 case ICmpInst::ICMP_EQ:
2136 case ICmpInst::ICMP_ULT:
2137 case ICmpInst::ICMP_ULE:
2138 return getFalse(ITy);
2143 if (LBO && match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
2144 // icmp pred (X /u Y), X
2145 if (Pred == ICmpInst::ICMP_UGT)
2146 return getFalse(ITy);
2147 if (Pred == ICmpInst::ICMP_ULE)
2148 return getTrue(ITy);
2151 if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
2152 LBO->getOperand(1) == RBO->getOperand(1)) {
2153 switch (LBO->getOpcode()) {
2155 case Instruction::UDiv:
2156 case Instruction::LShr:
2157 if (ICmpInst::isSigned(Pred))
2160 case Instruction::SDiv:
2161 case Instruction::AShr:
2162 if (!LBO->isExact() || !RBO->isExact())
2164 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2165 RBO->getOperand(0), TD, TLI, DT, MaxRecurse-1))
2168 case Instruction::Shl: {
2169 bool NUW = LBO->hasNoUnsignedWrap() && RBO->hasNoUnsignedWrap();
2170 bool NSW = LBO->hasNoSignedWrap() && RBO->hasNoSignedWrap();
2173 if (!NSW && ICmpInst::isSigned(Pred))
2175 if (Value *V = SimplifyICmpInst(Pred, LBO->getOperand(0),
2176 RBO->getOperand(0), TD, TLI, DT, MaxRecurse-1))
2183 // Simplify comparisons involving max/min.
2185 CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
2186 CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
2188 // Signed variants on "max(a,b)>=a -> true".
2189 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2190 if (A != RHS) std::swap(A, B); // smax(A, B) pred A.
2191 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2192 // We analyze this as smax(A, B) pred A.
2194 } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
2195 (A == LHS || B == LHS)) {
2196 if (A != LHS) std::swap(A, B); // A pred smax(A, B).
2197 EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
2198 // We analyze this as smax(A, B) swapped-pred A.
2199 P = CmpInst::getSwappedPredicate(Pred);
2200 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2201 (A == RHS || B == RHS)) {
2202 if (A != RHS) std::swap(A, B); // smin(A, B) pred A.
2203 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2204 // We analyze this as smax(-A, -B) swapped-pred -A.
2205 // Note that we do not need to actually form -A or -B thanks to EqP.
2206 P = CmpInst::getSwappedPredicate(Pred);
2207 } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
2208 (A == LHS || B == LHS)) {
2209 if (A != LHS) std::swap(A, B); // A pred smin(A, B).
2210 EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
2211 // We analyze this as smax(-A, -B) pred -A.
2212 // Note that we do not need to actually form -A or -B thanks to EqP.
2215 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2216 // Cases correspond to "max(A, B) p A".
2220 case CmpInst::ICMP_EQ:
2221 case CmpInst::ICMP_SLE:
2222 // Equivalent to "A EqP B". This may be the same as the condition tested
2223 // in the max/min; if so, we can just return that.
2224 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2226 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2228 // Otherwise, see if "A EqP B" simplifies.
2230 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, TLI, DT, MaxRecurse-1))
2233 case CmpInst::ICMP_NE:
2234 case CmpInst::ICMP_SGT: {
2235 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2236 // Equivalent to "A InvEqP B". This may be the same as the condition
2237 // tested in the max/min; if so, we can just return that.
2238 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2240 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2242 // Otherwise, see if "A InvEqP B" simplifies.
2244 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, TLI, DT, MaxRecurse-1))
2248 case CmpInst::ICMP_SGE:
2250 return getTrue(ITy);
2251 case CmpInst::ICMP_SLT:
2253 return getFalse(ITy);
2257 // Unsigned variants on "max(a,b)>=a -> true".
2258 P = CmpInst::BAD_ICMP_PREDICATE;
2259 if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
2260 if (A != RHS) std::swap(A, B); // umax(A, B) pred A.
2261 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2262 // We analyze this as umax(A, B) pred A.
2264 } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
2265 (A == LHS || B == LHS)) {
2266 if (A != LHS) std::swap(A, B); // A pred umax(A, B).
2267 EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
2268 // We analyze this as umax(A, B) swapped-pred A.
2269 P = CmpInst::getSwappedPredicate(Pred);
2270 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2271 (A == RHS || B == RHS)) {
2272 if (A != RHS) std::swap(A, B); // umin(A, B) pred A.
2273 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2274 // We analyze this as umax(-A, -B) swapped-pred -A.
2275 // Note that we do not need to actually form -A or -B thanks to EqP.
2276 P = CmpInst::getSwappedPredicate(Pred);
2277 } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
2278 (A == LHS || B == LHS)) {
2279 if (A != LHS) std::swap(A, B); // A pred umin(A, B).
2280 EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
2281 // We analyze this as umax(-A, -B) pred -A.
2282 // Note that we do not need to actually form -A or -B thanks to EqP.
2285 if (P != CmpInst::BAD_ICMP_PREDICATE) {
2286 // Cases correspond to "max(A, B) p A".
2290 case CmpInst::ICMP_EQ:
2291 case CmpInst::ICMP_ULE:
2292 // Equivalent to "A EqP B". This may be the same as the condition tested
2293 // in the max/min; if so, we can just return that.
2294 if (Value *V = ExtractEquivalentCondition(LHS, EqP, A, B))
2296 if (Value *V = ExtractEquivalentCondition(RHS, EqP, A, B))
2298 // Otherwise, see if "A EqP B" simplifies.
2300 if (Value *V = SimplifyICmpInst(EqP, A, B, TD, TLI, DT, MaxRecurse-1))
2303 case CmpInst::ICMP_NE:
2304 case CmpInst::ICMP_UGT: {
2305 CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
2306 // Equivalent to "A InvEqP B". This may be the same as the condition
2307 // tested in the max/min; if so, we can just return that.
2308 if (Value *V = ExtractEquivalentCondition(LHS, InvEqP, A, B))
2310 if (Value *V = ExtractEquivalentCondition(RHS, InvEqP, A, B))
2312 // Otherwise, see if "A InvEqP B" simplifies.
2314 if (Value *V = SimplifyICmpInst(InvEqP, A, B, TD, TLI, DT, MaxRecurse-1))
2318 case CmpInst::ICMP_UGE:
2320 return getTrue(ITy);
2321 case CmpInst::ICMP_ULT:
2323 return getFalse(ITy);
2327 // Variants on "max(x,y) >= min(x,z)".
2329 if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
2330 match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
2331 (A == C || A == D || B == C || B == D)) {
2332 // max(x, ?) pred min(x, ?).
2333 if (Pred == CmpInst::ICMP_SGE)
2335 return getTrue(ITy);
2336 if (Pred == CmpInst::ICMP_SLT)
2338 return getFalse(ITy);
2339 } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
2340 match(RHS, m_SMax(m_Value(C), m_Value(D))) &&
2341 (A == C || A == D || B == C || B == D)) {
2342 // min(x, ?) pred max(x, ?).
2343 if (Pred == CmpInst::ICMP_SLE)
2345 return getTrue(ITy);
2346 if (Pred == CmpInst::ICMP_SGT)
2348 return getFalse(ITy);
2349 } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
2350 match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
2351 (A == C || A == D || B == C || B == D)) {
2352 // max(x, ?) pred min(x, ?).
2353 if (Pred == CmpInst::ICMP_UGE)
2355 return getTrue(ITy);
2356 if (Pred == CmpInst::ICMP_ULT)
2358 return getFalse(ITy);
2359 } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
2360 match(RHS, m_UMax(m_Value(C), m_Value(D))) &&
2361 (A == C || A == D || B == C || B == D)) {
2362 // min(x, ?) pred max(x, ?).
2363 if (Pred == CmpInst::ICMP_ULE)
2365 return getTrue(ITy);
2366 if (Pred == CmpInst::ICMP_UGT)
2368 return getFalse(ITy);
2371 // Simplify comparisons of GEPs.
2372 if (GetElementPtrInst *GLHS = dyn_cast<GetElementPtrInst>(LHS)) {
2373 if (GEPOperator *GRHS = dyn_cast<GEPOperator>(RHS)) {
2374 if (GLHS->getPointerOperand() == GRHS->getPointerOperand() &&
2375 GLHS->hasAllConstantIndices() && GRHS->hasAllConstantIndices() &&
2376 (ICmpInst::isEquality(Pred) ||
2377 (GLHS->isInBounds() && GRHS->isInBounds() &&
2378 Pred == ICmpInst::getSignedPredicate(Pred)))) {
2379 // The bases are equal and the indices are constant. Build a constant
2380 // expression GEP with the same indices and a null base pointer to see
2381 // what constant folding can make out of it.
2382 Constant *Null = Constant::getNullValue(GLHS->getPointerOperandType());
2383 SmallVector<Value *, 4> IndicesLHS(GLHS->idx_begin(), GLHS->idx_end());
2384 Constant *NewLHS = ConstantExpr::getGetElementPtr(Null, IndicesLHS);
2386 SmallVector<Value *, 4> IndicesRHS(GRHS->idx_begin(), GRHS->idx_end());
2387 Constant *NewRHS = ConstantExpr::getGetElementPtr(Null, IndicesRHS);
2388 return ConstantExpr::getICmp(Pred, NewLHS, NewRHS);
2393 // If the comparison is with the result of a select instruction, check whether
2394 // comparing with either branch of the select always yields the same value.
2395 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2396 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
2399 // If the comparison is with the result of a phi instruction, check whether
2400 // doing the compare with each incoming phi value yields a common result.
2401 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2402 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
2408 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2409 const TargetData *TD,
2410 const TargetLibraryInfo *TLI,
2411 const DominatorTree *DT) {
2412 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
2415 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
2416 /// fold the result. If not, this returns null.
2417 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2418 const TargetData *TD,
2419 const TargetLibraryInfo *TLI,
2420 const DominatorTree *DT,
2421 unsigned MaxRecurse) {
2422 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
2423 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
2425 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
2426 if (Constant *CRHS = dyn_cast<Constant>(RHS))
2427 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD, TLI);
2429 // If we have a constant, make sure it is on the RHS.
2430 std::swap(LHS, RHS);
2431 Pred = CmpInst::getSwappedPredicate(Pred);
2434 // Fold trivial predicates.
2435 if (Pred == FCmpInst::FCMP_FALSE)
2436 return ConstantInt::get(GetCompareTy(LHS), 0);
2437 if (Pred == FCmpInst::FCMP_TRUE)
2438 return ConstantInt::get(GetCompareTy(LHS), 1);
2440 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
2441 return UndefValue::get(GetCompareTy(LHS));
2443 // fcmp x,x -> true/false. Not all compares are foldable.
2445 if (CmpInst::isTrueWhenEqual(Pred))
2446 return ConstantInt::get(GetCompareTy(LHS), 1);
2447 if (CmpInst::isFalseWhenEqual(Pred))
2448 return ConstantInt::get(GetCompareTy(LHS), 0);
2451 // Handle fcmp with constant RHS
2452 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2453 // If the constant is a nan, see if we can fold the comparison based on it.
2454 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2455 if (CFP->getValueAPF().isNaN()) {
2456 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
2457 return ConstantInt::getFalse(CFP->getContext());
2458 assert(FCmpInst::isUnordered(Pred) &&
2459 "Comparison must be either ordered or unordered!");
2460 // True if unordered.
2461 return ConstantInt::getTrue(CFP->getContext());
2463 // Check whether the constant is an infinity.
2464 if (CFP->getValueAPF().isInfinity()) {
2465 if (CFP->getValueAPF().isNegative()) {
2467 case FCmpInst::FCMP_OLT:
2468 // No value is ordered and less than negative infinity.
2469 return ConstantInt::getFalse(CFP->getContext());
2470 case FCmpInst::FCMP_UGE:
2471 // All values are unordered with or at least negative infinity.
2472 return ConstantInt::getTrue(CFP->getContext());
2478 case FCmpInst::FCMP_OGT:
2479 // No value is ordered and greater than infinity.
2480 return ConstantInt::getFalse(CFP->getContext());
2481 case FCmpInst::FCMP_ULE:
2482 // All values are unordered with and at most infinity.
2483 return ConstantInt::getTrue(CFP->getContext());
2492 // If the comparison is with the result of a select instruction, check whether
2493 // comparing with either branch of the select always yields the same value.
2494 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2495 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
2498 // If the comparison is with the result of a phi instruction, check whether
2499 // doing the compare with each incoming phi value yields a common result.
2500 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2501 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, TLI, DT, MaxRecurse))
2507 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2508 const TargetData *TD,
2509 const TargetLibraryInfo *TLI,
2510 const DominatorTree *DT) {
2511 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
2514 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
2515 /// the result. If not, this returns null.
2516 Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
2517 const TargetData *TD, const DominatorTree *) {
2518 // select true, X, Y -> X
2519 // select false, X, Y -> Y
2520 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
2521 return CB->getZExtValue() ? TrueVal : FalseVal;
2523 // select C, X, X -> X
2524 if (TrueVal == FalseVal)
2527 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
2528 if (isa<Constant>(TrueVal))
2532 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
2534 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
2540 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
2541 /// fold the result. If not, this returns null.
2542 Value *llvm::SimplifyGEPInst(ArrayRef<Value *> Ops, const TargetData *TD,
2543 const DominatorTree *) {
2544 // The type of the GEP pointer operand.
2545 PointerType *PtrTy = dyn_cast<PointerType>(Ops[0]->getType());
2546 // The GEP pointer operand is not a pointer, it's a vector of pointers.
2550 // getelementptr P -> P.
2551 if (Ops.size() == 1)
2554 if (isa<UndefValue>(Ops[0])) {
2555 // Compute the (pointer) type returned by the GEP instruction.
2556 Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, Ops.slice(1));
2557 Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
2558 return UndefValue::get(GEPTy);
2561 if (Ops.size() == 2) {
2562 // getelementptr P, 0 -> P.
2563 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
2566 // getelementptr P, N -> P if P points to a type of zero size.
2568 Type *Ty = PtrTy->getElementType();
2569 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
2574 // Check to see if this is constant foldable.
2575 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
2576 if (!isa<Constant>(Ops[i]))
2579 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]), Ops.slice(1));
2582 /// SimplifyInsertValueInst - Given operands for an InsertValueInst, see if we
2583 /// can fold the result. If not, this returns null.
2584 Value *llvm::SimplifyInsertValueInst(Value *Agg, Value *Val,
2585 ArrayRef<unsigned> Idxs,
2587 const DominatorTree *) {
2588 if (Constant *CAgg = dyn_cast<Constant>(Agg))
2589 if (Constant *CVal = dyn_cast<Constant>(Val))
2590 return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
2592 // insertvalue x, undef, n -> x
2593 if (match(Val, m_Undef()))
2596 // insertvalue x, (extractvalue y, n), n
2597 if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
2598 if (EV->getAggregateOperand()->getType() == Agg->getType() &&
2599 EV->getIndices() == Idxs) {
2600 // insertvalue undef, (extractvalue y, n), n -> y
2601 if (match(Agg, m_Undef()))
2602 return EV->getAggregateOperand();
2604 // insertvalue y, (extractvalue y, n), n -> y
2605 if (Agg == EV->getAggregateOperand())
2612 /// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
2613 static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
2614 // If all of the PHI's incoming values are the same then replace the PHI node
2615 // with the common value.
2616 Value *CommonValue = 0;
2617 bool HasUndefInput = false;
2618 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
2619 Value *Incoming = PN->getIncomingValue(i);
2620 // If the incoming value is the phi node itself, it can safely be skipped.
2621 if (Incoming == PN) continue;
2622 if (isa<UndefValue>(Incoming)) {
2623 // Remember that we saw an undef value, but otherwise ignore them.
2624 HasUndefInput = true;
2627 if (CommonValue && Incoming != CommonValue)
2628 return 0; // Not the same, bail out.
2629 CommonValue = Incoming;
2632 // If CommonValue is null then all of the incoming values were either undef or
2633 // equal to the phi node itself.
2635 return UndefValue::get(PN->getType());
2637 // If we have a PHI node like phi(X, undef, X), where X is defined by some
2638 // instruction, we cannot return X as the result of the PHI node unless it
2639 // dominates the PHI block.
2641 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
2646 //=== Helper functions for higher up the class hierarchy.
2648 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
2649 /// fold the result. If not, this returns null.
2650 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2651 const TargetData *TD,
2652 const TargetLibraryInfo *TLI,
2653 const DominatorTree *DT,
2654 unsigned MaxRecurse) {
2656 case Instruction::Add:
2657 return SimplifyAddInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2658 TD, TLI, DT, MaxRecurse);
2659 case Instruction::Sub:
2660 return SimplifySubInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2661 TD, TLI, DT, MaxRecurse);
2662 case Instruction::Mul: return SimplifyMulInst (LHS, RHS, TD, TLI, DT,
2664 case Instruction::SDiv: return SimplifySDivInst(LHS, RHS, TD, TLI, DT,
2666 case Instruction::UDiv: return SimplifyUDivInst(LHS, RHS, TD, TLI, DT,
2668 case Instruction::FDiv: return SimplifyFDivInst(LHS, RHS, TD, TLI, DT,
2670 case Instruction::SRem: return SimplifySRemInst(LHS, RHS, TD, TLI, DT,
2672 case Instruction::URem: return SimplifyURemInst(LHS, RHS, TD, TLI, DT,
2674 case Instruction::FRem: return SimplifyFRemInst(LHS, RHS, TD, TLI, DT,
2676 case Instruction::Shl:
2677 return SimplifyShlInst(LHS, RHS, /*isNSW*/false, /*isNUW*/false,
2678 TD, TLI, DT, MaxRecurse);
2679 case Instruction::LShr:
2680 return SimplifyLShrInst(LHS, RHS, /*isExact*/false, TD, TLI, DT,
2682 case Instruction::AShr:
2683 return SimplifyAShrInst(LHS, RHS, /*isExact*/false, TD, TLI, DT,
2685 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, TLI, DT,
2687 case Instruction::Or: return SimplifyOrInst (LHS, RHS, TD, TLI, DT,
2689 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, TLI, DT,
2692 if (Constant *CLHS = dyn_cast<Constant>(LHS))
2693 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
2694 Constant *COps[] = {CLHS, CRHS};
2695 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, TD, TLI);
2698 // If the operation is associative, try some generic simplifications.
2699 if (Instruction::isAssociative(Opcode))
2700 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, TLI, DT,
2704 // If the operation is with the result of a select instruction, check whether
2705 // operating on either branch of the select always yields the same value.
2706 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
2707 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, TLI, DT,
2711 // If the operation is with the result of a phi instruction, check whether
2712 // operating on all incoming values of the phi always yields the same value.
2713 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
2714 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, TLI, DT,
2722 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
2723 const TargetData *TD, const TargetLibraryInfo *TLI,
2724 const DominatorTree *DT) {
2725 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, TLI, DT, RecursionLimit);
2728 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
2729 /// fold the result.
2730 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2731 const TargetData *TD,
2732 const TargetLibraryInfo *TLI,
2733 const DominatorTree *DT,
2734 unsigned MaxRecurse) {
2735 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
2736 return SimplifyICmpInst(Predicate, LHS, RHS, TD, TLI, DT, MaxRecurse);
2737 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, TLI, DT, MaxRecurse);
2740 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
2741 const TargetData *TD, const TargetLibraryInfo *TLI,
2742 const DominatorTree *DT) {
2743 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, TLI, DT, RecursionLimit);
2746 static Value *SimplifyCallInst(CallInst *CI) {
2747 // call undef -> undef
2748 if (isa<UndefValue>(CI->getCalledValue()))
2749 return UndefValue::get(CI->getType());
2754 /// SimplifyInstruction - See if we can compute a simplified version of this
2755 /// instruction. If not, this returns null.
2756 Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
2757 const TargetLibraryInfo *TLI,
2758 const DominatorTree *DT) {
2761 switch (I->getOpcode()) {
2763 Result = ConstantFoldInstruction(I, TD, TLI);
2765 case Instruction::Add:
2766 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
2767 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2768 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2771 case Instruction::Sub:
2772 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
2773 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2774 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2777 case Instruction::Mul:
2778 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2780 case Instruction::SDiv:
2781 Result = SimplifySDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2783 case Instruction::UDiv:
2784 Result = SimplifyUDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2786 case Instruction::FDiv:
2787 Result = SimplifyFDivInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2789 case Instruction::SRem:
2790 Result = SimplifySRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2792 case Instruction::URem:
2793 Result = SimplifyURemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2795 case Instruction::FRem:
2796 Result = SimplifyFRemInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2798 case Instruction::Shl:
2799 Result = SimplifyShlInst(I->getOperand(0), I->getOperand(1),
2800 cast<BinaryOperator>(I)->hasNoSignedWrap(),
2801 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
2804 case Instruction::LShr:
2805 Result = SimplifyLShrInst(I->getOperand(0), I->getOperand(1),
2806 cast<BinaryOperator>(I)->isExact(),
2809 case Instruction::AShr:
2810 Result = SimplifyAShrInst(I->getOperand(0), I->getOperand(1),
2811 cast<BinaryOperator>(I)->isExact(),
2814 case Instruction::And:
2815 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2817 case Instruction::Or:
2818 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2820 case Instruction::Xor:
2821 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2823 case Instruction::ICmp:
2824 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
2825 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2827 case Instruction::FCmp:
2828 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
2829 I->getOperand(0), I->getOperand(1), TD, TLI, DT);
2831 case Instruction::Select:
2832 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
2833 I->getOperand(2), TD, DT);
2835 case Instruction::GetElementPtr: {
2836 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
2837 Result = SimplifyGEPInst(Ops, TD, DT);
2840 case Instruction::InsertValue: {
2841 InsertValueInst *IV = cast<InsertValueInst>(I);
2842 Result = SimplifyInsertValueInst(IV->getAggregateOperand(),
2843 IV->getInsertedValueOperand(),
2844 IV->getIndices(), TD, DT);
2847 case Instruction::PHI:
2848 Result = SimplifyPHINode(cast<PHINode>(I), DT);
2850 case Instruction::Call:
2851 Result = SimplifyCallInst(cast<CallInst>(I));
2855 /// If called on unreachable code, the above logic may report that the
2856 /// instruction simplified to itself. Make life easier for users by
2857 /// detecting that case here, returning a safe value instead.
2858 return Result == I ? UndefValue::get(I->getType()) : Result;
2861 /// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
2862 /// delete the From instruction. In addition to a basic RAUW, this does a
2863 /// recursive simplification of the newly formed instructions. This catches
2864 /// things where one simplification exposes other opportunities. This only
2865 /// simplifies and deletes scalar operations, it does not change the CFG.
2867 void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
2868 const TargetData *TD,
2869 const TargetLibraryInfo *TLI,
2870 const DominatorTree *DT) {
2871 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
2873 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
2874 // we can know if it gets deleted out from under us or replaced in a
2875 // recursive simplification.
2876 WeakVH FromHandle(From);
2877 WeakVH ToHandle(To);
2879 while (!From->use_empty()) {
2880 // Update the instruction to use the new value.
2881 Use &TheUse = From->use_begin().getUse();
2882 Instruction *User = cast<Instruction>(TheUse.getUser());
2885 // Check to see if the instruction can be folded due to the operand
2886 // replacement. For example changing (or X, Y) into (or X, -1) can replace
2887 // the 'or' with -1.
2888 Value *SimplifiedVal;
2890 // Sanity check to make sure 'User' doesn't dangle across
2891 // SimplifyInstruction.
2892 AssertingVH<> UserHandle(User);
2894 SimplifiedVal = SimplifyInstruction(User, TD, TLI, DT);
2895 if (SimplifiedVal == 0) continue;
2898 // Recursively simplify this user to the new value.
2899 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, TLI, DT);
2900 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
2903 assert(ToHandle && "To value deleted by recursive simplification?");
2905 // If the recursive simplification ended up revisiting and deleting
2906 // 'From' then we're done.
2911 // If 'From' has value handles referring to it, do a real RAUW to update them.
2912 From->replaceAllUsesWith(To);
2914 From->eraseFromParent();