1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
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 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions. This pass does not modify the CFG. This pass is where
12 // algebraic simplification happens.
14 // This pass combines things like:
20 // This is a simple worklist driven algorithm.
22 // This pass guarantees that the following canonicalizations are performed on
24 // 1. If a binary operator has a constant operand, it is moved to the RHS
25 // 2. Bitwise operators with constant operands are always grouped so that
26 // shifts are performed first, then or's, then and's, then xor's.
27 // 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All cmp instructions on boolean values are replaced with logical ops
29 // 5. add X, X is represented as (X*2) => (X << 1)
30 // 6. Multiplies with a power-of-two constant argument are transformed into
34 //===----------------------------------------------------------------------===//
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "InstCombine.h"
39 #include "llvm/IntrinsicInst.h"
40 #include "llvm/Analysis/ConstantFolding.h"
41 #include "llvm/Analysis/InstructionSimplify.h"
42 #include "llvm/Analysis/MemoryBuiltins.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Target/TargetLibraryInfo.h"
45 #include "llvm/Transforms/Utils/Local.h"
46 #include "llvm/Support/CFG.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/GetElementPtrTypeIterator.h"
49 #include "llvm/Support/PatternMatch.h"
50 #include "llvm/Support/ValueHandle.h"
51 #include "llvm/ADT/SmallPtrSet.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/ADT/StringSwitch.h"
54 #include "llvm-c/Initialization.h"
58 using namespace llvm::PatternMatch;
60 STATISTIC(NumCombined , "Number of insts combined");
61 STATISTIC(NumConstProp, "Number of constant folds");
62 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
63 STATISTIC(NumSunkInst , "Number of instructions sunk");
64 STATISTIC(NumExpand, "Number of expansions");
65 STATISTIC(NumFactor , "Number of factorizations");
66 STATISTIC(NumReassoc , "Number of reassociations");
68 // Initialization Routines
69 void llvm::initializeInstCombine(PassRegistry &Registry) {
70 initializeInstCombinerPass(Registry);
73 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
74 initializeInstCombine(*unwrap(R));
77 char InstCombiner::ID = 0;
78 INITIALIZE_PASS_BEGIN(InstCombiner, "instcombine",
79 "Combine redundant instructions", false, false)
80 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
81 INITIALIZE_PASS_END(InstCombiner, "instcombine",
82 "Combine redundant instructions", false, false)
84 void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
86 AU.addRequired<TargetLibraryInfo>();
90 /// ShouldChangeType - Return true if it is desirable to convert a computation
91 /// from 'From' to 'To'. We don't want to convert from a legal to an illegal
92 /// type for example, or from a smaller to a larger illegal type.
93 bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
94 assert(From->isIntegerTy() && To->isIntegerTy());
96 // If we don't have TD, we don't know if the source/dest are legal.
97 if (!TD) return false;
99 unsigned FromWidth = From->getPrimitiveSizeInBits();
100 unsigned ToWidth = To->getPrimitiveSizeInBits();
101 bool FromLegal = TD->isLegalInteger(FromWidth);
102 bool ToLegal = TD->isLegalInteger(ToWidth);
104 // If this is a legal integer from type, and the result would be an illegal
105 // type, don't do the transformation.
106 if (FromLegal && !ToLegal)
109 // Otherwise, if both are illegal, do not increase the size of the result. We
110 // do allow things like i160 -> i64, but not i64 -> i160.
111 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
117 // Return true, if No Signed Wrap should be maintained for I.
118 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
119 // where both B and C should be ConstantInts, results in a constant that does
120 // not overflow. This function only handles the Add and Sub opcodes. For
121 // all other opcodes, the function conservatively returns false.
122 static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
123 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
124 if (!OBO || !OBO->hasNoSignedWrap()) {
128 // We reason about Add and Sub Only.
129 Instruction::BinaryOps Opcode = I.getOpcode();
130 if (Opcode != Instruction::Add &&
131 Opcode != Instruction::Sub) {
135 ConstantInt *CB = dyn_cast<ConstantInt>(B);
136 ConstantInt *CC = dyn_cast<ConstantInt>(C);
142 const APInt &BVal = CB->getValue();
143 const APInt &CVal = CC->getValue();
144 bool Overflow = false;
146 if (Opcode == Instruction::Add) {
147 BVal.sadd_ov(CVal, Overflow);
149 BVal.ssub_ov(CVal, Overflow);
155 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
156 /// operators which are associative or commutative:
158 // Commutative operators:
160 // 1. Order operands such that they are listed from right (least complex) to
161 // left (most complex). This puts constants before unary operators before
164 // Associative operators:
166 // 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
167 // 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
169 // Associative and commutative operators:
171 // 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
172 // 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
173 // 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
174 // if C1 and C2 are constants.
176 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
177 Instruction::BinaryOps Opcode = I.getOpcode();
178 bool Changed = false;
181 // Order operands such that they are listed from right (least complex) to
182 // left (most complex). This puts constants before unary operators before
184 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
185 getComplexity(I.getOperand(1)))
186 Changed = !I.swapOperands();
188 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
189 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
191 if (I.isAssociative()) {
192 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
193 if (Op0 && Op0->getOpcode() == Opcode) {
194 Value *A = Op0->getOperand(0);
195 Value *B = Op0->getOperand(1);
196 Value *C = I.getOperand(1);
198 // Does "B op C" simplify?
199 if (Value *V = SimplifyBinOp(Opcode, B, C, TD)) {
200 // It simplifies to V. Form "A op V".
203 // Conservatively clear the optional flags, since they may not be
204 // preserved by the reassociation.
205 if (MaintainNoSignedWrap(I, B, C) &&
206 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
207 // Note: this is only valid because SimplifyBinOp doesn't look at
208 // the operands to Op0.
209 I.clearSubclassOptionalData();
210 I.setHasNoSignedWrap(true);
212 I.clearSubclassOptionalData();
221 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
222 if (Op1 && Op1->getOpcode() == Opcode) {
223 Value *A = I.getOperand(0);
224 Value *B = Op1->getOperand(0);
225 Value *C = Op1->getOperand(1);
227 // Does "A op B" simplify?
228 if (Value *V = SimplifyBinOp(Opcode, A, B, TD)) {
229 // It simplifies to V. Form "V op C".
232 // Conservatively clear the optional flags, since they may not be
233 // preserved by the reassociation.
234 I.clearSubclassOptionalData();
242 if (I.isAssociative() && I.isCommutative()) {
243 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
244 if (Op0 && Op0->getOpcode() == Opcode) {
245 Value *A = Op0->getOperand(0);
246 Value *B = Op0->getOperand(1);
247 Value *C = I.getOperand(1);
249 // Does "C op A" simplify?
250 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
251 // It simplifies to V. Form "V op B".
254 // Conservatively clear the optional flags, since they may not be
255 // preserved by the reassociation.
256 I.clearSubclassOptionalData();
263 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
264 if (Op1 && Op1->getOpcode() == Opcode) {
265 Value *A = I.getOperand(0);
266 Value *B = Op1->getOperand(0);
267 Value *C = Op1->getOperand(1);
269 // Does "C op A" simplify?
270 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
271 // It simplifies to V. Form "B op V".
274 // Conservatively clear the optional flags, since they may not be
275 // preserved by the reassociation.
276 I.clearSubclassOptionalData();
283 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
284 // if C1 and C2 are constants.
286 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
287 isa<Constant>(Op0->getOperand(1)) &&
288 isa<Constant>(Op1->getOperand(1)) &&
289 Op0->hasOneUse() && Op1->hasOneUse()) {
290 Value *A = Op0->getOperand(0);
291 Constant *C1 = cast<Constant>(Op0->getOperand(1));
292 Value *B = Op1->getOperand(0);
293 Constant *C2 = cast<Constant>(Op1->getOperand(1));
295 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
296 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
297 InsertNewInstWith(New, I);
299 I.setOperand(0, New);
300 I.setOperand(1, Folded);
301 // Conservatively clear the optional flags, since they may not be
302 // preserved by the reassociation.
303 I.clearSubclassOptionalData();
310 // No further simplifications.
315 /// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
316 /// "(X LOp Y) ROp (X LOp Z)".
317 static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
318 Instruction::BinaryOps ROp) {
323 case Instruction::And:
324 // And distributes over Or and Xor.
328 case Instruction::Or:
329 case Instruction::Xor:
333 case Instruction::Mul:
334 // Multiplication distributes over addition and subtraction.
338 case Instruction::Add:
339 case Instruction::Sub:
343 case Instruction::Or:
344 // Or distributes over And.
348 case Instruction::And:
354 /// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
355 /// "(X ROp Z) LOp (Y ROp Z)".
356 static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
357 Instruction::BinaryOps ROp) {
358 if (Instruction::isCommutative(ROp))
359 return LeftDistributesOverRight(ROp, LOp);
360 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
361 // but this requires knowing that the addition does not overflow and other
366 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
367 /// which some other binary operation distributes over either by factorizing
368 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
369 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
370 /// a win). Returns the simplified value, or null if it didn't simplify.
371 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
372 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
373 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
374 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
375 Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); // op
378 if (Op0 && Op1 && Op0->getOpcode() == Op1->getOpcode()) {
379 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
381 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
382 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
383 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
385 // Does "X op' Y" always equal "Y op' X"?
386 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
388 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
389 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
390 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
391 // commutative case, "(A op' B) op (C op' A)"?
392 if (A == C || (InnerCommutative && A == D)) {
395 // Consider forming "A op' (B op D)".
396 // If "B op D" simplifies then it can be formed with no cost.
397 Value *V = SimplifyBinOp(TopLevelOpcode, B, D, TD);
398 // If "B op D" doesn't simplify then only go on if both of the existing
399 // operations "A op' B" and "C op' D" will be zapped as no longer used.
400 if (!V && Op0->hasOneUse() && Op1->hasOneUse())
401 V = Builder->CreateBinOp(TopLevelOpcode, B, D, Op1->getName());
404 V = Builder->CreateBinOp(InnerOpcode, A, V);
410 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
411 if (RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
412 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
413 // commutative case, "(A op' B) op (B op' D)"?
414 if (B == D || (InnerCommutative && B == C)) {
417 // Consider forming "(A op C) op' B".
418 // If "A op C" simplifies then it can be formed with no cost.
419 Value *V = SimplifyBinOp(TopLevelOpcode, A, C, TD);
420 // If "A op C" doesn't simplify then only go on if both of the existing
421 // operations "A op' B" and "C op' D" will be zapped as no longer used.
422 if (!V && Op0->hasOneUse() && Op1->hasOneUse())
423 V = Builder->CreateBinOp(TopLevelOpcode, A, C, Op0->getName());
426 V = Builder->CreateBinOp(InnerOpcode, V, B);
434 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
435 // The instruction has the form "(A op' B) op C". See if expanding it out
436 // to "(A op C) op' (B op C)" results in simplifications.
437 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
438 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
440 // Do "A op C" and "B op C" both simplify?
441 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, TD))
442 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, TD)) {
443 // They do! Return "L op' R".
445 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
446 if ((L == A && R == B) ||
447 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
449 // Otherwise return "L op' R" if it simplifies.
450 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
452 // Otherwise, create a new instruction.
453 C = Builder->CreateBinOp(InnerOpcode, L, R);
459 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
460 // The instruction has the form "A op (B op' C)". See if expanding it out
461 // to "(A op B) op' (A op C)" results in simplifications.
462 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
463 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
465 // Do "A op B" and "A op C" both simplify?
466 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, TD))
467 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, TD)) {
468 // They do! Return "L op' R".
470 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
471 if ((L == B && R == C) ||
472 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
474 // Otherwise return "L op' R" if it simplifies.
475 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
477 // Otherwise, create a new instruction.
478 A = Builder->CreateBinOp(InnerOpcode, L, R);
487 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
488 // if the LHS is a constant zero (which is the 'negate' form).
490 Value *InstCombiner::dyn_castNegVal(Value *V) const {
491 if (BinaryOperator::isNeg(V))
492 return BinaryOperator::getNegArgument(V);
494 // Constants can be considered to be negated values if they can be folded.
495 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
496 return ConstantExpr::getNeg(C);
498 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
499 if (C->getType()->getElementType()->isIntegerTy())
500 return ConstantExpr::getNeg(C);
505 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
506 // instruction if the LHS is a constant negative zero (which is the 'negate'
509 Value *InstCombiner::dyn_castFNegVal(Value *V) const {
510 if (BinaryOperator::isFNeg(V))
511 return BinaryOperator::getFNegArgument(V);
513 // Constants can be considered to be negated values if they can be folded.
514 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
515 return ConstantExpr::getFNeg(C);
517 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
518 if (C->getType()->getElementType()->isFloatingPointTy())
519 return ConstantExpr::getFNeg(C);
524 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
526 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
527 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
530 // Figure out if the constant is the left or the right argument.
531 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
532 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
534 if (Constant *SOC = dyn_cast<Constant>(SO)) {
536 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
537 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
540 Value *Op0 = SO, *Op1 = ConstOperand;
544 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
545 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
546 SO->getName()+".op");
547 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
548 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
549 SO->getName()+".cmp");
550 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
551 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
552 SO->getName()+".cmp");
553 llvm_unreachable("Unknown binary instruction type!");
556 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
557 // constant as the other operand, try to fold the binary operator into the
558 // select arguments. This also works for Cast instructions, which obviously do
559 // not have a second operand.
560 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
561 // Don't modify shared select instructions
562 if (!SI->hasOneUse()) return 0;
563 Value *TV = SI->getOperand(1);
564 Value *FV = SI->getOperand(2);
566 if (isa<Constant>(TV) || isa<Constant>(FV)) {
567 // Bool selects with constant operands can be folded to logical ops.
568 if (SI->getType()->isIntegerTy(1)) return 0;
570 // If it's a bitcast involving vectors, make sure it has the same number of
571 // elements on both sides.
572 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
573 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
574 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
576 // Verify that either both or neither are vectors.
577 if ((SrcTy == NULL) != (DestTy == NULL)) return 0;
578 // If vectors, verify that they have the same number of elements.
579 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
583 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
584 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
586 return SelectInst::Create(SI->getCondition(),
587 SelectTrueVal, SelectFalseVal);
593 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
594 /// has a PHI node as operand #0, see if we can fold the instruction into the
595 /// PHI (which is only possible if all operands to the PHI are constants).
597 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
598 PHINode *PN = cast<PHINode>(I.getOperand(0));
599 unsigned NumPHIValues = PN->getNumIncomingValues();
600 if (NumPHIValues == 0)
603 // We normally only transform phis with a single use. However, if a PHI has
604 // multiple uses and they are all the same operation, we can fold *all* of the
605 // uses into the PHI.
606 if (!PN->hasOneUse()) {
607 // Walk the use list for the instruction, comparing them to I.
608 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
610 Instruction *User = cast<Instruction>(*UI);
611 if (User != &I && !I.isIdenticalTo(User))
614 // Otherwise, we can replace *all* users with the new PHI we form.
617 // Check to see if all of the operands of the PHI are simple constants
618 // (constantint/constantfp/undef). If there is one non-constant value,
619 // remember the BB it is in. If there is more than one or if *it* is a PHI,
620 // bail out. We don't do arbitrary constant expressions here because moving
621 // their computation can be expensive without a cost model.
622 BasicBlock *NonConstBB = 0;
623 for (unsigned i = 0; i != NumPHIValues; ++i) {
624 Value *InVal = PN->getIncomingValue(i);
625 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
628 if (isa<PHINode>(InVal)) return 0; // Itself a phi.
629 if (NonConstBB) return 0; // More than one non-const value.
631 NonConstBB = PN->getIncomingBlock(i);
633 // If the InVal is an invoke at the end of the pred block, then we can't
634 // insert a computation after it without breaking the edge.
635 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
636 if (II->getParent() == NonConstBB)
639 // If the incoming non-constant value is in I's block, we will remove one
640 // instruction, but insert another equivalent one, leading to infinite
642 if (NonConstBB == I.getParent())
646 // If there is exactly one non-constant value, we can insert a copy of the
647 // operation in that block. However, if this is a critical edge, we would be
648 // inserting the computation one some other paths (e.g. inside a loop). Only
649 // do this if the pred block is unconditionally branching into the phi block.
650 if (NonConstBB != 0) {
651 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
652 if (!BI || !BI->isUnconditional()) return 0;
655 // Okay, we can do the transformation: create the new PHI node.
656 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
657 InsertNewInstBefore(NewPN, *PN);
660 // If we are going to have to insert a new computation, do so right before the
661 // predecessors terminator.
663 Builder->SetInsertPoint(NonConstBB->getTerminator());
665 // Next, add all of the operands to the PHI.
666 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
667 // We only currently try to fold the condition of a select when it is a phi,
668 // not the true/false values.
669 Value *TrueV = SI->getTrueValue();
670 Value *FalseV = SI->getFalseValue();
671 BasicBlock *PhiTransBB = PN->getParent();
672 for (unsigned i = 0; i != NumPHIValues; ++i) {
673 BasicBlock *ThisBB = PN->getIncomingBlock(i);
674 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
675 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
677 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
678 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
680 InV = Builder->CreateSelect(PN->getIncomingValue(i),
681 TrueVInPred, FalseVInPred, "phitmp");
682 NewPN->addIncoming(InV, ThisBB);
684 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
685 Constant *C = cast<Constant>(I.getOperand(1));
686 for (unsigned i = 0; i != NumPHIValues; ++i) {
688 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
689 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
690 else if (isa<ICmpInst>(CI))
691 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
694 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
696 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
698 } else if (I.getNumOperands() == 2) {
699 Constant *C = cast<Constant>(I.getOperand(1));
700 for (unsigned i = 0; i != NumPHIValues; ++i) {
702 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
703 InV = ConstantExpr::get(I.getOpcode(), InC, C);
705 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
706 PN->getIncomingValue(i), C, "phitmp");
707 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
710 CastInst *CI = cast<CastInst>(&I);
711 Type *RetTy = CI->getType();
712 for (unsigned i = 0; i != NumPHIValues; ++i) {
714 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
715 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
717 InV = Builder->CreateCast(CI->getOpcode(),
718 PN->getIncomingValue(i), I.getType(), "phitmp");
719 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
723 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
725 Instruction *User = cast<Instruction>(*UI++);
726 if (User == &I) continue;
727 ReplaceInstUsesWith(*User, NewPN);
728 EraseInstFromFunction(*User);
730 return ReplaceInstUsesWith(I, NewPN);
733 /// FindElementAtOffset - Given a type and a constant offset, determine whether
734 /// or not there is a sequence of GEP indices into the type that will land us at
735 /// the specified offset. If so, fill them into NewIndices and return the
736 /// resultant element type, otherwise return null.
737 Type *InstCombiner::FindElementAtOffset(Type *Ty, int64_t Offset,
738 SmallVectorImpl<Value*> &NewIndices) {
740 if (!Ty->isSized()) return 0;
742 // Start with the index over the outer type. Note that the type size
743 // might be zero (even if the offset isn't zero) if the indexed type
744 // is something like [0 x {int, int}]
745 Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
746 int64_t FirstIdx = 0;
747 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
748 FirstIdx = Offset/TySize;
749 Offset -= FirstIdx*TySize;
751 // Handle hosts where % returns negative instead of values [0..TySize).
757 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
760 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
762 // Index into the types. If we fail, set OrigBase to null.
764 // Indexing into tail padding between struct/array elements.
765 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
768 if (StructType *STy = dyn_cast<StructType>(Ty)) {
769 const StructLayout *SL = TD->getStructLayout(STy);
770 assert(Offset < (int64_t)SL->getSizeInBytes() &&
771 "Offset must stay within the indexed type");
773 unsigned Elt = SL->getElementContainingOffset(Offset);
774 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
777 Offset -= SL->getElementOffset(Elt);
778 Ty = STy->getElementType(Elt);
779 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
780 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
781 assert(EltSize && "Cannot index into a zero-sized array");
782 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
784 Ty = AT->getElementType();
786 // Otherwise, we can't index into the middle of this atomic type, bail.
794 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
795 // If this GEP has only 0 indices, it is the same pointer as
796 // Src. If Src is not a trivial GEP too, don't combine
798 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
804 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
805 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
807 if (Value *V = SimplifyGEPInst(Ops, TD))
808 return ReplaceInstUsesWith(GEP, V);
810 Value *PtrOp = GEP.getOperand(0);
812 // Eliminate unneeded casts for indices, and replace indices which displace
813 // by multiples of a zero size type with zero.
815 bool MadeChange = false;
816 Type *IntPtrTy = TD->getIntPtrType(GEP.getContext());
818 gep_type_iterator GTI = gep_type_begin(GEP);
819 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
820 I != E; ++I, ++GTI) {
821 // Skip indices into struct types.
822 SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
823 if (!SeqTy) continue;
825 // If the element type has zero size then any index over it is equivalent
826 // to an index of zero, so replace it with zero if it is not zero already.
827 if (SeqTy->getElementType()->isSized() &&
828 TD->getTypeAllocSize(SeqTy->getElementType()) == 0)
829 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
830 *I = Constant::getNullValue(IntPtrTy);
834 if ((*I)->getType() != IntPtrTy) {
835 // If we are using a wider index than needed for this platform, shrink
836 // it to what we need. If narrower, sign-extend it to what we need.
837 // This explicit cast can make subsequent optimizations more obvious.
838 *I = Builder->CreateIntCast(*I, IntPtrTy, true);
842 if (MadeChange) return &GEP;
845 // Combine Indices - If the source pointer to this getelementptr instruction
846 // is a getelementptr instruction, combine the indices of the two
847 // getelementptr instructions into a single instruction.
849 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
850 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
853 // Note that if our source is a gep chain itself that we wait for that
854 // chain to be resolved before we perform this transformation. This
855 // avoids us creating a TON of code in some cases.
856 if (GEPOperator *SrcGEP =
857 dyn_cast<GEPOperator>(Src->getOperand(0)))
858 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
859 return 0; // Wait until our source is folded to completion.
861 SmallVector<Value*, 8> Indices;
863 // Find out whether the last index in the source GEP is a sequential idx.
864 bool EndsWithSequential = false;
865 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
867 EndsWithSequential = !(*I)->isStructTy();
869 // Can we combine the two pointer arithmetics offsets?
870 if (EndsWithSequential) {
871 // Replace: gep (gep %P, long B), long A, ...
872 // With: T = long A+B; gep %P, T, ...
875 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
876 Value *GO1 = GEP.getOperand(1);
877 if (SO1 == Constant::getNullValue(SO1->getType())) {
879 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
882 // If they aren't the same type, then the input hasn't been processed
883 // by the loop above yet (which canonicalizes sequential index types to
884 // intptr_t). Just avoid transforming this until the input has been
886 if (SO1->getType() != GO1->getType())
888 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
891 // Update the GEP in place if possible.
892 if (Src->getNumOperands() == 2) {
893 GEP.setOperand(0, Src->getOperand(0));
894 GEP.setOperand(1, Sum);
897 Indices.append(Src->op_begin()+1, Src->op_end()-1);
898 Indices.push_back(Sum);
899 Indices.append(GEP.op_begin()+2, GEP.op_end());
900 } else if (isa<Constant>(*GEP.idx_begin()) &&
901 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
902 Src->getNumOperands() != 1) {
903 // Otherwise we can do the fold if the first index of the GEP is a zero
904 Indices.append(Src->op_begin()+1, Src->op_end());
905 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
908 if (!Indices.empty())
909 return (GEP.isInBounds() && Src->isInBounds()) ?
910 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices,
912 GetElementPtrInst::Create(Src->getOperand(0), Indices, GEP.getName());
915 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
916 Value *StrippedPtr = PtrOp->stripPointerCasts();
917 PointerType *StrippedPtrTy =cast<PointerType>(StrippedPtr->getType());
918 if (StrippedPtr != PtrOp &&
919 StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace()) {
921 bool HasZeroPointerIndex = false;
922 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
923 HasZeroPointerIndex = C->isZero();
925 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
926 // into : GEP [10 x i8]* X, i32 0, ...
928 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
929 // into : GEP i8* X, ...
931 // This occurs when the program declares an array extern like "int X[];"
932 if (HasZeroPointerIndex) {
933 PointerType *CPTy = cast<PointerType>(PtrOp->getType());
934 if (ArrayType *CATy =
935 dyn_cast<ArrayType>(CPTy->getElementType())) {
936 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
937 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
939 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
940 GetElementPtrInst *Res =
941 GetElementPtrInst::Create(StrippedPtr, Idx, GEP.getName());
942 Res->setIsInBounds(GEP.isInBounds());
946 if (ArrayType *XATy =
947 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
948 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
949 if (CATy->getElementType() == XATy->getElementType()) {
950 // -> GEP [10 x i8]* X, i32 0, ...
951 // At this point, we know that the cast source type is a pointer
952 // to an array of the same type as the destination pointer
953 // array. Because the array type is never stepped over (there
954 // is a leading zero) we can fold the cast into this GEP.
955 GEP.setOperand(0, StrippedPtr);
960 } else if (GEP.getNumOperands() == 2) {
961 // Transform things like:
962 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
963 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
964 Type *SrcElTy = StrippedPtrTy->getElementType();
965 Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
966 if (TD && SrcElTy->isArrayTy() &&
967 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
968 TD->getTypeAllocSize(ResElTy)) {
970 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
971 Idx[1] = GEP.getOperand(1);
972 Value *NewGEP = GEP.isInBounds() ?
973 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
974 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
975 // V and GEP are both pointer types --> BitCast
976 return new BitCastInst(NewGEP, GEP.getType());
979 // Transform things like:
980 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
981 // (where tmp = 8*tmp2) into:
982 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
984 if (TD && SrcElTy->isArrayTy() && ResElTy->isIntegerTy(8)) {
985 uint64_t ArrayEltSize =
986 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
988 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
989 // allow either a mul, shift, or constant here.
991 ConstantInt *Scale = 0;
992 if (ArrayEltSize == 1) {
993 NewIdx = GEP.getOperand(1);
994 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
995 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
996 NewIdx = ConstantInt::get(CI->getType(), 1);
998 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
999 if (Inst->getOpcode() == Instruction::Shl &&
1000 isa<ConstantInt>(Inst->getOperand(1))) {
1001 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
1002 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
1003 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
1005 NewIdx = Inst->getOperand(0);
1006 } else if (Inst->getOpcode() == Instruction::Mul &&
1007 isa<ConstantInt>(Inst->getOperand(1))) {
1008 Scale = cast<ConstantInt>(Inst->getOperand(1));
1009 NewIdx = Inst->getOperand(0);
1013 // If the index will be to exactly the right offset with the scale taken
1014 // out, perform the transformation. Note, we don't know whether Scale is
1015 // signed or not. We'll use unsigned version of division/modulo
1016 // operation after making sure Scale doesn't have the sign bit set.
1017 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
1018 Scale->getZExtValue() % ArrayEltSize == 0) {
1019 Scale = ConstantInt::get(Scale->getType(),
1020 Scale->getZExtValue() / ArrayEltSize);
1021 if (Scale->getZExtValue() != 1) {
1022 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
1024 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
1027 // Insert the new GEP instruction.
1029 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
1031 Value *NewGEP = GEP.isInBounds() ?
1032 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()):
1033 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
1034 // The NewGEP must be pointer typed, so must the old one -> BitCast
1035 return new BitCastInst(NewGEP, GEP.getType());
1041 /// See if we can simplify:
1042 /// X = bitcast A* to B*
1043 /// Y = gep X, <...constant indices...>
1044 /// into a gep of the original struct. This is important for SROA and alias
1045 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
1046 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
1048 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices() &&
1049 StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace()) {
1051 // Determine how much the GEP moves the pointer. We are guaranteed to get
1052 // a constant back from EmitGEPOffset.
1053 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
1054 int64_t Offset = OffsetV->getSExtValue();
1056 // If this GEP instruction doesn't move the pointer, just replace the GEP
1057 // with a bitcast of the real input to the dest type.
1059 // If the bitcast is of an allocation, and the allocation will be
1060 // converted to match the type of the cast, don't touch this.
1061 if (isa<AllocaInst>(BCI->getOperand(0)) ||
1062 isMalloc(BCI->getOperand(0))) {
1063 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1064 if (Instruction *I = visitBitCast(*BCI)) {
1067 BCI->getParent()->getInstList().insert(BCI, I);
1068 ReplaceInstUsesWith(*BCI, I);
1073 return new BitCastInst(BCI->getOperand(0), GEP.getType());
1076 // Otherwise, if the offset is non-zero, we need to find out if there is a
1077 // field at Offset in 'A's type. If so, we can pull the cast through the
1079 SmallVector<Value*, 8> NewIndices;
1081 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
1082 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
1083 Value *NGEP = GEP.isInBounds() ?
1084 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices) :
1085 Builder->CreateGEP(BCI->getOperand(0), NewIndices);
1087 if (NGEP->getType() == GEP.getType())
1088 return ReplaceInstUsesWith(GEP, NGEP);
1089 NGEP->takeName(&GEP);
1090 return new BitCastInst(NGEP, GEP.getType());
1100 static bool IsOnlyNullComparedAndFreed(Value *V, SmallVectorImpl<WeakVH> &Users,
1105 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end();
1108 if (isFreeCall(U)) {
1112 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U)) {
1113 if (ICI->isEquality() && isa<ConstantPointerNull>(ICI->getOperand(1))) {
1114 Users.push_back(ICI);
1118 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
1119 if (IsOnlyNullComparedAndFreed(BCI, Users, Depth+1)) {
1120 Users.push_back(BCI);
1124 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1125 if (IsOnlyNullComparedAndFreed(GEPI, Users, Depth+1)) {
1126 Users.push_back(GEPI);
1130 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
1131 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
1132 II->getIntrinsicID() == Intrinsic::lifetime_end) {
1133 Users.push_back(II);
1142 Instruction *InstCombiner::visitMalloc(Instruction &MI) {
1143 // If we have a malloc call which is only used in any amount of comparisons
1144 // to null and free calls, delete the calls and replace the comparisons with
1145 // true or false as appropriate.
1146 SmallVector<WeakVH, 64> Users;
1147 if (IsOnlyNullComparedAndFreed(&MI, Users)) {
1148 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1149 Instruction *I = cast_or_null<Instruction>(&*Users[i]);
1152 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
1153 ReplaceInstUsesWith(*C,
1154 ConstantInt::get(Type::getInt1Ty(C->getContext()),
1155 C->isFalseWhenEqual()));
1156 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
1157 ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
1159 EraseInstFromFunction(*I);
1161 return EraseInstFromFunction(MI);
1168 Instruction *InstCombiner::visitFree(CallInst &FI) {
1169 Value *Op = FI.getArgOperand(0);
1171 // free undef -> unreachable.
1172 if (isa<UndefValue>(Op)) {
1173 // Insert a new store to null because we cannot modify the CFG here.
1174 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
1175 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
1176 return EraseInstFromFunction(FI);
1179 // If we have 'free null' delete the instruction. This can happen in stl code
1180 // when lots of inlining happens.
1181 if (isa<ConstantPointerNull>(Op))
1182 return EraseInstFromFunction(FI);
1189 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1190 // Change br (not X), label True, label False to: br X, label False, True
1192 BasicBlock *TrueDest;
1193 BasicBlock *FalseDest;
1194 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
1195 !isa<Constant>(X)) {
1196 // Swap Destinations and condition...
1198 BI.swapSuccessors();
1202 // Cannonicalize fcmp_one -> fcmp_oeq
1203 FCmpInst::Predicate FPred; Value *Y;
1204 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
1205 TrueDest, FalseDest)) &&
1206 BI.getCondition()->hasOneUse())
1207 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
1208 FPred == FCmpInst::FCMP_OGE) {
1209 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
1210 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
1212 // Swap Destinations and condition.
1213 BI.swapSuccessors();
1218 // Cannonicalize icmp_ne -> icmp_eq
1219 ICmpInst::Predicate IPred;
1220 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
1221 TrueDest, FalseDest)) &&
1222 BI.getCondition()->hasOneUse())
1223 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
1224 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
1225 IPred == ICmpInst::ICMP_SGE) {
1226 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
1227 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
1228 // Swap Destinations and condition.
1229 BI.swapSuccessors();
1237 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
1238 Value *Cond = SI.getCondition();
1239 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
1240 if (I->getOpcode() == Instruction::Add)
1241 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1242 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
1243 unsigned NumCases = SI.getNumCases();
1244 // Skip the first item since that's the default case.
1245 for (unsigned i = 1; i < NumCases; ++i) {
1246 ConstantInt* CaseVal = SI.getCaseValue(i);
1247 Constant* NewCaseVal = ConstantExpr::getSub(cast<Constant>(CaseVal),
1249 assert(isa<ConstantInt>(NewCaseVal) &&
1250 "Result of expression should be constant");
1251 SI.setSuccessorValue(i, cast<ConstantInt>(NewCaseVal));
1253 SI.setCondition(I->getOperand(0));
1261 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
1262 Value *Agg = EV.getAggregateOperand();
1264 if (!EV.hasIndices())
1265 return ReplaceInstUsesWith(EV, Agg);
1267 if (Constant *C = dyn_cast<Constant>(Agg)) {
1268 if (isa<UndefValue>(C))
1269 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
1271 if (isa<ConstantAggregateZero>(C))
1272 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
1274 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
1275 // Extract the element indexed by the first index out of the constant
1276 Value *V = C->getOperand(*EV.idx_begin());
1277 if (EV.getNumIndices() > 1)
1278 // Extract the remaining indices out of the constant indexed by the
1280 return ExtractValueInst::Create(V, EV.getIndices().slice(1));
1282 return ReplaceInstUsesWith(EV, V);
1284 return 0; // Can't handle other constants
1286 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
1287 // We're extracting from an insertvalue instruction, compare the indices
1288 const unsigned *exti, *exte, *insi, *inse;
1289 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
1290 exte = EV.idx_end(), inse = IV->idx_end();
1291 exti != exte && insi != inse;
1294 // The insert and extract both reference distinctly different elements.
1295 // This means the extract is not influenced by the insert, and we can
1296 // replace the aggregate operand of the extract with the aggregate
1297 // operand of the insert. i.e., replace
1298 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1299 // %E = extractvalue { i32, { i32 } } %I, 0
1301 // %E = extractvalue { i32, { i32 } } %A, 0
1302 return ExtractValueInst::Create(IV->getAggregateOperand(),
1305 if (exti == exte && insi == inse)
1306 // Both iterators are at the end: Index lists are identical. Replace
1307 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1308 // %C = extractvalue { i32, { i32 } } %B, 1, 0
1310 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
1312 // The extract list is a prefix of the insert list. i.e. replace
1313 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1314 // %E = extractvalue { i32, { i32 } } %I, 1
1316 // %X = extractvalue { i32, { i32 } } %A, 1
1317 // %E = insertvalue { i32 } %X, i32 42, 0
1318 // by switching the order of the insert and extract (though the
1319 // insertvalue should be left in, since it may have other uses).
1320 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
1322 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
1323 makeArrayRef(insi, inse));
1326 // The insert list is a prefix of the extract list
1327 // We can simply remove the common indices from the extract and make it
1328 // operate on the inserted value instead of the insertvalue result.
1330 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1331 // %E = extractvalue { i32, { i32 } } %I, 1, 0
1333 // %E extractvalue { i32 } { i32 42 }, 0
1334 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
1335 makeArrayRef(exti, exte));
1337 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
1338 // We're extracting from an intrinsic, see if we're the only user, which
1339 // allows us to simplify multiple result intrinsics to simpler things that
1340 // just get one value.
1341 if (II->hasOneUse()) {
1342 // Check if we're grabbing the overflow bit or the result of a 'with
1343 // overflow' intrinsic. If it's the latter we can remove the intrinsic
1344 // and replace it with a traditional binary instruction.
1345 switch (II->getIntrinsicID()) {
1346 case Intrinsic::uadd_with_overflow:
1347 case Intrinsic::sadd_with_overflow:
1348 if (*EV.idx_begin() == 0) { // Normal result.
1349 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1350 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
1351 EraseInstFromFunction(*II);
1352 return BinaryOperator::CreateAdd(LHS, RHS);
1355 // If the normal result of the add is dead, and the RHS is a constant,
1356 // we can transform this into a range comparison.
1357 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
1358 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
1359 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
1360 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
1361 ConstantExpr::getNot(CI));
1363 case Intrinsic::usub_with_overflow:
1364 case Intrinsic::ssub_with_overflow:
1365 if (*EV.idx_begin() == 0) { // Normal result.
1366 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1367 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
1368 EraseInstFromFunction(*II);
1369 return BinaryOperator::CreateSub(LHS, RHS);
1372 case Intrinsic::umul_with_overflow:
1373 case Intrinsic::smul_with_overflow:
1374 if (*EV.idx_begin() == 0) { // Normal result.
1375 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1376 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
1377 EraseInstFromFunction(*II);
1378 return BinaryOperator::CreateMul(LHS, RHS);
1386 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
1387 // If the (non-volatile) load only has one use, we can rewrite this to a
1388 // load from a GEP. This reduces the size of the load.
1389 // FIXME: If a load is used only by extractvalue instructions then this
1390 // could be done regardless of having multiple uses.
1391 if (L->isSimple() && L->hasOneUse()) {
1392 // extractvalue has integer indices, getelementptr has Value*s. Convert.
1393 SmallVector<Value*, 4> Indices;
1394 // Prefix an i32 0 since we need the first element.
1395 Indices.push_back(Builder->getInt32(0));
1396 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
1398 Indices.push_back(Builder->getInt32(*I));
1400 // We need to insert these at the location of the old load, not at that of
1401 // the extractvalue.
1402 Builder->SetInsertPoint(L->getParent(), L);
1403 Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), Indices);
1404 // Returning the load directly will cause the main loop to insert it in
1405 // the wrong spot, so use ReplaceInstUsesWith().
1406 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
1408 // We could simplify extracts from other values. Note that nested extracts may
1409 // already be simplified implicitly by the above: extract (extract (insert) )
1410 // will be translated into extract ( insert ( extract ) ) first and then just
1411 // the value inserted, if appropriate. Similarly for extracts from single-use
1412 // loads: extract (extract (load)) will be translated to extract (load (gep))
1413 // and if again single-use then via load (gep (gep)) to load (gep).
1414 // However, double extracts from e.g. function arguments or return values
1415 // aren't handled yet.
1419 enum Personality_Type {
1420 Unknown_Personality,
1421 GNU_Ada_Personality,
1422 GNU_CXX_Personality,
1423 GNU_ObjC_Personality
1426 /// RecognizePersonality - See if the given exception handling personality
1427 /// function is one that we understand. If so, return a description of it;
1428 /// otherwise return Unknown_Personality.
1429 static Personality_Type RecognizePersonality(Value *Pers) {
1430 Function *F = dyn_cast<Function>(Pers->stripPointerCasts());
1432 return Unknown_Personality;
1433 return StringSwitch<Personality_Type>(F->getName())
1434 .Case("__gnat_eh_personality", GNU_Ada_Personality)
1435 .Case("__gxx_personality_v0", GNU_CXX_Personality)
1436 .Case("__objc_personality_v0", GNU_ObjC_Personality)
1437 .Default(Unknown_Personality);
1440 /// isCatchAll - Return 'true' if the given typeinfo will match anything.
1441 static bool isCatchAll(Personality_Type Personality, Constant *TypeInfo) {
1442 switch (Personality) {
1443 case Unknown_Personality:
1445 case GNU_Ada_Personality:
1446 // While __gnat_all_others_value will match any Ada exception, it doesn't
1447 // match foreign exceptions (or didn't, before gcc-4.7).
1449 case GNU_CXX_Personality:
1450 case GNU_ObjC_Personality:
1451 return TypeInfo->isNullValue();
1453 llvm_unreachable("Unknown personality!");
1456 static bool shorter_filter(const Value *LHS, const Value *RHS) {
1458 cast<ArrayType>(LHS->getType())->getNumElements()
1460 cast<ArrayType>(RHS->getType())->getNumElements();
1463 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
1464 // The logic here should be correct for any real-world personality function.
1465 // However if that turns out not to be true, the offending logic can always
1466 // be conditioned on the personality function, like the catch-all logic is.
1467 Personality_Type Personality = RecognizePersonality(LI.getPersonalityFn());
1469 // Simplify the list of clauses, eg by removing repeated catch clauses
1470 // (these are often created by inlining).
1471 bool MakeNewInstruction = false; // If true, recreate using the following:
1472 SmallVector<Value *, 16> NewClauses; // - Clauses for the new instruction;
1473 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
1475 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
1476 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
1477 bool isLastClause = i + 1 == e;
1478 if (LI.isCatch(i)) {
1480 Value *CatchClause = LI.getClause(i);
1481 Constant *TypeInfo = cast<Constant>(CatchClause->stripPointerCasts());
1483 // If we already saw this clause, there is no point in having a second
1485 if (AlreadyCaught.insert(TypeInfo)) {
1486 // This catch clause was not already seen.
1487 NewClauses.push_back(CatchClause);
1489 // Repeated catch clause - drop the redundant copy.
1490 MakeNewInstruction = true;
1493 // If this is a catch-all then there is no point in keeping any following
1494 // clauses or marking the landingpad as having a cleanup.
1495 if (isCatchAll(Personality, TypeInfo)) {
1497 MakeNewInstruction = true;
1498 CleanupFlag = false;
1502 // A filter clause. If any of the filter elements were already caught
1503 // then they can be dropped from the filter. It is tempting to try to
1504 // exploit the filter further by saying that any typeinfo that does not
1505 // occur in the filter can't be caught later (and thus can be dropped).
1506 // However this would be wrong, since typeinfos can match without being
1507 // equal (for example if one represents a C++ class, and the other some
1508 // class derived from it).
1509 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
1510 Value *FilterClause = LI.getClause(i);
1511 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
1512 unsigned NumTypeInfos = FilterType->getNumElements();
1514 // An empty filter catches everything, so there is no point in keeping any
1515 // following clauses or marking the landingpad as having a cleanup. By
1516 // dealing with this case here the following code is made a bit simpler.
1517 if (!NumTypeInfos) {
1518 NewClauses.push_back(FilterClause);
1520 MakeNewInstruction = true;
1521 CleanupFlag = false;
1525 bool MakeNewFilter = false; // If true, make a new filter.
1526 SmallVector<Constant *, 16> NewFilterElts; // New elements.
1527 if (isa<ConstantAggregateZero>(FilterClause)) {
1528 // Not an empty filter - it contains at least one null typeinfo.
1529 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
1530 Constant *TypeInfo =
1531 Constant::getNullValue(FilterType->getElementType());
1532 // If this typeinfo is a catch-all then the filter can never match.
1533 if (isCatchAll(Personality, TypeInfo)) {
1534 // Throw the filter away.
1535 MakeNewInstruction = true;
1539 // There is no point in having multiple copies of this typeinfo, so
1540 // discard all but the first copy if there is more than one.
1541 NewFilterElts.push_back(TypeInfo);
1542 if (NumTypeInfos > 1)
1543 MakeNewFilter = true;
1545 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
1546 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
1547 NewFilterElts.reserve(NumTypeInfos);
1549 // Remove any filter elements that were already caught or that already
1550 // occurred in the filter. While there, see if any of the elements are
1551 // catch-alls. If so, the filter can be discarded.
1552 bool SawCatchAll = false;
1553 for (unsigned j = 0; j != NumTypeInfos; ++j) {
1554 Value *Elt = Filter->getOperand(j);
1555 Constant *TypeInfo = cast<Constant>(Elt->stripPointerCasts());
1556 if (isCatchAll(Personality, TypeInfo)) {
1557 // This element is a catch-all. Bail out, noting this fact.
1561 if (AlreadyCaught.count(TypeInfo))
1562 // Already caught by an earlier clause, so having it in the filter
1565 // There is no point in having multiple copies of the same typeinfo in
1566 // a filter, so only add it if we didn't already.
1567 if (SeenInFilter.insert(TypeInfo))
1568 NewFilterElts.push_back(cast<Constant>(Elt));
1570 // A filter containing a catch-all cannot match anything by definition.
1572 // Throw the filter away.
1573 MakeNewInstruction = true;
1577 // If we dropped something from the filter, make a new one.
1578 if (NewFilterElts.size() < NumTypeInfos)
1579 MakeNewFilter = true;
1581 if (MakeNewFilter) {
1582 FilterType = ArrayType::get(FilterType->getElementType(),
1583 NewFilterElts.size());
1584 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
1585 MakeNewInstruction = true;
1588 NewClauses.push_back(FilterClause);
1590 // If the new filter is empty then it will catch everything so there is
1591 // no point in keeping any following clauses or marking the landingpad
1592 // as having a cleanup. The case of the original filter being empty was
1593 // already handled above.
1594 if (MakeNewFilter && !NewFilterElts.size()) {
1595 assert(MakeNewInstruction && "New filter but not a new instruction!");
1596 CleanupFlag = false;
1602 // If several filters occur in a row then reorder them so that the shortest
1603 // filters come first (those with the smallest number of elements). This is
1604 // advantageous because shorter filters are more likely to match, speeding up
1605 // unwinding, but mostly because it increases the effectiveness of the other
1606 // filter optimizations below.
1607 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
1609 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
1610 for (j = i; j != e; ++j)
1611 if (!isa<ArrayType>(NewClauses[j]->getType()))
1614 // Check whether the filters are already sorted by length. We need to know
1615 // if sorting them is actually going to do anything so that we only make a
1616 // new landingpad instruction if it does.
1617 for (unsigned k = i; k + 1 < j; ++k)
1618 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
1619 // Not sorted, so sort the filters now. Doing an unstable sort would be
1620 // correct too but reordering filters pointlessly might confuse users.
1621 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
1623 MakeNewInstruction = true;
1627 // Look for the next batch of filters.
1631 // If typeinfos matched if and only if equal, then the elements of a filter L
1632 // that occurs later than a filter F could be replaced by the intersection of
1633 // the elements of F and L. In reality two typeinfos can match without being
1634 // equal (for example if one represents a C++ class, and the other some class
1635 // derived from it) so it would be wrong to perform this transform in general.
1636 // However the transform is correct and useful if F is a subset of L. In that
1637 // case L can be replaced by F, and thus removed altogether since repeating a
1638 // filter is pointless. So here we look at all pairs of filters F and L where
1639 // L follows F in the list of clauses, and remove L if every element of F is
1640 // an element of L. This can occur when inlining C++ functions with exception
1642 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
1643 // Examine each filter in turn.
1644 Value *Filter = NewClauses[i];
1645 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
1647 // Not a filter - skip it.
1649 unsigned FElts = FTy->getNumElements();
1650 // Examine each filter following this one. Doing this backwards means that
1651 // we don't have to worry about filters disappearing under us when removed.
1652 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
1653 Value *LFilter = NewClauses[j];
1654 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
1656 // Not a filter - skip it.
1658 // If Filter is a subset of LFilter, i.e. every element of Filter is also
1659 // an element of LFilter, then discard LFilter.
1660 SmallVector<Value *, 16>::iterator J = NewClauses.begin() + j;
1661 // If Filter is empty then it is a subset of LFilter.
1664 NewClauses.erase(J);
1665 MakeNewInstruction = true;
1666 // Move on to the next filter.
1669 unsigned LElts = LTy->getNumElements();
1670 // If Filter is longer than LFilter then it cannot be a subset of it.
1672 // Move on to the next filter.
1674 // At this point we know that LFilter has at least one element.
1675 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
1676 // Filter is a subset of LFilter iff Filter contains only zeros (as we
1677 // already know that Filter is not longer than LFilter).
1678 if (isa<ConstantAggregateZero>(Filter)) {
1679 assert(FElts <= LElts && "Should have handled this case earlier!");
1681 NewClauses.erase(J);
1682 MakeNewInstruction = true;
1684 // Move on to the next filter.
1687 ConstantArray *LArray = cast<ConstantArray>(LFilter);
1688 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
1689 // Since Filter is non-empty and contains only zeros, it is a subset of
1690 // LFilter iff LFilter contains a zero.
1691 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
1692 for (unsigned l = 0; l != LElts; ++l)
1693 if (LArray->getOperand(l)->isNullValue()) {
1694 // LFilter contains a zero - discard it.
1695 NewClauses.erase(J);
1696 MakeNewInstruction = true;
1699 // Move on to the next filter.
1702 // At this point we know that both filters are ConstantArrays. Loop over
1703 // operands to see whether every element of Filter is also an element of
1704 // LFilter. Since filters tend to be short this is probably faster than
1705 // using a method that scales nicely.
1706 ConstantArray *FArray = cast<ConstantArray>(Filter);
1707 bool AllFound = true;
1708 for (unsigned f = 0; f != FElts; ++f) {
1709 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
1711 for (unsigned l = 0; l != LElts; ++l) {
1712 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
1713 if (LTypeInfo == FTypeInfo) {
1723 NewClauses.erase(J);
1724 MakeNewInstruction = true;
1726 // Move on to the next filter.
1730 // If we changed any of the clauses, replace the old landingpad instruction
1732 if (MakeNewInstruction) {
1733 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
1734 LI.getPersonalityFn(),
1736 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
1737 NLI->addClause(NewClauses[i]);
1738 // A landing pad with no clauses must have the cleanup flag set. It is
1739 // theoretically possible, though highly unlikely, that we eliminated all
1740 // clauses. If so, force the cleanup flag to true.
1741 if (NewClauses.empty())
1743 NLI->setCleanup(CleanupFlag);
1747 // Even if none of the clauses changed, we may nonetheless have understood
1748 // that the cleanup flag is pointless. Clear it if so.
1749 if (LI.isCleanup() != CleanupFlag) {
1750 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
1751 LI.setCleanup(CleanupFlag);
1761 /// TryToSinkInstruction - Try to move the specified instruction from its
1762 /// current block into the beginning of DestBlock, which can only happen if it's
1763 /// safe to move the instruction past all of the instructions between it and the
1764 /// end of its block.
1765 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
1766 assert(I->hasOneUse() && "Invariants didn't hold!");
1768 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1769 if (isa<PHINode>(I) || isa<LandingPadInst>(I) || I->mayHaveSideEffects() ||
1770 isa<TerminatorInst>(I))
1773 // Do not sink alloca instructions out of the entry block.
1774 if (isa<AllocaInst>(I) && I->getParent() ==
1775 &DestBlock->getParent()->getEntryBlock())
1778 // We can only sink load instructions if there is nothing between the load and
1779 // the end of block that could change the value.
1780 if (I->mayReadFromMemory()) {
1781 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
1783 if (Scan->mayWriteToMemory())
1787 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
1788 I->moveBefore(InsertPos);
1794 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
1795 /// all reachable code to the worklist.
1797 /// This has a couple of tricks to make the code faster and more powerful. In
1798 /// particular, we constant fold and DCE instructions as we go, to avoid adding
1799 /// them to the worklist (this significantly speeds up instcombine on code where
1800 /// many instructions are dead or constant). Additionally, if we find a branch
1801 /// whose condition is a known constant, we only visit the reachable successors.
1803 static bool AddReachableCodeToWorklist(BasicBlock *BB,
1804 SmallPtrSet<BasicBlock*, 64> &Visited,
1806 const TargetData *TD,
1807 const TargetLibraryInfo *TLI) {
1808 bool MadeIRChange = false;
1809 SmallVector<BasicBlock*, 256> Worklist;
1810 Worklist.push_back(BB);
1812 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
1813 DenseMap<ConstantExpr*, Constant*> FoldedConstants;
1816 BB = Worklist.pop_back_val();
1818 // We have now visited this block! If we've already been here, ignore it.
1819 if (!Visited.insert(BB)) continue;
1821 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
1822 Instruction *Inst = BBI++;
1824 // DCE instruction if trivially dead.
1825 if (isInstructionTriviallyDead(Inst)) {
1827 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
1828 Inst->eraseFromParent();
1832 // ConstantProp instruction if trivially constant.
1833 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
1834 if (Constant *C = ConstantFoldInstruction(Inst, TD, TLI)) {
1835 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
1837 Inst->replaceAllUsesWith(C);
1839 Inst->eraseFromParent();
1844 // See if we can constant fold its operands.
1845 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
1847 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
1848 if (CE == 0) continue;
1850 Constant*& FoldRes = FoldedConstants[CE];
1852 FoldRes = ConstantFoldConstantExpression(CE, TD);
1856 if (FoldRes != CE) {
1858 MadeIRChange = true;
1863 InstrsForInstCombineWorklist.push_back(Inst);
1866 // Recursively visit successors. If this is a branch or switch on a
1867 // constant, only visit the reachable successor.
1868 TerminatorInst *TI = BB->getTerminator();
1869 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1870 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
1871 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
1872 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
1873 Worklist.push_back(ReachableBB);
1876 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1877 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
1878 // See if this is an explicit destination.
1879 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
1880 if (SI->getCaseValue(i) == Cond) {
1881 BasicBlock *ReachableBB = SI->getSuccessor(i);
1882 Worklist.push_back(ReachableBB);
1886 // Otherwise it is the default destination.
1887 Worklist.push_back(SI->getSuccessor(0));
1892 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
1893 Worklist.push_back(TI->getSuccessor(i));
1894 } while (!Worklist.empty());
1896 // Once we've found all of the instructions to add to instcombine's worklist,
1897 // add them in reverse order. This way instcombine will visit from the top
1898 // of the function down. This jives well with the way that it adds all uses
1899 // of instructions to the worklist after doing a transformation, thus avoiding
1900 // some N^2 behavior in pathological cases.
1901 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
1902 InstrsForInstCombineWorklist.size());
1904 return MadeIRChange;
1907 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
1908 MadeIRChange = false;
1910 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
1911 << F.getName() << "\n");
1914 // Do a depth-first traversal of the function, populate the worklist with
1915 // the reachable instructions. Ignore blocks that are not reachable. Keep
1916 // track of which blocks we visit.
1917 SmallPtrSet<BasicBlock*, 64> Visited;
1918 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD,
1921 // Do a quick scan over the function. If we find any blocks that are
1922 // unreachable, remove any instructions inside of them. This prevents
1923 // the instcombine code from having to deal with some bad special cases.
1924 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
1925 if (Visited.count(BB)) continue;
1927 // Delete the instructions backwards, as it has a reduced likelihood of
1928 // having to update as many def-use and use-def chains.
1929 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
1930 while (EndInst != BB->begin()) {
1931 // Delete the next to last instruction.
1932 BasicBlock::iterator I = EndInst;
1933 Instruction *Inst = --I;
1934 if (!Inst->use_empty())
1935 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
1936 if (isa<LandingPadInst>(Inst)) {
1940 if (!isa<DbgInfoIntrinsic>(Inst)) {
1942 MadeIRChange = true;
1944 Inst->eraseFromParent();
1949 while (!Worklist.isEmpty()) {
1950 Instruction *I = Worklist.RemoveOne();
1951 if (I == 0) continue; // skip null values.
1953 // Check to see if we can DCE the instruction.
1954 if (isInstructionTriviallyDead(I)) {
1955 DEBUG(errs() << "IC: DCE: " << *I << '\n');
1956 EraseInstFromFunction(*I);
1958 MadeIRChange = true;
1962 // Instruction isn't dead, see if we can constant propagate it.
1963 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
1964 if (Constant *C = ConstantFoldInstruction(I, TD, TLI)) {
1965 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
1967 // Add operands to the worklist.
1968 ReplaceInstUsesWith(*I, C);
1970 EraseInstFromFunction(*I);
1971 MadeIRChange = true;
1975 // See if we can trivially sink this instruction to a successor basic block.
1976 if (I->hasOneUse()) {
1977 BasicBlock *BB = I->getParent();
1978 Instruction *UserInst = cast<Instruction>(I->use_back());
1979 BasicBlock *UserParent;
1981 // Get the block the use occurs in.
1982 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
1983 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
1985 UserParent = UserInst->getParent();
1987 if (UserParent != BB) {
1988 bool UserIsSuccessor = false;
1989 // See if the user is one of our successors.
1990 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
1991 if (*SI == UserParent) {
1992 UserIsSuccessor = true;
1996 // If the user is one of our immediate successors, and if that successor
1997 // only has us as a predecessors (we'd have to split the critical edge
1998 // otherwise), we can keep going.
1999 if (UserIsSuccessor && UserParent->getSinglePredecessor())
2000 // Okay, the CFG is simple enough, try to sink this instruction.
2001 MadeIRChange |= TryToSinkInstruction(I, UserParent);
2005 // Now that we have an instruction, try combining it to simplify it.
2006 Builder->SetInsertPoint(I->getParent(), I);
2007 Builder->SetCurrentDebugLocation(I->getDebugLoc());
2012 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
2013 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
2015 if (Instruction *Result = visit(*I)) {
2017 // Should we replace the old instruction with a new one?
2019 DEBUG(errs() << "IC: Old = " << *I << '\n'
2020 << " New = " << *Result << '\n');
2022 if (!I->getDebugLoc().isUnknown())
2023 Result->setDebugLoc(I->getDebugLoc());
2024 // Everything uses the new instruction now.
2025 I->replaceAllUsesWith(Result);
2027 // Move the name to the new instruction first.
2028 Result->takeName(I);
2030 // Push the new instruction and any users onto the worklist.
2031 Worklist.Add(Result);
2032 Worklist.AddUsersToWorkList(*Result);
2034 // Insert the new instruction into the basic block...
2035 BasicBlock *InstParent = I->getParent();
2036 BasicBlock::iterator InsertPos = I;
2038 // If we replace a PHI with something that isn't a PHI, fix up the
2040 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2041 InsertPos = InstParent->getFirstInsertionPt();
2043 InstParent->getInstList().insert(InsertPos, Result);
2045 EraseInstFromFunction(*I);
2048 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
2049 << " New = " << *I << '\n');
2052 // If the instruction was modified, it's possible that it is now dead.
2053 // if so, remove it.
2054 if (isInstructionTriviallyDead(I)) {
2055 EraseInstFromFunction(*I);
2058 Worklist.AddUsersToWorkList(*I);
2061 MadeIRChange = true;
2066 return MadeIRChange;
2070 bool InstCombiner::runOnFunction(Function &F) {
2071 TD = getAnalysisIfAvailable<TargetData>();
2072 TLI = &getAnalysis<TargetLibraryInfo>();
2074 /// Builder - This is an IRBuilder that automatically inserts new
2075 /// instructions into the worklist when they are created.
2076 IRBuilder<true, TargetFolder, InstCombineIRInserter>
2077 TheBuilder(F.getContext(), TargetFolder(TD),
2078 InstCombineIRInserter(Worklist));
2079 Builder = &TheBuilder;
2081 bool EverMadeChange = false;
2083 // Lower dbg.declare intrinsics otherwise their value may be clobbered
2085 EverMadeChange = LowerDbgDeclare(F);
2087 // Iterate while there is work to do.
2088 unsigned Iteration = 0;
2089 while (DoOneIteration(F, Iteration++))
2090 EverMadeChange = true;
2093 return EverMadeChange;
2096 FunctionPass *llvm::createInstructionCombiningPass() {
2097 return new InstCombiner();