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 {
79 AU.addPreservedID(LCSSAID);
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(const Type *From, const 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)
112 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
113 /// operators which are associative or commutative:
115 // Commutative operators:
117 // 1. Order operands such that they are listed from right (least complex) to
118 // left (most complex). This puts constants before unary operators before
121 // Associative operators:
123 // 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
124 // 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
126 // Associative and commutative operators:
128 // 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
129 // 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
130 // 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
131 // if C1 and C2 are constants.
133 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
134 Instruction::BinaryOps Opcode = I.getOpcode();
135 bool Changed = false;
138 // Order operands such that they are listed from right (least complex) to
139 // left (most complex). This puts constants before unary operators before
141 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
142 getComplexity(I.getOperand(1)))
143 Changed = !I.swapOperands();
145 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
146 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
148 if (I.isAssociative()) {
149 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
150 if (Op0 && Op0->getOpcode() == Opcode) {
151 Value *A = Op0->getOperand(0);
152 Value *B = Op0->getOperand(1);
153 Value *C = I.getOperand(1);
155 // Does "B op C" simplify?
156 if (Value *V = SimplifyBinOp(Opcode, B, C, TD)) {
157 // It simplifies to V. Form "A op V".
160 // Conservatively clear the optional flags, since they may not be
161 // preserved by the reassociation.
162 I.clearSubclassOptionalData();
169 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
170 if (Op1 && Op1->getOpcode() == Opcode) {
171 Value *A = I.getOperand(0);
172 Value *B = Op1->getOperand(0);
173 Value *C = Op1->getOperand(1);
175 // Does "A op B" simplify?
176 if (Value *V = SimplifyBinOp(Opcode, A, B, TD)) {
177 // It simplifies to V. Form "V op C".
180 // Conservatively clear the optional flags, since they may not be
181 // preserved by the reassociation.
182 I.clearSubclassOptionalData();
190 if (I.isAssociative() && I.isCommutative()) {
191 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
192 if (Op0 && Op0->getOpcode() == Opcode) {
193 Value *A = Op0->getOperand(0);
194 Value *B = Op0->getOperand(1);
195 Value *C = I.getOperand(1);
197 // Does "C op A" simplify?
198 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
199 // It simplifies to V. Form "V op B".
202 // Conservatively clear the optional flags, since they may not be
203 // preserved by the reassociation.
204 I.clearSubclassOptionalData();
211 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
212 if (Op1 && Op1->getOpcode() == Opcode) {
213 Value *A = I.getOperand(0);
214 Value *B = Op1->getOperand(0);
215 Value *C = Op1->getOperand(1);
217 // Does "C op A" simplify?
218 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
219 // It simplifies to V. Form "B op V".
222 // Conservatively clear the optional flags, since they may not be
223 // preserved by the reassociation.
224 I.clearSubclassOptionalData();
231 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
232 // if C1 and C2 are constants.
234 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
235 isa<Constant>(Op0->getOperand(1)) &&
236 isa<Constant>(Op1->getOperand(1)) &&
237 Op0->hasOneUse() && Op1->hasOneUse()) {
238 Value *A = Op0->getOperand(0);
239 Constant *C1 = cast<Constant>(Op0->getOperand(1));
240 Value *B = Op1->getOperand(0);
241 Constant *C2 = cast<Constant>(Op1->getOperand(1));
243 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
244 Instruction *New = BinaryOperator::Create(Opcode, A, B, Op1->getName(),
247 I.setOperand(0, New);
248 I.setOperand(1, Folded);
249 // Conservatively clear the optional flags, since they may not be
250 // preserved by the reassociation.
251 I.clearSubclassOptionalData();
257 // No further simplifications.
262 /// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
263 /// "(X LOp Y) ROp (X LOp Z)".
264 static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
265 Instruction::BinaryOps ROp) {
270 case Instruction::And:
271 // And distributes over Or and Xor.
275 case Instruction::Or:
276 case Instruction::Xor:
280 case Instruction::Mul:
281 // Multiplication distributes over addition and subtraction.
285 case Instruction::Add:
286 case Instruction::Sub:
290 case Instruction::Or:
291 // Or distributes over And.
295 case Instruction::And:
301 /// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
302 /// "(X ROp Z) LOp (Y ROp Z)".
303 static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
304 Instruction::BinaryOps ROp) {
305 if (Instruction::isCommutative(ROp))
306 return LeftDistributesOverRight(ROp, LOp);
307 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
308 // but this requires knowing that the addition does not overflow and other
313 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
314 /// which some other binary operation distributes over either by factorizing
315 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
316 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
317 /// a win). Returns the simplified value, or null if it didn't simplify.
318 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
319 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
320 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
321 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
322 Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); // op
325 if (Op0 && Op1 && Op0->getOpcode() == Op1->getOpcode()) {
326 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
328 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
329 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
330 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
332 // Does "X op' Y" always equal "Y op' X"?
333 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
335 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
336 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
337 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
338 // commutative case, "(A op' B) op (C op' A)"?
339 if (A == C || (InnerCommutative && A == D)) {
342 // Consider forming "A op' (B op D)".
343 // If "B op D" simplifies then it can be formed with no cost.
344 Value *V = SimplifyBinOp(TopLevelOpcode, B, D, TD);
345 // If "B op D" doesn't simplify then only go on if both of the existing
346 // operations "A op' B" and "C op' D" will be zapped as no longer used.
347 if (!V && Op0->hasOneUse() && Op1->hasOneUse())
348 V = Builder->CreateBinOp(TopLevelOpcode, B, D, Op1->getName());
351 V = Builder->CreateBinOp(InnerOpcode, A, V);
357 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
358 if (RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
359 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
360 // commutative case, "(A op' B) op (B op' D)"?
361 if (B == D || (InnerCommutative && B == C)) {
364 // Consider forming "(A op C) op' B".
365 // If "A op C" simplifies then it can be formed with no cost.
366 Value *V = SimplifyBinOp(TopLevelOpcode, A, C, TD);
367 // If "A op C" doesn't simplify then only go on if both of the existing
368 // operations "A op' B" and "C op' D" will be zapped as no longer used.
369 if (!V && Op0->hasOneUse() && Op1->hasOneUse())
370 V = Builder->CreateBinOp(TopLevelOpcode, A, C, Op0->getName());
373 V = Builder->CreateBinOp(InnerOpcode, V, B);
381 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
382 // The instruction has the form "(A op' B) op C". See if expanding it out
383 // to "(A op C) op' (B op C)" results in simplifications.
384 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
385 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
387 // Do "A op C" and "B op C" both simplify?
388 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, TD))
389 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, TD)) {
390 // They do! Return "L op' R".
392 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
393 if ((L == A && R == B) ||
394 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
396 // Otherwise return "L op' R" if it simplifies.
397 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
399 // Otherwise, create a new instruction.
400 C = Builder->CreateBinOp(InnerOpcode, L, R);
406 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
407 // The instruction has the form "A op (B op' C)". See if expanding it out
408 // to "(A op B) op' (A op C)" results in simplifications.
409 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
410 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
412 // Do "A op B" and "A op C" both simplify?
413 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, TD))
414 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, TD)) {
415 // They do! Return "L op' R".
417 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
418 if ((L == B && R == C) ||
419 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
421 // Otherwise return "L op' R" if it simplifies.
422 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
424 // Otherwise, create a new instruction.
425 A = Builder->CreateBinOp(InnerOpcode, L, R);
434 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
435 // if the LHS is a constant zero (which is the 'negate' form).
437 Value *InstCombiner::dyn_castNegVal(Value *V) const {
438 if (BinaryOperator::isNeg(V))
439 return BinaryOperator::getNegArgument(V);
441 // Constants can be considered to be negated values if they can be folded.
442 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
443 return ConstantExpr::getNeg(C);
445 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
446 if (C->getType()->getElementType()->isIntegerTy())
447 return ConstantExpr::getNeg(C);
452 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
453 // instruction if the LHS is a constant negative zero (which is the 'negate'
456 Value *InstCombiner::dyn_castFNegVal(Value *V) const {
457 if (BinaryOperator::isFNeg(V))
458 return BinaryOperator::getFNegArgument(V);
460 // Constants can be considered to be negated values if they can be folded.
461 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
462 return ConstantExpr::getFNeg(C);
464 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
465 if (C->getType()->getElementType()->isFloatingPointTy())
466 return ConstantExpr::getFNeg(C);
471 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
473 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
474 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
477 // Figure out if the constant is the left or the right argument.
478 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
479 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
481 if (Constant *SOC = dyn_cast<Constant>(SO)) {
483 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
484 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
487 Value *Op0 = SO, *Op1 = ConstOperand;
491 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
492 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
493 SO->getName()+".op");
494 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
495 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
496 SO->getName()+".cmp");
497 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
498 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
499 SO->getName()+".cmp");
500 llvm_unreachable("Unknown binary instruction type!");
503 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
504 // constant as the other operand, try to fold the binary operator into the
505 // select arguments. This also works for Cast instructions, which obviously do
506 // not have a second operand.
507 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
508 // Don't modify shared select instructions
509 if (!SI->hasOneUse()) return 0;
510 Value *TV = SI->getOperand(1);
511 Value *FV = SI->getOperand(2);
513 if (isa<Constant>(TV) || isa<Constant>(FV)) {
514 // Bool selects with constant operands can be folded to logical ops.
515 if (SI->getType()->isIntegerTy(1)) return 0;
517 // If it's a bitcast involving vectors, make sure it has the same number of
518 // elements on both sides.
519 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
520 const VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
521 const VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
523 // Verify that either both or neither are vectors.
524 if ((SrcTy == NULL) != (DestTy == NULL)) return 0;
525 // If vectors, verify that they have the same number of elements.
526 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
530 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
531 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
533 return SelectInst::Create(SI->getCondition(),
534 SelectTrueVal, SelectFalseVal);
540 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
541 /// has a PHI node as operand #0, see if we can fold the instruction into the
542 /// PHI (which is only possible if all operands to the PHI are constants).
544 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
545 PHINode *PN = cast<PHINode>(I.getOperand(0));
546 unsigned NumPHIValues = PN->getNumIncomingValues();
547 if (NumPHIValues == 0)
550 // We normally only transform phis with a single use. However, if a PHI has
551 // multiple uses and they are all the same operation, we can fold *all* of the
552 // uses into the PHI.
553 if (!PN->hasOneUse()) {
554 // Walk the use list for the instruction, comparing them to I.
555 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
557 Instruction *User = cast<Instruction>(*UI);
558 if (User != &I && !I.isIdenticalTo(User))
561 // Otherwise, we can replace *all* users with the new PHI we form.
564 // Check to see if all of the operands of the PHI are simple constants
565 // (constantint/constantfp/undef). If there is one non-constant value,
566 // remember the BB it is in. If there is more than one or if *it* is a PHI,
567 // bail out. We don't do arbitrary constant expressions here because moving
568 // their computation can be expensive without a cost model.
569 BasicBlock *NonConstBB = 0;
570 for (unsigned i = 0; i != NumPHIValues; ++i) {
571 Value *InVal = PN->getIncomingValue(i);
572 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
575 if (isa<PHINode>(InVal)) return 0; // Itself a phi.
576 if (NonConstBB) return 0; // More than one non-const value.
578 NonConstBB = PN->getIncomingBlock(i);
580 // If the InVal is an invoke at the end of the pred block, then we can't
581 // insert a computation after it without breaking the edge.
582 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
583 if (II->getParent() == NonConstBB)
586 // If the incoming non-constant value is in I's block, we will remove one
587 // instruction, but insert another equivalent one, leading to infinite
589 if (NonConstBB == I.getParent())
593 // If there is exactly one non-constant value, we can insert a copy of the
594 // operation in that block. However, if this is a critical edge, we would be
595 // inserting the computation one some other paths (e.g. inside a loop). Only
596 // do this if the pred block is unconditionally branching into the phi block.
597 if (NonConstBB != 0) {
598 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
599 if (!BI || !BI->isUnconditional()) return 0;
602 // Okay, we can do the transformation: create the new PHI node.
603 PHINode *NewPN = PHINode::Create(I.getType(), "");
604 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
605 InsertNewInstBefore(NewPN, *PN);
608 // If we are going to have to insert a new computation, do so right before the
609 // predecessors terminator.
611 Builder->SetInsertPoint(NonConstBB->getTerminator());
613 // Next, add all of the operands to the PHI.
614 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
615 // We only currently try to fold the condition of a select when it is a phi,
616 // not the true/false values.
617 Value *TrueV = SI->getTrueValue();
618 Value *FalseV = SI->getFalseValue();
619 BasicBlock *PhiTransBB = PN->getParent();
620 for (unsigned i = 0; i != NumPHIValues; ++i) {
621 BasicBlock *ThisBB = PN->getIncomingBlock(i);
622 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
623 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
625 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
626 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
628 InV = Builder->CreateSelect(PN->getIncomingValue(i),
629 TrueVInPred, FalseVInPred, "phitmp");
630 NewPN->addIncoming(InV, ThisBB);
632 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
633 Constant *C = cast<Constant>(I.getOperand(1));
634 for (unsigned i = 0; i != NumPHIValues; ++i) {
636 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
637 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
638 else if (isa<ICmpInst>(CI))
639 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
642 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
644 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
646 } else if (I.getNumOperands() == 2) {
647 Constant *C = cast<Constant>(I.getOperand(1));
648 for (unsigned i = 0; i != NumPHIValues; ++i) {
650 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
651 InV = ConstantExpr::get(I.getOpcode(), InC, C);
653 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
654 PN->getIncomingValue(i), C, "phitmp");
655 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
658 CastInst *CI = cast<CastInst>(&I);
659 const Type *RetTy = CI->getType();
660 for (unsigned i = 0; i != NumPHIValues; ++i) {
662 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
663 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
665 InV = Builder->CreateCast(CI->getOpcode(),
666 PN->getIncomingValue(i), I.getType(), "phitmp");
667 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
671 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
673 Instruction *User = cast<Instruction>(*UI++);
674 if (User == &I) continue;
675 ReplaceInstUsesWith(*User, NewPN);
676 EraseInstFromFunction(*User);
678 return ReplaceInstUsesWith(I, NewPN);
681 /// FindElementAtOffset - Given a type and a constant offset, determine whether
682 /// or not there is a sequence of GEP indices into the type that will land us at
683 /// the specified offset. If so, fill them into NewIndices and return the
684 /// resultant element type, otherwise return null.
685 const Type *InstCombiner::FindElementAtOffset(const Type *Ty, int64_t Offset,
686 SmallVectorImpl<Value*> &NewIndices) {
688 if (!Ty->isSized()) return 0;
690 // Start with the index over the outer type. Note that the type size
691 // might be zero (even if the offset isn't zero) if the indexed type
692 // is something like [0 x {int, int}]
693 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
694 int64_t FirstIdx = 0;
695 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
696 FirstIdx = Offset/TySize;
697 Offset -= FirstIdx*TySize;
699 // Handle hosts where % returns negative instead of values [0..TySize).
705 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
708 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
710 // Index into the types. If we fail, set OrigBase to null.
712 // Indexing into tail padding between struct/array elements.
713 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
716 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
717 const StructLayout *SL = TD->getStructLayout(STy);
718 assert(Offset < (int64_t)SL->getSizeInBytes() &&
719 "Offset must stay within the indexed type");
721 unsigned Elt = SL->getElementContainingOffset(Offset);
722 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
725 Offset -= SL->getElementOffset(Elt);
726 Ty = STy->getElementType(Elt);
727 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
728 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
729 assert(EltSize && "Cannot index into a zero-sized array");
730 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
732 Ty = AT->getElementType();
734 // Otherwise, we can't index into the middle of this atomic type, bail.
744 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
745 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
747 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
748 return ReplaceInstUsesWith(GEP, V);
750 Value *PtrOp = GEP.getOperand(0);
752 // Eliminate unneeded casts for indices, and replace indices which displace
753 // by multiples of a zero size type with zero.
755 bool MadeChange = false;
756 const Type *IntPtrTy = TD->getIntPtrType(GEP.getContext());
758 gep_type_iterator GTI = gep_type_begin(GEP);
759 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
760 I != E; ++I, ++GTI) {
761 // Skip indices into struct types.
762 const SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
763 if (!SeqTy) continue;
765 // If the element type has zero size then any index over it is equivalent
766 // to an index of zero, so replace it with zero if it is not zero already.
767 if (SeqTy->getElementType()->isSized() &&
768 TD->getTypeAllocSize(SeqTy->getElementType()) == 0)
769 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
770 *I = Constant::getNullValue(IntPtrTy);
774 if ((*I)->getType() != IntPtrTy) {
775 // If we are using a wider index than needed for this platform, shrink
776 // it to what we need. If narrower, sign-extend it to what we need.
777 // This explicit cast can make subsequent optimizations more obvious.
778 *I = Builder->CreateIntCast(*I, IntPtrTy, true);
782 if (MadeChange) return &GEP;
785 // Combine Indices - If the source pointer to this getelementptr instruction
786 // is a getelementptr instruction, combine the indices of the two
787 // getelementptr instructions into a single instruction.
789 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
790 // Note that if our source is a gep chain itself that we wait for that
791 // chain to be resolved before we perform this transformation. This
792 // avoids us creating a TON of code in some cases.
794 if (GetElementPtrInst *SrcGEP =
795 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
796 if (SrcGEP->getNumOperands() == 2)
797 return 0; // Wait until our source is folded to completion.
799 SmallVector<Value*, 8> Indices;
801 // Find out whether the last index in the source GEP is a sequential idx.
802 bool EndsWithSequential = false;
803 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
805 EndsWithSequential = !(*I)->isStructTy();
807 // Can we combine the two pointer arithmetics offsets?
808 if (EndsWithSequential) {
809 // Replace: gep (gep %P, long B), long A, ...
810 // With: T = long A+B; gep %P, T, ...
813 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
814 Value *GO1 = GEP.getOperand(1);
815 if (SO1 == Constant::getNullValue(SO1->getType())) {
817 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
820 // If they aren't the same type, then the input hasn't been processed
821 // by the loop above yet (which canonicalizes sequential index types to
822 // intptr_t). Just avoid transforming this until the input has been
824 if (SO1->getType() != GO1->getType())
826 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
829 // Update the GEP in place if possible.
830 if (Src->getNumOperands() == 2) {
831 GEP.setOperand(0, Src->getOperand(0));
832 GEP.setOperand(1, Sum);
835 Indices.append(Src->op_begin()+1, Src->op_end()-1);
836 Indices.push_back(Sum);
837 Indices.append(GEP.op_begin()+2, GEP.op_end());
838 } else if (isa<Constant>(*GEP.idx_begin()) &&
839 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
840 Src->getNumOperands() != 1) {
841 // Otherwise we can do the fold if the first index of the GEP is a zero
842 Indices.append(Src->op_begin()+1, Src->op_end());
843 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
846 if (!Indices.empty())
847 return (GEP.isInBounds() && Src->isInBounds()) ?
848 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
849 Indices.end(), GEP.getName()) :
850 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
851 Indices.end(), GEP.getName());
854 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
855 Value *StrippedPtr = PtrOp->stripPointerCasts();
856 if (StrippedPtr != PtrOp) {
857 const PointerType *StrippedPtrTy =cast<PointerType>(StrippedPtr->getType());
859 bool HasZeroPointerIndex = false;
860 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
861 HasZeroPointerIndex = C->isZero();
863 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
864 // into : GEP [10 x i8]* X, i32 0, ...
866 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
867 // into : GEP i8* X, ...
869 // This occurs when the program declares an array extern like "int X[];"
870 if (HasZeroPointerIndex) {
871 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
872 if (const ArrayType *CATy =
873 dyn_cast<ArrayType>(CPTy->getElementType())) {
874 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
875 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
877 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
878 GetElementPtrInst *Res =
879 GetElementPtrInst::Create(StrippedPtr, Idx.begin(),
880 Idx.end(), GEP.getName());
881 Res->setIsInBounds(GEP.isInBounds());
885 if (const ArrayType *XATy =
886 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
887 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
888 if (CATy->getElementType() == XATy->getElementType()) {
889 // -> GEP [10 x i8]* X, i32 0, ...
890 // At this point, we know that the cast source type is a pointer
891 // to an array of the same type as the destination pointer
892 // array. Because the array type is never stepped over (there
893 // is a leading zero) we can fold the cast into this GEP.
894 GEP.setOperand(0, StrippedPtr);
899 } else if (GEP.getNumOperands() == 2) {
900 // Transform things like:
901 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
902 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
903 const Type *SrcElTy = StrippedPtrTy->getElementType();
904 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
905 if (TD && SrcElTy->isArrayTy() &&
906 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
907 TD->getTypeAllocSize(ResElTy)) {
909 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
910 Idx[1] = GEP.getOperand(1);
911 Value *NewGEP = GEP.isInBounds() ?
912 Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2, GEP.getName()) :
913 Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName());
914 // V and GEP are both pointer types --> BitCast
915 return new BitCastInst(NewGEP, GEP.getType());
918 // Transform things like:
919 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
920 // (where tmp = 8*tmp2) into:
921 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
923 if (TD && SrcElTy->isArrayTy() && ResElTy->isIntegerTy(8)) {
924 uint64_t ArrayEltSize =
925 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
927 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
928 // allow either a mul, shift, or constant here.
930 ConstantInt *Scale = 0;
931 if (ArrayEltSize == 1) {
932 NewIdx = GEP.getOperand(1);
933 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
934 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
935 NewIdx = ConstantInt::get(CI->getType(), 1);
937 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
938 if (Inst->getOpcode() == Instruction::Shl &&
939 isa<ConstantInt>(Inst->getOperand(1))) {
940 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
941 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
942 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
944 NewIdx = Inst->getOperand(0);
945 } else if (Inst->getOpcode() == Instruction::Mul &&
946 isa<ConstantInt>(Inst->getOperand(1))) {
947 Scale = cast<ConstantInt>(Inst->getOperand(1));
948 NewIdx = Inst->getOperand(0);
952 // If the index will be to exactly the right offset with the scale taken
953 // out, perform the transformation. Note, we don't know whether Scale is
954 // signed or not. We'll use unsigned version of division/modulo
955 // operation after making sure Scale doesn't have the sign bit set.
956 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
957 Scale->getZExtValue() % ArrayEltSize == 0) {
958 Scale = ConstantInt::get(Scale->getType(),
959 Scale->getZExtValue() / ArrayEltSize);
960 if (Scale->getZExtValue() != 1) {
961 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
963 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
966 // Insert the new GEP instruction.
968 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
970 Value *NewGEP = GEP.isInBounds() ?
971 Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2,GEP.getName()):
972 Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName());
973 // The NewGEP must be pointer typed, so must the old one -> BitCast
974 return new BitCastInst(NewGEP, GEP.getType());
980 /// See if we can simplify:
981 /// X = bitcast A* to B*
982 /// Y = gep X, <...constant indices...>
983 /// into a gep of the original struct. This is important for SROA and alias
984 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
985 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
987 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
988 // Determine how much the GEP moves the pointer. We are guaranteed to get
989 // a constant back from EmitGEPOffset.
990 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
991 int64_t Offset = OffsetV->getSExtValue();
993 // If this GEP instruction doesn't move the pointer, just replace the GEP
994 // with a bitcast of the real input to the dest type.
996 // If the bitcast is of an allocation, and the allocation will be
997 // converted to match the type of the cast, don't touch this.
998 if (isa<AllocaInst>(BCI->getOperand(0)) ||
999 isMalloc(BCI->getOperand(0))) {
1000 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1001 if (Instruction *I = visitBitCast(*BCI)) {
1004 BCI->getParent()->getInstList().insert(BCI, I);
1005 ReplaceInstUsesWith(*BCI, I);
1010 return new BitCastInst(BCI->getOperand(0), GEP.getType());
1013 // Otherwise, if the offset is non-zero, we need to find out if there is a
1014 // field at Offset in 'A's type. If so, we can pull the cast through the
1016 SmallVector<Value*, 8> NewIndices;
1018 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
1019 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
1020 Value *NGEP = GEP.isInBounds() ?
1021 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
1023 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
1026 if (NGEP->getType() == GEP.getType())
1027 return ReplaceInstUsesWith(GEP, NGEP);
1028 NGEP->takeName(&GEP);
1029 return new BitCastInst(NGEP, GEP.getType());
1039 static bool IsOnlyNullComparedAndFreed(const Value &V) {
1040 for (Value::const_use_iterator UI = V.use_begin(), UE = V.use_end();
1042 const User *U = *UI;
1045 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(U))
1046 if (ICI->isEquality() && isa<ConstantPointerNull>(ICI->getOperand(1)))
1053 Instruction *InstCombiner::visitMalloc(Instruction &MI) {
1054 // If we have a malloc call which is only used in any amount of comparisons
1055 // to null and free calls, delete the calls and replace the comparisons with
1056 // true or false as appropriate.
1057 if (IsOnlyNullComparedAndFreed(MI)) {
1058 for (Value::use_iterator UI = MI.use_begin(), UE = MI.use_end();
1060 // We can assume that every remaining use is a free call or an icmp eq/ne
1061 // to null, so the cast is safe.
1062 Instruction *I = cast<Instruction>(*UI);
1064 // Early increment here, as we're about to get rid of the user.
1067 if (isFreeCall(I)) {
1068 EraseInstFromFunction(*cast<CallInst>(I));
1071 // Again, the cast is safe.
1072 ICmpInst *C = cast<ICmpInst>(I);
1073 ReplaceInstUsesWith(*C, ConstantInt::get(Type::getInt1Ty(C->getContext()),
1074 C->isFalseWhenEqual()));
1075 EraseInstFromFunction(*C);
1077 return EraseInstFromFunction(MI);
1084 Instruction *InstCombiner::visitFree(CallInst &FI) {
1085 Value *Op = FI.getArgOperand(0);
1087 // free undef -> unreachable.
1088 if (isa<UndefValue>(Op)) {
1089 // Insert a new store to null because we cannot modify the CFG here.
1090 new StoreInst(ConstantInt::getTrue(FI.getContext()),
1091 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
1092 return EraseInstFromFunction(FI);
1095 // If we have 'free null' delete the instruction. This can happen in stl code
1096 // when lots of inlining happens.
1097 if (isa<ConstantPointerNull>(Op))
1098 return EraseInstFromFunction(FI);
1105 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1106 // Change br (not X), label True, label False to: br X, label False, True
1108 BasicBlock *TrueDest;
1109 BasicBlock *FalseDest;
1110 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
1111 !isa<Constant>(X)) {
1112 // Swap Destinations and condition...
1114 BI.setSuccessor(0, FalseDest);
1115 BI.setSuccessor(1, TrueDest);
1119 // Cannonicalize fcmp_one -> fcmp_oeq
1120 FCmpInst::Predicate FPred; Value *Y;
1121 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
1122 TrueDest, FalseDest)) &&
1123 BI.getCondition()->hasOneUse())
1124 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
1125 FPred == FCmpInst::FCMP_OGE) {
1126 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
1127 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
1129 // Swap Destinations and condition.
1130 BI.setSuccessor(0, FalseDest);
1131 BI.setSuccessor(1, TrueDest);
1136 // Cannonicalize icmp_ne -> icmp_eq
1137 ICmpInst::Predicate IPred;
1138 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
1139 TrueDest, FalseDest)) &&
1140 BI.getCondition()->hasOneUse())
1141 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
1142 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
1143 IPred == ICmpInst::ICMP_SGE) {
1144 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
1145 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
1146 // Swap Destinations and condition.
1147 BI.setSuccessor(0, FalseDest);
1148 BI.setSuccessor(1, TrueDest);
1156 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
1157 Value *Cond = SI.getCondition();
1158 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
1159 if (I->getOpcode() == Instruction::Add)
1160 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1161 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
1162 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
1164 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
1166 SI.setOperand(0, I->getOperand(0));
1174 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
1175 Value *Agg = EV.getAggregateOperand();
1177 if (!EV.hasIndices())
1178 return ReplaceInstUsesWith(EV, Agg);
1180 if (Constant *C = dyn_cast<Constant>(Agg)) {
1181 if (isa<UndefValue>(C))
1182 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
1184 if (isa<ConstantAggregateZero>(C))
1185 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
1187 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
1188 // Extract the element indexed by the first index out of the constant
1189 Value *V = C->getOperand(*EV.idx_begin());
1190 if (EV.getNumIndices() > 1)
1191 // Extract the remaining indices out of the constant indexed by the
1193 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
1195 return ReplaceInstUsesWith(EV, V);
1197 return 0; // Can't handle other constants
1199 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
1200 // We're extracting from an insertvalue instruction, compare the indices
1201 const unsigned *exti, *exte, *insi, *inse;
1202 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
1203 exte = EV.idx_end(), inse = IV->idx_end();
1204 exti != exte && insi != inse;
1207 // The insert and extract both reference distinctly different elements.
1208 // This means the extract is not influenced by the insert, and we can
1209 // replace the aggregate operand of the extract with the aggregate
1210 // operand of the insert. i.e., replace
1211 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1212 // %E = extractvalue { i32, { i32 } } %I, 0
1214 // %E = extractvalue { i32, { i32 } } %A, 0
1215 return ExtractValueInst::Create(IV->getAggregateOperand(),
1216 EV.idx_begin(), EV.idx_end());
1218 if (exti == exte && insi == inse)
1219 // Both iterators are at the end: Index lists are identical. Replace
1220 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1221 // %C = extractvalue { i32, { i32 } } %B, 1, 0
1223 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
1225 // The extract list is a prefix of the insert list. i.e. replace
1226 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1227 // %E = extractvalue { i32, { i32 } } %I, 1
1229 // %X = extractvalue { i32, { i32 } } %A, 1
1230 // %E = insertvalue { i32 } %X, i32 42, 0
1231 // by switching the order of the insert and extract (though the
1232 // insertvalue should be left in, since it may have other uses).
1233 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
1234 EV.idx_begin(), EV.idx_end());
1235 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
1239 // The insert list is a prefix of the extract list
1240 // We can simply remove the common indices from the extract and make it
1241 // operate on the inserted value instead of the insertvalue result.
1243 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1244 // %E = extractvalue { i32, { i32 } } %I, 1, 0
1246 // %E extractvalue { i32 } { i32 42 }, 0
1247 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
1250 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
1251 // We're extracting from an intrinsic, see if we're the only user, which
1252 // allows us to simplify multiple result intrinsics to simpler things that
1253 // just get one value.
1254 if (II->hasOneUse()) {
1255 // Check if we're grabbing the overflow bit or the result of a 'with
1256 // overflow' intrinsic. If it's the latter we can remove the intrinsic
1257 // and replace it with a traditional binary instruction.
1258 switch (II->getIntrinsicID()) {
1259 case Intrinsic::uadd_with_overflow:
1260 case Intrinsic::sadd_with_overflow:
1261 if (*EV.idx_begin() == 0) { // Normal result.
1262 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1263 II->replaceAllUsesWith(UndefValue::get(II->getType()));
1264 EraseInstFromFunction(*II);
1265 return BinaryOperator::CreateAdd(LHS, RHS);
1268 // If the normal result of the add is dead, and the RHS is a constant,
1269 // we can transform this into a range comparison.
1270 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
1271 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
1272 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
1273 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
1274 ConstantExpr::getNot(CI));
1276 case Intrinsic::usub_with_overflow:
1277 case Intrinsic::ssub_with_overflow:
1278 if (*EV.idx_begin() == 0) { // Normal result.
1279 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1280 II->replaceAllUsesWith(UndefValue::get(II->getType()));
1281 EraseInstFromFunction(*II);
1282 return BinaryOperator::CreateSub(LHS, RHS);
1285 case Intrinsic::umul_with_overflow:
1286 case Intrinsic::smul_with_overflow:
1287 if (*EV.idx_begin() == 0) { // Normal result.
1288 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1289 II->replaceAllUsesWith(UndefValue::get(II->getType()));
1290 EraseInstFromFunction(*II);
1291 return BinaryOperator::CreateMul(LHS, RHS);
1299 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
1300 // If the (non-volatile) load only has one use, we can rewrite this to a
1301 // load from a GEP. This reduces the size of the load.
1302 // FIXME: If a load is used only by extractvalue instructions then this
1303 // could be done regardless of having multiple uses.
1304 if (!L->isVolatile() && L->hasOneUse()) {
1305 // extractvalue has integer indices, getelementptr has Value*s. Convert.
1306 SmallVector<Value*, 4> Indices;
1307 // Prefix an i32 0 since we need the first element.
1308 Indices.push_back(Builder->getInt32(0));
1309 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
1311 Indices.push_back(Builder->getInt32(*I));
1313 // We need to insert these at the location of the old load, not at that of
1314 // the extractvalue.
1315 Builder->SetInsertPoint(L->getParent(), L);
1316 Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(),
1317 Indices.begin(), Indices.end());
1318 // Returning the load directly will cause the main loop to insert it in
1319 // the wrong spot, so use ReplaceInstUsesWith().
1320 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
1322 // We could simplify extracts from other values. Note that nested extracts may
1323 // already be simplified implicitly by the above: extract (extract (insert) )
1324 // will be translated into extract ( insert ( extract ) ) first and then just
1325 // the value inserted, if appropriate. Similarly for extracts from single-use
1326 // loads: extract (extract (load)) will be translated to extract (load (gep))
1327 // and if again single-use then via load (gep (gep)) to load (gep).
1328 // However, double extracts from e.g. function arguments or return values
1329 // aren't handled yet.
1336 /// TryToSinkInstruction - Try to move the specified instruction from its
1337 /// current block into the beginning of DestBlock, which can only happen if it's
1338 /// safe to move the instruction past all of the instructions between it and the
1339 /// end of its block.
1340 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
1341 assert(I->hasOneUse() && "Invariants didn't hold!");
1343 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1344 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
1347 // Do not sink alloca instructions out of the entry block.
1348 if (isa<AllocaInst>(I) && I->getParent() ==
1349 &DestBlock->getParent()->getEntryBlock())
1352 // We can only sink load instructions if there is nothing between the load and
1353 // the end of block that could change the value.
1354 if (I->mayReadFromMemory()) {
1355 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
1357 if (Scan->mayWriteToMemory())
1361 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
1363 I->moveBefore(InsertPos);
1369 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
1370 /// all reachable code to the worklist.
1372 /// This has a couple of tricks to make the code faster and more powerful. In
1373 /// particular, we constant fold and DCE instructions as we go, to avoid adding
1374 /// them to the worklist (this significantly speeds up instcombine on code where
1375 /// many instructions are dead or constant). Additionally, if we find a branch
1376 /// whose condition is a known constant, we only visit the reachable successors.
1378 static bool AddReachableCodeToWorklist(BasicBlock *BB,
1379 SmallPtrSet<BasicBlock*, 64> &Visited,
1381 const TargetData *TD) {
1382 bool MadeIRChange = false;
1383 SmallVector<BasicBlock*, 256> Worklist;
1384 Worklist.push_back(BB);
1386 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
1387 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
1390 BB = Worklist.pop_back_val();
1392 // We have now visited this block! If we've already been here, ignore it.
1393 if (!Visited.insert(BB)) continue;
1395 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
1396 Instruction *Inst = BBI++;
1398 // DCE instruction if trivially dead.
1399 if (isInstructionTriviallyDead(Inst)) {
1401 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
1402 Inst->eraseFromParent();
1406 // ConstantProp instruction if trivially constant.
1407 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
1408 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
1409 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
1411 Inst->replaceAllUsesWith(C);
1413 Inst->eraseFromParent();
1418 // See if we can constant fold its operands.
1419 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
1421 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
1422 if (CE == 0) continue;
1424 // If we already folded this constant, don't try again.
1425 if (!FoldedConstants.insert(CE))
1428 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
1429 if (NewC && NewC != CE) {
1431 MadeIRChange = true;
1436 InstrsForInstCombineWorklist.push_back(Inst);
1439 // Recursively visit successors. If this is a branch or switch on a
1440 // constant, only visit the reachable successor.
1441 TerminatorInst *TI = BB->getTerminator();
1442 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1443 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
1444 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
1445 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
1446 Worklist.push_back(ReachableBB);
1449 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1450 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
1451 // See if this is an explicit destination.
1452 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
1453 if (SI->getCaseValue(i) == Cond) {
1454 BasicBlock *ReachableBB = SI->getSuccessor(i);
1455 Worklist.push_back(ReachableBB);
1459 // Otherwise it is the default destination.
1460 Worklist.push_back(SI->getSuccessor(0));
1465 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
1466 Worklist.push_back(TI->getSuccessor(i));
1467 } while (!Worklist.empty());
1469 // Once we've found all of the instructions to add to instcombine's worklist,
1470 // add them in reverse order. This way instcombine will visit from the top
1471 // of the function down. This jives well with the way that it adds all uses
1472 // of instructions to the worklist after doing a transformation, thus avoiding
1473 // some N^2 behavior in pathological cases.
1474 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
1475 InstrsForInstCombineWorklist.size());
1477 return MadeIRChange;
1480 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
1481 MadeIRChange = false;
1483 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
1484 << F.getNameStr() << "\n");
1487 // Do a depth-first traversal of the function, populate the worklist with
1488 // the reachable instructions. Ignore blocks that are not reachable. Keep
1489 // track of which blocks we visit.
1490 SmallPtrSet<BasicBlock*, 64> Visited;
1491 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
1493 // Do a quick scan over the function. If we find any blocks that are
1494 // unreachable, remove any instructions inside of them. This prevents
1495 // the instcombine code from having to deal with some bad special cases.
1496 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1497 if (!Visited.count(BB)) {
1498 Instruction *Term = BB->getTerminator();
1499 while (Term != BB->begin()) { // Remove instrs bottom-up
1500 BasicBlock::iterator I = Term; --I;
1502 DEBUG(errs() << "IC: DCE: " << *I << '\n');
1503 // A debug intrinsic shouldn't force another iteration if we weren't
1504 // going to do one without it.
1505 if (!isa<DbgInfoIntrinsic>(I)) {
1507 MadeIRChange = true;
1510 // If I is not void type then replaceAllUsesWith undef.
1511 // This allows ValueHandlers and custom metadata to adjust itself.
1512 if (!I->getType()->isVoidTy())
1513 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1514 I->eraseFromParent();
1519 while (!Worklist.isEmpty()) {
1520 Instruction *I = Worklist.RemoveOne();
1521 if (I == 0) continue; // skip null values.
1523 // Check to see if we can DCE the instruction.
1524 if (isInstructionTriviallyDead(I)) {
1525 DEBUG(errs() << "IC: DCE: " << *I << '\n');
1526 EraseInstFromFunction(*I);
1528 MadeIRChange = true;
1532 // Instruction isn't dead, see if we can constant propagate it.
1533 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
1534 if (Constant *C = ConstantFoldInstruction(I, TD)) {
1535 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
1537 // Add operands to the worklist.
1538 ReplaceInstUsesWith(*I, C);
1540 EraseInstFromFunction(*I);
1541 MadeIRChange = true;
1545 // See if we can trivially sink this instruction to a successor basic block.
1546 if (I->hasOneUse()) {
1547 BasicBlock *BB = I->getParent();
1548 Instruction *UserInst = cast<Instruction>(I->use_back());
1549 BasicBlock *UserParent;
1551 // Get the block the use occurs in.
1552 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
1553 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
1555 UserParent = UserInst->getParent();
1557 if (UserParent != BB) {
1558 bool UserIsSuccessor = false;
1559 // See if the user is one of our successors.
1560 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
1561 if (*SI == UserParent) {
1562 UserIsSuccessor = true;
1566 // If the user is one of our immediate successors, and if that successor
1567 // only has us as a predecessors (we'd have to split the critical edge
1568 // otherwise), we can keep going.
1569 if (UserIsSuccessor && UserParent->getSinglePredecessor())
1570 // Okay, the CFG is simple enough, try to sink this instruction.
1571 MadeIRChange |= TryToSinkInstruction(I, UserParent);
1575 // Now that we have an instruction, try combining it to simplify it.
1576 Builder->SetInsertPoint(I->getParent(), I);
1581 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
1582 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
1584 if (Instruction *Result = visit(*I)) {
1586 // Should we replace the old instruction with a new one?
1588 DEBUG(errs() << "IC: Old = " << *I << '\n'
1589 << " New = " << *Result << '\n');
1591 Result->setDebugLoc(I->getDebugLoc());
1592 // Everything uses the new instruction now.
1593 I->replaceAllUsesWith(Result);
1595 // Push the new instruction and any users onto the worklist.
1596 Worklist.Add(Result);
1597 Worklist.AddUsersToWorkList(*Result);
1599 // Move the name to the new instruction first.
1600 Result->takeName(I);
1602 // Insert the new instruction into the basic block...
1603 BasicBlock *InstParent = I->getParent();
1604 BasicBlock::iterator InsertPos = I;
1606 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
1607 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
1610 InstParent->getInstList().insert(InsertPos, Result);
1612 EraseInstFromFunction(*I);
1615 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
1616 << " New = " << *I << '\n');
1619 // If the instruction was modified, it's possible that it is now dead.
1620 // if so, remove it.
1621 if (isInstructionTriviallyDead(I)) {
1622 EraseInstFromFunction(*I);
1625 Worklist.AddUsersToWorkList(*I);
1628 MadeIRChange = true;
1633 return MadeIRChange;
1637 bool InstCombiner::runOnFunction(Function &F) {
1638 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
1639 TD = getAnalysisIfAvailable<TargetData>();
1642 /// Builder - This is an IRBuilder that automatically inserts new
1643 /// instructions into the worklist when they are created.
1644 IRBuilder<true, TargetFolder, InstCombineIRInserter>
1645 TheBuilder(F.getContext(), TargetFolder(TD),
1646 InstCombineIRInserter(Worklist));
1647 Builder = &TheBuilder;
1649 bool EverMadeChange = false;
1651 // Iterate while there is work to do.
1652 unsigned Iteration = 0;
1653 while (DoOneIteration(F, Iteration++))
1654 EverMadeChange = true;
1657 return EverMadeChange;
1660 FunctionPass *llvm::createInstructionCombiningPass() {
1661 return new InstCombiner();