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-c/Initialization.h"
40 #include "llvm/ADT/SmallPtrSet.h"
41 #include "llvm/ADT/Statistic.h"
42 #include "llvm/ADT/StringSwitch.h"
43 #include "llvm/Analysis/ConstantFolding.h"
44 #include "llvm/Analysis/InstructionSimplify.h"
45 #include "llvm/Analysis/MemoryBuiltins.h"
46 #include "llvm/IR/DataLayout.h"
47 #include "llvm/IR/IntrinsicInst.h"
48 #include "llvm/Support/CFG.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/GetElementPtrTypeIterator.h"
52 #include "llvm/Support/PatternMatch.h"
53 #include "llvm/Support/ValueHandle.h"
54 #include "llvm/Target/TargetLibraryInfo.h"
55 #include "llvm/Transforms/Utils/Local.h"
59 using namespace llvm::PatternMatch;
61 STATISTIC(NumCombined , "Number of insts combined");
62 STATISTIC(NumConstProp, "Number of constant folds");
63 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
64 STATISTIC(NumSunkInst , "Number of instructions sunk");
65 STATISTIC(NumExpand, "Number of expansions");
66 STATISTIC(NumFactor , "Number of factorizations");
67 STATISTIC(NumReassoc , "Number of reassociations");
69 static cl::opt<bool> UnsafeFPShrink("enable-double-float-shrink", cl::Hidden,
71 cl::desc("Enable unsafe double to float "
72 "shrinking for math lib calls"));
74 // Initialization Routines
75 void llvm::initializeInstCombine(PassRegistry &Registry) {
76 initializeInstCombinerPass(Registry);
79 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
80 initializeInstCombine(*unwrap(R));
83 char InstCombiner::ID = 0;
84 INITIALIZE_PASS_BEGIN(InstCombiner, "instcombine",
85 "Combine redundant instructions", false, false)
86 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
87 INITIALIZE_PASS_END(InstCombiner, "instcombine",
88 "Combine redundant instructions", false, false)
90 void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
92 AU.addRequired<TargetLibraryInfo>();
96 Value *InstCombiner::EmitGEPOffset(User *GEP) {
97 return llvm::EmitGEPOffset(Builder, *getDataLayout(), GEP);
100 /// ShouldChangeType - Return true if it is desirable to convert a computation
101 /// from 'From' to 'To'. We don't want to convert from a legal to an illegal
102 /// type for example, or from a smaller to a larger illegal type.
103 bool InstCombiner::ShouldChangeType(Type *From, Type *To) const {
104 assert(From->isIntegerTy() && To->isIntegerTy());
106 // If we don't have TD, we don't know if the source/dest are legal.
107 if (!TD) return false;
109 unsigned FromWidth = From->getPrimitiveSizeInBits();
110 unsigned ToWidth = To->getPrimitiveSizeInBits();
111 bool FromLegal = TD->isLegalInteger(FromWidth);
112 bool ToLegal = TD->isLegalInteger(ToWidth);
114 // If this is a legal integer from type, and the result would be an illegal
115 // type, don't do the transformation.
116 if (FromLegal && !ToLegal)
119 // Otherwise, if both are illegal, do not increase the size of the result. We
120 // do allow things like i160 -> i64, but not i64 -> i160.
121 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
127 // Return true, if No Signed Wrap should be maintained for I.
128 // The No Signed Wrap flag can be kept if the operation "B (I.getOpcode) C",
129 // where both B and C should be ConstantInts, results in a constant that does
130 // not overflow. This function only handles the Add and Sub opcodes. For
131 // all other opcodes, the function conservatively returns false.
132 static bool MaintainNoSignedWrap(BinaryOperator &I, Value *B, Value *C) {
133 OverflowingBinaryOperator *OBO = dyn_cast<OverflowingBinaryOperator>(&I);
134 if (!OBO || !OBO->hasNoSignedWrap()) {
138 // We reason about Add and Sub Only.
139 Instruction::BinaryOps Opcode = I.getOpcode();
140 if (Opcode != Instruction::Add &&
141 Opcode != Instruction::Sub) {
145 ConstantInt *CB = dyn_cast<ConstantInt>(B);
146 ConstantInt *CC = dyn_cast<ConstantInt>(C);
152 const APInt &BVal = CB->getValue();
153 const APInt &CVal = CC->getValue();
154 bool Overflow = false;
156 if (Opcode == Instruction::Add) {
157 BVal.sadd_ov(CVal, Overflow);
159 BVal.ssub_ov(CVal, Overflow);
165 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
166 /// operators which are associative or commutative:
168 // Commutative operators:
170 // 1. Order operands such that they are listed from right (least complex) to
171 // left (most complex). This puts constants before unary operators before
174 // Associative operators:
176 // 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
177 // 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
179 // Associative and commutative operators:
181 // 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
182 // 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
183 // 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
184 // if C1 and C2 are constants.
186 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
187 Instruction::BinaryOps Opcode = I.getOpcode();
188 bool Changed = false;
191 // Order operands such that they are listed from right (least complex) to
192 // left (most complex). This puts constants before unary operators before
194 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
195 getComplexity(I.getOperand(1)))
196 Changed = !I.swapOperands();
198 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
199 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
201 if (I.isAssociative()) {
202 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
203 if (Op0 && Op0->getOpcode() == Opcode) {
204 Value *A = Op0->getOperand(0);
205 Value *B = Op0->getOperand(1);
206 Value *C = I.getOperand(1);
208 // Does "B op C" simplify?
209 if (Value *V = SimplifyBinOp(Opcode, B, C, TD)) {
210 // It simplifies to V. Form "A op V".
213 // Conservatively clear the optional flags, since they may not be
214 // preserved by the reassociation.
215 if (MaintainNoSignedWrap(I, B, C) &&
216 (!Op0 || (isa<BinaryOperator>(Op0) && Op0->hasNoSignedWrap()))) {
217 // Note: this is only valid because SimplifyBinOp doesn't look at
218 // the operands to Op0.
219 I.clearSubclassOptionalData();
220 I.setHasNoSignedWrap(true);
222 I.clearSubclassOptionalData();
231 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
232 if (Op1 && Op1->getOpcode() == Opcode) {
233 Value *A = I.getOperand(0);
234 Value *B = Op1->getOperand(0);
235 Value *C = Op1->getOperand(1);
237 // Does "A op B" simplify?
238 if (Value *V = SimplifyBinOp(Opcode, A, B, TD)) {
239 // It simplifies to V. Form "V op C".
242 // Conservatively clear the optional flags, since they may not be
243 // preserved by the reassociation.
244 I.clearSubclassOptionalData();
252 if (I.isAssociative() && I.isCommutative()) {
253 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
254 if (Op0 && Op0->getOpcode() == Opcode) {
255 Value *A = Op0->getOperand(0);
256 Value *B = Op0->getOperand(1);
257 Value *C = I.getOperand(1);
259 // Does "C op A" simplify?
260 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
261 // It simplifies to V. Form "V op B".
264 // Conservatively clear the optional flags, since they may not be
265 // preserved by the reassociation.
266 I.clearSubclassOptionalData();
273 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
274 if (Op1 && Op1->getOpcode() == Opcode) {
275 Value *A = I.getOperand(0);
276 Value *B = Op1->getOperand(0);
277 Value *C = Op1->getOperand(1);
279 // Does "C op A" simplify?
280 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
281 // It simplifies to V. Form "B op V".
284 // Conservatively clear the optional flags, since they may not be
285 // preserved by the reassociation.
286 I.clearSubclassOptionalData();
293 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
294 // if C1 and C2 are constants.
296 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
297 isa<Constant>(Op0->getOperand(1)) &&
298 isa<Constant>(Op1->getOperand(1)) &&
299 Op0->hasOneUse() && Op1->hasOneUse()) {
300 Value *A = Op0->getOperand(0);
301 Constant *C1 = cast<Constant>(Op0->getOperand(1));
302 Value *B = Op1->getOperand(0);
303 Constant *C2 = cast<Constant>(Op1->getOperand(1));
305 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
306 BinaryOperator *New = BinaryOperator::Create(Opcode, A, B);
307 InsertNewInstWith(New, I);
309 I.setOperand(0, New);
310 I.setOperand(1, Folded);
311 // Conservatively clear the optional flags, since they may not be
312 // preserved by the reassociation.
313 I.clearSubclassOptionalData();
320 // No further simplifications.
325 /// LeftDistributesOverRight - Whether "X LOp (Y ROp Z)" is always equal to
326 /// "(X LOp Y) ROp (X LOp Z)".
327 static bool LeftDistributesOverRight(Instruction::BinaryOps LOp,
328 Instruction::BinaryOps ROp) {
333 case Instruction::And:
334 // And distributes over Or and Xor.
338 case Instruction::Or:
339 case Instruction::Xor:
343 case Instruction::Mul:
344 // Multiplication distributes over addition and subtraction.
348 case Instruction::Add:
349 case Instruction::Sub:
353 case Instruction::Or:
354 // Or distributes over And.
358 case Instruction::And:
364 /// RightDistributesOverLeft - Whether "(X LOp Y) ROp Z" is always equal to
365 /// "(X ROp Z) LOp (Y ROp Z)".
366 static bool RightDistributesOverLeft(Instruction::BinaryOps LOp,
367 Instruction::BinaryOps ROp) {
368 if (Instruction::isCommutative(ROp))
369 return LeftDistributesOverRight(ROp, LOp);
370 // TODO: It would be nice to handle division, aka "(X + Y)/Z = X/Z + Y/Z",
371 // but this requires knowing that the addition does not overflow and other
376 /// SimplifyUsingDistributiveLaws - This tries to simplify binary operations
377 /// which some other binary operation distributes over either by factorizing
378 /// out common terms (eg "(A*B)+(A*C)" -> "A*(B+C)") or expanding out if this
379 /// results in simplifications (eg: "A & (B | C) -> (A&B) | (A&C)" if this is
380 /// a win). Returns the simplified value, or null if it didn't simplify.
381 Value *InstCombiner::SimplifyUsingDistributiveLaws(BinaryOperator &I) {
382 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
383 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
384 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
385 Instruction::BinaryOps TopLevelOpcode = I.getOpcode(); // op
388 if (Op0 && Op1 && Op0->getOpcode() == Op1->getOpcode()) {
389 // The instruction has the form "(A op' B) op (C op' D)". Try to factorize
391 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1);
392 Value *C = Op1->getOperand(0), *D = Op1->getOperand(1);
393 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
395 // Does "X op' Y" always equal "Y op' X"?
396 bool InnerCommutative = Instruction::isCommutative(InnerOpcode);
398 // Does "X op' (Y op Z)" always equal "(X op' Y) op (X op' Z)"?
399 if (LeftDistributesOverRight(InnerOpcode, TopLevelOpcode))
400 // Does the instruction have the form "(A op' B) op (A op' D)" or, in the
401 // commutative case, "(A op' B) op (C op' A)"?
402 if (A == C || (InnerCommutative && A == D)) {
405 // Consider forming "A op' (B op D)".
406 // If "B op D" simplifies then it can be formed with no cost.
407 Value *V = SimplifyBinOp(TopLevelOpcode, B, D, TD);
408 // If "B op D" doesn't simplify then only go on if both of the existing
409 // operations "A op' B" and "C op' D" will be zapped as no longer used.
410 if (!V && Op0->hasOneUse() && Op1->hasOneUse())
411 V = Builder->CreateBinOp(TopLevelOpcode, B, D, Op1->getName());
414 V = Builder->CreateBinOp(InnerOpcode, A, V);
420 // Does "(X op Y) op' Z" always equal "(X op' Z) op (Y op' Z)"?
421 if (RightDistributesOverLeft(TopLevelOpcode, InnerOpcode))
422 // Does the instruction have the form "(A op' B) op (C op' B)" or, in the
423 // commutative case, "(A op' B) op (B op' D)"?
424 if (B == D || (InnerCommutative && B == C)) {
427 // Consider forming "(A op C) op' B".
428 // If "A op C" simplifies then it can be formed with no cost.
429 Value *V = SimplifyBinOp(TopLevelOpcode, A, C, TD);
430 // If "A op C" doesn't simplify then only go on if both of the existing
431 // operations "A op' B" and "C op' D" will be zapped as no longer used.
432 if (!V && Op0->hasOneUse() && Op1->hasOneUse())
433 V = Builder->CreateBinOp(TopLevelOpcode, A, C, Op0->getName());
436 V = Builder->CreateBinOp(InnerOpcode, V, B);
444 if (Op0 && RightDistributesOverLeft(Op0->getOpcode(), TopLevelOpcode)) {
445 // The instruction has the form "(A op' B) op C". See if expanding it out
446 // to "(A op C) op' (B op C)" results in simplifications.
447 Value *A = Op0->getOperand(0), *B = Op0->getOperand(1), *C = RHS;
448 Instruction::BinaryOps InnerOpcode = Op0->getOpcode(); // op'
450 // Do "A op C" and "B op C" both simplify?
451 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, C, TD))
452 if (Value *R = SimplifyBinOp(TopLevelOpcode, B, C, TD)) {
453 // They do! Return "L op' R".
455 // If "L op' R" equals "A op' B" then "L op' R" is just the LHS.
456 if ((L == A && R == B) ||
457 (Instruction::isCommutative(InnerOpcode) && L == B && R == A))
459 // Otherwise return "L op' R" if it simplifies.
460 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
462 // Otherwise, create a new instruction.
463 C = Builder->CreateBinOp(InnerOpcode, L, R);
469 if (Op1 && LeftDistributesOverRight(TopLevelOpcode, Op1->getOpcode())) {
470 // The instruction has the form "A op (B op' C)". See if expanding it out
471 // to "(A op B) op' (A op C)" results in simplifications.
472 Value *A = LHS, *B = Op1->getOperand(0), *C = Op1->getOperand(1);
473 Instruction::BinaryOps InnerOpcode = Op1->getOpcode(); // op'
475 // Do "A op B" and "A op C" both simplify?
476 if (Value *L = SimplifyBinOp(TopLevelOpcode, A, B, TD))
477 if (Value *R = SimplifyBinOp(TopLevelOpcode, A, C, TD)) {
478 // They do! Return "L op' R".
480 // If "L op' R" equals "B op' C" then "L op' R" is just the RHS.
481 if ((L == B && R == C) ||
482 (Instruction::isCommutative(InnerOpcode) && L == C && R == B))
484 // Otherwise return "L op' R" if it simplifies.
485 if (Value *V = SimplifyBinOp(InnerOpcode, L, R, TD))
487 // Otherwise, create a new instruction.
488 A = Builder->CreateBinOp(InnerOpcode, L, R);
497 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
498 // if the LHS is a constant zero (which is the 'negate' form).
500 Value *InstCombiner::dyn_castNegVal(Value *V) const {
501 if (BinaryOperator::isNeg(V))
502 return BinaryOperator::getNegArgument(V);
504 // Constants can be considered to be negated values if they can be folded.
505 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
506 return ConstantExpr::getNeg(C);
508 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
509 if (C->getType()->getElementType()->isIntegerTy())
510 return ConstantExpr::getNeg(C);
515 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
516 // instruction if the LHS is a constant negative zero (which is the 'negate'
519 Value *InstCombiner::dyn_castFNegVal(Value *V, bool IgnoreZeroSign) const {
520 if (BinaryOperator::isFNeg(V, IgnoreZeroSign))
521 return BinaryOperator::getFNegArgument(V);
523 // Constants can be considered to be negated values if they can be folded.
524 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
525 return ConstantExpr::getFNeg(C);
527 if (ConstantDataVector *C = dyn_cast<ConstantDataVector>(V))
528 if (C->getType()->getElementType()->isFloatingPointTy())
529 return ConstantExpr::getFNeg(C);
534 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
536 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
537 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
540 // Figure out if the constant is the left or the right argument.
541 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
542 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
544 if (Constant *SOC = dyn_cast<Constant>(SO)) {
546 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
547 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
550 Value *Op0 = SO, *Op1 = ConstOperand;
554 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
555 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
556 SO->getName()+".op");
557 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
558 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
559 SO->getName()+".cmp");
560 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
561 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
562 SO->getName()+".cmp");
563 llvm_unreachable("Unknown binary instruction type!");
566 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
567 // constant as the other operand, try to fold the binary operator into the
568 // select arguments. This also works for Cast instructions, which obviously do
569 // not have a second operand.
570 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
571 // Don't modify shared select instructions
572 if (!SI->hasOneUse()) return 0;
573 Value *TV = SI->getOperand(1);
574 Value *FV = SI->getOperand(2);
576 if (isa<Constant>(TV) || isa<Constant>(FV)) {
577 // Bool selects with constant operands can be folded to logical ops.
578 if (SI->getType()->isIntegerTy(1)) return 0;
580 // If it's a bitcast involving vectors, make sure it has the same number of
581 // elements on both sides.
582 if (BitCastInst *BC = dyn_cast<BitCastInst>(&Op)) {
583 VectorType *DestTy = dyn_cast<VectorType>(BC->getDestTy());
584 VectorType *SrcTy = dyn_cast<VectorType>(BC->getSrcTy());
586 // Verify that either both or neither are vectors.
587 if ((SrcTy == NULL) != (DestTy == NULL)) return 0;
588 // If vectors, verify that they have the same number of elements.
589 if (SrcTy && SrcTy->getNumElements() != DestTy->getNumElements())
593 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
594 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
596 return SelectInst::Create(SI->getCondition(),
597 SelectTrueVal, SelectFalseVal);
603 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
604 /// has a PHI node as operand #0, see if we can fold the instruction into the
605 /// PHI (which is only possible if all operands to the PHI are constants).
607 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
608 PHINode *PN = cast<PHINode>(I.getOperand(0));
609 unsigned NumPHIValues = PN->getNumIncomingValues();
610 if (NumPHIValues == 0)
613 // We normally only transform phis with a single use. However, if a PHI has
614 // multiple uses and they are all the same operation, we can fold *all* of the
615 // uses into the PHI.
616 if (!PN->hasOneUse()) {
617 // Walk the use list for the instruction, comparing them to I.
618 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
620 Instruction *User = cast<Instruction>(*UI);
621 if (User != &I && !I.isIdenticalTo(User))
624 // Otherwise, we can replace *all* users with the new PHI we form.
627 // Check to see if all of the operands of the PHI are simple constants
628 // (constantint/constantfp/undef). If there is one non-constant value,
629 // remember the BB it is in. If there is more than one or if *it* is a PHI,
630 // bail out. We don't do arbitrary constant expressions here because moving
631 // their computation can be expensive without a cost model.
632 BasicBlock *NonConstBB = 0;
633 for (unsigned i = 0; i != NumPHIValues; ++i) {
634 Value *InVal = PN->getIncomingValue(i);
635 if (isa<Constant>(InVal) && !isa<ConstantExpr>(InVal))
638 if (isa<PHINode>(InVal)) return 0; // Itself a phi.
639 if (NonConstBB) return 0; // More than one non-const value.
641 NonConstBB = PN->getIncomingBlock(i);
643 // If the InVal is an invoke at the end of the pred block, then we can't
644 // insert a computation after it without breaking the edge.
645 if (InvokeInst *II = dyn_cast<InvokeInst>(InVal))
646 if (II->getParent() == NonConstBB)
649 // If the incoming non-constant value is in I's block, we will remove one
650 // instruction, but insert another equivalent one, leading to infinite
652 if (NonConstBB == I.getParent())
656 // If there is exactly one non-constant value, we can insert a copy of the
657 // operation in that block. However, if this is a critical edge, we would be
658 // inserting the computation one some other paths (e.g. inside a loop). Only
659 // do this if the pred block is unconditionally branching into the phi block.
660 if (NonConstBB != 0) {
661 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
662 if (!BI || !BI->isUnconditional()) return 0;
665 // Okay, we can do the transformation: create the new PHI node.
666 PHINode *NewPN = PHINode::Create(I.getType(), PN->getNumIncomingValues());
667 InsertNewInstBefore(NewPN, *PN);
670 // If we are going to have to insert a new computation, do so right before the
671 // predecessors terminator.
673 Builder->SetInsertPoint(NonConstBB->getTerminator());
675 // Next, add all of the operands to the PHI.
676 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
677 // We only currently try to fold the condition of a select when it is a phi,
678 // not the true/false values.
679 Value *TrueV = SI->getTrueValue();
680 Value *FalseV = SI->getFalseValue();
681 BasicBlock *PhiTransBB = PN->getParent();
682 for (unsigned i = 0; i != NumPHIValues; ++i) {
683 BasicBlock *ThisBB = PN->getIncomingBlock(i);
684 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
685 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
687 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
688 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
690 InV = Builder->CreateSelect(PN->getIncomingValue(i),
691 TrueVInPred, FalseVInPred, "phitmp");
692 NewPN->addIncoming(InV, ThisBB);
694 } else if (CmpInst *CI = dyn_cast<CmpInst>(&I)) {
695 Constant *C = cast<Constant>(I.getOperand(1));
696 for (unsigned i = 0; i != NumPHIValues; ++i) {
698 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
699 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
700 else if (isa<ICmpInst>(CI))
701 InV = Builder->CreateICmp(CI->getPredicate(), PN->getIncomingValue(i),
704 InV = Builder->CreateFCmp(CI->getPredicate(), PN->getIncomingValue(i),
706 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
708 } else if (I.getNumOperands() == 2) {
709 Constant *C = cast<Constant>(I.getOperand(1));
710 for (unsigned i = 0; i != NumPHIValues; ++i) {
712 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
713 InV = ConstantExpr::get(I.getOpcode(), InC, C);
715 InV = Builder->CreateBinOp(cast<BinaryOperator>(I).getOpcode(),
716 PN->getIncomingValue(i), C, "phitmp");
717 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
720 CastInst *CI = cast<CastInst>(&I);
721 Type *RetTy = CI->getType();
722 for (unsigned i = 0; i != NumPHIValues; ++i) {
724 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i)))
725 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
727 InV = Builder->CreateCast(CI->getOpcode(),
728 PN->getIncomingValue(i), I.getType(), "phitmp");
729 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
733 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
735 Instruction *User = cast<Instruction>(*UI++);
736 if (User == &I) continue;
737 ReplaceInstUsesWith(*User, NewPN);
738 EraseInstFromFunction(*User);
740 return ReplaceInstUsesWith(I, NewPN);
743 /// FindElementAtOffset - Given a type and a constant offset, determine whether
744 /// or not there is a sequence of GEP indices into the type that will land us at
745 /// the specified offset. If so, fill them into NewIndices and return the
746 /// resultant element type, otherwise return null.
747 Type *InstCombiner::FindElementAtOffset(Type *Ty, int64_t Offset,
748 SmallVectorImpl<Value*> &NewIndices) {
750 if (!Ty->isSized()) return 0;
752 // Start with the index over the outer type. Note that the type size
753 // might be zero (even if the offset isn't zero) if the indexed type
754 // is something like [0 x {int, int}]
755 Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
756 int64_t FirstIdx = 0;
757 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
758 FirstIdx = Offset/TySize;
759 Offset -= FirstIdx*TySize;
761 assert(Offset >= 0 && "Offset should never be negative!");
762 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
765 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
767 // Index into the types. If we fail, set OrigBase to null.
769 // Indexing into tail padding between struct/array elements.
770 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
773 if (StructType *STy = dyn_cast<StructType>(Ty)) {
774 const StructLayout *SL = TD->getStructLayout(STy);
775 assert(Offset < (int64_t)SL->getSizeInBytes() &&
776 "Offset must stay within the indexed type");
778 unsigned Elt = SL->getElementContainingOffset(Offset);
779 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
782 Offset -= SL->getElementOffset(Elt);
783 Ty = STy->getElementType(Elt);
784 } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
785 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
786 assert(EltSize && "Cannot index into a zero-sized array");
787 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
789 Ty = AT->getElementType();
791 // Otherwise, we can't index into the middle of this atomic type, bail.
799 static bool shouldMergeGEPs(GEPOperator &GEP, GEPOperator &Src) {
800 // If this GEP has only 0 indices, it is the same pointer as
801 // Src. If Src is not a trivial GEP too, don't combine
803 if (GEP.hasAllZeroIndices() && !Src.hasAllZeroIndices() &&
809 /// Descale - Return a value X such that Val = X * Scale, or null if none. If
810 /// the multiplication is known not to overflow then NoSignedWrap is set.
811 Value *InstCombiner::Descale(Value *Val, APInt Scale, bool &NoSignedWrap) {
812 assert(isa<IntegerType>(Val->getType()) && "Can only descale integers!");
813 assert(cast<IntegerType>(Val->getType())->getBitWidth() ==
814 Scale.getBitWidth() && "Scale not compatible with value!");
816 // If Val is zero or Scale is one then Val = Val * Scale.
817 if (match(Val, m_Zero()) || Scale == 1) {
822 // If Scale is zero then it does not divide Val.
823 if (Scale.isMinValue())
826 // Look through chains of multiplications, searching for a constant that is
827 // divisible by Scale. For example, descaling X*(Y*(Z*4)) by a factor of 4
828 // will find the constant factor 4 and produce X*(Y*Z). Descaling X*(Y*8) by
829 // a factor of 4 will produce X*(Y*2). The principle of operation is to bore
832 // Val = M1 * X || Analysis starts here and works down
833 // M1 = M2 * Y || Doesn't descend into terms with more
834 // M2 = Z * 4 \/ than one use
836 // Then to modify a term at the bottom:
839 // M1 = Z * Y || Replaced M2 with Z
841 // Then to work back up correcting nsw flags.
843 // Op - the term we are currently analyzing. Starts at Val then drills down.
844 // Replaced with its descaled value before exiting from the drill down loop.
847 // Parent - initially null, but after drilling down notes where Op came from.
848 // In the example above, Parent is (Val, 0) when Op is M1, because M1 is the
849 // 0'th operand of Val.
850 std::pair<Instruction*, unsigned> Parent;
852 // RequireNoSignedWrap - Set if the transform requires a descaling at deeper
853 // levels that doesn't overflow.
854 bool RequireNoSignedWrap = false;
856 // logScale - log base 2 of the scale. Negative if not a power of 2.
857 int32_t logScale = Scale.exactLogBase2();
859 for (;; Op = Parent.first->getOperand(Parent.second)) { // Drill down
861 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op)) {
862 // If Op is a constant divisible by Scale then descale to the quotient.
863 APInt Quotient(Scale), Remainder(Scale); // Init ensures right bitwidth.
864 APInt::sdivrem(CI->getValue(), Scale, Quotient, Remainder);
865 if (!Remainder.isMinValue())
866 // Not divisible by Scale.
868 // Replace with the quotient in the parent.
869 Op = ConstantInt::get(CI->getType(), Quotient);
874 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op)) {
876 if (BO->getOpcode() == Instruction::Mul) {
878 NoSignedWrap = BO->hasNoSignedWrap();
879 if (RequireNoSignedWrap && !NoSignedWrap)
882 // There are three cases for multiplication: multiplication by exactly
883 // the scale, multiplication by a constant different to the scale, and
884 // multiplication by something else.
885 Value *LHS = BO->getOperand(0);
886 Value *RHS = BO->getOperand(1);
888 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
889 // Multiplication by a constant.
890 if (CI->getValue() == Scale) {
891 // Multiplication by exactly the scale, replace the multiplication
892 // by its left-hand side in the parent.
897 // Otherwise drill down into the constant.
898 if (!Op->hasOneUse())
901 Parent = std::make_pair(BO, 1);
905 // Multiplication by something else. Drill down into the left-hand side
906 // since that's where the reassociate pass puts the good stuff.
907 if (!Op->hasOneUse())
910 Parent = std::make_pair(BO, 0);
914 if (logScale > 0 && BO->getOpcode() == Instruction::Shl &&
915 isa<ConstantInt>(BO->getOperand(1))) {
916 // Multiplication by a power of 2.
917 NoSignedWrap = BO->hasNoSignedWrap();
918 if (RequireNoSignedWrap && !NoSignedWrap)
921 Value *LHS = BO->getOperand(0);
922 int32_t Amt = cast<ConstantInt>(BO->getOperand(1))->
923 getLimitedValue(Scale.getBitWidth());
926 if (Amt == logScale) {
927 // Multiplication by exactly the scale, replace the multiplication
928 // by its left-hand side in the parent.
932 if (Amt < logScale || !Op->hasOneUse())
935 // Multiplication by more than the scale. Reduce the multiplying amount
936 // by the scale in the parent.
937 Parent = std::make_pair(BO, 1);
938 Op = ConstantInt::get(BO->getType(), Amt - logScale);
943 if (!Op->hasOneUse())
946 if (CastInst *Cast = dyn_cast<CastInst>(Op)) {
947 if (Cast->getOpcode() == Instruction::SExt) {
948 // Op is sign-extended from a smaller type, descale in the smaller type.
949 unsigned SmallSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
950 APInt SmallScale = Scale.trunc(SmallSize);
951 // Suppose Op = sext X, and we descale X as Y * SmallScale. We want to
952 // descale Op as (sext Y) * Scale. In order to have
953 // sext (Y * SmallScale) = (sext Y) * Scale
954 // some conditions need to hold however: SmallScale must sign-extend to
955 // Scale and the multiplication Y * SmallScale should not overflow.
956 if (SmallScale.sext(Scale.getBitWidth()) != Scale)
957 // SmallScale does not sign-extend to Scale.
959 assert(SmallScale.exactLogBase2() == logScale);
960 // Require that Y * SmallScale must not overflow.
961 RequireNoSignedWrap = true;
963 // Drill down through the cast.
964 Parent = std::make_pair(Cast, 0);
969 if (Cast->getOpcode() == Instruction::Trunc) {
970 // Op is truncated from a larger type, descale in the larger type.
971 // Suppose Op = trunc X, and we descale X as Y * sext Scale. Then
972 // trunc (Y * sext Scale) = (trunc Y) * Scale
973 // always holds. However (trunc Y) * Scale may overflow even if
974 // trunc (Y * sext Scale) does not, so nsw flags need to be cleared
975 // from this point up in the expression (see later).
976 if (RequireNoSignedWrap)
979 // Drill down through the cast.
980 unsigned LargeSize = Cast->getSrcTy()->getPrimitiveSizeInBits();
981 Parent = std::make_pair(Cast, 0);
982 Scale = Scale.sext(LargeSize);
983 if (logScale + 1 == (int32_t)Cast->getType()->getPrimitiveSizeInBits())
985 assert(Scale.exactLogBase2() == logScale);
990 // Unsupported expression, bail out.
994 // We know that we can successfully descale, so from here on we can safely
995 // modify the IR. Op holds the descaled version of the deepest term in the
996 // expression. NoSignedWrap is 'true' if multiplying Op by Scale is known
1000 // The expression only had one term.
1003 // Rewrite the parent using the descaled version of its operand.
1004 assert(Parent.first->hasOneUse() && "Drilled down when more than one use!");
1005 assert(Op != Parent.first->getOperand(Parent.second) &&
1006 "Descaling was a no-op?");
1007 Parent.first->setOperand(Parent.second, Op);
1008 Worklist.Add(Parent.first);
1010 // Now work back up the expression correcting nsw flags. The logic is based
1011 // on the following observation: if X * Y is known not to overflow as a signed
1012 // multiplication, and Y is replaced by a value Z with smaller absolute value,
1013 // then X * Z will not overflow as a signed multiplication either. As we work
1014 // our way up, having NoSignedWrap 'true' means that the descaled value at the
1015 // current level has strictly smaller absolute value than the original.
1016 Instruction *Ancestor = Parent.first;
1018 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Ancestor)) {
1019 // If the multiplication wasn't nsw then we can't say anything about the
1020 // value of the descaled multiplication, and we have to clear nsw flags
1021 // from this point on up.
1022 bool OpNoSignedWrap = BO->hasNoSignedWrap();
1023 NoSignedWrap &= OpNoSignedWrap;
1024 if (NoSignedWrap != OpNoSignedWrap) {
1025 BO->setHasNoSignedWrap(NoSignedWrap);
1026 Worklist.Add(Ancestor);
1028 } else if (Ancestor->getOpcode() == Instruction::Trunc) {
1029 // The fact that the descaled input to the trunc has smaller absolute
1030 // value than the original input doesn't tell us anything useful about
1031 // the absolute values of the truncations.
1032 NoSignedWrap = false;
1034 assert((Ancestor->getOpcode() != Instruction::SExt || NoSignedWrap) &&
1035 "Failed to keep proper track of nsw flags while drilling down?");
1037 if (Ancestor == Val)
1038 // Got to the top, all done!
1041 // Move up one level in the expression.
1042 assert(Ancestor->hasOneUse() && "Drilled down when more than one use!");
1043 Ancestor = Ancestor->use_back();
1047 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1048 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
1050 if (Value *V = SimplifyGEPInst(Ops, TD))
1051 return ReplaceInstUsesWith(GEP, V);
1053 Value *PtrOp = GEP.getOperand(0);
1055 // Eliminate unneeded casts for indices, and replace indices which displace
1056 // by multiples of a zero size type with zero.
1058 bool MadeChange = false;
1059 Type *IntPtrTy = TD->getIntPtrType(GEP.getPointerOperandType());
1061 gep_type_iterator GTI = gep_type_begin(GEP);
1062 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
1063 I != E; ++I, ++GTI) {
1064 // Skip indices into struct types.
1065 SequentialType *SeqTy = dyn_cast<SequentialType>(*GTI);
1066 if (!SeqTy) continue;
1068 // If the element type has zero size then any index over it is equivalent
1069 // to an index of zero, so replace it with zero if it is not zero already.
1070 if (SeqTy->getElementType()->isSized() &&
1071 TD->getTypeAllocSize(SeqTy->getElementType()) == 0)
1072 if (!isa<Constant>(*I) || !cast<Constant>(*I)->isNullValue()) {
1073 *I = Constant::getNullValue(IntPtrTy);
1077 Type *IndexTy = (*I)->getType();
1078 if (IndexTy != IntPtrTy) {
1079 // If we are using a wider index than needed for this platform, shrink
1080 // it to what we need. If narrower, sign-extend it to what we need.
1081 // This explicit cast can make subsequent optimizations more obvious.
1082 *I = Builder->CreateIntCast(*I, IntPtrTy, true);
1086 if (MadeChange) return &GEP;
1089 // Combine Indices - If the source pointer to this getelementptr instruction
1090 // is a getelementptr instruction, combine the indices of the two
1091 // getelementptr instructions into a single instruction.
1093 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
1094 if (!shouldMergeGEPs(*cast<GEPOperator>(&GEP), *Src))
1097 // Note that if our source is a gep chain itself then we wait for that
1098 // chain to be resolved before we perform this transformation. This
1099 // avoids us creating a TON of code in some cases.
1100 if (GEPOperator *SrcGEP =
1101 dyn_cast<GEPOperator>(Src->getOperand(0)))
1102 if (SrcGEP->getNumOperands() == 2 && shouldMergeGEPs(*Src, *SrcGEP))
1103 return 0; // Wait until our source is folded to completion.
1105 SmallVector<Value*, 8> Indices;
1107 // Find out whether the last index in the source GEP is a sequential idx.
1108 bool EndsWithSequential = false;
1109 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
1111 EndsWithSequential = !(*I)->isStructTy();
1113 // Can we combine the two pointer arithmetics offsets?
1114 if (EndsWithSequential) {
1115 // Replace: gep (gep %P, long B), long A, ...
1116 // With: T = long A+B; gep %P, T, ...
1119 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
1120 Value *GO1 = GEP.getOperand(1);
1121 if (SO1 == Constant::getNullValue(SO1->getType())) {
1123 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
1126 // If they aren't the same type, then the input hasn't been processed
1127 // by the loop above yet (which canonicalizes sequential index types to
1128 // intptr_t). Just avoid transforming this until the input has been
1130 if (SO1->getType() != GO1->getType())
1132 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
1135 // Update the GEP in place if possible.
1136 if (Src->getNumOperands() == 2) {
1137 GEP.setOperand(0, Src->getOperand(0));
1138 GEP.setOperand(1, Sum);
1141 Indices.append(Src->op_begin()+1, Src->op_end()-1);
1142 Indices.push_back(Sum);
1143 Indices.append(GEP.op_begin()+2, GEP.op_end());
1144 } else if (isa<Constant>(*GEP.idx_begin()) &&
1145 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
1146 Src->getNumOperands() != 1) {
1147 // Otherwise we can do the fold if the first index of the GEP is a zero
1148 Indices.append(Src->op_begin()+1, Src->op_end());
1149 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
1152 if (!Indices.empty())
1153 return (GEP.isInBounds() && Src->isInBounds()) ?
1154 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices,
1156 GetElementPtrInst::Create(Src->getOperand(0), Indices, GEP.getName());
1159 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
1160 Value *StrippedPtr = PtrOp->stripPointerCasts();
1161 PointerType *StrippedPtrTy = dyn_cast<PointerType>(StrippedPtr->getType());
1163 // We do not handle pointer-vector geps here.
1167 if (StrippedPtr != PtrOp &&
1168 StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace()) {
1170 bool HasZeroPointerIndex = false;
1171 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
1172 HasZeroPointerIndex = C->isZero();
1174 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
1175 // into : GEP [10 x i8]* X, i32 0, ...
1177 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
1178 // into : GEP i8* X, ...
1180 // This occurs when the program declares an array extern like "int X[];"
1181 if (HasZeroPointerIndex) {
1182 PointerType *CPTy = cast<PointerType>(PtrOp->getType());
1183 if (ArrayType *CATy =
1184 dyn_cast<ArrayType>(CPTy->getElementType())) {
1185 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
1186 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
1187 // -> GEP i8* X, ...
1188 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
1189 GetElementPtrInst *Res =
1190 GetElementPtrInst::Create(StrippedPtr, Idx, GEP.getName());
1191 Res->setIsInBounds(GEP.isInBounds());
1195 if (ArrayType *XATy =
1196 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
1197 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
1198 if (CATy->getElementType() == XATy->getElementType()) {
1199 // -> GEP [10 x i8]* X, i32 0, ...
1200 // At this point, we know that the cast source type is a pointer
1201 // to an array of the same type as the destination pointer
1202 // array. Because the array type is never stepped over (there
1203 // is a leading zero) we can fold the cast into this GEP.
1204 GEP.setOperand(0, StrippedPtr);
1209 } else if (GEP.getNumOperands() == 2) {
1210 // Transform things like:
1211 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
1212 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
1213 Type *SrcElTy = StrippedPtrTy->getElementType();
1214 Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
1215 if (TD && SrcElTy->isArrayTy() &&
1216 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
1217 TD->getTypeAllocSize(ResElTy)) {
1219 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
1220 Idx[1] = GEP.getOperand(1);
1221 Value *NewGEP = GEP.isInBounds() ?
1222 Builder->CreateInBoundsGEP(StrippedPtr, Idx, GEP.getName()) :
1223 Builder->CreateGEP(StrippedPtr, Idx, GEP.getName());
1224 // V and GEP are both pointer types --> BitCast
1225 return new BitCastInst(NewGEP, GEP.getType());
1228 // Transform things like:
1229 // %V = mul i64 %N, 4
1230 // %t = getelementptr i8* bitcast (i32* %arr to i8*), i32 %V
1231 // into: %t1 = getelementptr i32* %arr, i32 %N; bitcast
1232 if (TD && ResElTy->isSized() && SrcElTy->isSized()) {
1233 // Check that changing the type amounts to dividing the index by a scale
1235 uint64_t ResSize = TD->getTypeAllocSize(ResElTy);
1236 uint64_t SrcSize = TD->getTypeAllocSize(SrcElTy);
1237 if (ResSize && SrcSize % ResSize == 0) {
1238 Value *Idx = GEP.getOperand(1);
1239 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1240 uint64_t Scale = SrcSize / ResSize;
1242 // Earlier transforms ensure that the index has type IntPtrType, which
1243 // considerably simplifies the logic by eliminating implicit casts.
1244 assert(Idx->getType() == TD->getIntPtrType(GEP.getContext()) &&
1245 "Index not cast to pointer width?");
1248 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1249 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1250 // If the multiplication NewIdx * Scale may overflow then the new
1251 // GEP may not be "inbounds".
1252 Value *NewGEP = GEP.isInBounds() && NSW ?
1253 Builder->CreateInBoundsGEP(StrippedPtr, NewIdx, GEP.getName()) :
1254 Builder->CreateGEP(StrippedPtr, NewIdx, GEP.getName());
1255 // The NewGEP must be pointer typed, so must the old one -> BitCast
1256 return new BitCastInst(NewGEP, GEP.getType());
1261 // Similarly, transform things like:
1262 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
1263 // (where tmp = 8*tmp2) into:
1264 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
1265 if (TD && ResElTy->isSized() && SrcElTy->isSized() &&
1266 SrcElTy->isArrayTy()) {
1267 // Check that changing to the array element type amounts to dividing the
1268 // index by a scale factor.
1269 uint64_t ResSize = TD->getTypeAllocSize(ResElTy);
1270 uint64_t ArrayEltSize =
1271 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
1272 if (ResSize && ArrayEltSize % ResSize == 0) {
1273 Value *Idx = GEP.getOperand(1);
1274 unsigned BitWidth = Idx->getType()->getPrimitiveSizeInBits();
1275 uint64_t Scale = ArrayEltSize / ResSize;
1277 // Earlier transforms ensure that the index has type IntPtrType, which
1278 // considerably simplifies the logic by eliminating implicit casts.
1279 assert(Idx->getType() == TD->getIntPtrType(GEP.getContext()) &&
1280 "Index not cast to pointer width?");
1283 if (Value *NewIdx = Descale(Idx, APInt(BitWidth, Scale), NSW)) {
1284 // Successfully decomposed Idx as NewIdx * Scale, form a new GEP.
1285 // If the multiplication NewIdx * Scale may overflow then the new
1286 // GEP may not be "inbounds".
1288 Off[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
1290 Value *NewGEP = GEP.isInBounds() && NSW ?
1291 Builder->CreateInBoundsGEP(StrippedPtr, Off, GEP.getName()) :
1292 Builder->CreateGEP(StrippedPtr, Off, GEP.getName());
1293 // The NewGEP must be pointer typed, so must the old one -> BitCast
1294 return new BitCastInst(NewGEP, GEP.getType());
1301 /// See if we can simplify:
1302 /// X = bitcast A* to B*
1303 /// Y = gep X, <...constant indices...>
1304 /// into a gep of the original struct. This is important for SROA and alias
1305 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
1306 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
1307 APInt Offset(TD ? TD->getPointerSizeInBits() : 1, 0);
1309 !isa<BitCastInst>(BCI->getOperand(0)) &&
1310 GEP.accumulateConstantOffset(*TD, Offset) &&
1311 StrippedPtrTy->getAddressSpace() == GEP.getPointerAddressSpace()) {
1313 // If this GEP instruction doesn't move the pointer, just replace the GEP
1314 // with a bitcast of the real input to the dest type.
1316 // If the bitcast is of an allocation, and the allocation will be
1317 // converted to match the type of the cast, don't touch this.
1318 if (isa<AllocaInst>(BCI->getOperand(0)) ||
1319 isAllocationFn(BCI->getOperand(0), TLI)) {
1320 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
1321 if (Instruction *I = visitBitCast(*BCI)) {
1324 BCI->getParent()->getInstList().insert(BCI, I);
1325 ReplaceInstUsesWith(*BCI, I);
1330 return new BitCastInst(BCI->getOperand(0), GEP.getType());
1333 // Otherwise, if the offset is non-zero, we need to find out if there is a
1334 // field at Offset in 'A's type. If so, we can pull the cast through the
1336 SmallVector<Value*, 8> NewIndices;
1338 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
1339 if (FindElementAtOffset(InTy, Offset.getSExtValue(), NewIndices)) {
1340 Value *NGEP = GEP.isInBounds() ?
1341 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices) :
1342 Builder->CreateGEP(BCI->getOperand(0), NewIndices);
1344 if (NGEP->getType() == GEP.getType())
1345 return ReplaceInstUsesWith(GEP, NGEP);
1346 NGEP->takeName(&GEP);
1347 return new BitCastInst(NGEP, GEP.getType());
1358 isAllocSiteRemovable(Instruction *AI, SmallVectorImpl<WeakVH> &Users,
1359 const TargetLibraryInfo *TLI) {
1360 SmallVector<Instruction*, 4> Worklist;
1361 Worklist.push_back(AI);
1364 Instruction *PI = Worklist.pop_back_val();
1365 for (Value::use_iterator UI = PI->use_begin(), UE = PI->use_end(); UI != UE;
1367 Instruction *I = cast<Instruction>(*UI);
1368 switch (I->getOpcode()) {
1370 // Give up the moment we see something we can't handle.
1373 case Instruction::BitCast:
1374 case Instruction::GetElementPtr:
1376 Worklist.push_back(I);
1379 case Instruction::ICmp: {
1380 ICmpInst *ICI = cast<ICmpInst>(I);
1381 // We can fold eq/ne comparisons with null to false/true, respectively.
1382 if (!ICI->isEquality() || !isa<ConstantPointerNull>(ICI->getOperand(1)))
1388 case Instruction::Call:
1389 // Ignore no-op and store intrinsics.
1390 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1391 switch (II->getIntrinsicID()) {
1395 case Intrinsic::memmove:
1396 case Intrinsic::memcpy:
1397 case Intrinsic::memset: {
1398 MemIntrinsic *MI = cast<MemIntrinsic>(II);
1399 if (MI->isVolatile() || MI->getRawDest() != PI)
1403 case Intrinsic::dbg_declare:
1404 case Intrinsic::dbg_value:
1405 case Intrinsic::invariant_start:
1406 case Intrinsic::invariant_end:
1407 case Intrinsic::lifetime_start:
1408 case Intrinsic::lifetime_end:
1409 case Intrinsic::objectsize:
1415 if (isFreeCall(I, TLI)) {
1421 case Instruction::Store: {
1422 StoreInst *SI = cast<StoreInst>(I);
1423 if (SI->isVolatile() || SI->getPointerOperand() != PI)
1429 llvm_unreachable("missing a return?");
1431 } while (!Worklist.empty());
1435 Instruction *InstCombiner::visitAllocSite(Instruction &MI) {
1436 // If we have a malloc call which is only used in any amount of comparisons
1437 // to null and free calls, delete the calls and replace the comparisons with
1438 // true or false as appropriate.
1439 SmallVector<WeakVH, 64> Users;
1440 if (isAllocSiteRemovable(&MI, Users, TLI)) {
1441 for (unsigned i = 0, e = Users.size(); i != e; ++i) {
1442 Instruction *I = cast_or_null<Instruction>(&*Users[i]);
1445 if (ICmpInst *C = dyn_cast<ICmpInst>(I)) {
1446 ReplaceInstUsesWith(*C,
1447 ConstantInt::get(Type::getInt1Ty(C->getContext()),
1448 C->isFalseWhenEqual()));
1449 } else if (isa<BitCastInst>(I) || isa<GetElementPtrInst>(I)) {
1450 ReplaceInstUsesWith(*I, UndefValue::get(I->getType()));
1451 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1452 if (II->getIntrinsicID() == Intrinsic::objectsize) {
1453 ConstantInt *CI = cast<ConstantInt>(II->getArgOperand(1));
1454 uint64_t DontKnow = CI->isZero() ? -1ULL : 0;
1455 ReplaceInstUsesWith(*I, ConstantInt::get(I->getType(), DontKnow));
1458 EraseInstFromFunction(*I);
1461 if (InvokeInst *II = dyn_cast<InvokeInst>(&MI)) {
1462 // Replace invoke with a NOP intrinsic to maintain the original CFG
1463 Module *M = II->getParent()->getParent()->getParent();
1464 Function *F = Intrinsic::getDeclaration(M, Intrinsic::donothing);
1465 InvokeInst::Create(F, II->getNormalDest(), II->getUnwindDest(),
1466 ArrayRef<Value *>(), "", II->getParent());
1468 return EraseInstFromFunction(MI);
1473 /// \brief Move the call to free before a NULL test.
1475 /// Check if this free is accessed after its argument has been test
1476 /// against NULL (property 0).
1477 /// If yes, it is legal to move this call in its predecessor block.
1479 /// The move is performed only if the block containing the call to free
1480 /// will be removed, i.e.:
1481 /// 1. it has only one predecessor P, and P has two successors
1482 /// 2. it contains the call and an unconditional branch
1483 /// 3. its successor is the same as its predecessor's successor
1485 /// The profitability is out-of concern here and this function should
1486 /// be called only if the caller knows this transformation would be
1487 /// profitable (e.g., for code size).
1488 static Instruction *
1489 tryToMoveFreeBeforeNullTest(CallInst &FI) {
1490 Value *Op = FI.getArgOperand(0);
1491 BasicBlock *FreeInstrBB = FI.getParent();
1492 BasicBlock *PredBB = FreeInstrBB->getSinglePredecessor();
1494 // Validate part of constraint #1: Only one predecessor
1495 // FIXME: We can extend the number of predecessor, but in that case, we
1496 // would duplicate the call to free in each predecessor and it may
1497 // not be profitable even for code size.
1501 // Validate constraint #2: Does this block contains only the call to
1502 // free and an unconditional branch?
1503 // FIXME: We could check if we can speculate everything in the
1504 // predecessor block
1505 if (FreeInstrBB->size() != 2)
1508 if (!match(FreeInstrBB->getTerminator(), m_UnconditionalBr(SuccBB)))
1511 // Validate the rest of constraint #1 by matching on the pred branch.
1512 TerminatorInst *TI = PredBB->getTerminator();
1513 BasicBlock *TrueBB, *FalseBB;
1514 ICmpInst::Predicate Pred;
1515 if (!match(TI, m_Br(m_ICmp(Pred, m_Specific(Op), m_Zero()), TrueBB, FalseBB)))
1517 if (Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
1520 // Validate constraint #3: Ensure the null case just falls through.
1521 if (SuccBB != (Pred == ICmpInst::ICMP_EQ ? TrueBB : FalseBB))
1523 assert(FreeInstrBB == (Pred == ICmpInst::ICMP_EQ ? FalseBB : TrueBB) &&
1524 "Broken CFG: missing edge from predecessor to successor");
1531 Instruction *InstCombiner::visitFree(CallInst &FI) {
1532 Value *Op = FI.getArgOperand(0);
1534 // free undef -> unreachable.
1535 if (isa<UndefValue>(Op)) {
1536 // Insert a new store to null because we cannot modify the CFG here.
1537 Builder->CreateStore(ConstantInt::getTrue(FI.getContext()),
1538 UndefValue::get(Type::getInt1PtrTy(FI.getContext())));
1539 return EraseInstFromFunction(FI);
1542 // If we have 'free null' delete the instruction. This can happen in stl code
1543 // when lots of inlining happens.
1544 if (isa<ConstantPointerNull>(Op))
1545 return EraseInstFromFunction(FI);
1547 // If we optimize for code size, try to move the call to free before the null
1548 // test so that simplify cfg can remove the empty block and dead code
1549 // elimination the branch. I.e., helps to turn something like:
1550 // if (foo) free(foo);
1554 if (Instruction *I = tryToMoveFreeBeforeNullTest(FI))
1562 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1563 // Change br (not X), label True, label False to: br X, label False, True
1565 BasicBlock *TrueDest;
1566 BasicBlock *FalseDest;
1567 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
1568 !isa<Constant>(X)) {
1569 // Swap Destinations and condition...
1571 BI.swapSuccessors();
1575 // Cannonicalize fcmp_one -> fcmp_oeq
1576 FCmpInst::Predicate FPred; Value *Y;
1577 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
1578 TrueDest, FalseDest)) &&
1579 BI.getCondition()->hasOneUse())
1580 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
1581 FPred == FCmpInst::FCMP_OGE) {
1582 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
1583 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
1585 // Swap Destinations and condition.
1586 BI.swapSuccessors();
1591 // Cannonicalize icmp_ne -> icmp_eq
1592 ICmpInst::Predicate IPred;
1593 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
1594 TrueDest, FalseDest)) &&
1595 BI.getCondition()->hasOneUse())
1596 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
1597 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
1598 IPred == ICmpInst::ICMP_SGE) {
1599 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
1600 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
1601 // Swap Destinations and condition.
1602 BI.swapSuccessors();
1610 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
1611 Value *Cond = SI.getCondition();
1612 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
1613 if (I->getOpcode() == Instruction::Add)
1614 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1615 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
1616 // Skip the first item since that's the default case.
1617 for (SwitchInst::CaseIt i = SI.case_begin(), e = SI.case_end();
1619 ConstantInt* CaseVal = i.getCaseValue();
1620 Constant* NewCaseVal = ConstantExpr::getSub(cast<Constant>(CaseVal),
1622 assert(isa<ConstantInt>(NewCaseVal) &&
1623 "Result of expression should be constant");
1624 i.setValue(cast<ConstantInt>(NewCaseVal));
1626 SI.setCondition(I->getOperand(0));
1634 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
1635 Value *Agg = EV.getAggregateOperand();
1637 if (!EV.hasIndices())
1638 return ReplaceInstUsesWith(EV, Agg);
1640 if (Constant *C = dyn_cast<Constant>(Agg)) {
1641 if (Constant *C2 = C->getAggregateElement(*EV.idx_begin())) {
1642 if (EV.getNumIndices() == 0)
1643 return ReplaceInstUsesWith(EV, C2);
1644 // Extract the remaining indices out of the constant indexed by the
1646 return ExtractValueInst::Create(C2, EV.getIndices().slice(1));
1648 return 0; // Can't handle other constants
1651 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
1652 // We're extracting from an insertvalue instruction, compare the indices
1653 const unsigned *exti, *exte, *insi, *inse;
1654 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
1655 exte = EV.idx_end(), inse = IV->idx_end();
1656 exti != exte && insi != inse;
1659 // The insert and extract both reference distinctly different elements.
1660 // This means the extract is not influenced by the insert, and we can
1661 // replace the aggregate operand of the extract with the aggregate
1662 // operand of the insert. i.e., replace
1663 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1664 // %E = extractvalue { i32, { i32 } } %I, 0
1666 // %E = extractvalue { i32, { i32 } } %A, 0
1667 return ExtractValueInst::Create(IV->getAggregateOperand(),
1670 if (exti == exte && insi == inse)
1671 // Both iterators are at the end: Index lists are identical. Replace
1672 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1673 // %C = extractvalue { i32, { i32 } } %B, 1, 0
1675 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
1677 // The extract list is a prefix of the insert list. i.e. replace
1678 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
1679 // %E = extractvalue { i32, { i32 } } %I, 1
1681 // %X = extractvalue { i32, { i32 } } %A, 1
1682 // %E = insertvalue { i32 } %X, i32 42, 0
1683 // by switching the order of the insert and extract (though the
1684 // insertvalue should be left in, since it may have other uses).
1685 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
1687 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
1688 makeArrayRef(insi, inse));
1691 // The insert list is a prefix of the extract list
1692 // We can simply remove the common indices from the extract and make it
1693 // operate on the inserted value instead of the insertvalue result.
1695 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1696 // %E = extractvalue { i32, { i32 } } %I, 1, 0
1698 // %E extractvalue { i32 } { i32 42 }, 0
1699 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
1700 makeArrayRef(exti, exte));
1702 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
1703 // We're extracting from an intrinsic, see if we're the only user, which
1704 // allows us to simplify multiple result intrinsics to simpler things that
1705 // just get one value.
1706 if (II->hasOneUse()) {
1707 // Check if we're grabbing the overflow bit or the result of a 'with
1708 // overflow' intrinsic. If it's the latter we can remove the intrinsic
1709 // and replace it with a traditional binary instruction.
1710 switch (II->getIntrinsicID()) {
1711 case Intrinsic::uadd_with_overflow:
1712 case Intrinsic::sadd_with_overflow:
1713 if (*EV.idx_begin() == 0) { // Normal result.
1714 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1715 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
1716 EraseInstFromFunction(*II);
1717 return BinaryOperator::CreateAdd(LHS, RHS);
1720 // If the normal result of the add is dead, and the RHS is a constant,
1721 // we can transform this into a range comparison.
1722 // overflow = uadd a, -4 --> overflow = icmp ugt a, 3
1723 if (II->getIntrinsicID() == Intrinsic::uadd_with_overflow)
1724 if (ConstantInt *CI = dyn_cast<ConstantInt>(II->getArgOperand(1)))
1725 return new ICmpInst(ICmpInst::ICMP_UGT, II->getArgOperand(0),
1726 ConstantExpr::getNot(CI));
1728 case Intrinsic::usub_with_overflow:
1729 case Intrinsic::ssub_with_overflow:
1730 if (*EV.idx_begin() == 0) { // Normal result.
1731 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1732 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
1733 EraseInstFromFunction(*II);
1734 return BinaryOperator::CreateSub(LHS, RHS);
1737 case Intrinsic::umul_with_overflow:
1738 case Intrinsic::smul_with_overflow:
1739 if (*EV.idx_begin() == 0) { // Normal result.
1740 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1741 ReplaceInstUsesWith(*II, UndefValue::get(II->getType()));
1742 EraseInstFromFunction(*II);
1743 return BinaryOperator::CreateMul(LHS, RHS);
1751 if (LoadInst *L = dyn_cast<LoadInst>(Agg))
1752 // If the (non-volatile) load only has one use, we can rewrite this to a
1753 // load from a GEP. This reduces the size of the load.
1754 // FIXME: If a load is used only by extractvalue instructions then this
1755 // could be done regardless of having multiple uses.
1756 if (L->isSimple() && L->hasOneUse()) {
1757 // extractvalue has integer indices, getelementptr has Value*s. Convert.
1758 SmallVector<Value*, 4> Indices;
1759 // Prefix an i32 0 since we need the first element.
1760 Indices.push_back(Builder->getInt32(0));
1761 for (ExtractValueInst::idx_iterator I = EV.idx_begin(), E = EV.idx_end();
1763 Indices.push_back(Builder->getInt32(*I));
1765 // We need to insert these at the location of the old load, not at that of
1766 // the extractvalue.
1767 Builder->SetInsertPoint(L->getParent(), L);
1768 Value *GEP = Builder->CreateInBoundsGEP(L->getPointerOperand(), Indices);
1769 // Returning the load directly will cause the main loop to insert it in
1770 // the wrong spot, so use ReplaceInstUsesWith().
1771 return ReplaceInstUsesWith(EV, Builder->CreateLoad(GEP));
1773 // We could simplify extracts from other values. Note that nested extracts may
1774 // already be simplified implicitly by the above: extract (extract (insert) )
1775 // will be translated into extract ( insert ( extract ) ) first and then just
1776 // the value inserted, if appropriate. Similarly for extracts from single-use
1777 // loads: extract (extract (load)) will be translated to extract (load (gep))
1778 // and if again single-use then via load (gep (gep)) to load (gep).
1779 // However, double extracts from e.g. function arguments or return values
1780 // aren't handled yet.
1784 enum Personality_Type {
1785 Unknown_Personality,
1786 GNU_Ada_Personality,
1787 GNU_CXX_Personality,
1788 GNU_ObjC_Personality
1791 /// RecognizePersonality - See if the given exception handling personality
1792 /// function is one that we understand. If so, return a description of it;
1793 /// otherwise return Unknown_Personality.
1794 static Personality_Type RecognizePersonality(Value *Pers) {
1795 Function *F = dyn_cast<Function>(Pers->stripPointerCasts());
1797 return Unknown_Personality;
1798 return StringSwitch<Personality_Type>(F->getName())
1799 .Case("__gnat_eh_personality", GNU_Ada_Personality)
1800 .Case("__gxx_personality_v0", GNU_CXX_Personality)
1801 .Case("__objc_personality_v0", GNU_ObjC_Personality)
1802 .Default(Unknown_Personality);
1805 /// isCatchAll - Return 'true' if the given typeinfo will match anything.
1806 static bool isCatchAll(Personality_Type Personality, Constant *TypeInfo) {
1807 switch (Personality) {
1808 case Unknown_Personality:
1810 case GNU_Ada_Personality:
1811 // While __gnat_all_others_value will match any Ada exception, it doesn't
1812 // match foreign exceptions (or didn't, before gcc-4.7).
1814 case GNU_CXX_Personality:
1815 case GNU_ObjC_Personality:
1816 return TypeInfo->isNullValue();
1818 llvm_unreachable("Unknown personality!");
1821 static bool shorter_filter(const Value *LHS, const Value *RHS) {
1823 cast<ArrayType>(LHS->getType())->getNumElements()
1825 cast<ArrayType>(RHS->getType())->getNumElements();
1828 Instruction *InstCombiner::visitLandingPadInst(LandingPadInst &LI) {
1829 // The logic here should be correct for any real-world personality function.
1830 // However if that turns out not to be true, the offending logic can always
1831 // be conditioned on the personality function, like the catch-all logic is.
1832 Personality_Type Personality = RecognizePersonality(LI.getPersonalityFn());
1834 // Simplify the list of clauses, eg by removing repeated catch clauses
1835 // (these are often created by inlining).
1836 bool MakeNewInstruction = false; // If true, recreate using the following:
1837 SmallVector<Value *, 16> NewClauses; // - Clauses for the new instruction;
1838 bool CleanupFlag = LI.isCleanup(); // - The new instruction is a cleanup.
1840 SmallPtrSet<Value *, 16> AlreadyCaught; // Typeinfos known caught already.
1841 for (unsigned i = 0, e = LI.getNumClauses(); i != e; ++i) {
1842 bool isLastClause = i + 1 == e;
1843 if (LI.isCatch(i)) {
1845 Value *CatchClause = LI.getClause(i);
1846 Constant *TypeInfo = cast<Constant>(CatchClause->stripPointerCasts());
1848 // If we already saw this clause, there is no point in having a second
1850 if (AlreadyCaught.insert(TypeInfo)) {
1851 // This catch clause was not already seen.
1852 NewClauses.push_back(CatchClause);
1854 // Repeated catch clause - drop the redundant copy.
1855 MakeNewInstruction = true;
1858 // If this is a catch-all then there is no point in keeping any following
1859 // clauses or marking the landingpad as having a cleanup.
1860 if (isCatchAll(Personality, TypeInfo)) {
1862 MakeNewInstruction = true;
1863 CleanupFlag = false;
1867 // A filter clause. If any of the filter elements were already caught
1868 // then they can be dropped from the filter. It is tempting to try to
1869 // exploit the filter further by saying that any typeinfo that does not
1870 // occur in the filter can't be caught later (and thus can be dropped).
1871 // However this would be wrong, since typeinfos can match without being
1872 // equal (for example if one represents a C++ class, and the other some
1873 // class derived from it).
1874 assert(LI.isFilter(i) && "Unsupported landingpad clause!");
1875 Value *FilterClause = LI.getClause(i);
1876 ArrayType *FilterType = cast<ArrayType>(FilterClause->getType());
1877 unsigned NumTypeInfos = FilterType->getNumElements();
1879 // An empty filter catches everything, so there is no point in keeping any
1880 // following clauses or marking the landingpad as having a cleanup. By
1881 // dealing with this case here the following code is made a bit simpler.
1882 if (!NumTypeInfos) {
1883 NewClauses.push_back(FilterClause);
1885 MakeNewInstruction = true;
1886 CleanupFlag = false;
1890 bool MakeNewFilter = false; // If true, make a new filter.
1891 SmallVector<Constant *, 16> NewFilterElts; // New elements.
1892 if (isa<ConstantAggregateZero>(FilterClause)) {
1893 // Not an empty filter - it contains at least one null typeinfo.
1894 assert(NumTypeInfos > 0 && "Should have handled empty filter already!");
1895 Constant *TypeInfo =
1896 Constant::getNullValue(FilterType->getElementType());
1897 // If this typeinfo is a catch-all then the filter can never match.
1898 if (isCatchAll(Personality, TypeInfo)) {
1899 // Throw the filter away.
1900 MakeNewInstruction = true;
1904 // There is no point in having multiple copies of this typeinfo, so
1905 // discard all but the first copy if there is more than one.
1906 NewFilterElts.push_back(TypeInfo);
1907 if (NumTypeInfos > 1)
1908 MakeNewFilter = true;
1910 ConstantArray *Filter = cast<ConstantArray>(FilterClause);
1911 SmallPtrSet<Value *, 16> SeenInFilter; // For uniquing the elements.
1912 NewFilterElts.reserve(NumTypeInfos);
1914 // Remove any filter elements that were already caught or that already
1915 // occurred in the filter. While there, see if any of the elements are
1916 // catch-alls. If so, the filter can be discarded.
1917 bool SawCatchAll = false;
1918 for (unsigned j = 0; j != NumTypeInfos; ++j) {
1919 Value *Elt = Filter->getOperand(j);
1920 Constant *TypeInfo = cast<Constant>(Elt->stripPointerCasts());
1921 if (isCatchAll(Personality, TypeInfo)) {
1922 // This element is a catch-all. Bail out, noting this fact.
1926 if (AlreadyCaught.count(TypeInfo))
1927 // Already caught by an earlier clause, so having it in the filter
1930 // There is no point in having multiple copies of the same typeinfo in
1931 // a filter, so only add it if we didn't already.
1932 if (SeenInFilter.insert(TypeInfo))
1933 NewFilterElts.push_back(cast<Constant>(Elt));
1935 // A filter containing a catch-all cannot match anything by definition.
1937 // Throw the filter away.
1938 MakeNewInstruction = true;
1942 // If we dropped something from the filter, make a new one.
1943 if (NewFilterElts.size() < NumTypeInfos)
1944 MakeNewFilter = true;
1946 if (MakeNewFilter) {
1947 FilterType = ArrayType::get(FilterType->getElementType(),
1948 NewFilterElts.size());
1949 FilterClause = ConstantArray::get(FilterType, NewFilterElts);
1950 MakeNewInstruction = true;
1953 NewClauses.push_back(FilterClause);
1955 // If the new filter is empty then it will catch everything so there is
1956 // no point in keeping any following clauses or marking the landingpad
1957 // as having a cleanup. The case of the original filter being empty was
1958 // already handled above.
1959 if (MakeNewFilter && !NewFilterElts.size()) {
1960 assert(MakeNewInstruction && "New filter but not a new instruction!");
1961 CleanupFlag = false;
1967 // If several filters occur in a row then reorder them so that the shortest
1968 // filters come first (those with the smallest number of elements). This is
1969 // advantageous because shorter filters are more likely to match, speeding up
1970 // unwinding, but mostly because it increases the effectiveness of the other
1971 // filter optimizations below.
1972 for (unsigned i = 0, e = NewClauses.size(); i + 1 < e; ) {
1974 // Find the maximal 'j' s.t. the range [i, j) consists entirely of filters.
1975 for (j = i; j != e; ++j)
1976 if (!isa<ArrayType>(NewClauses[j]->getType()))
1979 // Check whether the filters are already sorted by length. We need to know
1980 // if sorting them is actually going to do anything so that we only make a
1981 // new landingpad instruction if it does.
1982 for (unsigned k = i; k + 1 < j; ++k)
1983 if (shorter_filter(NewClauses[k+1], NewClauses[k])) {
1984 // Not sorted, so sort the filters now. Doing an unstable sort would be
1985 // correct too but reordering filters pointlessly might confuse users.
1986 std::stable_sort(NewClauses.begin() + i, NewClauses.begin() + j,
1988 MakeNewInstruction = true;
1992 // Look for the next batch of filters.
1996 // If typeinfos matched if and only if equal, then the elements of a filter L
1997 // that occurs later than a filter F could be replaced by the intersection of
1998 // the elements of F and L. In reality two typeinfos can match without being
1999 // equal (for example if one represents a C++ class, and the other some class
2000 // derived from it) so it would be wrong to perform this transform in general.
2001 // However the transform is correct and useful if F is a subset of L. In that
2002 // case L can be replaced by F, and thus removed altogether since repeating a
2003 // filter is pointless. So here we look at all pairs of filters F and L where
2004 // L follows F in the list of clauses, and remove L if every element of F is
2005 // an element of L. This can occur when inlining C++ functions with exception
2007 for (unsigned i = 0; i + 1 < NewClauses.size(); ++i) {
2008 // Examine each filter in turn.
2009 Value *Filter = NewClauses[i];
2010 ArrayType *FTy = dyn_cast<ArrayType>(Filter->getType());
2012 // Not a filter - skip it.
2014 unsigned FElts = FTy->getNumElements();
2015 // Examine each filter following this one. Doing this backwards means that
2016 // we don't have to worry about filters disappearing under us when removed.
2017 for (unsigned j = NewClauses.size() - 1; j != i; --j) {
2018 Value *LFilter = NewClauses[j];
2019 ArrayType *LTy = dyn_cast<ArrayType>(LFilter->getType());
2021 // Not a filter - skip it.
2023 // If Filter is a subset of LFilter, i.e. every element of Filter is also
2024 // an element of LFilter, then discard LFilter.
2025 SmallVector<Value *, 16>::iterator J = NewClauses.begin() + j;
2026 // If Filter is empty then it is a subset of LFilter.
2029 NewClauses.erase(J);
2030 MakeNewInstruction = true;
2031 // Move on to the next filter.
2034 unsigned LElts = LTy->getNumElements();
2035 // If Filter is longer than LFilter then it cannot be a subset of it.
2037 // Move on to the next filter.
2039 // At this point we know that LFilter has at least one element.
2040 if (isa<ConstantAggregateZero>(LFilter)) { // LFilter only contains zeros.
2041 // Filter is a subset of LFilter iff Filter contains only zeros (as we
2042 // already know that Filter is not longer than LFilter).
2043 if (isa<ConstantAggregateZero>(Filter)) {
2044 assert(FElts <= LElts && "Should have handled this case earlier!");
2046 NewClauses.erase(J);
2047 MakeNewInstruction = true;
2049 // Move on to the next filter.
2052 ConstantArray *LArray = cast<ConstantArray>(LFilter);
2053 if (isa<ConstantAggregateZero>(Filter)) { // Filter only contains zeros.
2054 // Since Filter is non-empty and contains only zeros, it is a subset of
2055 // LFilter iff LFilter contains a zero.
2056 assert(FElts > 0 && "Should have eliminated the empty filter earlier!");
2057 for (unsigned l = 0; l != LElts; ++l)
2058 if (LArray->getOperand(l)->isNullValue()) {
2059 // LFilter contains a zero - discard it.
2060 NewClauses.erase(J);
2061 MakeNewInstruction = true;
2064 // Move on to the next filter.
2067 // At this point we know that both filters are ConstantArrays. Loop over
2068 // operands to see whether every element of Filter is also an element of
2069 // LFilter. Since filters tend to be short this is probably faster than
2070 // using a method that scales nicely.
2071 ConstantArray *FArray = cast<ConstantArray>(Filter);
2072 bool AllFound = true;
2073 for (unsigned f = 0; f != FElts; ++f) {
2074 Value *FTypeInfo = FArray->getOperand(f)->stripPointerCasts();
2076 for (unsigned l = 0; l != LElts; ++l) {
2077 Value *LTypeInfo = LArray->getOperand(l)->stripPointerCasts();
2078 if (LTypeInfo == FTypeInfo) {
2088 NewClauses.erase(J);
2089 MakeNewInstruction = true;
2091 // Move on to the next filter.
2095 // If we changed any of the clauses, replace the old landingpad instruction
2097 if (MakeNewInstruction) {
2098 LandingPadInst *NLI = LandingPadInst::Create(LI.getType(),
2099 LI.getPersonalityFn(),
2101 for (unsigned i = 0, e = NewClauses.size(); i != e; ++i)
2102 NLI->addClause(NewClauses[i]);
2103 // A landing pad with no clauses must have the cleanup flag set. It is
2104 // theoretically possible, though highly unlikely, that we eliminated all
2105 // clauses. If so, force the cleanup flag to true.
2106 if (NewClauses.empty())
2108 NLI->setCleanup(CleanupFlag);
2112 // Even if none of the clauses changed, we may nonetheless have understood
2113 // that the cleanup flag is pointless. Clear it if so.
2114 if (LI.isCleanup() != CleanupFlag) {
2115 assert(!CleanupFlag && "Adding a cleanup, not removing one?!");
2116 LI.setCleanup(CleanupFlag);
2126 /// TryToSinkInstruction - Try to move the specified instruction from its
2127 /// current block into the beginning of DestBlock, which can only happen if it's
2128 /// safe to move the instruction past all of the instructions between it and the
2129 /// end of its block.
2130 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
2131 assert(I->hasOneUse() && "Invariants didn't hold!");
2133 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
2134 if (isa<PHINode>(I) || isa<LandingPadInst>(I) || I->mayHaveSideEffects() ||
2135 isa<TerminatorInst>(I))
2138 // Do not sink alloca instructions out of the entry block.
2139 if (isa<AllocaInst>(I) && I->getParent() ==
2140 &DestBlock->getParent()->getEntryBlock())
2143 // We can only sink load instructions if there is nothing between the load and
2144 // the end of block that could change the value.
2145 if (I->mayReadFromMemory()) {
2146 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
2148 if (Scan->mayWriteToMemory())
2152 BasicBlock::iterator InsertPos = DestBlock->getFirstInsertionPt();
2153 I->moveBefore(InsertPos);
2159 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
2160 /// all reachable code to the worklist.
2162 /// This has a couple of tricks to make the code faster and more powerful. In
2163 /// particular, we constant fold and DCE instructions as we go, to avoid adding
2164 /// them to the worklist (this significantly speeds up instcombine on code where
2165 /// many instructions are dead or constant). Additionally, if we find a branch
2166 /// whose condition is a known constant, we only visit the reachable successors.
2168 static bool AddReachableCodeToWorklist(BasicBlock *BB,
2169 SmallPtrSet<BasicBlock*, 64> &Visited,
2171 const DataLayout *TD,
2172 const TargetLibraryInfo *TLI) {
2173 bool MadeIRChange = false;
2174 SmallVector<BasicBlock*, 256> Worklist;
2175 Worklist.push_back(BB);
2177 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
2178 DenseMap<ConstantExpr*, Constant*> FoldedConstants;
2181 BB = Worklist.pop_back_val();
2183 // We have now visited this block! If we've already been here, ignore it.
2184 if (!Visited.insert(BB)) continue;
2186 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
2187 Instruction *Inst = BBI++;
2189 // DCE instruction if trivially dead.
2190 if (isInstructionTriviallyDead(Inst, TLI)) {
2192 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
2193 Inst->eraseFromParent();
2197 // ConstantProp instruction if trivially constant.
2198 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
2199 if (Constant *C = ConstantFoldInstruction(Inst, TD, TLI)) {
2200 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
2202 Inst->replaceAllUsesWith(C);
2204 Inst->eraseFromParent();
2209 // See if we can constant fold its operands.
2210 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
2212 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
2213 if (CE == 0) continue;
2215 Constant*& FoldRes = FoldedConstants[CE];
2217 FoldRes = ConstantFoldConstantExpression(CE, TD, TLI);
2221 if (FoldRes != CE) {
2223 MadeIRChange = true;
2228 InstrsForInstCombineWorklist.push_back(Inst);
2231 // Recursively visit successors. If this is a branch or switch on a
2232 // constant, only visit the reachable successor.
2233 TerminatorInst *TI = BB->getTerminator();
2234 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
2235 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
2236 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
2237 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
2238 Worklist.push_back(ReachableBB);
2241 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
2242 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
2243 // See if this is an explicit destination.
2244 for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
2246 if (i.getCaseValue() == Cond) {
2247 BasicBlock *ReachableBB = i.getCaseSuccessor();
2248 Worklist.push_back(ReachableBB);
2252 // Otherwise it is the default destination.
2253 Worklist.push_back(SI->getDefaultDest());
2258 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
2259 Worklist.push_back(TI->getSuccessor(i));
2260 } while (!Worklist.empty());
2262 // Once we've found all of the instructions to add to instcombine's worklist,
2263 // add them in reverse order. This way instcombine will visit from the top
2264 // of the function down. This jives well with the way that it adds all uses
2265 // of instructions to the worklist after doing a transformation, thus avoiding
2266 // some N^2 behavior in pathological cases.
2267 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
2268 InstrsForInstCombineWorklist.size());
2270 return MadeIRChange;
2273 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
2274 MadeIRChange = false;
2276 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
2277 << F.getName() << "\n");
2280 // Do a depth-first traversal of the function, populate the worklist with
2281 // the reachable instructions. Ignore blocks that are not reachable. Keep
2282 // track of which blocks we visit.
2283 SmallPtrSet<BasicBlock*, 64> Visited;
2284 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD,
2287 // Do a quick scan over the function. If we find any blocks that are
2288 // unreachable, remove any instructions inside of them. This prevents
2289 // the instcombine code from having to deal with some bad special cases.
2290 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
2291 if (Visited.count(BB)) continue;
2293 // Delete the instructions backwards, as it has a reduced likelihood of
2294 // having to update as many def-use and use-def chains.
2295 Instruction *EndInst = BB->getTerminator(); // Last not to be deleted.
2296 while (EndInst != BB->begin()) {
2297 // Delete the next to last instruction.
2298 BasicBlock::iterator I = EndInst;
2299 Instruction *Inst = --I;
2300 if (!Inst->use_empty())
2301 Inst->replaceAllUsesWith(UndefValue::get(Inst->getType()));
2302 if (isa<LandingPadInst>(Inst)) {
2306 if (!isa<DbgInfoIntrinsic>(Inst)) {
2308 MadeIRChange = true;
2310 Inst->eraseFromParent();
2315 while (!Worklist.isEmpty()) {
2316 Instruction *I = Worklist.RemoveOne();
2317 if (I == 0) continue; // skip null values.
2319 // Check to see if we can DCE the instruction.
2320 if (isInstructionTriviallyDead(I, TLI)) {
2321 DEBUG(errs() << "IC: DCE: " << *I << '\n');
2322 EraseInstFromFunction(*I);
2324 MadeIRChange = true;
2328 // Instruction isn't dead, see if we can constant propagate it.
2329 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
2330 if (Constant *C = ConstantFoldInstruction(I, TD, TLI)) {
2331 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
2333 // Add operands to the worklist.
2334 ReplaceInstUsesWith(*I, C);
2336 EraseInstFromFunction(*I);
2337 MadeIRChange = true;
2341 // See if we can trivially sink this instruction to a successor basic block.
2342 if (I->hasOneUse()) {
2343 BasicBlock *BB = I->getParent();
2344 Instruction *UserInst = cast<Instruction>(I->use_back());
2345 BasicBlock *UserParent;
2347 // Get the block the use occurs in.
2348 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
2349 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
2351 UserParent = UserInst->getParent();
2353 if (UserParent != BB) {
2354 bool UserIsSuccessor = false;
2355 // See if the user is one of our successors.
2356 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
2357 if (*SI == UserParent) {
2358 UserIsSuccessor = true;
2362 // If the user is one of our immediate successors, and if that successor
2363 // only has us as a predecessors (we'd have to split the critical edge
2364 // otherwise), we can keep going.
2365 if (UserIsSuccessor && UserParent->getSinglePredecessor())
2366 // Okay, the CFG is simple enough, try to sink this instruction.
2367 MadeIRChange |= TryToSinkInstruction(I, UserParent);
2371 // Now that we have an instruction, try combining it to simplify it.
2372 Builder->SetInsertPoint(I->getParent(), I);
2373 Builder->SetCurrentDebugLocation(I->getDebugLoc());
2378 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
2379 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
2381 if (Instruction *Result = visit(*I)) {
2383 // Should we replace the old instruction with a new one?
2385 DEBUG(errs() << "IC: Old = " << *I << '\n'
2386 << " New = " << *Result << '\n');
2388 if (!I->getDebugLoc().isUnknown())
2389 Result->setDebugLoc(I->getDebugLoc());
2390 // Everything uses the new instruction now.
2391 I->replaceAllUsesWith(Result);
2393 // Move the name to the new instruction first.
2394 Result->takeName(I);
2396 // Push the new instruction and any users onto the worklist.
2397 Worklist.Add(Result);
2398 Worklist.AddUsersToWorkList(*Result);
2400 // Insert the new instruction into the basic block...
2401 BasicBlock *InstParent = I->getParent();
2402 BasicBlock::iterator InsertPos = I;
2404 // If we replace a PHI with something that isn't a PHI, fix up the
2406 if (!isa<PHINode>(Result) && isa<PHINode>(InsertPos))
2407 InsertPos = InstParent->getFirstInsertionPt();
2409 InstParent->getInstList().insert(InsertPos, Result);
2411 EraseInstFromFunction(*I);
2414 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
2415 << " New = " << *I << '\n');
2418 // If the instruction was modified, it's possible that it is now dead.
2419 // if so, remove it.
2420 if (isInstructionTriviallyDead(I, TLI)) {
2421 EraseInstFromFunction(*I);
2424 Worklist.AddUsersToWorkList(*I);
2427 MadeIRChange = true;
2432 return MadeIRChange;
2436 class InstCombinerLibCallSimplifier : public LibCallSimplifier {
2439 InstCombinerLibCallSimplifier(const DataLayout *TD,
2440 const TargetLibraryInfo *TLI,
2442 : LibCallSimplifier(TD, TLI, UnsafeFPShrink) {
2446 /// replaceAllUsesWith - override so that instruction replacement
2447 /// can be defined in terms of the instruction combiner framework.
2448 virtual void replaceAllUsesWith(Instruction *I, Value *With) const {
2449 IC->ReplaceInstUsesWith(*I, With);
2454 bool InstCombiner::runOnFunction(Function &F) {
2455 TD = getAnalysisIfAvailable<DataLayout>();
2456 TLI = &getAnalysis<TargetLibraryInfo>();
2458 MinimizeSize = F.getAttributes().hasAttribute(AttributeSet::FunctionIndex,
2459 Attribute::MinSize);
2461 /// Builder - This is an IRBuilder that automatically inserts new
2462 /// instructions into the worklist when they are created.
2463 IRBuilder<true, TargetFolder, InstCombineIRInserter>
2464 TheBuilder(F.getContext(), TargetFolder(TD),
2465 InstCombineIRInserter(Worklist));
2466 Builder = &TheBuilder;
2468 InstCombinerLibCallSimplifier TheSimplifier(TD, TLI, this);
2469 Simplifier = &TheSimplifier;
2471 bool EverMadeChange = false;
2473 // Lower dbg.declare intrinsics otherwise their value may be clobbered
2475 EverMadeChange = LowerDbgDeclare(F);
2477 // Iterate while there is work to do.
2478 unsigned Iteration = 0;
2479 while (DoOneIteration(F, Iteration++))
2480 EverMadeChange = true;
2483 return EverMadeChange;
2486 FunctionPass *llvm::createInstructionCombiningPass() {
2487 return new InstCombiner();