1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // InstructionCombining - Combine instructions to form fewer, simple
4 // instructions. This pass does not modify the CFG This pass is where algebraic
5 // simplification happens.
7 // This pass combines things like:
13 // This is a simple worklist driven algorithm.
15 //===----------------------------------------------------------------------===//
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
19 #include "llvm/Transforms/Utils/Local.h"
20 #include "llvm/ConstantHandling.h"
21 #include "llvm/iMemory.h"
22 #include "llvm/iOther.h"
23 #include "llvm/iPHINode.h"
24 #include "llvm/iOperators.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/InstIterator.h"
27 #include "llvm/Support/InstVisitor.h"
28 #include "Support/StatisticReporter.h"
31 static Statistic<> NumCombined ("instcombine\t- Number of insts combined");
32 static Statistic<> NumConstProp("instcombine\t- Number of constant folds");
33 static Statistic<> NumDeadInst ("instcombine\t- Number of dead inst eliminate");
36 class InstCombiner : public FunctionPass,
37 public InstVisitor<InstCombiner, Instruction*> {
38 // Worklist of all of the instructions that need to be simplified.
39 std::vector<Instruction*> WorkList;
41 void AddUsesToWorkList(Instruction &I) {
42 // The instruction was simplified, add all users of the instruction to
43 // the work lists because they might get more simplified now...
45 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
47 WorkList.push_back(cast<Instruction>(*UI));
50 // removeFromWorkList - remove all instances of I from the worklist.
51 void removeFromWorkList(Instruction *I);
53 virtual bool runOnFunction(Function &F);
55 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
59 // Visitation implementation - Implement instruction combining for different
60 // instruction types. The semantics are as follows:
62 // null - No change was made
63 // I - Change was made, I is still valid, I may be dead though
64 // otherwise - Change was made, replace I with returned instruction
66 Instruction *visitAdd(BinaryOperator &I);
67 Instruction *visitSub(BinaryOperator &I);
68 Instruction *visitMul(BinaryOperator &I);
69 Instruction *visitDiv(BinaryOperator &I);
70 Instruction *visitRem(BinaryOperator &I);
71 Instruction *visitAnd(BinaryOperator &I);
72 Instruction *visitOr (BinaryOperator &I);
73 Instruction *visitXor(BinaryOperator &I);
74 Instruction *visitSetCondInst(BinaryOperator &I);
75 Instruction *visitShiftInst(Instruction &I);
76 Instruction *visitCastInst(CastInst &CI);
77 Instruction *visitPHINode(PHINode &PN);
78 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
80 // visitInstruction - Specify what to return for unhandled instructions...
81 Instruction *visitInstruction(Instruction &I) { return 0; }
83 // InsertNewInstBefore - insert an instruction New before instruction Old
84 // in the program. Add the new instruction to the worklist.
86 void InsertNewInstBefore(Instruction *New, Instruction &Old) {
87 assert(New && New->getParent() == 0 &&
88 "New instruction already inserted into a basic block!");
89 BasicBlock *BB = Old.getParent();
90 BB->getInstList().insert(&Old, New); // Insert inst
91 WorkList.push_back(New); // Add to worklist
94 // ReplaceInstUsesWith - This method is to be used when an instruction is
95 // found to be dead, replacable with another preexisting expression. Here
96 // we add all uses of I to the worklist, replace all uses of I with the new
97 // value, then return I, so that the inst combiner will know that I was
100 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
101 AddUsesToWorkList(I); // Add all modified instrs to worklist
102 I.replaceAllUsesWith(V);
107 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
111 // Make sure that this instruction has a constant on the right hand side if it
112 // has any constant arguments. If not, fix it an return true.
114 static bool SimplifyBinOp(BinaryOperator &I) {
115 if (isa<Constant>(I.getOperand(0)) && !isa<Constant>(I.getOperand(1)))
116 return !I.swapOperands();
120 // dyn_castNegInst - Given a 'sub' instruction, return the RHS of the
121 // instruction if the LHS is a constant zero (which is the 'negate' form).
123 static inline Value *dyn_castNegInst(Value *V) {
124 Instruction *I = dyn_cast<Instruction>(V);
125 if (!I || I->getOpcode() != Instruction::Sub) return 0;
127 if (I->getOperand(0) == Constant::getNullValue(I->getType()))
128 return I->getOperand(1);
132 static inline Value *dyn_castNotInst(Value *V) {
133 Instruction *I = dyn_cast<Instruction>(V);
134 if (!I || I->getOpcode() != Instruction::Xor) return 0;
136 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1)))
137 if (CI->isAllOnesValue())
138 return I->getOperand(0);
142 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
143 bool Changed = SimplifyBinOp(I);
144 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
146 // Eliminate 'add int %X, 0'
147 if (RHS == Constant::getNullValue(I.getType()))
148 return ReplaceInstUsesWith(I, LHS);
151 if (Value *V = dyn_castNegInst(LHS))
152 return BinaryOperator::create(Instruction::Sub, RHS, V);
155 if (Value *V = dyn_castNegInst(RHS))
156 return BinaryOperator::create(Instruction::Sub, LHS, V);
158 // Simplify add instructions with a constant RHS...
159 if (Constant *Op2 = dyn_cast<Constant>(RHS)) {
160 if (BinaryOperator *ILHS = dyn_cast<BinaryOperator>(LHS)) {
161 if (ILHS->getOpcode() == Instruction::Add &&
162 isa<Constant>(ILHS->getOperand(1))) {
164 // %Y = add int %X, 1
165 // %Z = add int %Y, 1
167 // %Z = add int %X, 2
169 if (Constant *Val = *Op2 + *cast<Constant>(ILHS->getOperand(1))) {
170 I.setOperand(0, ILHS->getOperand(0));
171 I.setOperand(1, Val);
178 return Changed ? &I : 0;
181 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
182 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
184 if (Op0 == Op1) // sub X, X -> 0
185 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
187 // If this is a subtract instruction with a constant RHS, convert it to an add
188 // instruction of a negative constant
190 if (Constant *Op2 = dyn_cast<Constant>(Op1))
191 if (Constant *RHS = *Constant::getNullValue(I.getType()) - *Op2) // 0 - RHS
192 return BinaryOperator::create(Instruction::Add, Op0, RHS, I.getName());
194 // If this is a 'B = x-(-A)', change to B = x+A...
195 if (Value *V = dyn_castNegInst(Op1))
196 return BinaryOperator::create(Instruction::Add, Op0, V);
198 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression is
199 // not used by anyone else...
201 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
202 if (Op1I->use_size() == 1 && Op1I->getOpcode() == Instruction::Sub) {
203 // Swap the two operands of the subexpr...
204 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
205 Op1I->setOperand(0, IIOp1);
206 Op1I->setOperand(1, IIOp0);
208 // Create the new top level add instruction...
209 return BinaryOperator::create(Instruction::Add, Op0, Op1);
214 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
215 bool Changed = SimplifyBinOp(I);
216 Value *Op1 = I.getOperand(0);
218 // Simplify mul instructions with a constant RHS...
219 if (Constant *Op2 = dyn_cast<Constant>(I.getOperand(1))) {
220 if (I.getType()->isInteger() && cast<ConstantInt>(Op2)->equalsInt(1))
221 return ReplaceInstUsesWith(I, Op1); // Eliminate 'mul int %X, 1'
223 if (I.getType()->isInteger() && cast<ConstantInt>(Op2)->equalsInt(2))
224 // Convert 'mul int %X, 2' to 'add int %X, %X'
225 return BinaryOperator::create(Instruction::Add, Op1, Op1, I.getName());
227 if (Op2->isNullValue())
228 return ReplaceInstUsesWith(I, Op2); // Eliminate 'mul int %X, 0'
231 return Changed ? &I : 0;
235 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
237 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1)))
238 if (RHS->equalsInt(1))
239 return ReplaceInstUsesWith(I, I.getOperand(0));
244 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
246 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1)))
247 if (RHS->equalsInt(1))
248 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
253 // isMaxValueMinusOne - return true if this is Max-1
254 static bool isMaxValueMinusOne(const ConstantInt *C) {
255 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
256 // Calculate -1 casted to the right type...
257 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
258 uint64_t Val = ~0ULL; // All ones
259 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
260 return CU->getValue() == Val-1;
263 const ConstantSInt *CS = cast<ConstantSInt>(C);
265 // Calculate 0111111111..11111
266 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
267 int64_t Val = INT64_MAX; // All ones
268 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
269 return CS->getValue() == Val-1;
272 // isMinValuePlusOne - return true if this is Min+1
273 static bool isMinValuePlusOne(const ConstantInt *C) {
274 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
275 return CU->getValue() == 1;
277 const ConstantSInt *CS = cast<ConstantSInt>(C);
279 // Calculate 1111111111000000000000
280 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
281 int64_t Val = -1; // All ones
282 Val <<= TypeBits-1; // Shift over to the right spot
283 return CS->getValue() == Val+1;
287 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
288 bool Changed = SimplifyBinOp(I);
289 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
291 // and X, X = X and X, 0 == 0
292 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
293 return ReplaceInstUsesWith(I, Op1);
296 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
297 if (RHS->isAllOnesValue())
298 return ReplaceInstUsesWith(I, Op0);
300 // and (not A), (not B) == not (or A, B)
301 if (Op0->use_size() == 1 && Op1->use_size() == 1)
302 if (Value *A = dyn_castNotInst(Op0))
303 if (Value *B = dyn_castNotInst(Op1)) {
304 Instruction *Or = BinaryOperator::create(Instruction::Or, A, B,
305 I.getName()+".demorgan");
306 InsertNewInstBefore(Or, I);
307 return BinaryOperator::createNot(Or, I.getName());
310 return Changed ? &I : 0;
315 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
316 bool Changed = SimplifyBinOp(I);
317 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
319 // or X, X = X or X, 0 == X
320 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
321 return ReplaceInstUsesWith(I, Op0);
324 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
325 if (RHS->isAllOnesValue())
326 return ReplaceInstUsesWith(I, Op1);
328 return Changed ? &I : 0;
333 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
334 bool Changed = SimplifyBinOp(I);
335 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
339 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
341 if (ConstantIntegral *Op1C = dyn_cast<ConstantIntegral>(Op1)) {
343 if (Op1C->isNullValue())
344 return ReplaceInstUsesWith(I, Op0);
346 // Is this a "NOT" instruction?
347 if (Op1C->isAllOnesValue()) {
348 // xor (xor X, -1), -1 = not (not X) = X
349 if (Value *X = dyn_castNotInst(Op0))
350 return ReplaceInstUsesWith(I, X);
352 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
353 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0))
354 if (SCI->use_size() == 1)
355 return new SetCondInst(SCI->getInverseCondition(),
356 SCI->getOperand(0), SCI->getOperand(1));
360 return Changed ? &I : 0;
363 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
364 static Constant *AddOne(ConstantInt *C) {
365 Constant *Result = *C + *ConstantInt::get(C->getType(), 1);
366 assert(Result && "Constant folding integer addition failed!");
369 static Constant *SubOne(ConstantInt *C) {
370 Constant *Result = *C - *ConstantInt::get(C->getType(), 1);
371 assert(Result && "Constant folding integer addition failed!");
375 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
376 // true when both operands are equal...
378 static bool isTrueWhenEqual(Instruction &I) {
379 return I.getOpcode() == Instruction::SetEQ ||
380 I.getOpcode() == Instruction::SetGE ||
381 I.getOpcode() == Instruction::SetLE;
384 Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
385 bool Changed = SimplifyBinOp(I);
386 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
387 const Type *Ty = Op0->getType();
391 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
393 // setcc <global*>, 0 - Global value addresses are never null!
394 if (isa<GlobalValue>(Op0) && isa<ConstantPointerNull>(Op1))
395 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
397 // setcc's with boolean values can always be turned into bitwise operations
398 if (Ty == Type::BoolTy) {
399 // If this is <, >, or !=, we can change this into a simple xor instruction
400 if (!isTrueWhenEqual(I))
401 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
403 // Otherwise we need to make a temporary intermediate instruction and insert
404 // it into the instruction stream. This is what we are after:
406 // seteq bool %A, %B -> ~(A^B)
407 // setle bool %A, %B -> ~A | B
408 // setge bool %A, %B -> A | ~B
410 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
411 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
413 InsertNewInstBefore(Xor, I);
414 return BinaryOperator::createNot(Xor, I.getName());
417 // Handle the setXe cases...
418 assert(I.getOpcode() == Instruction::SetGE ||
419 I.getOpcode() == Instruction::SetLE);
421 if (I.getOpcode() == Instruction::SetGE)
422 std::swap(Op0, Op1); // Change setge -> setle
424 // Now we just have the SetLE case.
425 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
426 InsertNewInstBefore(Not, I);
427 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
430 // Check to see if we are doing one of many comparisons against constant
431 // integers at the end of their ranges...
433 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
434 // Check to see if we are comparing against the minimum or maximum value...
435 if (CI->isMinValue()) {
436 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
437 return ReplaceInstUsesWith(I, ConstantBool::False);
438 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
439 return ReplaceInstUsesWith(I, ConstantBool::True);
440 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
441 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
442 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
443 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
445 } else if (CI->isMaxValue()) {
446 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
447 return ReplaceInstUsesWith(I, ConstantBool::False);
448 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
449 return ReplaceInstUsesWith(I, ConstantBool::True);
450 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
451 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
452 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
453 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
455 // Comparing against a value really close to min or max?
456 } else if (isMinValuePlusOne(CI)) {
457 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
458 return BinaryOperator::create(Instruction::SetEQ, Op0,
459 SubOne(CI), I.getName());
460 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
461 return BinaryOperator::create(Instruction::SetNE, Op0,
462 SubOne(CI), I.getName());
464 } else if (isMaxValueMinusOne(CI)) {
465 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
466 return BinaryOperator::create(Instruction::SetEQ, Op0,
467 AddOne(CI), I.getName());
468 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
469 return BinaryOperator::create(Instruction::SetNE, Op0,
470 AddOne(CI), I.getName());
474 return Changed ? &I : 0;
479 Instruction *InstCombiner::visitShiftInst(Instruction &I) {
480 assert(I.getOperand(1)->getType() == Type::UByteTy);
481 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
483 // shl X, 0 == X and shr X, 0 == X
484 // shl 0, X == 0 and shr 0, X == 0
485 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
486 Op0 == Constant::getNullValue(Op0->getType()))
487 return ReplaceInstUsesWith(I, Op0);
489 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr of
492 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
493 if (I.getOpcode() == Instruction::Shr) {
494 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
495 if (CUI->getValue() >= TypeBits && !(Op0->getType()->isSigned()))
496 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
499 // Check to see if we are shifting left by 1. If so, turn it into an add
501 if (I.getOpcode() == Instruction::Shl && CUI->equalsInt(1))
502 // Convert 'shl int %X, 2' to 'add int %X, %X'
503 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
510 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
513 static inline bool isEliminableCastOfCast(const CastInst &CI,
514 const CastInst *CSrc) {
515 assert(CI.getOperand(0) == CSrc);
516 const Type *SrcTy = CSrc->getOperand(0)->getType();
517 const Type *MidTy = CSrc->getType();
518 const Type *DstTy = CI.getType();
520 // It is legal to eliminate the instruction if casting A->B->A if the sizes
521 // are identical and the bits don't get reinterpreted (for example
522 // int->float->int would not be allowed)
523 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertableTo(MidTy))
526 // Allow free casting and conversion of sizes as long as the sign doesn't
528 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
529 unsigned SrcSize = SrcTy->getPrimitiveSize();
530 unsigned MidSize = MidTy->getPrimitiveSize();
531 unsigned DstSize = DstTy->getPrimitiveSize();
533 // Cases where we are monotonically decreasing the size of the type are
534 // always ok, regardless of what sign changes are going on.
536 if (SrcSize >= MidSize && MidSize >= DstSize)
539 // If we are monotonically growing, things are more complex.
541 if (SrcSize <= MidSize && MidSize <= DstSize) {
542 // We have eight combinations of signedness to worry about. Here's the
544 static const int SignTable[8] = {
545 // CODE, SrcSigned, MidSigned, DstSigned, Comment
546 1, // U U U Always ok
547 1, // U U S Always ok
548 3, // U S U Ok iff SrcSize != MidSize
549 3, // U S S Ok iff SrcSize != MidSize
551 2, // S U S Ok iff MidSize == DstSize
552 1, // S S U Always ok
553 1, // S S S Always ok
556 // Choose an action based on the current entry of the signtable that this
557 // cast of cast refers to...
558 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
559 switch (SignTable[Row]) {
560 case 0: return false; // Never ok
561 case 1: return true; // Always ok
562 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
563 case 3: // Ok iff SrcSize != MidSize
564 return SrcSize != MidSize || SrcTy == Type::BoolTy;
565 default: assert(0 && "Bad entry in sign table!");
570 // Otherwise, we cannot succeed. Specifically we do not want to allow things
571 // like: short -> ushort -> uint, because this can create wrong results if
572 // the input short is negative!
578 // CastInst simplification
580 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
581 // If the user is casting a value to the same type, eliminate this cast
583 if (CI.getType() == CI.getOperand(0)->getType())
584 return ReplaceInstUsesWith(CI, CI.getOperand(0));
586 // If casting the result of another cast instruction, try to eliminate this
589 if (CastInst *CSrc = dyn_cast<CastInst>(CI.getOperand(0))) {
590 if (isEliminableCastOfCast(CI, CSrc)) {
591 // This instruction now refers directly to the cast's src operand. This
592 // has a good chance of making CSrc dead.
593 CI.setOperand(0, CSrc->getOperand(0));
597 // If this is an A->B->A cast, and we are dealing with integral types, try
598 // to convert this into a logical 'and' instruction.
600 if (CSrc->getOperand(0)->getType() == CI.getType() &&
601 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
602 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
603 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
604 assert(CSrc->getType() != Type::ULongTy &&
605 "Cannot have type bigger than ulong!");
606 unsigned AndValue = (1U << CSrc->getType()->getPrimitiveSize()*8)-1;
607 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
608 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
617 // PHINode simplification
619 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
620 // If the PHI node only has one incoming value, eliminate the PHI node...
621 if (PN.getNumIncomingValues() == 0)
622 return ReplaceInstUsesWith(PN, Constant::getNullValue(PN.getType()));
623 if (PN.getNumIncomingValues() == 1)
624 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
626 // Otherwise if all of the incoming values are the same for the PHI, replace
627 // the PHI node with the incoming value.
630 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
631 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
632 if (InVal && PN.getIncomingValue(i) != InVal)
633 return 0; // Not the same, bail out.
635 InVal = PN.getIncomingValue(i);
637 // The only case that could cause InVal to be null is if we have a PHI node
638 // that only has entries for itself. In this case, there is no entry into the
639 // loop, so kill the PHI.
641 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
643 // All of the incoming values are the same, replace the PHI node now.
644 return ReplaceInstUsesWith(PN, InVal);
648 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
649 // Is it 'getelementptr %P, uint 0' or 'getelementptr %P'
650 // If so, eliminate the noop.
651 if ((GEP.getNumOperands() == 2 &&
652 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
653 GEP.getNumOperands() == 1)
654 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
656 // Combine Indices - If the source pointer to this getelementptr instruction
657 // is a getelementptr instruction, combine the indices of the two
658 // getelementptr instructions into a single instruction.
660 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
661 std::vector<Value *> Indices;
663 // Can we combine the two pointer arithmetics offsets?
664 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
665 isa<Constant>(GEP.getOperand(1))) {
666 // Replace the index list on this GEP with the index on the getelementptr
667 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
668 Indices[0] = *cast<Constant>(Src->getOperand(1)) +
669 *cast<Constant>(GEP.getOperand(1));
670 assert(Indices[0] != 0 && "Constant folding of uint's failed!?");
672 } else if (*GEP.idx_begin() == ConstantUInt::getNullValue(Type::LongTy)) {
673 // Otherwise we can do the fold if the first index of the GEP is a zero
674 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
675 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
678 if (!Indices.empty())
679 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
681 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
682 // GEP of global variable. If all of the indices for this GEP are
683 // constants, we can promote this to a constexpr instead of an instruction.
685 // Scan for nonconstants...
686 std::vector<Constant*> Indices;
687 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
688 for (; I != E && isa<Constant>(*I); ++I)
689 Indices.push_back(cast<Constant>(*I));
691 if (I == E) { // If they are all constants...
693 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
695 // Replace all uses of the GEP with the new constexpr...
696 return ReplaceInstUsesWith(GEP, CE);
704 void InstCombiner::removeFromWorkList(Instruction *I) {
705 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
709 bool InstCombiner::runOnFunction(Function &F) {
710 bool Changed = false;
712 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
714 while (!WorkList.empty()) {
715 Instruction *I = WorkList.back(); // Get an instruction from the worklist
718 // Check to see if we can DCE or ConstantPropogate the instruction...
719 // Check to see if we can DIE the instruction...
720 if (isInstructionTriviallyDead(I)) {
721 // Add operands to the worklist...
722 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
723 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
724 WorkList.push_back(Op);
727 BasicBlock::iterator BBI = I;
728 if (dceInstruction(BBI)) {
729 removeFromWorkList(I);
734 // Instruction isn't dead, see if we can constant propogate it...
735 if (Constant *C = ConstantFoldInstruction(I)) {
736 // Add operands to the worklist...
737 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
738 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
739 WorkList.push_back(Op);
740 I->replaceAllUsesWith(C);
742 BasicBlock::iterator BBI = I;
743 if (dceInstruction(BBI)) {
744 removeFromWorkList(I);
749 // Now that we have an instruction, try combining it to simplify it...
750 if (Instruction *Result = visit(*I)) {
752 // Should we replace the old instruction with a new one?
754 // Instructions can end up on the worklist more than once. Make sure
755 // we do not process an instruction that has been deleted.
756 removeFromWorkList(I);
757 ReplaceInstWithInst(I, Result);
759 BasicBlock::iterator II = I;
761 // If the instruction was modified, it's possible that it is now dead.
763 if (dceInstruction(II)) {
764 // Instructions may end up in the worklist more than once. Erase them
766 removeFromWorkList(I);
772 WorkList.push_back(Result);
773 AddUsesToWorkList(*Result);
782 Pass *createInstructionCombiningPass() {
783 return new InstCombiner();