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/ADT/Statistic.h"
22 #include "llvm/Analysis/InstructionSimplify.h"
23 #include "llvm/Analysis/ConstantFolding.h"
24 #include "llvm/Analysis/Dominators.h"
25 #include "llvm/Support/PatternMatch.h"
26 #include "llvm/Support/ValueHandle.h"
27 #include "llvm/Target/TargetData.h"
29 using namespace llvm::PatternMatch;
31 #define RecursionLimit 4
33 STATISTIC(NumExpand, "Number of expansions");
34 STATISTIC(NumFactor , "Number of factorizations");
35 STATISTIC(NumReassoc, "Number of reassociations");
37 static Value *SimplifyAndInst(Value *, Value *, const TargetData *,
38 const DominatorTree *, unsigned);
39 static Value *SimplifyBinOp(unsigned, Value *, Value *, const TargetData *,
40 const DominatorTree *, unsigned);
41 static Value *SimplifyCmpInst(unsigned, Value *, Value *, const TargetData *,
42 const DominatorTree *, unsigned);
43 static Value *SimplifyOrInst(Value *, Value *, const TargetData *,
44 const DominatorTree *, unsigned);
45 static Value *SimplifyXorInst(Value *, Value *, const TargetData *,
46 const DominatorTree *, unsigned);
48 /// equal - Return true if the given values are known to be equal, false if they
49 /// are not equal or it is not clear whether they are equal or not.
50 static bool equal(Value *A, Value *B, unsigned MaxRecurse) {
51 // If the pointers are equal then the values are!
54 // From this point on either recursion is used or the result is false, so bail
55 // out at once if we already hit the recursion limit.
58 // If these are instructions, see if they compute the same value.
59 Instruction *AI = dyn_cast<Instruction>(A), *BI = dyn_cast<Instruction>(B);
62 // If one of the instructions has extra flags attached then be conservative
63 // and say that the instructions differ.
64 if (!AI->hasSameSubclassOptionalData(BI))
66 // For some reason alloca's are not considered to read or write memory, yet
67 // each one nonetheless manages to return a different value...
68 if (isa<AllocaInst>(AI))
70 // Do not consider instructions to be equal if they may access memory.
71 if (AI->mayReadFromMemory() || AI->mayWriteToMemory())
73 // If the instructions do not perform the same computation then bail out.
74 if (!BI->isSameOperationAs(AI))
77 // Check whether all operands are equal. If they are then the instructions
78 // have the same value.
79 bool AllOperandsEqual = true;
80 for (unsigned i = 0, e = AI->getNumOperands(); i != e; ++i)
81 if (!equal(AI->getOperand(i), BI->getOperand(i), MaxRecurse)) {
82 AllOperandsEqual = false;
88 // If the instructions are commutative and their operands are equal when
89 // swapped then the instructions have the same value.
90 return AI->isCommutative() &&
91 equal(AI->getOperand(0), BI->getOperand(1), MaxRecurse) &&
92 equal(AI->getOperand(1), BI->getOperand(0), MaxRecurse);
95 /// ValueDominatesPHI - Does the given value dominate the specified phi node?
96 static bool ValueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
97 Instruction *I = dyn_cast<Instruction>(V);
99 // Arguments and constants dominate all instructions.
102 // If we have a DominatorTree then do a precise test.
104 return DT->dominates(I, P);
106 // Otherwise, if the instruction is in the entry block, and is not an invoke,
107 // then it obviously dominates all phi nodes.
108 if (I->getParent() == &I->getParent()->getParent()->getEntryBlock() &&
115 /// ExpandBinOp - Simplify "A op (B op' C)" by distributing op over op', turning
116 /// it into "(A op B) op' (A op C)". Here "op" is given by Opcode and "op'" is
117 /// given by OpcodeToExpand, while "A" corresponds to LHS and "B op' C" to RHS.
118 /// Also performs the transform "(A op' B) op C" -> "(A op C) op' (B op C)".
119 /// Returns the simplified value, or null if no simplification was performed.
120 static Value *ExpandBinOp(unsigned Opcode, Value *LHS, Value *RHS,
121 unsigned OpcToExpand, const TargetData *TD,
122 const DominatorTree *DT, unsigned MaxRecurse) {
123 Instruction::BinaryOps OpcodeToExpand = (Instruction::BinaryOps)OpcToExpand;
124 // Recursion is always used, so bail out at once if we already hit the limit.
128 // Check whether the expression has the form "(A op' B) op C".
129 if (BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS))
130 if (Op0->getOpcode() == OpcodeToExpand) {
131 // It does! Try turning it into "(A op C) op' (B op C)".
132 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
133 // Do "A op C" and "B op C" both simplify?
134 if (Value *L = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse))
135 if (Value *R = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
136 // They do! Return "L op' R" if it simplifies or is already available.
137 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
138 if ((equal(L, A, MaxRecurse) && equal(R, B, MaxRecurse)) ||
139 (Instruction::isCommutative(OpcodeToExpand) &&
140 equal(L, B, MaxRecurse) && equal(R, A, MaxRecurse))) {
144 // Otherwise return "L op' R" if it simplifies.
145 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
153 // Check whether the expression has the form "A op (B op' C)".
154 if (BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS))
155 if (Op1->getOpcode() == OpcodeToExpand) {
156 // It does! Try turning it into "(A op B) op' (A op C)".
157 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
158 // Do "A op B" and "A op C" both simplify?
159 if (Value *L = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse))
160 if (Value *R = SimplifyBinOp(Opcode, A, C, TD, DT, MaxRecurse)) {
161 // They do! Return "L op' R" if it simplifies or is already available.
162 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
163 if ((equal(L, B, MaxRecurse) && equal(R, C, MaxRecurse)) ||
164 (Instruction::isCommutative(OpcodeToExpand) &&
165 equal(L, C, MaxRecurse) && equal(R, B, MaxRecurse))) {
169 // Otherwise return "L op' R" if it simplifies.
170 if (Value *V = SimplifyBinOp(OpcodeToExpand, L, R, TD, DT,
181 /// FactorizeBinOp - Simplify "LHS Opcode RHS" by factorizing out a common term
182 /// using the operation OpCodeToExtract. For example, when Opcode is Add and
183 /// OpCodeToExtract is Mul then this tries to turn "(A*B)+(A*C)" into "A*(B+C)".
184 /// Returns the simplified value, or null if no simplification was performed.
185 static Value *FactorizeBinOp(unsigned Opcode, Value *LHS, Value *RHS,
186 unsigned OpcToExtract, const TargetData *TD,
187 const DominatorTree *DT, unsigned MaxRecurse) {
188 Instruction::BinaryOps OpcodeToExtract = (Instruction::BinaryOps)OpcToExtract;
189 // Recursion is always used, so bail out at once if we already hit the limit.
193 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
194 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
196 if (!Op0 || Op0->getOpcode() != OpcodeToExtract ||
197 !Op1 || Op1->getOpcode() != OpcodeToExtract)
200 // The expression has the form "(A op' B) op (C op' D)".
201 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
202 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
204 // Use left distributivity, i.e. "X op' (Y op Z) = (X op' Y) op (X op' Z)".
205 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
206 // commutative case, "(A op' B) op (C op' A)"?
207 bool AEqualsC = equal(A, C, MaxRecurse);
208 if (AEqualsC || (Instruction::isCommutative(OpcodeToExtract) &&
209 equal(A, D, MaxRecurse))) {
210 Value *DD = AEqualsC ? D : C;
211 // Form "A op' (B op DD)" if it simplifies completely.
212 // Does "B op DD" simplify?
213 if (Value *V = SimplifyBinOp(Opcode, B, DD, TD, DT, MaxRecurse)) {
214 // It does! Return "A op' V" if it simplifies or is already available.
215 // If V equals B then "A op' V" is just the LHS. If V equals DD then
216 // "A op' V" is just the RHS.
217 if (equal(V, B, MaxRecurse)) {
221 if (equal(V, DD, MaxRecurse)) {
225 // Otherwise return "A op' V" if it simplifies.
226 if (Value *W = SimplifyBinOp(OpcodeToExtract, A, V, TD, DT, MaxRecurse)) {
233 // Use right distributivity, i.e. "(X op Y) op' Z = (X op' Z) op (Y op' Z)".
234 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
235 // commutative case, "(A op' B) op (B op' D)"?
236 bool BEqualsD = equal(B, D, MaxRecurse);
237 if (BEqualsD || (Instruction::isCommutative(OpcodeToExtract) &&
238 equal(B, C, MaxRecurse))) {
239 Value *CC = BEqualsD ? C : D;
240 // Form "(A op CC) op' B" if it simplifies completely..
241 // Does "A op CC" simplify?
242 if (Value *V = SimplifyBinOp(Opcode, A, CC, TD, DT, MaxRecurse)) {
243 // It does! Return "V op' B" if it simplifies or is already available.
244 // If V equals A then "V op' B" is just the LHS. If V equals CC then
245 // "V op' B" is just the RHS.
246 if (equal(V, A, MaxRecurse)) {
250 if (equal(V, CC, MaxRecurse)) {
254 // Otherwise return "V op' B" if it simplifies.
255 if (Value *W = SimplifyBinOp(OpcodeToExtract, V, B, TD, DT, MaxRecurse)) {
265 /// SimplifyAssociativeBinOp - Generic simplifications for associative binary
266 /// operations. Returns the simpler value, or null if none was found.
267 static Value *SimplifyAssociativeBinOp(unsigned Opc, Value *LHS, Value *RHS,
268 const TargetData *TD,
269 const DominatorTree *DT,
270 unsigned MaxRecurse) {
271 Instruction::BinaryOps Opcode = (Instruction::BinaryOps)Opc;
272 assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
274 // Recursion is always used, so bail out at once if we already hit the limit.
278 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
279 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
281 // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
282 if (Op0 && Op0->getOpcode() == Opcode) {
283 Value *A = Op0->getOperand(0);
284 Value *B = Op0->getOperand(1);
287 // Does "B op C" simplify?
288 if (Value *V = SimplifyBinOp(Opcode, B, C, TD, DT, MaxRecurse)) {
289 // It does! Return "A op V" if it simplifies or is already available.
290 // If V equals B then "A op V" is just the LHS.
291 if (equal(V, B, MaxRecurse)) return LHS;
292 // Otherwise return "A op V" if it simplifies.
293 if (Value *W = SimplifyBinOp(Opcode, A, V, TD, DT, MaxRecurse)) {
300 // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
301 if (Op1 && Op1->getOpcode() == Opcode) {
303 Value *B = Op1->getOperand(0);
304 Value *C = Op1->getOperand(1);
306 // Does "A op B" simplify?
307 if (Value *V = SimplifyBinOp(Opcode, A, B, TD, DT, MaxRecurse)) {
308 // It does! Return "V op C" if it simplifies or is already available.
309 // If V equals B then "V op C" is just the RHS.
310 if (equal(V, B, MaxRecurse)) return RHS;
311 // Otherwise return "V op C" if it simplifies.
312 if (Value *W = SimplifyBinOp(Opcode, V, C, TD, DT, MaxRecurse)) {
319 // The remaining transforms require commutativity as well as associativity.
320 if (!Instruction::isCommutative(Opcode))
323 // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
324 if (Op0 && Op0->getOpcode() == Opcode) {
325 Value *A = Op0->getOperand(0);
326 Value *B = Op0->getOperand(1);
329 // Does "C op A" simplify?
330 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
331 // It does! Return "V op B" if it simplifies or is already available.
332 // If V equals A then "V op B" is just the LHS.
333 if (equal(V, A, MaxRecurse)) return LHS;
334 // Otherwise return "V op B" if it simplifies.
335 if (Value *W = SimplifyBinOp(Opcode, V, B, TD, DT, MaxRecurse)) {
342 // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
343 if (Op1 && Op1->getOpcode() == Opcode) {
345 Value *B = Op1->getOperand(0);
346 Value *C = Op1->getOperand(1);
348 // Does "C op A" simplify?
349 if (Value *V = SimplifyBinOp(Opcode, C, A, TD, DT, MaxRecurse)) {
350 // It does! Return "B op V" if it simplifies or is already available.
351 // If V equals C then "B op V" is just the RHS.
352 if (equal(V, C, MaxRecurse)) return RHS;
353 // Otherwise return "B op V" if it simplifies.
354 if (Value *W = SimplifyBinOp(Opcode, B, V, TD, DT, MaxRecurse)) {
364 /// ThreadBinOpOverSelect - In the case of a binary operation with a select
365 /// instruction as an operand, try to simplify the binop by seeing whether
366 /// evaluating it on both branches of the select results in the same value.
367 /// Returns the common value if so, otherwise returns null.
368 static Value *ThreadBinOpOverSelect(unsigned Opcode, Value *LHS, Value *RHS,
369 const TargetData *TD,
370 const DominatorTree *DT,
371 unsigned MaxRecurse) {
372 // Recursion is always used, so bail out at once if we already hit the limit.
377 if (isa<SelectInst>(LHS)) {
378 SI = cast<SelectInst>(LHS);
380 assert(isa<SelectInst>(RHS) && "No select instruction operand!");
381 SI = cast<SelectInst>(RHS);
384 // Evaluate the BinOp on the true and false branches of the select.
388 TV = SimplifyBinOp(Opcode, SI->getTrueValue(), RHS, TD, DT, MaxRecurse);
389 FV = SimplifyBinOp(Opcode, SI->getFalseValue(), RHS, TD, DT, MaxRecurse);
391 TV = SimplifyBinOp(Opcode, LHS, SI->getTrueValue(), TD, DT, MaxRecurse);
392 FV = SimplifyBinOp(Opcode, LHS, SI->getFalseValue(), TD, DT, MaxRecurse);
395 // If they both failed to simplify then return null.
399 // If they simplified to the same value, then return the common value.
400 if (TV && FV && equal(TV, FV, MaxRecurse))
403 // If one branch simplified to undef, return the other one.
404 if (TV && isa<UndefValue>(TV))
406 if (FV && isa<UndefValue>(FV))
409 // If applying the operation did not change the true and false select values,
410 // then the result of the binop is the select itself.
411 if (TV && equal(TV, SI->getTrueValue(), MaxRecurse) &&
412 FV && equal(FV, SI->getFalseValue(), MaxRecurse))
415 // If one branch simplified and the other did not, and the simplified
416 // value is equal to the unsimplified one, return the simplified value.
417 // For example, select (cond, X, X & Z) & Z -> X & Z.
418 if ((FV && !TV) || (TV && !FV)) {
419 // Check that the simplified value has the form "X op Y" where "op" is the
420 // same as the original operation.
421 Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
422 if (Simplified && Simplified->getOpcode() == Opcode) {
423 // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
424 // We already know that "op" is the same as for the simplified value. See
425 // if the operands match too. If so, return the simplified value.
426 Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
427 Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
428 Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
429 if (equal(Simplified->getOperand(0), UnsimplifiedLHS, MaxRecurse) &&
430 equal(Simplified->getOperand(1), UnsimplifiedRHS, MaxRecurse))
432 if (Simplified->isCommutative() &&
433 equal(Simplified->getOperand(1), UnsimplifiedLHS, MaxRecurse) &&
434 equal(Simplified->getOperand(0), UnsimplifiedRHS, MaxRecurse))
442 /// ThreadCmpOverSelect - In the case of a comparison with a select instruction,
443 /// try to simplify the comparison by seeing whether both branches of the select
444 /// result in the same value. Returns the common value if so, otherwise returns
446 static Value *ThreadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
447 Value *RHS, const TargetData *TD,
448 const DominatorTree *DT,
449 unsigned MaxRecurse) {
450 // Recursion is always used, so bail out at once if we already hit the limit.
454 // Make sure the select is on the LHS.
455 if (!isa<SelectInst>(LHS)) {
457 Pred = CmpInst::getSwappedPredicate(Pred);
459 assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
460 SelectInst *SI = cast<SelectInst>(LHS);
462 // Now that we have "cmp select(cond, TV, FV), RHS", analyse it.
463 // Does "cmp TV, RHS" simplify?
464 if (Value *TCmp = SimplifyCmpInst(Pred, SI->getTrueValue(), RHS, TD, DT,
466 // It does! Does "cmp FV, RHS" simplify?
467 if (Value *FCmp = SimplifyCmpInst(Pred, SI->getFalseValue(), RHS, TD, DT,
469 // It does! If they simplified to the same value, then use it as the
470 // result of the original comparison.
471 if (equal(TCmp, FCmp, MaxRecurse))
476 /// ThreadBinOpOverPHI - In the case of a binary operation with an operand that
477 /// is a PHI instruction, try to simplify the binop by seeing whether evaluating
478 /// it on the incoming phi values yields the same result for every value. If so
479 /// returns the common value, otherwise returns null.
480 static Value *ThreadBinOpOverPHI(unsigned Opcode, Value *LHS, Value *RHS,
481 const TargetData *TD, const DominatorTree *DT,
482 unsigned MaxRecurse) {
483 // Recursion is always used, so bail out at once if we already hit the limit.
488 if (isa<PHINode>(LHS)) {
489 PI = cast<PHINode>(LHS);
490 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
491 if (!ValueDominatesPHI(RHS, PI, DT))
494 assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
495 PI = cast<PHINode>(RHS);
496 // Bail out if LHS and the phi may be mutually interdependent due to a loop.
497 if (!ValueDominatesPHI(LHS, PI, DT))
501 // Evaluate the BinOp on the incoming phi values.
502 Value *CommonValue = 0;
503 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
504 Value *Incoming = PI->getIncomingValue(i);
505 // If the incoming value is the phi node itself, it can safely be skipped.
506 if (Incoming == PI) continue;
507 Value *V = PI == LHS ?
508 SimplifyBinOp(Opcode, Incoming, RHS, TD, DT, MaxRecurse) :
509 SimplifyBinOp(Opcode, LHS, Incoming, TD, DT, MaxRecurse);
510 // If the operation failed to simplify, or simplified to a different value
511 // to previously, then give up.
512 if (!V || (CommonValue && V != CommonValue))
520 /// ThreadCmpOverPHI - In the case of a comparison with a PHI instruction, try
521 /// try to simplify the comparison by seeing whether comparing with all of the
522 /// incoming phi values yields the same result every time. If so returns the
523 /// common result, otherwise returns null.
524 static Value *ThreadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
525 const TargetData *TD, const DominatorTree *DT,
526 unsigned MaxRecurse) {
527 // Recursion is always used, so bail out at once if we already hit the limit.
531 // Make sure the phi is on the LHS.
532 if (!isa<PHINode>(LHS)) {
534 Pred = CmpInst::getSwappedPredicate(Pred);
536 assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
537 PHINode *PI = cast<PHINode>(LHS);
539 // Bail out if RHS and the phi may be mutually interdependent due to a loop.
540 if (!ValueDominatesPHI(RHS, PI, DT))
543 // Evaluate the BinOp on the incoming phi values.
544 Value *CommonValue = 0;
545 for (unsigned i = 0, e = PI->getNumIncomingValues(); i != e; ++i) {
546 Value *Incoming = PI->getIncomingValue(i);
547 // If the incoming value is the phi node itself, it can safely be skipped.
548 if (Incoming == PI) continue;
549 Value *V = SimplifyCmpInst(Pred, Incoming, RHS, TD, DT, MaxRecurse);
550 // If the operation failed to simplify, or simplified to a different value
551 // to previously, then give up.
552 if (!V || (CommonValue && V != CommonValue))
560 /// SimplifyAddInst - Given operands for an Add, see if we can
561 /// fold the result. If not, this returns null.
562 static Value *SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
563 const TargetData *TD, const DominatorTree *DT,
564 unsigned MaxRecurse) {
565 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
566 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
567 Constant *Ops[] = { CLHS, CRHS };
568 return ConstantFoldInstOperands(Instruction::Add, CLHS->getType(),
572 // Canonicalize the constant to the RHS.
576 // X + undef -> undef
577 if (isa<UndefValue>(Op1))
581 if (match(Op1, m_Zero()))
587 Value *X = 0, *Y = 0;
588 if ((match(Op1, m_Sub(m_Value(Y), m_Value(X))) && equal(X, Op0, MaxRecurse))||
589 (match(Op0, m_Sub(m_Value(Y), m_Value(X))) && equal(X, Op1, MaxRecurse)))
592 // X + ~X -> -1 since ~X = -X-1
593 if ((match(Op0, m_Not(m_Value(X))) && equal(X, Op1, MaxRecurse)) ||
594 (match(Op1, m_Not(m_Value(X))) && equal(X, Op0, MaxRecurse)))
595 return Constant::getAllOnesValue(Op0->getType());
598 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
599 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
602 // Try some generic simplifications for associative operations.
603 if (Value *V = SimplifyAssociativeBinOp(Instruction::Add, Op0, Op1, TD, DT,
607 // Mul distributes over Add. Try some generic simplifications based on this.
608 if (Value *V = FactorizeBinOp(Instruction::Add, Op0, Op1, Instruction::Mul,
612 // Threading Add over selects and phi nodes is pointless, so don't bother.
613 // Threading over the select in "A + select(cond, B, C)" means evaluating
614 // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
615 // only if B and C are equal. If B and C are equal then (since we assume
616 // that operands have already been simplified) "select(cond, B, C)" should
617 // have been simplified to the common value of B and C already. Analysing
618 // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
619 // for threading over phi nodes.
624 Value *llvm::SimplifyAddInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
625 const TargetData *TD, const DominatorTree *DT) {
626 return ::SimplifyAddInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
629 /// SimplifySubInst - Given operands for a Sub, see if we can
630 /// fold the result. If not, this returns null.
631 static Value *SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
632 const TargetData *TD, const DominatorTree *DT,
633 unsigned MaxRecurse) {
634 if (Constant *CLHS = dyn_cast<Constant>(Op0))
635 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
636 Constant *Ops[] = { CLHS, CRHS };
637 return ConstantFoldInstOperands(Instruction::Sub, CLHS->getType(),
641 // X - undef -> undef
642 // undef - X -> undef
643 if (isa<UndefValue>(Op0) || isa<UndefValue>(Op1))
644 return UndefValue::get(Op0->getType());
647 if (match(Op1, m_Zero()))
651 if (equal(Op0, Op1, MaxRecurse))
652 return Constant::getNullValue(Op0->getType());
656 Value *X = 0, *Y = 0;
657 if ((match(Op0, m_Add(m_Value(X), m_Value(Y))) && equal(Y, Op1, MaxRecurse))||
658 (match(Op0, m_Add(m_Value(Y), m_Value(X))) && equal(Y, Op1, MaxRecurse)))
662 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
663 if (Value *V = SimplifyXorInst(Op0, Op1, TD, DT, MaxRecurse-1))
666 // Mul distributes over Sub. Try some generic simplifications based on this.
667 if (Value *V = FactorizeBinOp(Instruction::Sub, Op0, Op1, Instruction::Mul,
671 // Threading Sub over selects and phi nodes is pointless, so don't bother.
672 // Threading over the select in "A - select(cond, B, C)" means evaluating
673 // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
674 // only if B and C are equal. If B and C are equal then (since we assume
675 // that operands have already been simplified) "select(cond, B, C)" should
676 // have been simplified to the common value of B and C already. Analysing
677 // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
678 // for threading over phi nodes.
683 Value *llvm::SimplifySubInst(Value *Op0, Value *Op1, bool isNSW, bool isNUW,
684 const TargetData *TD, const DominatorTree *DT) {
685 return ::SimplifySubInst(Op0, Op1, isNSW, isNUW, TD, DT, RecursionLimit);
688 /// SimplifyMulInst - Given operands for a Mul, see if we can
689 /// fold the result. If not, this returns null.
690 static Value *SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
691 const DominatorTree *DT, unsigned MaxRecurse) {
692 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
693 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
694 Constant *Ops[] = { CLHS, CRHS };
695 return ConstantFoldInstOperands(Instruction::Mul, CLHS->getType(),
699 // Canonicalize the constant to the RHS.
704 if (isa<UndefValue>(Op1))
705 return Constant::getNullValue(Op0->getType());
708 if (match(Op1, m_Zero()))
712 if (match(Op1, m_One()))
716 if (MaxRecurse && Op0->getType()->isIntegerTy(1))
717 if (Value *V = SimplifyAndInst(Op0, Op1, TD, DT, MaxRecurse-1))
720 // Try some generic simplifications for associative operations.
721 if (Value *V = SimplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, TD, DT,
725 // Mul distributes over Add. Try some generic simplifications based on this.
726 if (Value *V = ExpandBinOp(Instruction::Mul, Op0, Op1, Instruction::Add,
730 // If the operation is with the result of a select instruction, check whether
731 // operating on either branch of the select always yields the same value.
732 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
733 if (Value *V = ThreadBinOpOverSelect(Instruction::Mul, Op0, Op1, TD, DT,
737 // If the operation is with the result of a phi instruction, check whether
738 // operating on all incoming values of the phi always yields the same value.
739 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
740 if (Value *V = ThreadBinOpOverPHI(Instruction::Mul, Op0, Op1, TD, DT,
747 Value *llvm::SimplifyMulInst(Value *Op0, Value *Op1, const TargetData *TD,
748 const DominatorTree *DT) {
749 return ::SimplifyMulInst(Op0, Op1, TD, DT, RecursionLimit);
752 /// SimplifyAndInst - Given operands for an And, see if we can
753 /// fold the result. If not, this returns null.
754 static Value *SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
755 const DominatorTree *DT, unsigned MaxRecurse) {
756 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
757 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
758 Constant *Ops[] = { CLHS, CRHS };
759 return ConstantFoldInstOperands(Instruction::And, CLHS->getType(),
763 // Canonicalize the constant to the RHS.
768 if (isa<UndefValue>(Op1))
769 return Constant::getNullValue(Op0->getType());
772 if (equal(Op0, Op1, MaxRecurse))
776 if (match(Op1, m_Zero()))
780 if (match(Op1, m_AllOnes()))
783 // A & ~A = ~A & A = 0
784 Value *A = 0, *B = 0;
785 if ((match(Op0, m_Not(m_Value(A))) && equal(A, Op1, MaxRecurse)) ||
786 (match(Op1, m_Not(m_Value(A))) && equal(A, Op0, MaxRecurse)))
787 return Constant::getNullValue(Op0->getType());
790 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
791 (equal(A, Op1, MaxRecurse) || equal(B, Op1, MaxRecurse)))
795 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
796 (equal(A, Op0, MaxRecurse) || equal(B, Op0, MaxRecurse)))
799 // Try some generic simplifications for associative operations.
800 if (Value *V = SimplifyAssociativeBinOp(Instruction::And, Op0, Op1, TD, DT,
804 // And distributes over Or. Try some generic simplifications based on this.
805 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Or,
809 // And distributes over Xor. Try some generic simplifications based on this.
810 if (Value *V = ExpandBinOp(Instruction::And, Op0, Op1, Instruction::Xor,
814 // Or distributes over And. Try some generic simplifications based on this.
815 if (Value *V = FactorizeBinOp(Instruction::And, Op0, Op1, Instruction::Or,
819 // If the operation is with the result of a select instruction, check whether
820 // operating on either branch of the select always yields the same value.
821 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
822 if (Value *V = ThreadBinOpOverSelect(Instruction::And, Op0, Op1, TD, DT,
826 // If the operation is with the result of a phi instruction, check whether
827 // operating on all incoming values of the phi always yields the same value.
828 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
829 if (Value *V = ThreadBinOpOverPHI(Instruction::And, Op0, Op1, TD, DT,
836 Value *llvm::SimplifyAndInst(Value *Op0, Value *Op1, const TargetData *TD,
837 const DominatorTree *DT) {
838 return ::SimplifyAndInst(Op0, Op1, TD, DT, RecursionLimit);
841 /// SimplifyOrInst - Given operands for an Or, see if we can
842 /// fold the result. If not, this returns null.
843 static Value *SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
844 const DominatorTree *DT, unsigned MaxRecurse) {
845 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
846 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
847 Constant *Ops[] = { CLHS, CRHS };
848 return ConstantFoldInstOperands(Instruction::Or, CLHS->getType(),
852 // Canonicalize the constant to the RHS.
857 if (isa<UndefValue>(Op1))
858 return Constant::getAllOnesValue(Op0->getType());
861 if (equal(Op0, Op1, MaxRecurse))
865 if (match(Op1, m_Zero()))
869 if (match(Op1, m_AllOnes()))
872 // A | ~A = ~A | A = -1
873 Value *A = 0, *B = 0;
874 if ((match(Op0, m_Not(m_Value(A))) && equal(A, Op1, MaxRecurse)) ||
875 (match(Op1, m_Not(m_Value(A))) && equal(A, Op0, MaxRecurse)))
876 return Constant::getAllOnesValue(Op0->getType());
879 if (match(Op0, m_And(m_Value(A), m_Value(B))) &&
880 (equal(A, Op1, MaxRecurse) || equal(B, Op1, MaxRecurse)))
884 if (match(Op1, m_And(m_Value(A), m_Value(B))) &&
885 (equal(A, Op0, MaxRecurse) || equal(B, Op0, MaxRecurse)))
888 // Try some generic simplifications for associative operations.
889 if (Value *V = SimplifyAssociativeBinOp(Instruction::Or, Op0, Op1, TD, DT,
893 // Or distributes over And. Try some generic simplifications based on this.
894 if (Value *V = ExpandBinOp(Instruction::Or, Op0, Op1, Instruction::And,
898 // And distributes over Or. Try some generic simplifications based on this.
899 if (Value *V = FactorizeBinOp(Instruction::Or, Op0, Op1, Instruction::And,
903 // If the operation is with the result of a select instruction, check whether
904 // operating on either branch of the select always yields the same value.
905 if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
906 if (Value *V = ThreadBinOpOverSelect(Instruction::Or, Op0, Op1, TD, DT,
910 // If the operation is with the result of a phi instruction, check whether
911 // operating on all incoming values of the phi always yields the same value.
912 if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
913 if (Value *V = ThreadBinOpOverPHI(Instruction::Or, Op0, Op1, TD, DT,
920 Value *llvm::SimplifyOrInst(Value *Op0, Value *Op1, const TargetData *TD,
921 const DominatorTree *DT) {
922 return ::SimplifyOrInst(Op0, Op1, TD, DT, RecursionLimit);
925 /// SimplifyXorInst - Given operands for a Xor, see if we can
926 /// fold the result. If not, this returns null.
927 static Value *SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
928 const DominatorTree *DT, unsigned MaxRecurse) {
929 if (Constant *CLHS = dyn_cast<Constant>(Op0)) {
930 if (Constant *CRHS = dyn_cast<Constant>(Op1)) {
931 Constant *Ops[] = { CLHS, CRHS };
932 return ConstantFoldInstOperands(Instruction::Xor, CLHS->getType(),
936 // Canonicalize the constant to the RHS.
940 // A ^ undef -> undef
941 if (isa<UndefValue>(Op1))
945 if (match(Op1, m_Zero()))
949 if (equal(Op0, Op1, MaxRecurse))
950 return Constant::getNullValue(Op0->getType());
952 // A ^ ~A = ~A ^ A = -1
954 if ((match(Op0, m_Not(m_Value(A))) && equal(A, Op1, MaxRecurse)) ||
955 (match(Op1, m_Not(m_Value(A))) && equal(A, Op0, MaxRecurse)))
956 return Constant::getAllOnesValue(Op0->getType());
958 // Try some generic simplifications for associative operations.
959 if (Value *V = SimplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, TD, DT,
963 // And distributes over Xor. Try some generic simplifications based on this.
964 if (Value *V = FactorizeBinOp(Instruction::Xor, Op0, Op1, Instruction::And,
968 // Threading Xor over selects and phi nodes is pointless, so don't bother.
969 // Threading over the select in "A ^ select(cond, B, C)" means evaluating
970 // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
971 // only if B and C are equal. If B and C are equal then (since we assume
972 // that operands have already been simplified) "select(cond, B, C)" should
973 // have been simplified to the common value of B and C already. Analysing
974 // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
975 // for threading over phi nodes.
980 Value *llvm::SimplifyXorInst(Value *Op0, Value *Op1, const TargetData *TD,
981 const DominatorTree *DT) {
982 return ::SimplifyXorInst(Op0, Op1, TD, DT, RecursionLimit);
985 static const Type *GetCompareTy(Value *Op) {
986 return CmpInst::makeCmpResultType(Op->getType());
989 /// SimplifyICmpInst - Given operands for an ICmpInst, see if we can
990 /// fold the result. If not, this returns null.
991 static Value *SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
992 const TargetData *TD, const DominatorTree *DT,
993 unsigned MaxRecurse) {
994 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
995 assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
997 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
998 if (Constant *CRHS = dyn_cast<Constant>(RHS))
999 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
1001 // If we have a constant, make sure it is on the RHS.
1002 std::swap(LHS, RHS);
1003 Pred = CmpInst::getSwappedPredicate(Pred);
1006 // ITy - This is the return type of the compare we're considering.
1007 const Type *ITy = GetCompareTy(LHS);
1009 // icmp X, X -> true/false
1010 // X icmp undef -> true/false. For example, icmp ugt %X, undef -> false
1011 // because X could be 0.
1012 if (isa<UndefValue>(RHS) || equal(LHS, RHS, MaxRecurse))
1013 return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
1015 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
1016 // addresses never equal each other! We already know that Op0 != Op1.
1017 if ((isa<GlobalValue>(LHS) || isa<AllocaInst>(LHS) ||
1018 isa<ConstantPointerNull>(LHS)) &&
1019 (isa<GlobalValue>(RHS) || isa<AllocaInst>(RHS) ||
1020 isa<ConstantPointerNull>(RHS)))
1021 return ConstantInt::get(ITy, CmpInst::isFalseWhenEqual(Pred));
1023 // See if we are doing a comparison with a constant.
1024 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
1025 // If we have an icmp le or icmp ge instruction, turn it into the
1026 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
1027 // them being folded in the code below.
1030 case ICmpInst::ICMP_ULE:
1031 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
1032 return ConstantInt::getTrue(CI->getContext());
1034 case ICmpInst::ICMP_SLE:
1035 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
1036 return ConstantInt::getTrue(CI->getContext());
1038 case ICmpInst::ICMP_UGE:
1039 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
1040 return ConstantInt::getTrue(CI->getContext());
1042 case ICmpInst::ICMP_SGE:
1043 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
1044 return ConstantInt::getTrue(CI->getContext());
1049 // If the comparison is with the result of a select instruction, check whether
1050 // comparing with either branch of the select always yields the same value.
1051 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
1052 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
1055 // If the comparison is with the result of a phi instruction, check whether
1056 // doing the compare with each incoming phi value yields a common result.
1057 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1058 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
1064 Value *llvm::SimplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1065 const TargetData *TD, const DominatorTree *DT) {
1066 return ::SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
1069 /// SimplifyFCmpInst - Given operands for an FCmpInst, see if we can
1070 /// fold the result. If not, this returns null.
1071 static Value *SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1072 const TargetData *TD, const DominatorTree *DT,
1073 unsigned MaxRecurse) {
1074 CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
1075 assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
1077 if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
1078 if (Constant *CRHS = dyn_cast<Constant>(RHS))
1079 return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, TD);
1081 // If we have a constant, make sure it is on the RHS.
1082 std::swap(LHS, RHS);
1083 Pred = CmpInst::getSwappedPredicate(Pred);
1086 // Fold trivial predicates.
1087 if (Pred == FCmpInst::FCMP_FALSE)
1088 return ConstantInt::get(GetCompareTy(LHS), 0);
1089 if (Pred == FCmpInst::FCMP_TRUE)
1090 return ConstantInt::get(GetCompareTy(LHS), 1);
1092 if (isa<UndefValue>(RHS)) // fcmp pred X, undef -> undef
1093 return UndefValue::get(GetCompareTy(LHS));
1095 // fcmp x,x -> true/false. Not all compares are foldable.
1096 if (equal(LHS, RHS, MaxRecurse)) {
1097 if (CmpInst::isTrueWhenEqual(Pred))
1098 return ConstantInt::get(GetCompareTy(LHS), 1);
1099 if (CmpInst::isFalseWhenEqual(Pred))
1100 return ConstantInt::get(GetCompareTy(LHS), 0);
1103 // Handle fcmp with constant RHS
1104 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1105 // If the constant is a nan, see if we can fold the comparison based on it.
1106 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1107 if (CFP->getValueAPF().isNaN()) {
1108 if (FCmpInst::isOrdered(Pred)) // True "if ordered and foo"
1109 return ConstantInt::getFalse(CFP->getContext());
1110 assert(FCmpInst::isUnordered(Pred) &&
1111 "Comparison must be either ordered or unordered!");
1112 // True if unordered.
1113 return ConstantInt::getTrue(CFP->getContext());
1115 // Check whether the constant is an infinity.
1116 if (CFP->getValueAPF().isInfinity()) {
1117 if (CFP->getValueAPF().isNegative()) {
1119 case FCmpInst::FCMP_OLT:
1120 // No value is ordered and less than negative infinity.
1121 return ConstantInt::getFalse(CFP->getContext());
1122 case FCmpInst::FCMP_UGE:
1123 // All values are unordered with or at least negative infinity.
1124 return ConstantInt::getTrue(CFP->getContext());
1130 case FCmpInst::FCMP_OGT:
1131 // No value is ordered and greater than infinity.
1132 return ConstantInt::getFalse(CFP->getContext());
1133 case FCmpInst::FCMP_ULE:
1134 // All values are unordered with and at most infinity.
1135 return ConstantInt::getTrue(CFP->getContext());
1144 // If the comparison is with the result of a select instruction, check whether
1145 // comparing with either branch of the select always yields the same value.
1146 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
1147 if (Value *V = ThreadCmpOverSelect(Pred, LHS, RHS, TD, DT, MaxRecurse))
1150 // If the comparison is with the result of a phi instruction, check whether
1151 // doing the compare with each incoming phi value yields a common result.
1152 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1153 if (Value *V = ThreadCmpOverPHI(Pred, LHS, RHS, TD, DT, MaxRecurse))
1159 Value *llvm::SimplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1160 const TargetData *TD, const DominatorTree *DT) {
1161 return ::SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
1164 /// SimplifySelectInst - Given operands for a SelectInst, see if we can fold
1165 /// the result. If not, this returns null.
1166 static Value *SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
1167 const TargetData *TD, const DominatorTree *,
1168 unsigned MaxRecurse) {
1169 // select true, X, Y -> X
1170 // select false, X, Y -> Y
1171 if (ConstantInt *CB = dyn_cast<ConstantInt>(CondVal))
1172 return CB->getZExtValue() ? TrueVal : FalseVal;
1174 // select C, X, X -> X
1175 if (equal(TrueVal, FalseVal, MaxRecurse))
1178 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
1180 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
1182 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
1183 if (isa<Constant>(TrueVal))
1191 Value *llvm::SimplifySelectInst(Value *CondVal, Value *TrueVal, Value *FalseVal,
1192 const TargetData *TD, const DominatorTree *DT) {
1193 return ::SimplifySelectInst(CondVal, TrueVal, FalseVal, TD, DT,
1197 /// SimplifyGEPInst - Given operands for an GetElementPtrInst, see if we can
1198 /// fold the result. If not, this returns null.
1199 Value *llvm::SimplifyGEPInst(Value *const *Ops, unsigned NumOps,
1200 const TargetData *TD, const DominatorTree *) {
1201 // The type of the GEP pointer operand.
1202 const PointerType *PtrTy = cast<PointerType>(Ops[0]->getType());
1204 // getelementptr P -> P.
1208 if (isa<UndefValue>(Ops[0])) {
1209 // Compute the (pointer) type returned by the GEP instruction.
1210 const Type *LastType = GetElementPtrInst::getIndexedType(PtrTy, &Ops[1],
1212 const Type *GEPTy = PointerType::get(LastType, PtrTy->getAddressSpace());
1213 return UndefValue::get(GEPTy);
1217 // getelementptr P, 0 -> P.
1218 if (ConstantInt *C = dyn_cast<ConstantInt>(Ops[1]))
1221 // getelementptr P, N -> P if P points to a type of zero size.
1223 const Type *Ty = PtrTy->getElementType();
1224 if (Ty->isSized() && TD->getTypeAllocSize(Ty) == 0)
1229 // Check to see if this is constant foldable.
1230 for (unsigned i = 0; i != NumOps; ++i)
1231 if (!isa<Constant>(Ops[i]))
1234 return ConstantExpr::getGetElementPtr(cast<Constant>(Ops[0]),
1235 (Constant *const*)Ops+1, NumOps-1);
1238 /// SimplifyPHINode - See if we can fold the given phi. If not, returns null.
1239 static Value *SimplifyPHINode(PHINode *PN, const DominatorTree *DT) {
1240 // If all of the PHI's incoming values are the same then replace the PHI node
1241 // with the common value.
1242 Value *CommonValue = 0;
1243 bool HasUndefInput = false;
1244 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1245 Value *Incoming = PN->getIncomingValue(i);
1246 // If the incoming value is the phi node itself, it can safely be skipped.
1247 if (Incoming == PN) continue;
1248 if (isa<UndefValue>(Incoming)) {
1249 // Remember that we saw an undef value, but otherwise ignore them.
1250 HasUndefInput = true;
1253 if (CommonValue && Incoming != CommonValue)
1254 return 0; // Not the same, bail out.
1255 CommonValue = Incoming;
1258 // If CommonValue is null then all of the incoming values were either undef or
1259 // equal to the phi node itself.
1261 return UndefValue::get(PN->getType());
1263 // If we have a PHI node like phi(X, undef, X), where X is defined by some
1264 // instruction, we cannot return X as the result of the PHI node unless it
1265 // dominates the PHI block.
1267 return ValueDominatesPHI(CommonValue, PN, DT) ? CommonValue : 0;
1273 //=== Helper functions for higher up the class hierarchy.
1275 /// SimplifyBinOp - Given operands for a BinaryOperator, see if we can
1276 /// fold the result. If not, this returns null.
1277 static Value *SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
1278 const TargetData *TD, const DominatorTree *DT,
1279 unsigned MaxRecurse) {
1281 case Instruction::Add: return SimplifyAddInst(LHS, RHS, /* isNSW */ false,
1282 /* isNUW */ false, TD, DT,
1284 case Instruction::Sub: return SimplifySubInst(LHS, RHS, /* isNSW */ false,
1285 /* isNUW */ false, TD, DT,
1287 case Instruction::Mul: return SimplifyMulInst(LHS, RHS, TD, DT, MaxRecurse);
1288 case Instruction::And: return SimplifyAndInst(LHS, RHS, TD, DT, MaxRecurse);
1289 case Instruction::Or: return SimplifyOrInst(LHS, RHS, TD, DT, MaxRecurse);
1290 case Instruction::Xor: return SimplifyXorInst(LHS, RHS, TD, DT, MaxRecurse);
1292 if (Constant *CLHS = dyn_cast<Constant>(LHS))
1293 if (Constant *CRHS = dyn_cast<Constant>(RHS)) {
1294 Constant *COps[] = {CLHS, CRHS};
1295 return ConstantFoldInstOperands(Opcode, LHS->getType(), COps, 2, TD);
1298 // If the operation is associative, try some generic simplifications.
1299 if (Instruction::isAssociative(Opcode))
1300 if (Value *V = SimplifyAssociativeBinOp(Opcode, LHS, RHS, TD, DT,
1304 // If the operation is with the result of a select instruction, check whether
1305 // operating on either branch of the select always yields the same value.
1306 if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
1307 if (Value *V = ThreadBinOpOverSelect(Opcode, LHS, RHS, TD, DT,
1311 // If the operation is with the result of a phi instruction, check whether
1312 // operating on all incoming values of the phi always yields the same value.
1313 if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
1314 if (Value *V = ThreadBinOpOverPHI(Opcode, LHS, RHS, TD, DT, MaxRecurse))
1321 Value *llvm::SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
1322 const TargetData *TD, const DominatorTree *DT) {
1323 return ::SimplifyBinOp(Opcode, LHS, RHS, TD, DT, RecursionLimit);
1326 /// SimplifyCmpInst - Given operands for a CmpInst, see if we can
1327 /// fold the result.
1328 static Value *SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1329 const TargetData *TD, const DominatorTree *DT,
1330 unsigned MaxRecurse) {
1331 if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
1332 return SimplifyICmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
1333 return SimplifyFCmpInst(Predicate, LHS, RHS, TD, DT, MaxRecurse);
1336 Value *llvm::SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
1337 const TargetData *TD, const DominatorTree *DT) {
1338 return ::SimplifyCmpInst(Predicate, LHS, RHS, TD, DT, RecursionLimit);
1341 /// SimplifyInstruction - See if we can compute a simplified version of this
1342 /// instruction. If not, this returns null.
1343 Value *llvm::SimplifyInstruction(Instruction *I, const TargetData *TD,
1344 const DominatorTree *DT) {
1347 switch (I->getOpcode()) {
1349 Result = ConstantFoldInstruction(I, TD);
1351 case Instruction::Add:
1352 Result = SimplifyAddInst(I->getOperand(0), I->getOperand(1),
1353 cast<BinaryOperator>(I)->hasNoSignedWrap(),
1354 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
1357 case Instruction::Sub:
1358 Result = SimplifySubInst(I->getOperand(0), I->getOperand(1),
1359 cast<BinaryOperator>(I)->hasNoSignedWrap(),
1360 cast<BinaryOperator>(I)->hasNoUnsignedWrap(),
1363 case Instruction::Mul:
1364 Result = SimplifyMulInst(I->getOperand(0), I->getOperand(1), TD, DT);
1366 case Instruction::And:
1367 Result = SimplifyAndInst(I->getOperand(0), I->getOperand(1), TD, DT);
1369 case Instruction::Or:
1370 Result = SimplifyOrInst(I->getOperand(0), I->getOperand(1), TD, DT);
1372 case Instruction::Xor:
1373 Result = SimplifyXorInst(I->getOperand(0), I->getOperand(1), TD, DT);
1375 case Instruction::ICmp:
1376 Result = SimplifyICmpInst(cast<ICmpInst>(I)->getPredicate(),
1377 I->getOperand(0), I->getOperand(1), TD, DT);
1379 case Instruction::FCmp:
1380 Result = SimplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(),
1381 I->getOperand(0), I->getOperand(1), TD, DT);
1383 case Instruction::Select:
1384 Result = SimplifySelectInst(I->getOperand(0), I->getOperand(1),
1385 I->getOperand(2), TD, DT);
1387 case Instruction::GetElementPtr: {
1388 SmallVector<Value*, 8> Ops(I->op_begin(), I->op_end());
1389 Result = SimplifyGEPInst(&Ops[0], Ops.size(), TD, DT);
1392 case Instruction::PHI:
1393 Result = SimplifyPHINode(cast<PHINode>(I), DT);
1397 /// If called on unreachable code, the above logic may report that the
1398 /// instruction simplified to itself. Make life easier for users by
1399 /// detecting that case here, returning a safe value instead.
1400 return Result == I ? UndefValue::get(I->getType()) : Result;
1403 /// ReplaceAndSimplifyAllUses - Perform From->replaceAllUsesWith(To) and then
1404 /// delete the From instruction. In addition to a basic RAUW, this does a
1405 /// recursive simplification of the newly formed instructions. This catches
1406 /// things where one simplification exposes other opportunities. This only
1407 /// simplifies and deletes scalar operations, it does not change the CFG.
1409 void llvm::ReplaceAndSimplifyAllUses(Instruction *From, Value *To,
1410 const TargetData *TD,
1411 const DominatorTree *DT) {
1412 assert(From != To && "ReplaceAndSimplifyAllUses(X,X) is not valid!");
1414 // FromHandle/ToHandle - This keeps a WeakVH on the from/to values so that
1415 // we can know if it gets deleted out from under us or replaced in a
1416 // recursive simplification.
1417 WeakVH FromHandle(From);
1418 WeakVH ToHandle(To);
1420 while (!From->use_empty()) {
1421 // Update the instruction to use the new value.
1422 Use &TheUse = From->use_begin().getUse();
1423 Instruction *User = cast<Instruction>(TheUse.getUser());
1426 // Check to see if the instruction can be folded due to the operand
1427 // replacement. For example changing (or X, Y) into (or X, -1) can replace
1428 // the 'or' with -1.
1429 Value *SimplifiedVal;
1431 // Sanity check to make sure 'User' doesn't dangle across
1432 // SimplifyInstruction.
1433 AssertingVH<> UserHandle(User);
1435 SimplifiedVal = SimplifyInstruction(User, TD, DT);
1436 if (SimplifiedVal == 0) continue;
1439 // Recursively simplify this user to the new value.
1440 ReplaceAndSimplifyAllUses(User, SimplifiedVal, TD, DT);
1441 From = dyn_cast_or_null<Instruction>((Value*)FromHandle);
1444 assert(ToHandle && "To value deleted by recursive simplification?");
1446 // If the recursive simplification ended up revisiting and deleting
1447 // 'From' then we're done.
1452 // If 'From' has value handles referring to it, do a real RAUW to update them.
1453 From->replaceAllUsesWith(To);
1455 From->eraseFromParent();