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");
62 // Initialization Routines
63 void llvm::initializeInstCombine(PassRegistry &Registry) {
64 initializeInstCombinerPass(Registry);
67 void LLVMInitializeInstCombine(LLVMPassRegistryRef R) {
68 initializeInstCombine(*unwrap(R));
71 char InstCombiner::ID = 0;
72 INITIALIZE_PASS(InstCombiner, "instcombine",
73 "Combine redundant instructions", false, false)
75 void InstCombiner::getAnalysisUsage(AnalysisUsage &AU) const {
76 AU.addPreservedID(LCSSAID);
81 /// ShouldChangeType - Return true if it is desirable to convert a computation
82 /// from 'From' to 'To'. We don't want to convert from a legal to an illegal
83 /// type for example, or from a smaller to a larger illegal type.
84 bool InstCombiner::ShouldChangeType(const Type *From, const Type *To) const {
85 assert(From->isIntegerTy() && To->isIntegerTy());
87 // If we don't have TD, we don't know if the source/dest are legal.
88 if (!TD) return false;
90 unsigned FromWidth = From->getPrimitiveSizeInBits();
91 unsigned ToWidth = To->getPrimitiveSizeInBits();
92 bool FromLegal = TD->isLegalInteger(FromWidth);
93 bool ToLegal = TD->isLegalInteger(ToWidth);
95 // If this is a legal integer from type, and the result would be an illegal
96 // type, don't do the transformation.
97 if (FromLegal && !ToLegal)
100 // Otherwise, if both are illegal, do not increase the size of the result. We
101 // do allow things like i160 -> i64, but not i64 -> i160.
102 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
109 /// SimplifyAssociativeOrCommutative - This performs a few simplifications for
110 /// operators which are associative or commutative:
112 // Commutative operators:
114 // 1. Order operands such that they are listed from right (least complex) to
115 // left (most complex). This puts constants before unary operators before
118 // Associative operators:
120 // 2. Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
121 // 3. Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
123 // Associative and commutative operators:
125 // 4. Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
126 // 5. Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
127 // 6. Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
128 // if C1 and C2 are constants.
130 bool InstCombiner::SimplifyAssociativeOrCommutative(BinaryOperator &I) {
131 Instruction::BinaryOps Opcode = I.getOpcode();
132 bool Changed = false;
135 // Order operands such that they are listed from right (least complex) to
136 // left (most complex). This puts constants before unary operators before
138 if (I.isCommutative() && getComplexity(I.getOperand(0)) <
139 getComplexity(I.getOperand(1)))
140 Changed = !I.swapOperands();
142 BinaryOperator *Op0 = dyn_cast<BinaryOperator>(I.getOperand(0));
143 BinaryOperator *Op1 = dyn_cast<BinaryOperator>(I.getOperand(1));
145 if (I.isAssociative()) {
146 // Transform: "(A op B) op C" ==> "A op (B op C)" if "B op C" simplifies.
147 if (Op0 && Op0->getOpcode() == Opcode) {
148 Value *A = Op0->getOperand(0);
149 Value *B = Op0->getOperand(1);
150 Value *C = I.getOperand(1);
152 // Does "B op C" simplify?
153 if (Value *V = SimplifyBinOp(Opcode, B, C, TD)) {
154 // It simplifies to V. Form "A op V".
162 // Transform: "A op (B op C)" ==> "(A op B) op C" if "A op B" simplifies.
163 if (Op1 && Op1->getOpcode() == Opcode) {
164 Value *A = I.getOperand(0);
165 Value *B = Op1->getOperand(0);
166 Value *C = Op1->getOperand(1);
168 // Does "A op B" simplify?
169 if (Value *V = SimplifyBinOp(Opcode, A, B, TD)) {
170 // It simplifies to V. Form "V op C".
179 if (I.isAssociative() && I.isCommutative()) {
180 // Transform: "(A op B) op C" ==> "(C op A) op B" if "C op A" simplifies.
181 if (Op0 && Op0->getOpcode() == Opcode) {
182 Value *A = Op0->getOperand(0);
183 Value *B = Op0->getOperand(1);
184 Value *C = I.getOperand(1);
186 // Does "C op A" simplify?
187 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
188 // It simplifies to V. Form "V op B".
196 // Transform: "A op (B op C)" ==> "B op (C op A)" if "C op A" simplifies.
197 if (Op1 && Op1->getOpcode() == Opcode) {
198 Value *A = I.getOperand(0);
199 Value *B = Op1->getOperand(0);
200 Value *C = Op1->getOperand(1);
202 // Does "C op A" simplify?
203 if (Value *V = SimplifyBinOp(Opcode, C, A, TD)) {
204 // It simplifies to V. Form "B op V".
212 // Transform: "(A op C1) op (B op C2)" ==> "(A op B) op (C1 op C2)"
213 // if C1 and C2 are constants.
215 Op0->getOpcode() == Opcode && Op1->getOpcode() == Opcode &&
216 isa<Constant>(Op0->getOperand(1)) &&
217 isa<Constant>(Op1->getOperand(1)) &&
218 Op0->hasOneUse() && Op1->hasOneUse()) {
219 Value *A = Op0->getOperand(0);
220 Constant *C1 = cast<Constant>(Op0->getOperand(1));
221 Value *B = Op1->getOperand(0);
222 Constant *C2 = cast<Constant>(Op1->getOperand(1));
224 Constant *Folded = ConstantExpr::get(Opcode, C1, C2);
225 Instruction *New = BinaryOperator::Create(Opcode, A, B, Op1->getName(),
228 I.setOperand(0, New);
229 I.setOperand(1, Folded);
235 // No further simplifications.
240 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
241 // if the LHS is a constant zero (which is the 'negate' form).
243 Value *InstCombiner::dyn_castNegVal(Value *V) const {
244 if (BinaryOperator::isNeg(V))
245 return BinaryOperator::getNegArgument(V);
247 // Constants can be considered to be negated values if they can be folded.
248 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
249 return ConstantExpr::getNeg(C);
251 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
252 if (C->getType()->getElementType()->isIntegerTy())
253 return ConstantExpr::getNeg(C);
258 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
259 // instruction if the LHS is a constant negative zero (which is the 'negate'
262 Value *InstCombiner::dyn_castFNegVal(Value *V) const {
263 if (BinaryOperator::isFNeg(V))
264 return BinaryOperator::getFNegArgument(V);
266 // Constants can be considered to be negated values if they can be folded.
267 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
268 return ConstantExpr::getFNeg(C);
270 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
271 if (C->getType()->getElementType()->isFloatingPointTy())
272 return ConstantExpr::getFNeg(C);
277 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
279 if (CastInst *CI = dyn_cast<CastInst>(&I))
280 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
282 // Figure out if the constant is the left or the right argument.
283 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
284 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
286 if (Constant *SOC = dyn_cast<Constant>(SO)) {
288 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
289 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
292 Value *Op0 = SO, *Op1 = ConstOperand;
296 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
297 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
298 SO->getName()+".op");
299 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
300 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
301 SO->getName()+".cmp");
302 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
303 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
304 SO->getName()+".cmp");
305 llvm_unreachable("Unknown binary instruction type!");
308 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
309 // constant as the other operand, try to fold the binary operator into the
310 // select arguments. This also works for Cast instructions, which obviously do
311 // not have a second operand.
312 Instruction *InstCombiner::FoldOpIntoSelect(Instruction &Op, SelectInst *SI) {
313 // Don't modify shared select instructions
314 if (!SI->hasOneUse()) return 0;
315 Value *TV = SI->getOperand(1);
316 Value *FV = SI->getOperand(2);
318 if (isa<Constant>(TV) || isa<Constant>(FV)) {
319 // Bool selects with constant operands can be folded to logical ops.
320 if (SI->getType()->isIntegerTy(1)) return 0;
322 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, this);
323 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, this);
325 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
332 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
333 /// has a PHI node as operand #0, see if we can fold the instruction into the
334 /// PHI (which is only possible if all operands to the PHI are constants).
336 /// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
337 /// that would normally be unprofitable because they strongly encourage jump
339 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
340 bool AllowAggressive) {
341 AllowAggressive = false;
342 PHINode *PN = cast<PHINode>(I.getOperand(0));
343 unsigned NumPHIValues = PN->getNumIncomingValues();
344 if (NumPHIValues == 0 ||
345 // We normally only transform phis with a single use, unless we're trying
346 // hard to make jump threading happen.
347 (!PN->hasOneUse() && !AllowAggressive))
351 // Check to see if all of the operands of the PHI are simple constants
352 // (constantint/constantfp/undef). If there is one non-constant value,
353 // remember the BB it is in. If there is more than one or if *it* is a PHI,
354 // bail out. We don't do arbitrary constant expressions here because moving
355 // their computation can be expensive without a cost model.
356 BasicBlock *NonConstBB = 0;
357 for (unsigned i = 0; i != NumPHIValues; ++i)
358 if (!isa<Constant>(PN->getIncomingValue(i)) ||
359 isa<ConstantExpr>(PN->getIncomingValue(i))) {
360 if (NonConstBB) return 0; // More than one non-const value.
361 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
362 NonConstBB = PN->getIncomingBlock(i);
364 // If the incoming non-constant value is in I's block, we have an infinite
366 if (NonConstBB == I.getParent())
370 // If there is exactly one non-constant value, we can insert a copy of the
371 // operation in that block. However, if this is a critical edge, we would be
372 // inserting the computation one some other paths (e.g. inside a loop). Only
373 // do this if the pred block is unconditionally branching into the phi block.
374 if (NonConstBB != 0 && !AllowAggressive) {
375 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
376 if (!BI || !BI->isUnconditional()) return 0;
379 // Okay, we can do the transformation: create the new PHI node.
380 PHINode *NewPN = PHINode::Create(I.getType(), "");
381 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
382 InsertNewInstBefore(NewPN, *PN);
385 // Next, add all of the operands to the PHI.
386 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
387 // We only currently try to fold the condition of a select when it is a phi,
388 // not the true/false values.
389 Value *TrueV = SI->getTrueValue();
390 Value *FalseV = SI->getFalseValue();
391 BasicBlock *PhiTransBB = PN->getParent();
392 for (unsigned i = 0; i != NumPHIValues; ++i) {
393 BasicBlock *ThisBB = PN->getIncomingBlock(i);
394 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
395 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
397 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
398 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
400 assert(PN->getIncomingBlock(i) == NonConstBB);
401 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
403 "phitmp", NonConstBB->getTerminator());
404 Worklist.Add(cast<Instruction>(InV));
406 NewPN->addIncoming(InV, ThisBB);
408 } else if (I.getNumOperands() == 2) {
409 Constant *C = cast<Constant>(I.getOperand(1));
410 for (unsigned i = 0; i != NumPHIValues; ++i) {
412 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
413 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
414 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
416 InV = ConstantExpr::get(I.getOpcode(), InC, C);
418 assert(PN->getIncomingBlock(i) == NonConstBB);
419 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
420 InV = BinaryOperator::Create(BO->getOpcode(),
421 PN->getIncomingValue(i), C, "phitmp",
422 NonConstBB->getTerminator());
423 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
424 InV = CmpInst::Create(CI->getOpcode(),
426 PN->getIncomingValue(i), C, "phitmp",
427 NonConstBB->getTerminator());
429 llvm_unreachable("Unknown binop!");
431 Worklist.Add(cast<Instruction>(InV));
433 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
436 CastInst *CI = cast<CastInst>(&I);
437 const Type *RetTy = CI->getType();
438 for (unsigned i = 0; i != NumPHIValues; ++i) {
440 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
441 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
443 assert(PN->getIncomingBlock(i) == NonConstBB);
444 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
445 I.getType(), "phitmp",
446 NonConstBB->getTerminator());
447 Worklist.Add(cast<Instruction>(InV));
449 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
452 return ReplaceInstUsesWith(I, NewPN);
455 /// FindElementAtOffset - Given a type and a constant offset, determine whether
456 /// or not there is a sequence of GEP indices into the type that will land us at
457 /// the specified offset. If so, fill them into NewIndices and return the
458 /// resultant element type, otherwise return null.
459 const Type *InstCombiner::FindElementAtOffset(const Type *Ty, int64_t Offset,
460 SmallVectorImpl<Value*> &NewIndices) {
462 if (!Ty->isSized()) return 0;
464 // Start with the index over the outer type. Note that the type size
465 // might be zero (even if the offset isn't zero) if the indexed type
466 // is something like [0 x {int, int}]
467 const Type *IntPtrTy = TD->getIntPtrType(Ty->getContext());
468 int64_t FirstIdx = 0;
469 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
470 FirstIdx = Offset/TySize;
471 Offset -= FirstIdx*TySize;
473 // Handle hosts where % returns negative instead of values [0..TySize).
479 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
482 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
484 // Index into the types. If we fail, set OrigBase to null.
486 // Indexing into tail padding between struct/array elements.
487 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
490 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
491 const StructLayout *SL = TD->getStructLayout(STy);
492 assert(Offset < (int64_t)SL->getSizeInBytes() &&
493 "Offset must stay within the indexed type");
495 unsigned Elt = SL->getElementContainingOffset(Offset);
496 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(Ty->getContext()),
499 Offset -= SL->getElementOffset(Elt);
500 Ty = STy->getElementType(Elt);
501 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
502 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
503 assert(EltSize && "Cannot index into a zero-sized array");
504 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
506 Ty = AT->getElementType();
508 // Otherwise, we can't index into the middle of this atomic type, bail.
518 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
519 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
521 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
522 return ReplaceInstUsesWith(GEP, V);
524 Value *PtrOp = GEP.getOperand(0);
526 // Eliminate unneeded casts for indices.
528 bool MadeChange = false;
529 unsigned PtrSize = TD->getPointerSizeInBits();
531 gep_type_iterator GTI = gep_type_begin(GEP);
532 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
533 I != E; ++I, ++GTI) {
534 if (!isa<SequentialType>(*GTI)) continue;
536 // If we are using a wider index than needed for this platform, shrink it
537 // to what we need. If narrower, sign-extend it to what we need. This
538 // explicit cast can make subsequent optimizations more obvious.
539 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
540 if (OpBits == PtrSize)
543 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
546 if (MadeChange) return &GEP;
549 // Combine Indices - If the source pointer to this getelementptr instruction
550 // is a getelementptr instruction, combine the indices of the two
551 // getelementptr instructions into a single instruction.
553 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
554 // Note that if our source is a gep chain itself that we wait for that
555 // chain to be resolved before we perform this transformation. This
556 // avoids us creating a TON of code in some cases.
558 if (GetElementPtrInst *SrcGEP =
559 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
560 if (SrcGEP->getNumOperands() == 2)
561 return 0; // Wait until our source is folded to completion.
563 SmallVector<Value*, 8> Indices;
565 // Find out whether the last index in the source GEP is a sequential idx.
566 bool EndsWithSequential = false;
567 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
569 EndsWithSequential = !(*I)->isStructTy();
571 // Can we combine the two pointer arithmetics offsets?
572 if (EndsWithSequential) {
573 // Replace: gep (gep %P, long B), long A, ...
574 // With: T = long A+B; gep %P, T, ...
577 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
578 Value *GO1 = GEP.getOperand(1);
579 if (SO1 == Constant::getNullValue(SO1->getType())) {
581 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
584 // If they aren't the same type, then the input hasn't been processed
585 // by the loop above yet (which canonicalizes sequential index types to
586 // intptr_t). Just avoid transforming this until the input has been
588 if (SO1->getType() != GO1->getType())
590 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
593 // Update the GEP in place if possible.
594 if (Src->getNumOperands() == 2) {
595 GEP.setOperand(0, Src->getOperand(0));
596 GEP.setOperand(1, Sum);
599 Indices.append(Src->op_begin()+1, Src->op_end()-1);
600 Indices.push_back(Sum);
601 Indices.append(GEP.op_begin()+2, GEP.op_end());
602 } else if (isa<Constant>(*GEP.idx_begin()) &&
603 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
604 Src->getNumOperands() != 1) {
605 // Otherwise we can do the fold if the first index of the GEP is a zero
606 Indices.append(Src->op_begin()+1, Src->op_end());
607 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
610 if (!Indices.empty())
611 return (GEP.isInBounds() && Src->isInBounds()) ?
612 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
613 Indices.end(), GEP.getName()) :
614 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
615 Indices.end(), GEP.getName());
618 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
619 Value *StrippedPtr = PtrOp->stripPointerCasts();
620 if (StrippedPtr != PtrOp) {
621 const PointerType *StrippedPtrTy =cast<PointerType>(StrippedPtr->getType());
623 bool HasZeroPointerIndex = false;
624 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
625 HasZeroPointerIndex = C->isZero();
627 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
628 // into : GEP [10 x i8]* X, i32 0, ...
630 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
631 // into : GEP i8* X, ...
633 // This occurs when the program declares an array extern like "int X[];"
634 if (HasZeroPointerIndex) {
635 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
636 if (const ArrayType *CATy =
637 dyn_cast<ArrayType>(CPTy->getElementType())) {
638 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
639 if (CATy->getElementType() == StrippedPtrTy->getElementType()) {
641 SmallVector<Value*, 8> Idx(GEP.idx_begin()+1, GEP.idx_end());
642 GetElementPtrInst *Res =
643 GetElementPtrInst::Create(StrippedPtr, Idx.begin(),
644 Idx.end(), GEP.getName());
645 Res->setIsInBounds(GEP.isInBounds());
649 if (const ArrayType *XATy =
650 dyn_cast<ArrayType>(StrippedPtrTy->getElementType())){
651 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
652 if (CATy->getElementType() == XATy->getElementType()) {
653 // -> GEP [10 x i8]* X, i32 0, ...
654 // At this point, we know that the cast source type is a pointer
655 // to an array of the same type as the destination pointer
656 // array. Because the array type is never stepped over (there
657 // is a leading zero) we can fold the cast into this GEP.
658 GEP.setOperand(0, StrippedPtr);
663 } else if (GEP.getNumOperands() == 2) {
664 // Transform things like:
665 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
666 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
667 const Type *SrcElTy = StrippedPtrTy->getElementType();
668 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
669 if (TD && SrcElTy->isArrayTy() &&
670 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
671 TD->getTypeAllocSize(ResElTy)) {
673 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
674 Idx[1] = GEP.getOperand(1);
675 Value *NewGEP = GEP.isInBounds() ?
676 Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2, GEP.getName()) :
677 Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName());
678 // V and GEP are both pointer types --> BitCast
679 return new BitCastInst(NewGEP, GEP.getType());
682 // Transform things like:
683 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
684 // (where tmp = 8*tmp2) into:
685 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
687 if (TD && SrcElTy->isArrayTy() && ResElTy->isIntegerTy(8)) {
688 uint64_t ArrayEltSize =
689 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
691 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
692 // allow either a mul, shift, or constant here.
694 ConstantInt *Scale = 0;
695 if (ArrayEltSize == 1) {
696 NewIdx = GEP.getOperand(1);
697 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
698 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
699 NewIdx = ConstantInt::get(CI->getType(), 1);
701 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
702 if (Inst->getOpcode() == Instruction::Shl &&
703 isa<ConstantInt>(Inst->getOperand(1))) {
704 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
705 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
706 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
708 NewIdx = Inst->getOperand(0);
709 } else if (Inst->getOpcode() == Instruction::Mul &&
710 isa<ConstantInt>(Inst->getOperand(1))) {
711 Scale = cast<ConstantInt>(Inst->getOperand(1));
712 NewIdx = Inst->getOperand(0);
716 // If the index will be to exactly the right offset with the scale taken
717 // out, perform the transformation. Note, we don't know whether Scale is
718 // signed or not. We'll use unsigned version of division/modulo
719 // operation after making sure Scale doesn't have the sign bit set.
720 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
721 Scale->getZExtValue() % ArrayEltSize == 0) {
722 Scale = ConstantInt::get(Scale->getType(),
723 Scale->getZExtValue() / ArrayEltSize);
724 if (Scale->getZExtValue() != 1) {
725 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
727 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
730 // Insert the new GEP instruction.
732 Idx[0] = Constant::getNullValue(Type::getInt32Ty(GEP.getContext()));
734 Value *NewGEP = GEP.isInBounds() ?
735 Builder->CreateInBoundsGEP(StrippedPtr, Idx, Idx + 2,GEP.getName()):
736 Builder->CreateGEP(StrippedPtr, Idx, Idx + 2, GEP.getName());
737 // The NewGEP must be pointer typed, so must the old one -> BitCast
738 return new BitCastInst(NewGEP, GEP.getType());
744 /// See if we can simplify:
745 /// X = bitcast A* to B*
746 /// Y = gep X, <...constant indices...>
747 /// into a gep of the original struct. This is important for SROA and alias
748 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
749 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
751 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
752 // Determine how much the GEP moves the pointer. We are guaranteed to get
753 // a constant back from EmitGEPOffset.
754 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP));
755 int64_t Offset = OffsetV->getSExtValue();
757 // If this GEP instruction doesn't move the pointer, just replace the GEP
758 // with a bitcast of the real input to the dest type.
760 // If the bitcast is of an allocation, and the allocation will be
761 // converted to match the type of the cast, don't touch this.
762 if (isa<AllocaInst>(BCI->getOperand(0)) ||
763 isMalloc(BCI->getOperand(0))) {
764 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
765 if (Instruction *I = visitBitCast(*BCI)) {
768 BCI->getParent()->getInstList().insert(BCI, I);
769 ReplaceInstUsesWith(*BCI, I);
774 return new BitCastInst(BCI->getOperand(0), GEP.getType());
777 // Otherwise, if the offset is non-zero, we need to find out if there is a
778 // field at Offset in 'A's type. If so, we can pull the cast through the
780 SmallVector<Value*, 8> NewIndices;
782 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
783 if (FindElementAtOffset(InTy, Offset, NewIndices)) {
784 Value *NGEP = GEP.isInBounds() ?
785 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
787 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
790 if (NGEP->getType() == GEP.getType())
791 return ReplaceInstUsesWith(GEP, NGEP);
792 NGEP->takeName(&GEP);
793 return new BitCastInst(NGEP, GEP.getType());
803 static bool IsOnlyNullComparedAndFreed(const Value &V) {
804 for (Value::const_use_iterator UI = V.use_begin(), UE = V.use_end();
809 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(U))
810 if (ICI->isEquality() && isa<ConstantPointerNull>(ICI->getOperand(1)))
817 Instruction *InstCombiner::visitMalloc(Instruction &MI) {
818 // If we have a malloc call which is only used in any amount of comparisons
819 // to null and free calls, delete the calls and replace the comparisons with
820 // true or false as appropriate.
821 if (IsOnlyNullComparedAndFreed(MI)) {
822 for (Value::use_iterator UI = MI.use_begin(), UE = MI.use_end();
824 // We can assume that every remaining use is a free call or an icmp eq/ne
825 // to null, so the cast is safe.
826 Instruction *I = cast<Instruction>(*UI);
828 // Early increment here, as we're about to get rid of the user.
832 EraseInstFromFunction(*cast<CallInst>(I));
835 // Again, the cast is safe.
836 ICmpInst *C = cast<ICmpInst>(I);
837 ReplaceInstUsesWith(*C, ConstantInt::get(Type::getInt1Ty(C->getContext()),
838 C->isFalseWhenEqual()));
839 EraseInstFromFunction(*C);
841 return EraseInstFromFunction(MI);
848 Instruction *InstCombiner::visitFree(CallInst &FI) {
849 Value *Op = FI.getArgOperand(0);
851 // free undef -> unreachable.
852 if (isa<UndefValue>(Op)) {
853 // Insert a new store to null because we cannot modify the CFG here.
854 new StoreInst(ConstantInt::getTrue(FI.getContext()),
855 UndefValue::get(Type::getInt1PtrTy(FI.getContext())), &FI);
856 return EraseInstFromFunction(FI);
859 // If we have 'free null' delete the instruction. This can happen in stl code
860 // when lots of inlining happens.
861 if (isa<ConstantPointerNull>(Op))
862 return EraseInstFromFunction(FI);
869 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
870 // Change br (not X), label True, label False to: br X, label False, True
872 BasicBlock *TrueDest;
873 BasicBlock *FalseDest;
874 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
876 // Swap Destinations and condition...
878 BI.setSuccessor(0, FalseDest);
879 BI.setSuccessor(1, TrueDest);
883 // Cannonicalize fcmp_one -> fcmp_oeq
884 FCmpInst::Predicate FPred; Value *Y;
885 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
886 TrueDest, FalseDest)) &&
887 BI.getCondition()->hasOneUse())
888 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
889 FPred == FCmpInst::FCMP_OGE) {
890 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
891 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
893 // Swap Destinations and condition.
894 BI.setSuccessor(0, FalseDest);
895 BI.setSuccessor(1, TrueDest);
900 // Cannonicalize icmp_ne -> icmp_eq
901 ICmpInst::Predicate IPred;
902 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
903 TrueDest, FalseDest)) &&
904 BI.getCondition()->hasOneUse())
905 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
906 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
907 IPred == ICmpInst::ICMP_SGE) {
908 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
909 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
910 // Swap Destinations and condition.
911 BI.setSuccessor(0, FalseDest);
912 BI.setSuccessor(1, TrueDest);
920 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
921 Value *Cond = SI.getCondition();
922 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
923 if (I->getOpcode() == Instruction::Add)
924 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
925 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
926 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
928 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
930 SI.setOperand(0, I->getOperand(0));
938 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
939 Value *Agg = EV.getAggregateOperand();
941 if (!EV.hasIndices())
942 return ReplaceInstUsesWith(EV, Agg);
944 if (Constant *C = dyn_cast<Constant>(Agg)) {
945 if (isa<UndefValue>(C))
946 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
948 if (isa<ConstantAggregateZero>(C))
949 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
951 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
952 // Extract the element indexed by the first index out of the constant
953 Value *V = C->getOperand(*EV.idx_begin());
954 if (EV.getNumIndices() > 1)
955 // Extract the remaining indices out of the constant indexed by the
957 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
959 return ReplaceInstUsesWith(EV, V);
961 return 0; // Can't handle other constants
963 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
964 // We're extracting from an insertvalue instruction, compare the indices
965 const unsigned *exti, *exte, *insi, *inse;
966 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
967 exte = EV.idx_end(), inse = IV->idx_end();
968 exti != exte && insi != inse;
971 // The insert and extract both reference distinctly different elements.
972 // This means the extract is not influenced by the insert, and we can
973 // replace the aggregate operand of the extract with the aggregate
974 // operand of the insert. i.e., replace
975 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
976 // %E = extractvalue { i32, { i32 } } %I, 0
978 // %E = extractvalue { i32, { i32 } } %A, 0
979 return ExtractValueInst::Create(IV->getAggregateOperand(),
980 EV.idx_begin(), EV.idx_end());
982 if (exti == exte && insi == inse)
983 // Both iterators are at the end: Index lists are identical. Replace
984 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
985 // %C = extractvalue { i32, { i32 } } %B, 1, 0
987 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
989 // The extract list is a prefix of the insert list. i.e. replace
990 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
991 // %E = extractvalue { i32, { i32 } } %I, 1
993 // %X = extractvalue { i32, { i32 } } %A, 1
994 // %E = insertvalue { i32 } %X, i32 42, 0
995 // by switching the order of the insert and extract (though the
996 // insertvalue should be left in, since it may have other uses).
997 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
998 EV.idx_begin(), EV.idx_end());
999 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
1003 // The insert list is a prefix of the extract list
1004 // We can simply remove the common indices from the extract and make it
1005 // operate on the inserted value instead of the insertvalue result.
1007 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
1008 // %E = extractvalue { i32, { i32 } } %I, 1, 0
1010 // %E extractvalue { i32 } { i32 42 }, 0
1011 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
1014 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
1015 // We're extracting from an intrinsic, see if we're the only user, which
1016 // allows us to simplify multiple result intrinsics to simpler things that
1017 // just get one value.
1018 if (II->hasOneUse()) {
1019 // Check if we're grabbing the overflow bit or the result of a 'with
1020 // overflow' intrinsic. If it's the latter we can remove the intrinsic
1021 // and replace it with a traditional binary instruction.
1022 switch (II->getIntrinsicID()) {
1023 case Intrinsic::uadd_with_overflow:
1024 case Intrinsic::sadd_with_overflow:
1025 if (*EV.idx_begin() == 0) { // Normal result.
1026 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1027 II->replaceAllUsesWith(UndefValue::get(II->getType()));
1028 EraseInstFromFunction(*II);
1029 return BinaryOperator::CreateAdd(LHS, RHS);
1032 case Intrinsic::usub_with_overflow:
1033 case Intrinsic::ssub_with_overflow:
1034 if (*EV.idx_begin() == 0) { // Normal result.
1035 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1036 II->replaceAllUsesWith(UndefValue::get(II->getType()));
1037 EraseInstFromFunction(*II);
1038 return BinaryOperator::CreateSub(LHS, RHS);
1041 case Intrinsic::umul_with_overflow:
1042 case Intrinsic::smul_with_overflow:
1043 if (*EV.idx_begin() == 0) { // Normal result.
1044 Value *LHS = II->getArgOperand(0), *RHS = II->getArgOperand(1);
1045 II->replaceAllUsesWith(UndefValue::get(II->getType()));
1046 EraseInstFromFunction(*II);
1047 return BinaryOperator::CreateMul(LHS, RHS);
1055 // Can't simplify extracts from other values. Note that nested extracts are
1056 // already simplified implicitely by the above (extract ( extract (insert) )
1057 // will be translated into extract ( insert ( extract ) ) first and then just
1058 // the value inserted, if appropriate).
1065 /// TryToSinkInstruction - Try to move the specified instruction from its
1066 /// current block into the beginning of DestBlock, which can only happen if it's
1067 /// safe to move the instruction past all of the instructions between it and the
1068 /// end of its block.
1069 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
1070 assert(I->hasOneUse() && "Invariants didn't hold!");
1072 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
1073 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
1076 // Do not sink alloca instructions out of the entry block.
1077 if (isa<AllocaInst>(I) && I->getParent() ==
1078 &DestBlock->getParent()->getEntryBlock())
1081 // We can only sink load instructions if there is nothing between the load and
1082 // the end of block that could change the value.
1083 if (I->mayReadFromMemory()) {
1084 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
1086 if (Scan->mayWriteToMemory())
1090 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
1092 I->moveBefore(InsertPos);
1098 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
1099 /// all reachable code to the worklist.
1101 /// This has a couple of tricks to make the code faster and more powerful. In
1102 /// particular, we constant fold and DCE instructions as we go, to avoid adding
1103 /// them to the worklist (this significantly speeds up instcombine on code where
1104 /// many instructions are dead or constant). Additionally, if we find a branch
1105 /// whose condition is a known constant, we only visit the reachable successors.
1107 static bool AddReachableCodeToWorklist(BasicBlock *BB,
1108 SmallPtrSet<BasicBlock*, 64> &Visited,
1110 const TargetData *TD) {
1111 bool MadeIRChange = false;
1112 SmallVector<BasicBlock*, 256> Worklist;
1113 Worklist.push_back(BB);
1115 SmallVector<Instruction*, 128> InstrsForInstCombineWorklist;
1116 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
1119 BB = Worklist.pop_back_val();
1121 // We have now visited this block! If we've already been here, ignore it.
1122 if (!Visited.insert(BB)) continue;
1124 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
1125 Instruction *Inst = BBI++;
1127 // DCE instruction if trivially dead.
1128 if (isInstructionTriviallyDead(Inst)) {
1130 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
1131 Inst->eraseFromParent();
1135 // ConstantProp instruction if trivially constant.
1136 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
1137 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
1138 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
1140 Inst->replaceAllUsesWith(C);
1142 Inst->eraseFromParent();
1147 // See if we can constant fold its operands.
1148 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
1150 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
1151 if (CE == 0) continue;
1153 // If we already folded this constant, don't try again.
1154 if (!FoldedConstants.insert(CE))
1157 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
1158 if (NewC && NewC != CE) {
1160 MadeIRChange = true;
1165 InstrsForInstCombineWorklist.push_back(Inst);
1168 // Recursively visit successors. If this is a branch or switch on a
1169 // constant, only visit the reachable successor.
1170 TerminatorInst *TI = BB->getTerminator();
1171 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
1172 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
1173 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
1174 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
1175 Worklist.push_back(ReachableBB);
1178 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
1179 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
1180 // See if this is an explicit destination.
1181 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
1182 if (SI->getCaseValue(i) == Cond) {
1183 BasicBlock *ReachableBB = SI->getSuccessor(i);
1184 Worklist.push_back(ReachableBB);
1188 // Otherwise it is the default destination.
1189 Worklist.push_back(SI->getSuccessor(0));
1194 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
1195 Worklist.push_back(TI->getSuccessor(i));
1196 } while (!Worklist.empty());
1198 // Once we've found all of the instructions to add to instcombine's worklist,
1199 // add them in reverse order. This way instcombine will visit from the top
1200 // of the function down. This jives well with the way that it adds all uses
1201 // of instructions to the worklist after doing a transformation, thus avoiding
1202 // some N^2 behavior in pathological cases.
1203 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
1204 InstrsForInstCombineWorklist.size());
1206 return MadeIRChange;
1209 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
1210 MadeIRChange = false;
1212 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
1213 << F.getNameStr() << "\n");
1216 // Do a depth-first traversal of the function, populate the worklist with
1217 // the reachable instructions. Ignore blocks that are not reachable. Keep
1218 // track of which blocks we visit.
1219 SmallPtrSet<BasicBlock*, 64> Visited;
1220 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
1222 // Do a quick scan over the function. If we find any blocks that are
1223 // unreachable, remove any instructions inside of them. This prevents
1224 // the instcombine code from having to deal with some bad special cases.
1225 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
1226 if (!Visited.count(BB)) {
1227 Instruction *Term = BB->getTerminator();
1228 while (Term != BB->begin()) { // Remove instrs bottom-up
1229 BasicBlock::iterator I = Term; --I;
1231 DEBUG(errs() << "IC: DCE: " << *I << '\n');
1232 // A debug intrinsic shouldn't force another iteration if we weren't
1233 // going to do one without it.
1234 if (!isa<DbgInfoIntrinsic>(I)) {
1236 MadeIRChange = true;
1239 // If I is not void type then replaceAllUsesWith undef.
1240 // This allows ValueHandlers and custom metadata to adjust itself.
1241 if (!I->getType()->isVoidTy())
1242 I->replaceAllUsesWith(UndefValue::get(I->getType()));
1243 I->eraseFromParent();
1248 while (!Worklist.isEmpty()) {
1249 Instruction *I = Worklist.RemoveOne();
1250 if (I == 0) continue; // skip null values.
1252 // Check to see if we can DCE the instruction.
1253 if (isInstructionTriviallyDead(I)) {
1254 DEBUG(errs() << "IC: DCE: " << *I << '\n');
1255 EraseInstFromFunction(*I);
1257 MadeIRChange = true;
1261 // Instruction isn't dead, see if we can constant propagate it.
1262 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
1263 if (Constant *C = ConstantFoldInstruction(I, TD)) {
1264 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
1266 // Add operands to the worklist.
1267 ReplaceInstUsesWith(*I, C);
1269 EraseInstFromFunction(*I);
1270 MadeIRChange = true;
1274 // See if we can trivially sink this instruction to a successor basic block.
1275 if (I->hasOneUse()) {
1276 BasicBlock *BB = I->getParent();
1277 Instruction *UserInst = cast<Instruction>(I->use_back());
1278 BasicBlock *UserParent;
1280 // Get the block the use occurs in.
1281 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
1282 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
1284 UserParent = UserInst->getParent();
1286 if (UserParent != BB) {
1287 bool UserIsSuccessor = false;
1288 // See if the user is one of our successors.
1289 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
1290 if (*SI == UserParent) {
1291 UserIsSuccessor = true;
1295 // If the user is one of our immediate successors, and if that successor
1296 // only has us as a predecessors (we'd have to split the critical edge
1297 // otherwise), we can keep going.
1298 if (UserIsSuccessor && UserParent->getSinglePredecessor())
1299 // Okay, the CFG is simple enough, try to sink this instruction.
1300 MadeIRChange |= TryToSinkInstruction(I, UserParent);
1304 // Now that we have an instruction, try combining it to simplify it.
1305 Builder->SetInsertPoint(I->getParent(), I);
1310 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
1311 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
1313 if (Instruction *Result = visit(*I)) {
1315 // Should we replace the old instruction with a new one?
1317 DEBUG(errs() << "IC: Old = " << *I << '\n'
1318 << " New = " << *Result << '\n');
1320 // Everything uses the new instruction now.
1321 I->replaceAllUsesWith(Result);
1323 // Push the new instruction and any users onto the worklist.
1324 Worklist.Add(Result);
1325 Worklist.AddUsersToWorkList(*Result);
1327 // Move the name to the new instruction first.
1328 Result->takeName(I);
1330 // Insert the new instruction into the basic block...
1331 BasicBlock *InstParent = I->getParent();
1332 BasicBlock::iterator InsertPos = I;
1334 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
1335 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
1338 InstParent->getInstList().insert(InsertPos, Result);
1340 EraseInstFromFunction(*I);
1343 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
1344 << " New = " << *I << '\n');
1347 // If the instruction was modified, it's possible that it is now dead.
1348 // if so, remove it.
1349 if (isInstructionTriviallyDead(I)) {
1350 EraseInstFromFunction(*I);
1353 Worklist.AddUsersToWorkList(*I);
1356 MadeIRChange = true;
1361 return MadeIRChange;
1365 bool InstCombiner::runOnFunction(Function &F) {
1366 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
1367 TD = getAnalysisIfAvailable<TargetData>();
1370 /// Builder - This is an IRBuilder that automatically inserts new
1371 /// instructions into the worklist when they are created.
1372 IRBuilder<true, TargetFolder, InstCombineIRInserter>
1373 TheBuilder(F.getContext(), TargetFolder(TD),
1374 InstCombineIRInserter(Worklist));
1375 Builder = &TheBuilder;
1377 bool EverMadeChange = false;
1379 // Iterate while there is work to do.
1380 unsigned Iteration = 0;
1381 while (DoOneIteration(F, Iteration++))
1382 EverMadeChange = true;
1385 return EverMadeChange;
1388 FunctionPass *llvm::createInstructionCombiningPass() {
1389 return new InstCombiner();