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/Transforms/Utils/Local.h"
45 #include "llvm/Support/CFG.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/GetElementPtrTypeIterator.h"
48 #include "llvm/Support/PatternMatch.h"
49 #include "llvm/Support/ValueHandle.h"
50 #include "llvm/ADT/SmallPtrSet.h"
51 #include "llvm/ADT/Statistic.h"
52 #include "llvm-c/Initialization.h"
56 using namespace llvm::PatternMatch;
58 STATISTIC(NumCombined , "Number of insts combined");
59 STATISTIC(NumConstProp, "Number of constant folds");
60 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
61 STATISTIC(NumSunkInst , "Number of instructions sunk");
62 STATISTIC(NumExpand, "Number of expansions");
63 STATISTIC(NumFactor , "Number of factorizations");
64 STATISTIC(NumReassoc , "Number of reassociations");
66 // Initialization Routines
67 void llvm::initializeInstCombine(PassRegistry &Registry) {
68 initializeInstCombinerPass(Registry);
71 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
72 initializeInstCombine(*unwrap(R));
75 char InstCombiner::ID = 0;
76 INITIALIZE_PASS(InstCombiner, "instcombine",
77 "Combine redundant instructions", false, false)
79 void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
84 /// ShouldChangeType - Return true if it is desirable to convert a computation
85 /// from 'From' to 'To'. We don't want to convert from a legal to an illegal
86 /// type for example, or from a smaller to a larger illegal type.
87 bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
88 assert(From->isIntegerTy() && To->isIntegerTy());
90 // If we don't have TD, we don't know if the source/dest are legal.
91 if (!TD) return false;
93 unsigned FromWidth = From->getPrimitiveSizeInBits();
94 unsigned ToWidth = To->getPrimitiveSizeInBits();
95 bool FromLegal = TD->isLegalInteger(FromWidth);
96 bool ToLegal = TD->isLegalInteger(ToWidth);
98 // If this is a legal integer from type, and the result would be an illegal
99 // type, don't do the transformation.
100 if (FromLegal && !ToLegal)
103 // Otherwise, if both are illegal, do not increase the size of the result. We
104 // do allow things like i160 -> i64, but not i64 -> i160.
105 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
111 // Return true, if No Signed Wrap should be maintained for I.
112 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
113 // where both B and C should be ConstantInts, results in a constant that does
114 // not overflow. This function only handles the Add and Sub opcodes. For
115 // all other opcodes, the function conservatively returns false.
116 static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
117 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
118 if (!OBO || !OBO->hasNoSignedWrap()) {
122 // We reason about Add and Sub Only.
123 Instruction::BinaryOps Opcode = I.getOpcode();
124 if (Opcode != Instruction::Add &&
125 Opcode != Instruction::Sub) {
129 ConstantInt *CB = dyn_cast<ConstantInt>(B);
130 ConstantInt *CC = dyn_cast<ConstantInt>(C);
136 const APInt &BVal = CB->getValue();
137 const APInt &CVal = CC->getValue();
138 bool Overflow = false;
140 if (Opcode == Instruction::Add) {
141 BVal.sadd_ov(CVal, Overflow);
143 BVal.ssub_ov(CVal, Overflow);
150 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
151 /// operators which are associative or commutative:
153 // Commutative operators:
155 // 1. Order operands such that they are listed from right (least complex) to
156 // left (most complex). This puts constants before unary operators before
159 // Associative operators:
161 // 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
162 // 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
164 // Associative and commutative operators:
166 // 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
167 // 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
168 // 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
169 // if C1 and C2 are constants.
171 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
172 Instruction::BinaryOps Opcode = I.getOpcode();
173 bool Changed = false;
176 // Order operands such that they are listed from right (least complex) to
177 // left (most complex). This puts constants before unary operators before
179 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
180 getComplexity(I.getOperand(1)))
181 Changed = !I.swapOperands();
183 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
184 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
186 if (I.isAssociative()) {
187 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
188 if (Op0 && Op0->getOpcode() == Opcode) {
189 Value *A = Op0->getOperand(0);
190 Value *B = Op0->getOperand(1);
191 Value *C = I.getOperand(1);
193 // Does "B op C" simplify?
194 if (Value *V = SimplifyBinOp(Opcode, B, C, TD)) {
195 // It simplifies to V. Form "A op V".
198 // Conservatively clear the optional flags, since they may not be
199 // preserved by the reassociation.
200 if (MaintainNoSignedWrap(I, B, C)) {
201 I.clearSubclassOptionalData();
202 I.setHasNoSignedWrap(true);
204 I.clearSubclassOptionalData();
213 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
214 if (Op1 && Op1->getOpcode() == Opcode) {
215 Value *A = I.getOperand(0);
216 Value *B = Op1->getOperand(0);
217 Value *C = Op1->getOperand(1);
219 // Does "A op B" simplify?
220 if (Value *V = SimplifyBinOp(Opcode, A, B, TD)) {
221 // It simplifies to V. Form "V op C".
224 // Conservatively clear the optional flags, since they may not be
225 // preserved by the reassociation.
226 I.clearSubclassOptionalData();
234 if (I.isAssociative() && I.isCommutative()) {
235 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
236 if (Op0 && Op0->getOpcode() == Opcode) {
237 Value *A = Op0->getOperand(0);
238 Value *B = Op0->getOperand(1);
239 Value *C = I.getOperand(1);
241 // Does "C op A" simplify?
242 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
243 // It simplifies to V. Form "V op B".
246 // Conservatively clear the optional flags, since they may not be
247 // preserved by the reassociation.
248 I.clearSubclassOptionalData();
255 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
256 if (Op1 && Op1->getOpcode() == Opcode) {
257 Value *A = I.getOperand(0);
258 Value *B = Op1->getOperand(0);
259 Value *C = Op1->getOperand(1);
261 // Does "C op A" simplify?
262 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
263 // It simplifies to V. Form "B op V".
266 // Conservatively clear the optional flags, since they may not be
267 // preserved by the reassociation.
268 I.clearSubclassOptionalData();
275 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
276 // if C1 and C2 are constants.
278 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
279 isa<Constant>(Op0->getOperand(1)) &&
280 isa<Constant>(Op1->getOperand(1)) &&
281 Op0->hasOneUse() && Op1->hasOneUse()) {
282 Value *A = Op0->getOperand(0);
283 Constant *C1 = cast<Constant>(Op0->getOperand(1));
284 Value *B = Op1->getOperand(0);
285 Constant *C2 = cast<Constant>(Op1->getOperand(1));
287 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
288 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
289 InsertNewInstWith(New, I);
291 I.setOperand(0, New);
292 I.setOperand(1, Folded);
293 // Conservatively clear the optional flags, since they may not be
294 // preserved by the reassociation.
295 if (MaintainNoSignedWrap(I, C1, C2)) {
296 I.clearSubclassOptionalData();
297 I.setHasNoSignedWrap(true);
298 New->setHasNoSignedWrap(true);
300 I.clearSubclassOptionalData();
308 // No further simplifications.
313 /// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
314 /// "(X LOp Y) ROp (X LOp Z)".
315 static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
316 Instruction::BinaryOps ROp) {
321 case Instruction::And:
322 // And distributes over Or and Xor.
326 case Instruction::Or:
327 case Instruction::Xor:
331 case Instruction::Mul:
332 // Multiplication distributes over addition and subtraction.
336 case Instruction::Add:
337 case Instruction::Sub:
341 case Instruction::Or:
342 // Or distributes over And.
346 case Instruction::And:
352 /// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
353 /// "(X ROp Z) LOp (Y ROp Z)".
354 static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
355 Instruction::BinaryOps ROp) {
356 if (Instruction::isCommutative(ROp))
357 return LeftDistributesOverRight(ROp, LOp);
358 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
359 // but this requires knowing that the addition does not overflow and other
364 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
365 /// which some other binary operation distributes over either by factorizing
366 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
367 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
368 /// a win). Returns the simplified value, or null if it didn't simplify.
369 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
370 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
371 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
372 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
373 Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); // op
376 if (Op0 && Op1 && Op0->getOpcode() == Op1->getOpcode()) {
377 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
379 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
380 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
381 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
383 // Does "X op' Y" always equal "Y op' X"?
384 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
386 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
387 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
388 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
389 // commutative case, "(A op' B) op (C op' A)"?
390 if (A == C || (InnerCommutative && A == D)) {
393 // Consider forming "A op' (B op D)".
394 // If "B op D" simplifies then it can be formed with no cost.
395 Value *V = SimplifyBinOp(TopLevelOpcode, B, D, TD);
396 // If "B op D" doesn't simplify then only go on if both of the existing
397 // operations "A op' B" and "C op' D" will be zapped as no longer used.
398 if (!V && Op0->hasOneUse() && Op1->hasOneUse())
399 V = Builder->CreateBinOp(TopLevelOpcode, B, D, Op1->getName());
402 V = Builder->CreateBinOp(InnerOpcode, A, V);
408 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
409 if (RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
410 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
411 // commutative case, "(A op' B) op (B op' D)"?
412 if (B == D || (InnerCommutative && B == C)) {
415 // Consider forming "(A op C) op' B".
416 // If "A op C" simplifies then it can be formed with no cost.
417 Value *V = SimplifyBinOp(TopLevelOpcode, A, C, TD);
418 // If "A op C" doesn't simplify then only go on if both of the existing
419 // operations "A op' B" and "C op' D" will be zapped as no longer used.
420 if (!V && Op0->hasOneUse() && Op1->hasOneUse())
421 V = Builder->CreateBinOp(TopLevelOpcode, A, C, Op0->getName());
424 V = Builder->CreateBinOp(InnerOpcode, V, B);
432 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
433 // The instruction has the form "(A op' B) op C". See if expanding it out
434 // to "(A op C) op' (B op C)" results in simplifications.
435 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
436 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
438 // Do "A op C" and "B op C" both simplify?
439 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, TD))
440 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, TD)) {
441 // They do! Return "L op' R".
443 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
444 if ((L == A && R == B) ||
445 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
447 // Otherwise return "L op' R" if it simplifies.
448 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
450 // Otherwise, create a new instruction.
451 C = Builder->CreateBinOp(InnerOpcode, L, R);
457 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
458 // The instruction has the form "A op (B op' C)". See if expanding it out
459 // to "(A op B) op' (A op C)" results in simplifications.
460 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
461 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
463 // Do "A op B" and "A op C" both simplify?
464 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, TD))
465 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, TD)) {
466 // They do! Return "L op' R".
468 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
469 if ((L == B && R == C) ||
470 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
472 // Otherwise return "L op' R" if it simplifies.
473 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
475 // Otherwise, create a new instruction.
476 A = Builder->CreateBinOp(InnerOpcode, L, R);
485 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
486 // if the LHS is a constant zero (which is the 'negate' form).
488 Value *InstCombiner::dyn_castNegVal(Value *V) const {
489 if (BinaryOperator::isNeg(V))
490 return BinaryOperator::getNegArgument(V);
492 // Constants can be considered to be negated values if they can be folded.
493 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
494 return ConstantExpr::getNeg(C);
496 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
497 if (C->getType()->getElementType()->isIntegerTy())
498 return ConstantExpr::getNeg(C);
503 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
504 // instruction if the LHS is a constant negative zero (which is the 'negate'
507 Value *InstCombiner::dyn_castFNegVal(Value *V) const {
508 if (BinaryOperator::isFNeg(V))
509 return BinaryOperator::getFNegArgument(V);
511 // Constants can be considered to be negated values if they can be folded.
512 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
513 return ConstantExpr::getFNeg(C);
515 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
516 if (C->getType()->getElementType()->isFloatingPointTy())
517 return ConstantExpr::getFNeg(C);
522 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
524 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
525 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
528 // Figure out if the constant is the left or the right argument.
529 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
530 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
532 if (Constant *SOC = dyn_cast<Constant>(SO)) {
534 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
535 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
538 Value *Op0 = SO, *Op1 = ConstOperand;
542 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
543 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
544 SO->getName()+".op");
545 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
546 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
547 SO->getName()+".cmp");
548 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
549 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
550 SO->getName()+".cmp");
551 llvm_unreachable("Unknown binary instruction type!");
554 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
555 // constant as the other operand, try to fold the binary operator into the
556 // select arguments. This also works for Cast instructions, which obviously do
557 // not have a second operand.
558 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
559 // Don't modify shared select instructions
560 if (!SI->hasOneUse()) return 0;
561 Value *TV = SI->getOperand(1);
562 Value *FV = SI->getOperand(2);
564 if (isa<Constant>(TV) || isa<Constant>(FV)) {
565 // Bool selects with constant operands can be folded to logical ops.
566 if (SI->getType()->isIntegerTy(1)) return 0;
568 // If it's a bitcast involving vectors, make sure it has the same number of
569 // elements on both sides.
570 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
571 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
572 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
574 // Verify that either both or neither are vectors.
575 if ((SrcTy == NULL) != (DestTy == NULL)) return 0;
576 // If vectors, verify that they have the same number of elements.
577 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
581 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
582 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
584 return SelectInst::Create(SI->getCondition(),
585 SelectTrueVal, SelectFalseVal);
591 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
592 /// has a PHI node as operand #0, see if we can fold the instruction into the
593 /// PHI (which is only possible if all operands to the PHI are constants).
595 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
596 PHINode *PN = cast<PHINode>(I.getOperand(0));
597 unsigned NumPHIValues = PN->getNumIncomingValues();
598 if (NumPHIValues == 0)
601 // We normally only transform phis with a single use. However, if a PHI has
602 // multiple uses and they are all the same operation, we can fold *all* of the
603 // uses into the PHI.
604 if (!PN->hasOneUse()) {
605 // Walk the use list for the instruction, comparing them to I.
606 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
608 Instruction *User = cast<Instruction>(*UI);
609 if (User != &I && !I.isIdenticalTo(User))
612 // Otherwise, we can replace *all* users with the new PHI we form.
615 // Check to see if all of the operands of the PHI are simple constants
616 // (constantint/constantfp/undef). If there is one non-constant value,
617 // remember the BB it is in. If there is more than one or if *it* is a PHI,
618 // bail out. We don't do arbitrary constant expressions here because moving
619 // their computation can be expensive without a cost model.
620 BasicBlock *NonConstBB = 0;
621 for (unsigned i = 0; i != NumPHIValues; ++i) {
622 Value *InVal = PN->getIncomingValue(i);
623 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
626 if (isa<PHINode>(InVal)) return 0; // Itself a phi.
627 if (NonConstBB) return 0; // More than one non-const value.
629 NonConstBB = PN->getIncomingBlock(i);
631 // If the InVal is an invoke at the end of the pred block, then we can't
632 // insert a computation after it without breaking the edge.
633 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
634 if (II->getParent() == NonConstBB)
637 // If the incoming non-constant value is in I's block, we will remove one
638 // instruction, but insert another equivalent one, leading to infinite
640 if (NonConstBB == I.getParent())
644 // If there is exactly one non-constant value, we can insert a copy of the
645 // operation in that block. However, if this is a critical edge, we would be
646 // inserting the computation one some other paths (e.g. inside a loop). Only
647 // do this if the pred block is unconditionally branching into the phi block.
648 if (NonConstBB != 0) {
649 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
650 if (!BI || !BI->isUnconditional()) return 0;
653 // Okay, we can do the transformation: create the new PHI node.
654 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
655 InsertNewInstBefore(NewPN, *PN);
658 // If we are going to have to insert a new computation, do so right before the
659 // predecessors terminator.
661 Builder->SetInsertPoint(NonConstBB->getTerminator());
663 // Next, add all of the operands to the PHI.
664 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
665 // We only currently try to fold the condition of a select when it is a phi,
666 // not the true/false values.
667 Value *TrueV = SI->getTrueValue();
668 Value *FalseV = SI->getFalseValue();
669 BasicBlock *PhiTransBB = PN->getParent();
670 for (unsigned i = 0; i != NumPHIValues; ++i) {
671 BasicBlock *ThisBB = PN->getIncomingBlock(i);
672 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
673 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
675 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
676 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
678 InV = Builder->CreateSelect(PN->getIncomingValue(i),
679 TrueVInPred, FalseVInPred, "phitmp");
680 NewPN->addIncoming(InV, ThisBB);
682 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
683 Constant *C = cast<Constant>(I.getOperand(1));
684 for (unsigned i = 0; i != NumPHIValues; ++i) {
686 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
687 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
688 else if (isa<ICmpInst>(CI))
689 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
692 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
694 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
696 } else if (I.getNumOperands() == 2) {
697 Constant *C = cast<Constant>(I.getOperand(1));
698 for (unsigned i = 0; i != NumPHIValues; ++i) {
700 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
701 InV = ConstantExpr::get(I.getOpcode(), InC, C);
703 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
704 PN->getIncomingValue(i), C, "phitmp");
705 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
708 CastInst *CI = cast<CastInst>(&I);
709 Type *RetTy = CI->getType();
710 for (unsigned i = 0; i != NumPHIValues; ++i) {
712 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
713 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
715 InV = Builder->CreateCast(CI->getOpcode(),
716 PN->getIncomingValue(i), I.getType(), "phitmp");
717 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
721 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
723 Instruction *User = cast<Instruction>(*UI++);
724 if (User == &I) continue;
725 ReplaceInstUsesWith(*User, NewPN);
726 EraseInstFromFunction(*User);
728 return ReplaceInstUsesWith(I, NewPN);
731 /// FindElementAtOffset - Given a type and a constant offset, determine whether
732 /// or not there is a sequence of GEP indices into the type that will land us at
733 /// the specified offset. If so, fill them into NewIndices and return the
734 /// resultant element type, otherwise return null.
735 Type *InstCombiner::FindElementAtOffset(Type *Ty, int64_t Offset,
736 SmallVectorImpl<Value*> &NewIndices) {
738 if (!Ty->isSized()) return 0;
740 // Start with the index over the outer type. Note that the type size
741 // might be zero (even if the offset isn't zero) if the indexed type
742 // is something like [0 x {int, int}]
743 Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
744 int64_t FirstIdx = 0;
745 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
746 FirstIdx = Offset/TySize;
747 Offset -= FirstIdx*TySize;
749 // Handle hosts where % returns negative instead of values [0..TySize).
755 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
758 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
760 // Index into the types. If we fail, set OrigBase to null.
762 // Indexing into tail padding between struct/array elements.
763 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
766 if (StructType *STy = dyn_cast<StructType>(Ty)) {
767 const StructLayout *SL = TD->getStructLayout(STy);
768 assert(Offset < (int64_t)SL->getSizeInBytes() &&
769 "Offset must stay within the indexed type");
771 unsigned Elt = SL->getElementContainingOffset(Offset);
772 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
775 Offset -= SL->getElementOffset(Elt);
776 Ty = STy->getElementType(Elt);
777 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
778 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
779 assert(EltSize && "Cannot index into a zero-sized array");
780 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
782 Ty = AT->getElementType();
784 // Otherwise, we can't index into the middle of this atomic type, bail.
792 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
793 // If this GEP has only 0 indices, it is the same pointer as
794 // Src. If Src is not a trivial GEP too, don't combine
796 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
802 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
803 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
805 if (Value *V = SimplifyGEPInst(Ops, TD))
806 return ReplaceInstUsesWith(GEP, V);
808 Value *PtrOp = GEP.getOperand(0);
810 // Eliminate unneeded casts for indices, and replace indices which displace
811 // by multiples of a zero size type with zero.
813 bool MadeChange = false;
814 Type *IntPtrTy = TD->getIntPtrType(GEP.getContext());
816 gep_type_iterator GTI = gep_type_begin(GEP);
817 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
818 I != E; ++I, ++GTI) {
819 // Skip indices into struct types.
820 SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
821 if (!SeqTy) continue;
823 // If the element type has zero size then any index over it is equivalent
824 // to an index of zero, so replace it with zero if it is not zero already.
825 if (SeqTy->getElementType()->isSized() &&
826 TD->getTypeAllocSize(SeqTy->getElementType()) == 0)
827 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
828 *I = Constant::getNullValue(IntPtrTy);
832 if ((*I)->getType() != IntPtrTy) {
833 // If we are using a wider index than needed for this platform, shrink
834 // it to what we need. If narrower, sign-extend it to what we need.
835 // This explicit cast can make subsequent optimizations more obvious.
836 *I = Builder->CreateIntCast(*I, IntPtrTy, true);
840 if (MadeChange) return &GEP;
843 // Combine Indices - If the source pointer to this getelementptr instruction
844 // is a getelementptr instruction, combine the indices of the two
845 // getelementptr instructions into a single instruction.
847 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
848 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
851 // Note that if our source is a gep chain itself that we wait for that
852 // chain to be resolved before we perform this transformation. This
853 // avoids us creating a TON of code in some cases.
854 if (GEPOperator *SrcGEP =
855 dyn_cast<GEPOperator>(Src->getOperand(0)))
856 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
857 return 0; // Wait until our source is folded to completion.
859 SmallVector<Value*, 8> Indices;
861 // Find out whether the last index in the source GEP is a sequential idx.
862 bool EndsWithSequential = false;
863 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
865 EndsWithSequential = !(*I)->isStructTy();
867 // Can we combine the two pointer arithmetics offsets?
868 if (EndsWithSequential) {
869 // Replace: gep (gep %P, long B), long A, ...
870 // With: T = long A+B; gep %P, T, ...
873 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
874 Value *GO1 = GEP.getOperand(1);
875 if (SO1 == Constant::getNullValue(SO1->getType())) {
877 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
880 // If they aren't the same type, then the input hasn't been processed
881 // by the loop above yet (which canonicalizes sequential index types to
882 // intptr_t). Just avoid transforming this until the input has been
884 if (SO1->getType() != GO1->getType())
886 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
889 // Update the GEP in place if possible.
890 if (Src->getNumOperands() == 2) {
891 GEP.setOperand(0, Src->getOperand(0));
892 GEP.setOperand(1, Sum);
895 Indices.append(Src->op_begin()+1, Src->op_end()-1);
896 Indices.push_back(Sum);
897 Indices.append(GEP.op_begin()+2, GEP.op_end());
898 } else if (isa<Constant>(*GEP.idx_begin()) &&
899 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
900 Src->getNumOperands() != 1) {
901 // Otherwise we can do the fold if the first index of the GEP is a zero
902 Indices.append(Src->op_begin()+1, Src->op_end());
903 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
906 if (!Indices.empty())
907 return (GEP.isInBounds() && Src->isInBounds()) ?
908 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices,
910 GetElementPtrInst::Create(Src->getOperand(0), Indices, GEP.getName());
913 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
914 Value *StrippedPtr = PtrOp->stripPointerCasts();
915 PointerType *StrippedPtrTy =cast<PointerType>(StrippedPtr->getType());
916 if (StrippedPtr != PtrOp &&
917 StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace()) {
919 bool HasZeroPointerIndex = false;
920 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
921 HasZeroPointerIndex = C->isZero();
923 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
924 // into : GEP [10 x i8]* X, i32 0, ...
926 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
927 // into : GEP i8* X, ...
929 // This occurs when the program declares an array extern like "int X[];"
930 if (HasZeroPointerIndex) {
931 PointerType *CPTy = cast<PointerType>(PtrOp->getType());
932 if (ArrayType *CATy =
933 dyn_cast<ArrayType>(CPTy->getElementType())) {
934 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
935 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
937 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
938 GetElementPtrInst *Res =
939 GetElementPtrInst::Create(StrippedPtr, Idx, GEP.getName());
940 Res->setIsInBounds(GEP.isInBounds());
944 if (ArrayType *XATy =
945 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
946 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
947 if (CATy->getElementType() == XATy->getElementType()) {
948 // -> GEP [10 x i8]* X, i32 0, ...
949 // At this point, we know that the cast source type is a pointer
950 // to an array of the same type as the destination pointer
951 // array. Because the array type is never stepped over (there
952 // is a leading zero) we can fold the cast into this GEP.
953 GEP.setOperand(0, StrippedPtr);
958 } else if (GEP.getNumOperands() == 2) {
959 // Transform things like:
960 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
961 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
962 Type *SrcElTy = StrippedPtrTy->getElementType();
963 Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
964 if (TD && SrcElTy->isArrayTy() &&
965 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
966 TD->getTypeAllocSize(ResElTy)) {
968 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
969 Idx[1] = GEP.getOperand(1);
970 Value *NewGEP = GEP.isInBounds() ?
971 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
972 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
973 // V and GEP are both pointer types --> BitCast
974 return new BitCastInst(NewGEP, GEP.getType());
977 // Transform things like:
978 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
979 // (where tmp = 8*tmp2) into:
980 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
982 if (TD && SrcElTy->isArrayTy() && ResElTy->isIntegerTy(8)) {
983 uint64_t ArrayEltSize =
984 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
986 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
987 // allow either a mul, shift, or constant here.
989 ConstantInt *Scale = 0;
990 if (ArrayEltSize == 1) {
991 NewIdx = GEP.getOperand(1);
992 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
993 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
994 NewIdx = ConstantInt::get(CI->getType(), 1);
996 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
997 if (Inst->getOpcode() == Instruction::Shl &&
998 isa<ConstantInt>(Inst->getOperand(1))) {
999 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
1000 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
1001 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
1003 NewIdx = Inst->getOperand(0);
1004 } else if (Inst->getOpcode() == Instruction::Mul &&
1005 isa<ConstantInt>(Inst->getOperand(1))) {
1006 Scale = cast<ConstantInt>(Inst->getOperand(1));
1007 NewIdx = Inst->getOperand(0);
1011 // If the index will be to exactly the right offset with the scale taken
1012 // out, perform the transformation. Note, we don't know whether Scale is
1013 // signed or not. We'll use unsigned version of division/modulo
1014 // operation after making sure Scale doesn't have the sign bit set.
1015 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
1016 Scale->getZExtValue() % ArrayEltSize == 0) {
1017 Scale = ConstantInt::get(Scale->getType(),
1018 Scale->getZExtValue() / ArrayEltSize);
1019 if (Scale->getZExtValue() != 1) {
1020 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
1022 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
1025 // Insert the new GEP instruction.
1027 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
1029 Value *NewGEP = GEP.isInBounds() ?
1030 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()):
1031 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
1032 // The NewGEP must be pointer typed, so must the old one -> BitCast
1033 return new BitCastInst(NewGEP, GEP.getType());
1039 /// See if we can simplify:
1040 /// X = bitcast A* to B*
1041 /// Y = gep X, <...constant indices...>
1042 /// into a gep of the original struct. This is important for SROA and alias
1043 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
1044 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
1046 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices() &&
1047 StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace()) {
1049 // Determine how much the GEP moves the pointer. We are guaranteed to get
1050 // a constant back from EmitGEPOffset.
1051 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
1052 int64_t Offset = OffsetV->getSExtValue();
1054 // If this GEP instruction doesn't move the pointer, just replace the GEP
1055 // with a bitcast of the real input to the dest type.
1057 // If the bitcast is of an allocation, and the allocation will be
1058 // converted to match the type of the cast, don't touch this.
1059 if (isa<AllocaInst>(BCI->getOperand(0)) ||
1060 isMalloc(BCI->getOperand(0))) {
1061 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1062 if (Instruction *I = visitBitCast(*BCI)) {
1065 BCI->getParent()->getInstList().insert(BCI, I);
1066 ReplaceInstUsesWith(*BCI, I);
1071 return new BitCastInst(BCI->getOperand(0), GEP.getType());
1074 // Otherwise, if the offset is non-zero, we need to find out if there is a
1075 // field at Offset in 'A's type. If so, we can pull the cast through the
1077 SmallVector<Value*, 8> NewIndices;
1079 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
1080 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
1081 Value *NGEP = GEP.isInBounds() ?
1082 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices) :
1083 Builder->CreateGEP(BCI->getOperand(0), NewIndices);
1085 if (NGEP->getType() == GEP.getType())
1086 return ReplaceInstUsesWith(GEP, NGEP);
1087 NGEP->takeName(&GEP);
1088 return new BitCastInst(NGEP, GEP.getType());
1098 static bool IsOnlyNullComparedAndFreed(Value *V, SmallVectorImpl<WeakVH> &Users,
1103 for (Value::use_iterator UI = V->use_begin(), UE = V->use_end();
1106 if (isFreeCall(U)) {
1110 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U)) {
1111 if (ICI->isEquality() && isa<ConstantPointerNull>(ICI->getOperand(1))) {
1112 Users.push_back(ICI);
1116 if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
1117 if (IsOnlyNullComparedAndFreed(BCI, Users, Depth+1)) {
1118 Users.push_back(BCI);
1122 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1123 if (IsOnlyNullComparedAndFreed(GEPI, Users, Depth+1)) {
1124 Users.push_back(GEPI);
1128 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(U)) {
1129 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
1130 II->getIntrinsicID() == Intrinsic::lifetime_end) {
1131 Users.push_back(II);
1140 Instruction *InstCombiner::visitMalloc(Instruction &MI) {
1141 // If we have a malloc call which is only used in any amount of comparisons
1142 // to null and free calls, delete the calls and replace the comparisons with
1143 // true or false as appropriate.
1144 SmallVector<WeakVH, 64> Users;
1145 if (IsOnlyNullComparedAndFreed(&MI, Users)) {
1146 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1147 Instruction *I = cast_or_null<Instruction>(&*Users[i]);
1150 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
1151 ReplaceInstUsesWith(*C,
1152 ConstantInt::get(Type::getInt1Ty(C->getContext()),
1153 C->isFalseWhenEqual()));
1154 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
1155 ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
1157 EraseInstFromFunction(*I);
1159 return EraseInstFromFunction(MI);
1166 Instruction *InstCombiner::visitFree(CallInst &FI) {
1167 Value *Op = FI.getArgOperand(0);
1169 // free undef -> unreachable.
1170 if (isa<UndefValue>(Op)) {
1171 // Insert a new store to null because we cannot modify the CFG here.
1172 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
1173 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
1174 return EraseInstFromFunction(FI);
1177 // If we have 'free null' delete the instruction. This can happen in stl code
1178 // when lots of inlining happens.
1179 if (isa<ConstantPointerNull>(Op))
1180 return EraseInstFromFunction(FI);
1187 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1188 // Change br (not X), label True, label False to: br X, label False, True
1190 BasicBlock *TrueDest;
1191 BasicBlock *FalseDest;
1192 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
1193 !isa<Constant>(X)) {
1194 // Swap Destinations and condition...
1196 BI.setSuccessor(0, FalseDest);
1197 BI.setSuccessor(1, TrueDest);
1201 // Cannonicalize fcmp_one -> fcmp_oeq
1202 FCmpInst::Predicate FPred; Value *Y;
1203 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
1204 TrueDest, FalseDest)) &&
1205 BI.getCondition()->hasOneUse())
1206 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
1207 FPred == FCmpInst::FCMP_OGE) {
1208 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
1209 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
1211 // Swap Destinations and condition.
1212 BI.setSuccessor(0, FalseDest);
1213 BI.setSuccessor(1, TrueDest);
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.setSuccessor(0, FalseDest);
1230 BI.setSuccessor(1, TrueDest);
1238 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
1239 Value *Cond = SI.getCondition();
1240 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
1241 if (I->getOpcode() == Instruction::Add)
1242 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1243 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
1244 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
1246 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
1248 SI.setOperand(0, I->getOperand(0));
1256 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
1257 Value *Agg = EV.getAggregateOperand();
1259 if (!EV.hasIndices())
1260 return ReplaceInstUsesWith(EV, Agg);
1262 if (Constant *C = dyn_cast<Constant>(Agg)) {
1263 if (isa<UndefValue>(C))
1264 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
1266 if (isa<ConstantAggregateZero>(C))
1267 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
1269 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
1270 // Extract the element indexed by the first index out of the constant
1271 Value *V = C->getOperand(*EV.idx_begin());
1272 if (EV.getNumIndices() > 1)
1273 // Extract the remaining indices out of the constant indexed by the
1275 return ExtractValueInst::Create(V, EV.getIndices().slice(1));
1277 return ReplaceInstUsesWith(EV, V);
1279 return 0; // Can't handle other constants
1281 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
1282 // We're extracting from an insertvalue instruction, compare the indices
1283 const unsigned *exti, *exte, *insi, *inse;
1284 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
1285 exte = EV.idx_end(), inse = IV->idx_end();
1286 exti != exte && insi != inse;
1289 // The insert and extract both reference distinctly different elements.
1290 // This means the extract is not influenced by the insert, and we can
1291 // replace the aggregate operand of the extract with the aggregate
1292 // operand of the insert. i.e., replace
1293 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1294 // %E = extractvalue { i32, { i32 } } %I, 0
1296 // %E = extractvalue { i32, { i32 } } %A, 0
1297 return ExtractValueInst::Create(IV->getAggregateOperand(),
1300 if (exti == exte && insi == inse)
1301 // Both iterators are at the end: Index lists are identical. Replace
1302 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1303 // %C = extractvalue { i32, { i32 } } %B, 1, 0
1305 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
1307 // The extract list is a prefix of the insert list. i.e. replace
1308 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1309 // %E = extractvalue { i32, { i32 } } %I, 1
1311 // %X = extractvalue { i32, { i32 } } %A, 1
1312 // %E = insertvalue { i32 } %X, i32 42, 0
1313 // by switching the order of the insert and extract (though the
1314 // insertvalue should be left in, since it may have other uses).
1315 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
1317 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
1318 makeArrayRef(insi, inse));
1321 // The insert list is a prefix of the extract list
1322 // We can simply remove the common indices from the extract and make it
1323 // operate on the inserted value instead of the insertvalue result.
1325 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1326 // %E = extractvalue { i32, { i32 } } %I, 1, 0
1328 // %E extractvalue { i32 } { i32 42 }, 0
1329 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
1330 makeArrayRef(exti, exte));
1332 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
1333 // We're extracting from an intrinsic, see if we're the only user, which
1334 // allows us to simplify multiple result intrinsics to simpler things that
1335 // just get one value.
1336 if (II->hasOneUse()) {
1337 // Check if we're grabbing the overflow bit or the result of a 'with
1338 // overflow' intrinsic. If it's the latter we can remove the intrinsic
1339 // and replace it with a traditional binary instruction.
1340 switch (II->getIntrinsicID()) {
1341 case Intrinsic::uadd_with_overflow:
1342 case Intrinsic::sadd_with_overflow:
1343 if (*EV.idx_begin() == 0) { // Normal result.
1344 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1345 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
1346 EraseInstFromFunction(*II);
1347 return BinaryOperator::CreateAdd(LHS, RHS);
1350 // If the normal result of the add is dead, and the RHS is a constant,
1351 // we can transform this into a range comparison.
1352 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
1353 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
1354 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
1355 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
1356 ConstantExpr::getNot(CI));
1358 case Intrinsic::usub_with_overflow:
1359 case Intrinsic::ssub_with_overflow:
1360 if (*EV.idx_begin() == 0) { // Normal result.
1361 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1362 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
1363 EraseInstFromFunction(*II);
1364 return BinaryOperator::CreateSub(LHS, RHS);
1367 case Intrinsic::umul_with_overflow:
1368 case Intrinsic::smul_with_overflow:
1369 if (*EV.idx_begin() == 0) { // Normal result.
1370 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1371 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
1372 EraseInstFromFunction(*II);
1373 return BinaryOperator::CreateMul(LHS, RHS);
1381 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
1382 // If the (non-volatile) load only has one use, we can rewrite this to a
1383 // load from a GEP. This reduces the size of the load.
1384 // FIXME: If a load is used only by extractvalue instructions then this
1385 // could be done regardless of having multiple uses.
1386 if (!L->isVolatile() && L->hasOneUse()) {
1387 // extractvalue has integer indices, getelementptr has Value*s. Convert.
1388 SmallVector<Value*, 4> Indices;
1389 // Prefix an i32 0 since we need the first element.
1390 Indices.push_back(Builder->getInt32(0));
1391 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
1393 Indices.push_back(Builder->getInt32(*I));
1395 // We need to insert these at the location of the old load, not at that of
1396 // the extractvalue.
1397 Builder->SetInsertPoint(L->getParent(), L);
1398 Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), Indices);
1399 // Returning the load directly will cause the main loop to insert it in
1400 // the wrong spot, so use ReplaceInstUsesWith().
1401 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
1403 // We could simplify extracts from other values. Note that nested extracts may
1404 // already be simplified implicitly by the above: extract (extract (insert) )
1405 // will be translated into extract ( insert ( extract ) ) first and then just
1406 // the value inserted, if appropriate. Similarly for extracts from single-use
1407 // loads: extract (extract (load)) will be translated to extract (load (gep))
1408 // and if again single-use then via load (gep (gep)) to load (gep).
1409 // However, double extracts from e.g. function arguments or return values
1410 // aren't handled yet.
1417 /// TryToSinkInstruction - Try to move the specified instruction from its
1418 /// current block into the beginning of DestBlock, which can only happen if it's
1419 /// safe to move the instruction past all of the instructions between it and the
1420 /// end of its block.
1421 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
1422 assert(I->hasOneUse() && "Invariants didn't hold!");
1424 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1425 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
1428 // Do not sink alloca instructions out of the entry block.
1429 if (isa<AllocaInst>(I) && I->getParent() ==
1430 &DestBlock->getParent()->getEntryBlock())
1433 // We can only sink load instructions if there is nothing between the load and
1434 // the end of block that could change the value.
1435 if (I->mayReadFromMemory()) {
1436 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
1438 if (Scan->mayWriteToMemory())
1442 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
1444 I->moveBefore(InsertPos);
1450 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
1451 /// all reachable code to the worklist.
1453 /// This has a couple of tricks to make the code faster and more powerful. In
1454 /// particular, we constant fold and DCE instructions as we go, to avoid adding
1455 /// them to the worklist (this significantly speeds up instcombine on code where
1456 /// many instructions are dead or constant). Additionally, if we find a branch
1457 /// whose condition is a known constant, we only visit the reachable successors.
1459 static bool AddReachableCodeToWorklist(BasicBlock *BB,
1460 SmallPtrSet<BasicBlock*, 64> &Visited,
1462 const TargetData *TD) {
1463 bool MadeIRChange = false;
1464 SmallVector<BasicBlock*, 256> Worklist;
1465 Worklist.push_back(BB);
1467 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
1468 DenseMap<ConstantExpr*, Constant*> FoldedConstants;
1471 BB = Worklist.pop_back_val();
1473 // We have now visited this block! If we've already been here, ignore it.
1474 if (!Visited.insert(BB)) continue;
1476 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
1477 Instruction *Inst = BBI++;
1479 // DCE instruction if trivially dead.
1480 if (isInstructionTriviallyDead(Inst)) {
1482 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
1483 Inst->eraseFromParent();
1487 // ConstantProp instruction if trivially constant.
1488 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
1489 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
1490 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
1492 Inst->replaceAllUsesWith(C);
1494 Inst->eraseFromParent();
1499 // See if we can constant fold its operands.
1500 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
1502 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
1503 if (CE == 0) continue;
1505 Constant*& FoldRes = FoldedConstants[CE];
1507 FoldRes = ConstantFoldConstantExpression(CE, TD);
1511 if (FoldRes != CE) {
1513 MadeIRChange = true;
1518 InstrsForInstCombineWorklist.push_back(Inst);
1521 // Recursively visit successors. If this is a branch or switch on a
1522 // constant, only visit the reachable successor.
1523 TerminatorInst *TI = BB->getTerminator();
1524 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1525 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
1526 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
1527 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
1528 Worklist.push_back(ReachableBB);
1531 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1532 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
1533 // See if this is an explicit destination.
1534 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
1535 if (SI->getCaseValue(i) == Cond) {
1536 BasicBlock *ReachableBB = SI->getSuccessor(i);
1537 Worklist.push_back(ReachableBB);
1541 // Otherwise it is the default destination.
1542 Worklist.push_back(SI->getSuccessor(0));
1547 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
1548 Worklist.push_back(TI->getSuccessor(i));
1549 } while (!Worklist.empty());
1551 // Once we've found all of the instructions to add to instcombine's worklist,
1552 // add them in reverse order. This way instcombine will visit from the top
1553 // of the function down. This jives well with the way that it adds all uses
1554 // of instructions to the worklist after doing a transformation, thus avoiding
1555 // some N^2 behavior in pathological cases.
1556 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
1557 InstrsForInstCombineWorklist.size());
1559 return MadeIRChange;
1562 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
1563 MadeIRChange = false;
1565 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
1566 << F.getNameStr() << "\n");
1569 // Do a depth-first traversal of the function, populate the worklist with
1570 // the reachable instructions. Ignore blocks that are not reachable. Keep
1571 // track of which blocks we visit.
1572 SmallPtrSet<BasicBlock*, 64> Visited;
1573 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
1575 // Do a quick scan over the function. If we find any blocks that are
1576 // unreachable, remove any instructions inside of them. This prevents
1577 // the instcombine code from having to deal with some bad special cases.
1578 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1579 if (!Visited.count(BB)) {
1580 Instruction *Term = BB->getTerminator();
1581 while (Term != BB->begin()) { // Remove instrs bottom-up
1582 BasicBlock::iterator I = Term; --I;
1584 DEBUG(errs() << "IC: DCE: " << *I << '\n');
1585 // A debug intrinsic shouldn't force another iteration if we weren't
1586 // going to do one without it.
1587 if (!isa<DbgInfoIntrinsic>(I)) {
1589 MadeIRChange = true;
1592 // If I is not void type then replaceAllUsesWith undef.
1593 // This allows ValueHandlers and custom metadata to adjust itself.
1594 if (!I->getType()->isVoidTy())
1595 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1596 I->eraseFromParent();
1601 while (!Worklist.isEmpty()) {
1602 Instruction *I = Worklist.RemoveOne();
1603 if (I == 0) continue; // skip null values.
1605 // Check to see if we can DCE the instruction.
1606 if (isInstructionTriviallyDead(I)) {
1607 DEBUG(errs() << "IC: DCE: " << *I << '\n');
1608 EraseInstFromFunction(*I);
1610 MadeIRChange = true;
1614 // Instruction isn't dead, see if we can constant propagate it.
1615 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
1616 if (Constant *C = ConstantFoldInstruction(I, TD)) {
1617 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
1619 // Add operands to the worklist.
1620 ReplaceInstUsesWith(*I, C);
1622 EraseInstFromFunction(*I);
1623 MadeIRChange = true;
1627 // See if we can trivially sink this instruction to a successor basic block.
1628 if (I->hasOneUse()) {
1629 BasicBlock *BB = I->getParent();
1630 Instruction *UserInst = cast<Instruction>(I->use_back());
1631 BasicBlock *UserParent;
1633 // Get the block the use occurs in.
1634 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
1635 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
1637 UserParent = UserInst->getParent();
1639 if (UserParent != BB) {
1640 bool UserIsSuccessor = false;
1641 // See if the user is one of our successors.
1642 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
1643 if (*SI == UserParent) {
1644 UserIsSuccessor = true;
1648 // If the user is one of our immediate successors, and if that successor
1649 // only has us as a predecessors (we'd have to split the critical edge
1650 // otherwise), we can keep going.
1651 if (UserIsSuccessor && UserParent->getSinglePredecessor())
1652 // Okay, the CFG is simple enough, try to sink this instruction.
1653 MadeIRChange |= TryToSinkInstruction(I, UserParent);
1657 // Now that we have an instruction, try combining it to simplify it.
1658 Builder->SetInsertPoint(I->getParent(), I);
1659 Builder->SetCurrentDebugLocation(I->getDebugLoc());
1664 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
1665 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
1667 if (Instruction *Result = visit(*I)) {
1669 // Should we replace the old instruction with a new one?
1671 DEBUG(errs() << "IC: Old = " << *I << '\n'
1672 << " New = " << *Result << '\n');
1674 if (!I->getDebugLoc().isUnknown())
1675 Result->setDebugLoc(I->getDebugLoc());
1676 // Everything uses the new instruction now.
1677 I->replaceAllUsesWith(Result);
1679 // Push the new instruction and any users onto the worklist.
1680 Worklist.Add(Result);
1681 Worklist.AddUsersToWorkList(*Result);
1683 // Move the name to the new instruction first.
1684 Result->takeName(I);
1686 // Insert the new instruction into the basic block...
1687 BasicBlock *InstParent = I->getParent();
1688 BasicBlock::iterator InsertPos = I;
1690 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
1691 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
1694 InstParent->getInstList().insert(InsertPos, Result);
1696 EraseInstFromFunction(*I);
1699 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
1700 << " New = " << *I << '\n');
1703 // If the instruction was modified, it's possible that it is now dead.
1704 // if so, remove it.
1705 if (isInstructionTriviallyDead(I)) {
1706 EraseInstFromFunction(*I);
1709 Worklist.AddUsersToWorkList(*I);
1712 MadeIRChange = true;
1717 return MadeIRChange;
1721 bool InstCombiner::runOnFunction(Function &F) {
1722 TD = getAnalysisIfAvailable<TargetData>();
1725 /// Builder - This is an IRBuilder that automatically inserts new
1726 /// instructions into the worklist when they are created.
1727 IRBuilder<true, TargetFolder, InstCombineIRInserter>
1728 TheBuilder(F.getContext(), TargetFolder(TD),
1729 InstCombineIRInserter(Worklist));
1730 Builder = &TheBuilder;
1732 bool EverMadeChange = false;
1734 // Lower dbg.declare intrinsics otherwise their value may be clobbered
1736 EverMadeChange = LowerDbgDeclare(F);
1738 // Iterate while there is work to do.
1739 unsigned Iteration = 0;
1740 while (DoOneIteration(F, Iteration++))
1741 EverMadeChange = true;
1744 return EverMadeChange;
1747 FunctionPass *llvm::createInstructionCombiningPass() {
1748 return new InstCombiner();