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/ADT/SmallPtrSet.h"
50 #include "llvm/ADT/Statistic.h"
51 #include "llvm-c/Initialization.h"
55 using namespace llvm::PatternMatch;
57 STATISTIC(NumCombined , "Number of insts combined");
58 STATISTIC(NumConstProp, "Number of constant folds");
59 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
60 STATISTIC(NumSunkInst , "Number of instructions sunk");
61 STATISTIC(NumExpand, "Number of expansions");
62 STATISTIC(NumFactor , "Number of factorizations");
63 STATISTIC(NumReassoc , "Number of reassociations");
65 // Initialization Routines
66 void llvm::initializeInstCombine(PassRegistry &Registry) {
67 initializeInstCombinerPass(Registry);
70 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
71 initializeInstCombine(*unwrap(R));
74 char InstCombiner::ID = 0;
75 INITIALIZE_PASS(InstCombiner, "instcombine",
76 "Combine redundant instructions", false, false)
78 void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
83 /// ShouldChangeType - Return true if it is desirable to convert a computation
84 /// from 'From' to 'To'. We don't want to convert from a legal to an illegal
85 /// type for example, or from a smaller to a larger illegal type.
86 bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
87 assert(From->isIntegerTy() && To->isIntegerTy());
89 // If we don't have TD, we don't know if the source/dest are legal.
90 if (!TD) return false;
92 unsigned FromWidth = From->getPrimitiveSizeInBits();
93 unsigned ToWidth = To->getPrimitiveSizeInBits();
94 bool FromLegal = TD->isLegalInteger(FromWidth);
95 bool ToLegal = TD->isLegalInteger(ToWidth);
97 // If this is a legal integer from type, and the result would be an illegal
98 // type, don't do the transformation.
99 if (FromLegal && !ToLegal)
102 // Otherwise, if both are illegal, do not increase the size of the result. We
103 // do allow things like i160 -> i64, but not i64 -> i160.
104 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
111 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
112 /// operators which are associative or commutative:
114 // Commutative operators:
116 // 1. Order operands such that they are listed from right (least complex) to
117 // left (most complex). This puts constants before unary operators before
120 // Associative operators:
122 // 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
123 // 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
125 // Associative and commutative operators:
127 // 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
128 // 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
129 // 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
130 // if C1 and C2 are constants.
132 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
133 Instruction::BinaryOps Opcode = I.getOpcode();
134 bool Changed = false;
137 // Order operands such that they are listed from right (least complex) to
138 // left (most complex). This puts constants before unary operators before
140 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
141 getComplexity(I.getOperand(1)))
142 Changed = !I.swapOperands();
144 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
145 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
147 if (I.isAssociative()) {
148 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
149 if (Op0 && Op0->getOpcode() == Opcode) {
150 Value *A = Op0->getOperand(0);
151 Value *B = Op0->getOperand(1);
152 Value *C = I.getOperand(1);
154 // Does "B op C" simplify?
155 if (Value *V = SimplifyBinOp(Opcode, B, C, TD)) {
156 // It simplifies to V. Form "A op V".
159 // Conservatively clear the optional flags, since they may not be
160 // preserved by the reassociation.
161 I.clearSubclassOptionalData();
168 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
169 if (Op1 && Op1->getOpcode() == Opcode) {
170 Value *A = I.getOperand(0);
171 Value *B = Op1->getOperand(0);
172 Value *C = Op1->getOperand(1);
174 // Does "A op B" simplify?
175 if (Value *V = SimplifyBinOp(Opcode, A, B, TD)) {
176 // It simplifies to V. Form "V op C".
179 // Conservatively clear the optional flags, since they may not be
180 // preserved by the reassociation.
181 I.clearSubclassOptionalData();
189 if (I.isAssociative() && I.isCommutative()) {
190 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
191 if (Op0 && Op0->getOpcode() == Opcode) {
192 Value *A = Op0->getOperand(0);
193 Value *B = Op0->getOperand(1);
194 Value *C = I.getOperand(1);
196 // Does "C op A" simplify?
197 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
198 // It simplifies to V. Form "V op B".
201 // Conservatively clear the optional flags, since they may not be
202 // preserved by the reassociation.
203 I.clearSubclassOptionalData();
210 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
211 if (Op1 && Op1->getOpcode() == Opcode) {
212 Value *A = I.getOperand(0);
213 Value *B = Op1->getOperand(0);
214 Value *C = Op1->getOperand(1);
216 // Does "C op A" simplify?
217 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
218 // It simplifies to V. Form "B op V".
221 // Conservatively clear the optional flags, since they may not be
222 // preserved by the reassociation.
223 I.clearSubclassOptionalData();
230 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
231 // if C1 and C2 are constants.
233 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
234 isa<Constant>(Op0->getOperand(1)) &&
235 isa<Constant>(Op1->getOperand(1)) &&
236 Op0->hasOneUse() && Op1->hasOneUse()) {
237 Value *A = Op0->getOperand(0);
238 Constant *C1 = cast<Constant>(Op0->getOperand(1));
239 Value *B = Op1->getOperand(0);
240 Constant *C2 = cast<Constant>(Op1->getOperand(1));
242 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
243 Instruction *New = BinaryOperator::Create(Opcode, A, B);
244 InsertNewInstWith(New, I);
246 I.setOperand(0, New);
247 I.setOperand(1, Folded);
248 // Conservatively clear the optional flags, since they may not be
249 // preserved by the reassociation.
250 I.clearSubclassOptionalData();
256 // No further simplifications.
261 /// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
262 /// "(X LOp Y) ROp (X LOp Z)".
263 static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
264 Instruction::BinaryOps ROp) {
269 case Instruction::And:
270 // And distributes over Or and Xor.
274 case Instruction::Or:
275 case Instruction::Xor:
279 case Instruction::Mul:
280 // Multiplication distributes over addition and subtraction.
284 case Instruction::Add:
285 case Instruction::Sub:
289 case Instruction::Or:
290 // Or distributes over And.
294 case Instruction::And:
300 /// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
301 /// "(X ROp Z) LOp (Y ROp Z)".
302 static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
303 Instruction::BinaryOps ROp) {
304 if (Instruction::isCommutative(ROp))
305 return LeftDistributesOverRight(ROp, LOp);
306 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
307 // but this requires knowing that the addition does not overflow and other
312 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
313 /// which some other binary operation distributes over either by factorizing
314 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
315 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
316 /// a win). Returns the simplified value, or null if it didn't simplify.
317 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
318 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
319 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
320 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
321 Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); // op
324 if (Op0 && Op1 && Op0->getOpcode() == Op1->getOpcode()) {
325 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
327 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
328 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
329 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
331 // Does "X op' Y" always equal "Y op' X"?
332 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
334 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
335 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
336 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
337 // commutative case, "(A op' B) op (C op' A)"?
338 if (A == C || (InnerCommutative && A == D)) {
341 // Consider forming "A op' (B op D)".
342 // If "B op D" simplifies then it can be formed with no cost.
343 Value *V = SimplifyBinOp(TopLevelOpcode, B, D, TD);
344 // If "B op D" doesn't simplify then only go on if both of the existing
345 // operations "A op' B" and "C op' D" will be zapped as no longer used.
346 if (!V && Op0->hasOneUse() && Op1->hasOneUse())
347 V = Builder->CreateBinOp(TopLevelOpcode, B, D, Op1->getName());
350 V = Builder->CreateBinOp(InnerOpcode, A, V);
356 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
357 if (RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
358 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
359 // commutative case, "(A op' B) op (B op' D)"?
360 if (B == D || (InnerCommutative && B == C)) {
363 // Consider forming "(A op C) op' B".
364 // If "A op C" simplifies then it can be formed with no cost.
365 Value *V = SimplifyBinOp(TopLevelOpcode, A, C, TD);
366 // If "A op C" doesn't simplify then only go on if both of the existing
367 // operations "A op' B" and "C op' D" will be zapped as no longer used.
368 if (!V && Op0->hasOneUse() && Op1->hasOneUse())
369 V = Builder->CreateBinOp(TopLevelOpcode, A, C, Op0->getName());
372 V = Builder->CreateBinOp(InnerOpcode, V, B);
380 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
381 // The instruction has the form "(A op' B) op C". See if expanding it out
382 // to "(A op C) op' (B op C)" results in simplifications.
383 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
384 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
386 // Do "A op C" and "B op C" both simplify?
387 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, TD))
388 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, TD)) {
389 // They do! Return "L op' R".
391 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
392 if ((L == A && R == B) ||
393 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
395 // Otherwise return "L op' R" if it simplifies.
396 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
398 // Otherwise, create a new instruction.
399 C = Builder->CreateBinOp(InnerOpcode, L, R);
405 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
406 // The instruction has the form "A op (B op' C)". See if expanding it out
407 // to "(A op B) op' (A op C)" results in simplifications.
408 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
409 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
411 // Do "A op B" and "A op C" both simplify?
412 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, TD))
413 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, TD)) {
414 // They do! Return "L op' R".
416 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
417 if ((L == B && R == C) ||
418 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
420 // Otherwise return "L op' R" if it simplifies.
421 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
423 // Otherwise, create a new instruction.
424 A = Builder->CreateBinOp(InnerOpcode, L, R);
433 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
434 // if the LHS is a constant zero (which is the 'negate' form).
436 Value *InstCombiner::dyn_castNegVal(Value *V) const {
437 if (BinaryOperator::isNeg(V))
438 return BinaryOperator::getNegArgument(V);
440 // Constants can be considered to be negated values if they can be folded.
441 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
442 return ConstantExpr::getNeg(C);
444 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
445 if (C->getType()->getElementType()->isIntegerTy())
446 return ConstantExpr::getNeg(C);
451 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
452 // instruction if the LHS is a constant negative zero (which is the 'negate'
455 Value *InstCombiner::dyn_castFNegVal(Value *V) const {
456 if (BinaryOperator::isFNeg(V))
457 return BinaryOperator::getFNegArgument(V);
459 // Constants can be considered to be negated values if they can be folded.
460 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
461 return ConstantExpr::getFNeg(C);
463 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
464 if (C->getType()->getElementType()->isFloatingPointTy())
465 return ConstantExpr::getFNeg(C);
470 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
472 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
473 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
476 // Figure out if the constant is the left or the right argument.
477 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
478 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
480 if (Constant *SOC = dyn_cast<Constant>(SO)) {
482 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
483 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
486 Value *Op0 = SO, *Op1 = ConstOperand;
490 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
491 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
492 SO->getName()+".op");
493 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
494 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
495 SO->getName()+".cmp");
496 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
497 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
498 SO->getName()+".cmp");
499 llvm_unreachable("Unknown binary instruction type!");
502 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
503 // constant as the other operand, try to fold the binary operator into the
504 // select arguments. This also works for Cast instructions, which obviously do
505 // not have a second operand.
506 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
507 // Don't modify shared select instructions
508 if (!SI->hasOneUse()) return 0;
509 Value *TV = SI->getOperand(1);
510 Value *FV = SI->getOperand(2);
512 if (isa<Constant>(TV) || isa<Constant>(FV)) {
513 // Bool selects with constant operands can be folded to logical ops.
514 if (SI->getType()->isIntegerTy(1)) return 0;
516 // If it's a bitcast involving vectors, make sure it has the same number of
517 // elements on both sides.
518 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
519 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
520 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
522 // Verify that either both or neither are vectors.
523 if ((SrcTy == NULL) != (DestTy == NULL)) return 0;
524 // If vectors, verify that they have the same number of elements.
525 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
529 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
530 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
532 return SelectInst::Create(SI->getCondition(),
533 SelectTrueVal, SelectFalseVal);
539 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
540 /// has a PHI node as operand #0, see if we can fold the instruction into the
541 /// PHI (which is only possible if all operands to the PHI are constants).
543 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
544 PHINode *PN = cast<PHINode>(I.getOperand(0));
545 unsigned NumPHIValues = PN->getNumIncomingValues();
546 if (NumPHIValues == 0)
549 // We normally only transform phis with a single use. However, if a PHI has
550 // multiple uses and they are all the same operation, we can fold *all* of the
551 // uses into the PHI.
552 if (!PN->hasOneUse()) {
553 // Walk the use list for the instruction, comparing them to I.
554 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
556 Instruction *User = cast<Instruction>(*UI);
557 if (User != &I && !I.isIdenticalTo(User))
560 // Otherwise, we can replace *all* users with the new PHI we form.
563 // Check to see if all of the operands of the PHI are simple constants
564 // (constantint/constantfp/undef). If there is one non-constant value,
565 // remember the BB it is in. If there is more than one or if *it* is a PHI,
566 // bail out. We don't do arbitrary constant expressions here because moving
567 // their computation can be expensive without a cost model.
568 BasicBlock *NonConstBB = 0;
569 for (unsigned i = 0; i != NumPHIValues; ++i) {
570 Value *InVal = PN->getIncomingValue(i);
571 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
574 if (isa<PHINode>(InVal)) return 0; // Itself a phi.
575 if (NonConstBB) return 0; // More than one non-const value.
577 NonConstBB = PN->getIncomingBlock(i);
579 // If the InVal is an invoke at the end of the pred block, then we can't
580 // insert a computation after it without breaking the edge.
581 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
582 if (II->getParent() == NonConstBB)
585 // If the incoming non-constant value is in I's block, we will remove one
586 // instruction, but insert another equivalent one, leading to infinite
588 if (NonConstBB == I.getParent())
592 // If there is exactly one non-constant value, we can insert a copy of the
593 // operation in that block. However, if this is a critical edge, we would be
594 // inserting the computation one some other paths (e.g. inside a loop). Only
595 // do this if the pred block is unconditionally branching into the phi block.
596 if (NonConstBB != 0) {
597 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
598 if (!BI || !BI->isUnconditional()) return 0;
601 // Okay, we can do the transformation: create the new PHI node.
602 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
603 InsertNewInstBefore(NewPN, *PN);
606 // If we are going to have to insert a new computation, do so right before the
607 // predecessors terminator.
609 Builder->SetInsertPoint(NonConstBB->getTerminator());
611 // Next, add all of the operands to the PHI.
612 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
613 // We only currently try to fold the condition of a select when it is a phi,
614 // not the true/false values.
615 Value *TrueV = SI->getTrueValue();
616 Value *FalseV = SI->getFalseValue();
617 BasicBlock *PhiTransBB = PN->getParent();
618 for (unsigned i = 0; i != NumPHIValues; ++i) {
619 BasicBlock *ThisBB = PN->getIncomingBlock(i);
620 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
621 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
623 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
624 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
626 InV = Builder->CreateSelect(PN->getIncomingValue(i),
627 TrueVInPred, FalseVInPred, "phitmp");
628 NewPN->addIncoming(InV, ThisBB);
630 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
631 Constant *C = cast<Constant>(I.getOperand(1));
632 for (unsigned i = 0; i != NumPHIValues; ++i) {
634 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
635 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
636 else if (isa<ICmpInst>(CI))
637 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
640 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
642 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
644 } else if (I.getNumOperands() == 2) {
645 Constant *C = cast<Constant>(I.getOperand(1));
646 for (unsigned i = 0; i != NumPHIValues; ++i) {
648 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
649 InV = ConstantExpr::get(I.getOpcode(), InC, C);
651 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
652 PN->getIncomingValue(i), C, "phitmp");
653 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
656 CastInst *CI = cast<CastInst>(&I);
657 Type *RetTy = CI->getType();
658 for (unsigned i = 0; i != NumPHIValues; ++i) {
660 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
661 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
663 InV = Builder->CreateCast(CI->getOpcode(),
664 PN->getIncomingValue(i), I.getType(), "phitmp");
665 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
669 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
671 Instruction *User = cast<Instruction>(*UI++);
672 if (User == &I) continue;
673 ReplaceInstUsesWith(*User, NewPN);
674 EraseInstFromFunction(*User);
676 return ReplaceInstUsesWith(I, NewPN);
679 /// FindElementAtOffset - Given a type and a constant offset, determine whether
680 /// or not there is a sequence of GEP indices into the type that will land us at
681 /// the specified offset. If so, fill them into NewIndices and return the
682 /// resultant element type, otherwise return null.
683 Type *InstCombiner::FindElementAtOffset(Type *Ty, int64_t Offset,
684 SmallVectorImpl<Value*> &NewIndices) {
686 if (!Ty->isSized()) return 0;
688 // Start with the index over the outer type. Note that the type size
689 // might be zero (even if the offset isn't zero) if the indexed type
690 // is something like [0 x {int, int}]
691 Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
692 int64_t FirstIdx = 0;
693 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
694 FirstIdx = Offset/TySize;
695 Offset -= FirstIdx*TySize;
697 // Handle hosts where % returns negative instead of values [0..TySize).
703 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
706 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
708 // Index into the types. If we fail, set OrigBase to null.
710 // Indexing into tail padding between struct/array elements.
711 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
714 if (StructType *STy = dyn_cast<StructType>(Ty)) {
715 const StructLayout *SL = TD->getStructLayout(STy);
716 assert(Offset < (int64_t)SL->getSizeInBytes() &&
717 "Offset must stay within the indexed type");
719 unsigned Elt = SL->getElementContainingOffset(Offset);
720 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
723 Offset -= SL->getElementOffset(Elt);
724 Ty = STy->getElementType(Elt);
725 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
726 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
727 assert(EltSize && "Cannot index into a zero-sized array");
728 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
730 Ty = AT->getElementType();
732 // Otherwise, we can't index into the middle of this atomic type, bail.
740 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
741 // If this GEP has only 0 indices, it is the same pointer as
742 // Src. If Src is not a trivial GEP too, don't combine
744 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
750 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
751 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
753 if (Value *V = SimplifyGEPInst(Ops, TD))
754 return ReplaceInstUsesWith(GEP, V);
756 Value *PtrOp = GEP.getOperand(0);
758 // Eliminate unneeded casts for indices, and replace indices which displace
759 // by multiples of a zero size type with zero.
761 bool MadeChange = false;
762 Type *IntPtrTy = TD->getIntPtrType(GEP.getContext());
764 gep_type_iterator GTI = gep_type_begin(GEP);
765 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
766 I != E; ++I, ++GTI) {
767 // Skip indices into struct types.
768 SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
769 if (!SeqTy) continue;
771 // If the element type has zero size then any index over it is equivalent
772 // to an index of zero, so replace it with zero if it is not zero already.
773 if (SeqTy->getElementType()->isSized() &&
774 TD->getTypeAllocSize(SeqTy->getElementType()) == 0)
775 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
776 *I = Constant::getNullValue(IntPtrTy);
780 if ((*I)->getType() != IntPtrTy) {
781 // If we are using a wider index than needed for this platform, shrink
782 // it to what we need. If narrower, sign-extend it to what we need.
783 // This explicit cast can make subsequent optimizations more obvious.
784 *I = Builder->CreateIntCast(*I, IntPtrTy, true);
788 if (MadeChange) return &GEP;
791 // Combine Indices - If the source pointer to this getelementptr instruction
792 // is a getelementptr instruction, combine the indices of the two
793 // getelementptr instructions into a single instruction.
795 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
796 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
799 // Note that if our source is a gep chain itself that we wait for that
800 // chain to be resolved before we perform this transformation. This
801 // avoids us creating a TON of code in some cases.
802 if (GEPOperator *SrcGEP =
803 dyn_cast<GEPOperator>(Src->getOperand(0)))
804 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
805 return 0; // Wait until our source is folded to completion.
807 SmallVector<Value*, 8> Indices;
809 // Find out whether the last index in the source GEP is a sequential idx.
810 bool EndsWithSequential = false;
811 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
813 EndsWithSequential = !(*I)->isStructTy();
815 // Can we combine the two pointer arithmetics offsets?
816 if (EndsWithSequential) {
817 // Replace: gep (gep %P, long B), long A, ...
818 // With: T = long A+B; gep %P, T, ...
821 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
822 Value *GO1 = GEP.getOperand(1);
823 if (SO1 == Constant::getNullValue(SO1->getType())) {
825 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
828 // If they aren't the same type, then the input hasn't been processed
829 // by the loop above yet (which canonicalizes sequential index types to
830 // intptr_t). Just avoid transforming this until the input has been
832 if (SO1->getType() != GO1->getType())
834 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
837 // Update the GEP in place if possible.
838 if (Src->getNumOperands() == 2) {
839 GEP.setOperand(0, Src->getOperand(0));
840 GEP.setOperand(1, Sum);
843 Indices.append(Src->op_begin()+1, Src->op_end()-1);
844 Indices.push_back(Sum);
845 Indices.append(GEP.op_begin()+2, GEP.op_end());
846 } else if (isa<Constant>(*GEP.idx_begin()) &&
847 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
848 Src->getNumOperands() != 1) {
849 // Otherwise we can do the fold if the first index of the GEP is a zero
850 Indices.append(Src->op_begin()+1, Src->op_end());
851 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
854 if (!Indices.empty())
855 return (GEP.isInBounds() && Src->isInBounds()) ?
856 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices,
858 GetElementPtrInst::Create(Src->getOperand(0), Indices, GEP.getName());
861 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
862 Value *StrippedPtr = PtrOp->stripPointerCasts();
863 PointerType *StrippedPtrTy =cast<PointerType>(StrippedPtr->getType());
864 if (StrippedPtr != PtrOp &&
865 StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace()) {
867 bool HasZeroPointerIndex = false;
868 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
869 HasZeroPointerIndex = C->isZero();
871 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
872 // into : GEP [10 x i8]* X, i32 0, ...
874 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
875 // into : GEP i8* X, ...
877 // This occurs when the program declares an array extern like "int X[];"
878 if (HasZeroPointerIndex) {
879 PointerType *CPTy = cast<PointerType>(PtrOp->getType());
880 if (ArrayType *CATy =
881 dyn_cast<ArrayType>(CPTy->getElementType())) {
882 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
883 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
885 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
886 GetElementPtrInst *Res =
887 GetElementPtrInst::Create(StrippedPtr, Idx, GEP.getName());
888 Res->setIsInBounds(GEP.isInBounds());
892 if (ArrayType *XATy =
893 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
894 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
895 if (CATy->getElementType() == XATy->getElementType()) {
896 // -> GEP [10 x i8]* X, i32 0, ...
897 // At this point, we know that the cast source type is a pointer
898 // to an array of the same type as the destination pointer
899 // array. Because the array type is never stepped over (there
900 // is a leading zero) we can fold the cast into this GEP.
901 GEP.setOperand(0, StrippedPtr);
906 } else if (GEP.getNumOperands() == 2) {
907 // Transform things like:
908 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
909 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
910 Type *SrcElTy = StrippedPtrTy->getElementType();
911 Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
912 if (TD && SrcElTy->isArrayTy() &&
913 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
914 TD->getTypeAllocSize(ResElTy)) {
916 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
917 Idx[1] = GEP.getOperand(1);
918 Value *NewGEP = GEP.isInBounds() ?
919 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
920 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
921 // V and GEP are both pointer types --> BitCast
922 return new BitCastInst(NewGEP, GEP.getType());
925 // Transform things like:
926 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
927 // (where tmp = 8*tmp2) into:
928 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
930 if (TD && SrcElTy->isArrayTy() && ResElTy->isIntegerTy(8)) {
931 uint64_t ArrayEltSize =
932 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
934 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
935 // allow either a mul, shift, or constant here.
937 ConstantInt *Scale = 0;
938 if (ArrayEltSize == 1) {
939 NewIdx = GEP.getOperand(1);
940 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
941 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
942 NewIdx = ConstantInt::get(CI->getType(), 1);
944 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
945 if (Inst->getOpcode() == Instruction::Shl &&
946 isa<ConstantInt>(Inst->getOperand(1))) {
947 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
948 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
949 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
951 NewIdx = Inst->getOperand(0);
952 } else if (Inst->getOpcode() == Instruction::Mul &&
953 isa<ConstantInt>(Inst->getOperand(1))) {
954 Scale = cast<ConstantInt>(Inst->getOperand(1));
955 NewIdx = Inst->getOperand(0);
959 // If the index will be to exactly the right offset with the scale taken
960 // out, perform the transformation. Note, we don't know whether Scale is
961 // signed or not. We'll use unsigned version of division/modulo
962 // operation after making sure Scale doesn't have the sign bit set.
963 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
964 Scale->getZExtValue() % ArrayEltSize == 0) {
965 Scale = ConstantInt::get(Scale->getType(),
966 Scale->getZExtValue() / ArrayEltSize);
967 if (Scale->getZExtValue() != 1) {
968 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
970 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
973 // Insert the new GEP instruction.
975 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
977 Value *NewGEP = GEP.isInBounds() ?
978 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()):
979 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
980 // The NewGEP must be pointer typed, so must the old one -> BitCast
981 return new BitCastInst(NewGEP, GEP.getType());
987 /// See if we can simplify:
988 /// X = bitcast A* to B*
989 /// Y = gep X, <...constant indices...>
990 /// into a gep of the original struct. This is important for SROA and alias
991 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
992 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
994 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices() &&
995 StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace()) {
997 // Determine how much the GEP moves the pointer. We are guaranteed to get
998 // a constant back from EmitGEPOffset.
999 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
1000 int64_t Offset = OffsetV->getSExtValue();
1002 // If this GEP instruction doesn't move the pointer, just replace the GEP
1003 // with a bitcast of the real input to the dest type.
1005 // If the bitcast is of an allocation, and the allocation will be
1006 // converted to match the type of the cast, don't touch this.
1007 if (isa<AllocaInst>(BCI->getOperand(0)) ||
1008 isMalloc(BCI->getOperand(0))) {
1009 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1010 if (Instruction *I = visitBitCast(*BCI)) {
1013 BCI->getParent()->getInstList().insert(BCI, I);
1014 ReplaceInstUsesWith(*BCI, I);
1019 return new BitCastInst(BCI->getOperand(0), GEP.getType());
1022 // Otherwise, if the offset is non-zero, we need to find out if there is a
1023 // field at Offset in 'A's type. If so, we can pull the cast through the
1025 SmallVector<Value*, 8> NewIndices;
1027 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
1028 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
1029 Value *NGEP = GEP.isInBounds() ?
1030 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices) :
1031 Builder->CreateGEP(BCI->getOperand(0), NewIndices);
1033 if (NGEP->getType() == GEP.getType())
1034 return ReplaceInstUsesWith(GEP, NGEP);
1035 NGEP->takeName(&GEP);
1036 return new BitCastInst(NGEP, GEP.getType());
1046 static bool IsOnlyNullComparedAndFreed(const Value &V) {
1047 for (Value::const_use_iterator UI = V.use_begin(), UE = V.use_end();
1049 const User *U = *UI;
1052 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(U))
1053 if (ICI->isEquality() && isa<ConstantPointerNull>(ICI->getOperand(1)))
1060 Instruction *InstCombiner::visitMalloc(Instruction &MI) {
1061 // If we have a malloc call which is only used in any amount of comparisons
1062 // to null and free calls, delete the calls and replace the comparisons with
1063 // true or false as appropriate.
1064 if (IsOnlyNullComparedAndFreed(MI)) {
1065 for (Value::use_iterator UI = MI.use_begin(), UE = MI.use_end();
1067 // We can assume that every remaining use is a free call or an icmp eq/ne
1068 // to null, so the cast is safe.
1069 Instruction *I = cast<Instruction>(*UI);
1071 // Early increment here, as we're about to get rid of the user.
1074 if (isFreeCall(I)) {
1075 EraseInstFromFunction(*cast<CallInst>(I));
1078 // Again, the cast is safe.
1079 ICmpInst *C = cast<ICmpInst>(I);
1080 ReplaceInstUsesWith(*C, ConstantInt::get(Type::getInt1Ty(C->getContext()),
1081 C->isFalseWhenEqual()));
1082 EraseInstFromFunction(*C);
1084 return EraseInstFromFunction(MI);
1091 Instruction *InstCombiner::visitFree(CallInst &FI) {
1092 Value *Op = FI.getArgOperand(0);
1094 // free undef -> unreachable.
1095 if (isa<UndefValue>(Op)) {
1096 // Insert a new store to null because we cannot modify the CFG here.
1097 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
1098 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
1099 return EraseInstFromFunction(FI);
1102 // If we have 'free null' delete the instruction. This can happen in stl code
1103 // when lots of inlining happens.
1104 if (isa<ConstantPointerNull>(Op))
1105 return EraseInstFromFunction(FI);
1112 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1113 // Change br (not X), label True, label False to: br X, label False, True
1115 BasicBlock *TrueDest;
1116 BasicBlock *FalseDest;
1117 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
1118 !isa<Constant>(X)) {
1119 // Swap Destinations and condition...
1121 BI.setSuccessor(0, FalseDest);
1122 BI.setSuccessor(1, TrueDest);
1126 // Cannonicalize fcmp_one -> fcmp_oeq
1127 FCmpInst::Predicate FPred; Value *Y;
1128 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
1129 TrueDest, FalseDest)) &&
1130 BI.getCondition()->hasOneUse())
1131 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
1132 FPred == FCmpInst::FCMP_OGE) {
1133 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
1134 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
1136 // Swap Destinations and condition.
1137 BI.setSuccessor(0, FalseDest);
1138 BI.setSuccessor(1, TrueDest);
1143 // Cannonicalize icmp_ne -> icmp_eq
1144 ICmpInst::Predicate IPred;
1145 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
1146 TrueDest, FalseDest)) &&
1147 BI.getCondition()->hasOneUse())
1148 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
1149 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
1150 IPred == ICmpInst::ICMP_SGE) {
1151 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
1152 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
1153 // Swap Destinations and condition.
1154 BI.setSuccessor(0, FalseDest);
1155 BI.setSuccessor(1, TrueDest);
1163 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
1164 Value *Cond = SI.getCondition();
1165 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
1166 if (I->getOpcode() == Instruction::Add)
1167 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1168 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
1169 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
1171 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
1173 SI.setOperand(0, I->getOperand(0));
1181 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
1182 Value *Agg = EV.getAggregateOperand();
1184 if (!EV.hasIndices())
1185 return ReplaceInstUsesWith(EV, Agg);
1187 if (Constant *C = dyn_cast<Constant>(Agg)) {
1188 if (isa<UndefValue>(C))
1189 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
1191 if (isa<ConstantAggregateZero>(C))
1192 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
1194 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
1195 // Extract the element indexed by the first index out of the constant
1196 Value *V = C->getOperand(*EV.idx_begin());
1197 if (EV.getNumIndices() > 1)
1198 // Extract the remaining indices out of the constant indexed by the
1200 return ExtractValueInst::Create(V, EV.getIndices().slice(1));
1202 return ReplaceInstUsesWith(EV, V);
1204 return 0; // Can't handle other constants
1206 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
1207 // We're extracting from an insertvalue instruction, compare the indices
1208 const unsigned *exti, *exte, *insi, *inse;
1209 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
1210 exte = EV.idx_end(), inse = IV->idx_end();
1211 exti != exte && insi != inse;
1214 // The insert and extract both reference distinctly different elements.
1215 // This means the extract is not influenced by the insert, and we can
1216 // replace the aggregate operand of the extract with the aggregate
1217 // operand of the insert. i.e., replace
1218 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1219 // %E = extractvalue { i32, { i32 } } %I, 0
1221 // %E = extractvalue { i32, { i32 } } %A, 0
1222 return ExtractValueInst::Create(IV->getAggregateOperand(),
1225 if (exti == exte && insi == inse)
1226 // Both iterators are at the end: Index lists are identical. Replace
1227 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1228 // %C = extractvalue { i32, { i32 } } %B, 1, 0
1230 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
1232 // The extract list is a prefix of the insert list. i.e. replace
1233 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1234 // %E = extractvalue { i32, { i32 } } %I, 1
1236 // %X = extractvalue { i32, { i32 } } %A, 1
1237 // %E = insertvalue { i32 } %X, i32 42, 0
1238 // by switching the order of the insert and extract (though the
1239 // insertvalue should be left in, since it may have other uses).
1240 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
1242 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
1243 makeArrayRef(insi, inse));
1246 // The insert list is a prefix of the extract list
1247 // We can simply remove the common indices from the extract and make it
1248 // operate on the inserted value instead of the insertvalue result.
1250 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1251 // %E = extractvalue { i32, { i32 } } %I, 1, 0
1253 // %E extractvalue { i32 } { i32 42 }, 0
1254 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
1255 makeArrayRef(exti, exte));
1257 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
1258 // We're extracting from an intrinsic, see if we're the only user, which
1259 // allows us to simplify multiple result intrinsics to simpler things that
1260 // just get one value.
1261 if (II->hasOneUse()) {
1262 // Check if we're grabbing the overflow bit or the result of a 'with
1263 // overflow' intrinsic. If it's the latter we can remove the intrinsic
1264 // and replace it with a traditional binary instruction.
1265 switch (II->getIntrinsicID()) {
1266 case Intrinsic::uadd_with_overflow:
1267 case Intrinsic::sadd_with_overflow:
1268 if (*EV.idx_begin() == 0) { // Normal result.
1269 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1270 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
1271 EraseInstFromFunction(*II);
1272 return BinaryOperator::CreateAdd(LHS, RHS);
1275 // If the normal result of the add is dead, and the RHS is a constant,
1276 // we can transform this into a range comparison.
1277 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
1278 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
1279 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
1280 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
1281 ConstantExpr::getNot(CI));
1283 case Intrinsic::usub_with_overflow:
1284 case Intrinsic::ssub_with_overflow:
1285 if (*EV.idx_begin() == 0) { // Normal result.
1286 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1287 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
1288 EraseInstFromFunction(*II);
1289 return BinaryOperator::CreateSub(LHS, RHS);
1292 case Intrinsic::umul_with_overflow:
1293 case Intrinsic::smul_with_overflow:
1294 if (*EV.idx_begin() == 0) { // Normal result.
1295 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1296 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
1297 EraseInstFromFunction(*II);
1298 return BinaryOperator::CreateMul(LHS, RHS);
1306 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
1307 // If the (non-volatile) load only has one use, we can rewrite this to a
1308 // load from a GEP. This reduces the size of the load.
1309 // FIXME: If a load is used only by extractvalue instructions then this
1310 // could be done regardless of having multiple uses.
1311 if (!L->isVolatile() && L->hasOneUse()) {
1312 // extractvalue has integer indices, getelementptr has Value*s. Convert.
1313 SmallVector<Value*, 4> Indices;
1314 // Prefix an i32 0 since we need the first element.
1315 Indices.push_back(Builder->getInt32(0));
1316 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
1318 Indices.push_back(Builder->getInt32(*I));
1320 // We need to insert these at the location of the old load, not at that of
1321 // the extractvalue.
1322 Builder->SetInsertPoint(L->getParent(), L);
1323 Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), Indices);
1324 // Returning the load directly will cause the main loop to insert it in
1325 // the wrong spot, so use ReplaceInstUsesWith().
1326 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
1328 // We could simplify extracts from other values. Note that nested extracts may
1329 // already be simplified implicitly by the above: extract (extract (insert) )
1330 // will be translated into extract ( insert ( extract ) ) first and then just
1331 // the value inserted, if appropriate. Similarly for extracts from single-use
1332 // loads: extract (extract (load)) will be translated to extract (load (gep))
1333 // and if again single-use then via load (gep (gep)) to load (gep).
1334 // However, double extracts from e.g. function arguments or return values
1335 // aren't handled yet.
1342 /// TryToSinkInstruction - Try to move the specified instruction from its
1343 /// current block into the beginning of DestBlock, which can only happen if it's
1344 /// safe to move the instruction past all of the instructions between it and the
1345 /// end of its block.
1346 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
1347 assert(I->hasOneUse() && "Invariants didn't hold!");
1349 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1350 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
1353 // Do not sink alloca instructions out of the entry block.
1354 if (isa<AllocaInst>(I) && I->getParent() ==
1355 &DestBlock->getParent()->getEntryBlock())
1358 // We can only sink load instructions if there is nothing between the load and
1359 // the end of block that could change the value.
1360 if (I->mayReadFromMemory()) {
1361 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
1363 if (Scan->mayWriteToMemory())
1367 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
1369 I->moveBefore(InsertPos);
1375 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
1376 /// all reachable code to the worklist.
1378 /// This has a couple of tricks to make the code faster and more powerful. In
1379 /// particular, we constant fold and DCE instructions as we go, to avoid adding
1380 /// them to the worklist (this significantly speeds up instcombine on code where
1381 /// many instructions are dead or constant). Additionally, if we find a branch
1382 /// whose condition is a known constant, we only visit the reachable successors.
1384 static bool AddReachableCodeToWorklist(BasicBlock *BB,
1385 SmallPtrSet<BasicBlock*, 64> &Visited,
1387 const TargetData *TD) {
1388 bool MadeIRChange = false;
1389 SmallVector<BasicBlock*, 256> Worklist;
1390 Worklist.push_back(BB);
1392 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
1393 DenseMap<ConstantExpr*, Constant*> FoldedConstants;
1396 BB = Worklist.pop_back_val();
1398 // We have now visited this block! If we've already been here, ignore it.
1399 if (!Visited.insert(BB)) continue;
1401 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
1402 Instruction *Inst = BBI++;
1404 // DCE instruction if trivially dead.
1405 if (isInstructionTriviallyDead(Inst)) {
1407 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
1408 Inst->eraseFromParent();
1412 // ConstantProp instruction if trivially constant.
1413 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
1414 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
1415 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
1417 Inst->replaceAllUsesWith(C);
1419 Inst->eraseFromParent();
1424 // See if we can constant fold its operands.
1425 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
1427 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
1428 if (CE == 0) continue;
1430 Constant*& FoldRes = FoldedConstants[CE];
1432 FoldRes = ConstantFoldConstantExpression(CE, TD);
1436 if (FoldRes != CE) {
1438 MadeIRChange = true;
1443 InstrsForInstCombineWorklist.push_back(Inst);
1446 // Recursively visit successors. If this is a branch or switch on a
1447 // constant, only visit the reachable successor.
1448 TerminatorInst *TI = BB->getTerminator();
1449 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1450 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
1451 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
1452 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
1453 Worklist.push_back(ReachableBB);
1456 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1457 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
1458 // See if this is an explicit destination.
1459 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
1460 if (SI->getCaseValue(i) == Cond) {
1461 BasicBlock *ReachableBB = SI->getSuccessor(i);
1462 Worklist.push_back(ReachableBB);
1466 // Otherwise it is the default destination.
1467 Worklist.push_back(SI->getSuccessor(0));
1472 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
1473 Worklist.push_back(TI->getSuccessor(i));
1474 } while (!Worklist.empty());
1476 // Once we've found all of the instructions to add to instcombine's worklist,
1477 // add them in reverse order. This way instcombine will visit from the top
1478 // of the function down. This jives well with the way that it adds all uses
1479 // of instructions to the worklist after doing a transformation, thus avoiding
1480 // some N^2 behavior in pathological cases.
1481 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
1482 InstrsForInstCombineWorklist.size());
1484 return MadeIRChange;
1487 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
1488 MadeIRChange = false;
1490 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
1491 << F.getNameStr() << "\n");
1494 // Do a depth-first traversal of the function, populate the worklist with
1495 // the reachable instructions. Ignore blocks that are not reachable. Keep
1496 // track of which blocks we visit.
1497 SmallPtrSet<BasicBlock*, 64> Visited;
1498 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
1500 // Do a quick scan over the function. If we find any blocks that are
1501 // unreachable, remove any instructions inside of them. This prevents
1502 // the instcombine code from having to deal with some bad special cases.
1503 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1504 if (!Visited.count(BB)) {
1505 Instruction *Term = BB->getTerminator();
1506 while (Term != BB->begin()) { // Remove instrs bottom-up
1507 BasicBlock::iterator I = Term; --I;
1509 DEBUG(errs() << "IC: DCE: " << *I << '\n');
1510 // A debug intrinsic shouldn't force another iteration if we weren't
1511 // going to do one without it.
1512 if (!isa<DbgInfoIntrinsic>(I)) {
1514 MadeIRChange = true;
1517 // If I is not void type then replaceAllUsesWith undef.
1518 // This allows ValueHandlers and custom metadata to adjust itself.
1519 if (!I->getType()->isVoidTy())
1520 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1521 I->eraseFromParent();
1526 while (!Worklist.isEmpty()) {
1527 Instruction *I = Worklist.RemoveOne();
1528 if (I == 0) continue; // skip null values.
1530 // Check to see if we can DCE the instruction.
1531 if (isInstructionTriviallyDead(I)) {
1532 DEBUG(errs() << "IC: DCE: " << *I << '\n');
1533 EraseInstFromFunction(*I);
1535 MadeIRChange = true;
1539 // Instruction isn't dead, see if we can constant propagate it.
1540 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
1541 if (Constant *C = ConstantFoldInstruction(I, TD)) {
1542 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
1544 // Add operands to the worklist.
1545 ReplaceInstUsesWith(*I, C);
1547 EraseInstFromFunction(*I);
1548 MadeIRChange = true;
1552 // See if we can trivially sink this instruction to a successor basic block.
1553 if (I->hasOneUse()) {
1554 BasicBlock *BB = I->getParent();
1555 Instruction *UserInst = cast<Instruction>(I->use_back());
1556 BasicBlock *UserParent;
1558 // Get the block the use occurs in.
1559 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
1560 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
1562 UserParent = UserInst->getParent();
1564 if (UserParent != BB) {
1565 bool UserIsSuccessor = false;
1566 // See if the user is one of our successors.
1567 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
1568 if (*SI == UserParent) {
1569 UserIsSuccessor = true;
1573 // If the user is one of our immediate successors, and if that successor
1574 // only has us as a predecessors (we'd have to split the critical edge
1575 // otherwise), we can keep going.
1576 if (UserIsSuccessor && UserParent->getSinglePredecessor())
1577 // Okay, the CFG is simple enough, try to sink this instruction.
1578 MadeIRChange |= TryToSinkInstruction(I, UserParent);
1582 // Now that we have an instruction, try combining it to simplify it.
1583 Builder->SetInsertPoint(I->getParent(), I);
1584 Builder->SetCurrentDebugLocation(I->getDebugLoc());
1589 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
1590 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
1592 if (Instruction *Result = visit(*I)) {
1594 // Should we replace the old instruction with a new one?
1596 DEBUG(errs() << "IC: Old = " << *I << '\n'
1597 << " New = " << *Result << '\n');
1599 if (!I->getDebugLoc().isUnknown())
1600 Result->setDebugLoc(I->getDebugLoc());
1601 // Everything uses the new instruction now.
1602 I->replaceAllUsesWith(Result);
1604 // Push the new instruction and any users onto the worklist.
1605 Worklist.Add(Result);
1606 Worklist.AddUsersToWorkList(*Result);
1608 // Move the name to the new instruction first.
1609 Result->takeName(I);
1611 // Insert the new instruction into the basic block...
1612 BasicBlock *InstParent = I->getParent();
1613 BasicBlock::iterator InsertPos = I;
1615 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
1616 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
1619 InstParent->getInstList().insert(InsertPos, Result);
1621 EraseInstFromFunction(*I);
1624 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
1625 << " New = " << *I << '\n');
1628 // If the instruction was modified, it's possible that it is now dead.
1629 // if so, remove it.
1630 if (isInstructionTriviallyDead(I)) {
1631 EraseInstFromFunction(*I);
1634 Worklist.AddUsersToWorkList(*I);
1637 MadeIRChange = true;
1642 return MadeIRChange;
1646 bool InstCombiner::runOnFunction(Function &F) {
1647 TD = getAnalysisIfAvailable<TargetData>();
1650 /// Builder - This is an IRBuilder that automatically inserts new
1651 /// instructions into the worklist when they are created.
1652 IRBuilder<true, TargetFolder, InstCombineIRInserter>
1653 TheBuilder(F.getContext(), TargetFolder(TD),
1654 InstCombineIRInserter(Worklist));
1655 Builder = &TheBuilder;
1657 bool EverMadeChange = false;
1659 // Lower dbg.declare intrinsics otherwise their value may be clobbered
1661 EverMadeChange = LowerDbgDeclare(F);
1663 // Iterate while there is work to do.
1664 unsigned Iteration = 0;
1665 while (DoOneIteration(F, Iteration++))
1666 EverMadeChange = true;
1669 return EverMadeChange;
1672 FunctionPass *llvm::createInstructionCombiningPass() {
1673 return new InstCombiner();