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/Instructions.h"
21 #include "llvm/Pass.h"
22 #include "llvm/Constants.h"
23 #include "llvm/ConstantHandling.h"
24 #include "llvm/DerivedTypes.h"
25 #include "llvm/Support/InstIterator.h"
26 #include "llvm/Support/InstVisitor.h"
27 #include "llvm/Support/CallSite.h"
28 #include "Support/Statistic.h"
32 Statistic<> NumCombined ("instcombine", "Number of insts combined");
33 Statistic<> NumConstProp("instcombine", "Number of constant folds");
34 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
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(ShiftInst &I);
76 Instruction *visitCastInst(CastInst &CI);
77 Instruction *visitCallInst(CallInst &CI);
78 Instruction *visitInvokeInst(InvokeInst &II);
79 Instruction *visitPHINode(PHINode &PN);
80 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
81 Instruction *visitAllocationInst(AllocationInst &AI);
82 Instruction *visitBranchInst(BranchInst &BI);
84 // visitInstruction - Specify what to return for unhandled instructions...
85 Instruction *visitInstruction(Instruction &I) { return 0; }
88 bool transformConstExprCastCall(CallSite CS);
90 // InsertNewInstBefore - insert an instruction New before instruction Old
91 // in the program. Add the new instruction to the worklist.
93 void InsertNewInstBefore(Instruction *New, Instruction &Old) {
94 assert(New && New->getParent() == 0 &&
95 "New instruction already inserted into a basic block!");
96 BasicBlock *BB = Old.getParent();
97 BB->getInstList().insert(&Old, New); // Insert inst
98 WorkList.push_back(New); // Add to worklist
101 // ReplaceInstUsesWith - This method is to be used when an instruction is
102 // found to be dead, replacable with another preexisting expression. Here
103 // we add all uses of I to the worklist, replace all uses of I with the new
104 // value, then return I, so that the inst combiner will know that I was
107 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
108 AddUsesToWorkList(I); // Add all modified instrs to worklist
109 I.replaceAllUsesWith(V);
113 // SimplifyCommutative - This performs a few simplifications for commutative
115 bool SimplifyCommutative(BinaryOperator &I);
118 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
121 // getComplexity: Assign a complexity or rank value to LLVM Values...
122 // 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
123 static unsigned getComplexity(Value *V) {
124 if (isa<Instruction>(V)) {
125 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
129 if (isa<Argument>(V)) return 2;
130 return isa<Constant>(V) ? 0 : 1;
133 // isOnlyUse - Return true if this instruction will be deleted if we stop using
135 static bool isOnlyUse(Value *V) {
136 return V->use_size() == 1 || isa<Constant>(V);
139 // SimplifyCommutative - This performs a few simplifications for commutative
142 // 1. Order operands such that they are listed from right (least complex) to
143 // left (most complex). This puts constants before unary operators before
146 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
147 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
149 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
150 bool Changed = false;
151 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
152 Changed = !I.swapOperands();
154 if (!I.isAssociative()) return Changed;
155 Instruction::BinaryOps Opcode = I.getOpcode();
156 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
157 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
158 if (isa<Constant>(I.getOperand(1))) {
159 Constant *Folded = ConstantExpr::get(I.getOpcode(),
160 cast<Constant>(I.getOperand(1)),
161 cast<Constant>(Op->getOperand(1)));
162 I.setOperand(0, Op->getOperand(0));
163 I.setOperand(1, Folded);
165 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
166 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
167 isOnlyUse(Op) && isOnlyUse(Op1)) {
168 Constant *C1 = cast<Constant>(Op->getOperand(1));
169 Constant *C2 = cast<Constant>(Op1->getOperand(1));
171 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
172 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
173 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
176 WorkList.push_back(New);
177 I.setOperand(0, New);
178 I.setOperand(1, Folded);
185 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
186 // if the LHS is a constant zero (which is the 'negate' form).
188 static inline Value *dyn_castNegVal(Value *V) {
189 if (BinaryOperator::isNeg(V))
190 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
192 // Constants can be considered to be negated values if they can be folded...
193 if (Constant *C = dyn_cast<Constant>(V))
194 return ConstantExpr::get(Instruction::Sub,
195 Constant::getNullValue(V->getType()), C);
199 static inline Value *dyn_castNotVal(Value *V) {
200 if (BinaryOperator::isNot(V))
201 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
203 // Constants can be considered to be not'ed values...
204 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
205 return ConstantExpr::get(Instruction::Xor,
206 ConstantIntegral::getAllOnesValue(C->getType()),C);
210 // dyn_castFoldableMul - If this value is a multiply that can be folded into
211 // other computations (because it has a constant operand), return the
212 // non-constant operand of the multiply.
214 static inline Value *dyn_castFoldableMul(Value *V) {
215 if (V->use_size() == 1 && V->getType()->isInteger())
216 if (Instruction *I = dyn_cast<Instruction>(V))
217 if (I->getOpcode() == Instruction::Mul)
218 if (isa<Constant>(I->getOperand(1)))
219 return I->getOperand(0);
223 // dyn_castMaskingAnd - If this value is an And instruction masking a value with
224 // a constant, return the constant being anded with.
226 static inline Constant *dyn_castMaskingAnd(Value *V) {
227 if (Instruction *I = dyn_cast<Instruction>(V))
228 if (I->getOpcode() == Instruction::And)
229 return dyn_cast<Constant>(I->getOperand(1));
231 // If this is a constant, it acts just like we were masking with it.
232 return dyn_cast<Constant>(V);
235 // Log2 - Calculate the log base 2 for the specified value if it is exactly a
237 static unsigned Log2(uint64_t Val) {
238 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
241 if (Val & 1) return 0; // Multiple bits set?
248 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
249 bool Changed = SimplifyCommutative(I);
250 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
252 // Eliminate 'add int %X, 0'
253 if (RHS == Constant::getNullValue(I.getType()))
254 return ReplaceInstUsesWith(I, LHS);
257 if (Value *V = dyn_castNegVal(LHS))
258 return BinaryOperator::create(Instruction::Sub, RHS, V);
261 if (!isa<Constant>(RHS))
262 if (Value *V = dyn_castNegVal(RHS))
263 return BinaryOperator::create(Instruction::Sub, LHS, V);
265 // X*C + X --> X * (C+1)
266 if (dyn_castFoldableMul(LHS) == RHS) {
268 ConstantExpr::get(Instruction::Add,
269 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
270 ConstantInt::get(I.getType(), 1));
271 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
274 // X + X*C --> X * (C+1)
275 if (dyn_castFoldableMul(RHS) == LHS) {
277 ConstantExpr::get(Instruction::Add,
278 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
279 ConstantInt::get(I.getType(), 1));
280 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
283 // (A & C1)+(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
284 if (Constant *C1 = dyn_castMaskingAnd(LHS))
285 if (Constant *C2 = dyn_castMaskingAnd(RHS))
286 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
287 return BinaryOperator::create(Instruction::Or, LHS, RHS);
289 return Changed ? &I : 0;
292 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
293 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
295 if (Op0 == Op1) // sub X, X -> 0
296 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
298 // If this is a 'B = x-(-A)', change to B = x+A...
299 if (Value *V = dyn_castNegVal(Op1))
300 return BinaryOperator::create(Instruction::Add, Op0, V);
302 // Replace (-1 - A) with (~A)...
303 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
304 if (C->isAllOnesValue())
305 return BinaryOperator::createNot(Op1);
307 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
308 if (Op1I->use_size() == 1) {
309 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
310 // is not used by anyone else...
312 if (Op1I->getOpcode() == Instruction::Sub) {
313 // Swap the two operands of the subexpr...
314 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
315 Op1I->setOperand(0, IIOp1);
316 Op1I->setOperand(1, IIOp0);
318 // Create the new top level add instruction...
319 return BinaryOperator::create(Instruction::Add, Op0, Op1);
322 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
324 if (Op1I->getOpcode() == Instruction::And &&
325 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
326 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
328 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
329 return BinaryOperator::create(Instruction::And, Op0, NewNot);
332 // X - X*C --> X * (1-C)
333 if (dyn_castFoldableMul(Op1I) == Op0) {
335 ConstantExpr::get(Instruction::Sub,
336 ConstantInt::get(I.getType(), 1),
337 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
338 assert(CP1 && "Couldn't constant fold 1-C?");
339 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
343 // X*C - X --> X * (C-1)
344 if (dyn_castFoldableMul(Op0) == Op1) {
346 ConstantExpr::get(Instruction::Sub,
347 cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
348 ConstantInt::get(I.getType(), 1));
349 assert(CP1 && "Couldn't constant fold C - 1?");
350 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
356 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
357 bool Changed = SimplifyCommutative(I);
358 Value *Op0 = I.getOperand(0);
360 // Simplify mul instructions with a constant RHS...
361 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
362 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
363 const Type *Ty = CI->getType();
364 uint64_t Val = Ty->isSigned() ?
365 (uint64_t)cast<ConstantSInt>(CI)->getValue() :
366 cast<ConstantUInt>(CI)->getValue();
369 return ReplaceInstUsesWith(I, Op1); // Eliminate 'mul double %X, 0'
371 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul int %X, 1'
372 case 2: // Convert 'mul int %X, 2' to 'add int %X, %X'
373 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
376 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
377 return new ShiftInst(Instruction::Shl, Op0,
378 ConstantUInt::get(Type::UByteTy, C));
380 ConstantFP *Op1F = cast<ConstantFP>(Op1);
381 if (Op1F->isNullValue())
382 return ReplaceInstUsesWith(I, Op1);
384 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
385 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
386 if (Op1F->getValue() == 1.0)
387 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
391 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
392 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
393 return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
395 return Changed ? &I : 0;
398 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
400 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
401 if (RHS->equalsInt(1))
402 return ReplaceInstUsesWith(I, I.getOperand(0));
404 // Check to see if this is an unsigned division with an exact power of 2,
405 // if so, convert to a right shift.
406 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
407 if (uint64_t Val = C->getValue()) // Don't break X / 0
408 if (uint64_t C = Log2(Val))
409 return new ShiftInst(Instruction::Shr, I.getOperand(0),
410 ConstantUInt::get(Type::UByteTy, C));
413 // 0 / X == 0, we don't need to preserve faults!
414 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
415 if (LHS->equalsInt(0))
416 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
422 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
423 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
424 if (RHS->equalsInt(1)) // X % 1 == 0
425 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
427 // Check to see if this is an unsigned remainder with an exact power of 2,
428 // if so, convert to a bitwise and.
429 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
430 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
432 return BinaryOperator::create(Instruction::And, I.getOperand(0),
433 ConstantUInt::get(I.getType(), Val-1));
436 // 0 % X == 0, we don't need to preserve faults!
437 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
438 if (LHS->equalsInt(0))
439 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
444 // isMaxValueMinusOne - return true if this is Max-1
445 static bool isMaxValueMinusOne(const ConstantInt *C) {
446 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
447 // Calculate -1 casted to the right type...
448 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
449 uint64_t Val = ~0ULL; // All ones
450 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
451 return CU->getValue() == Val-1;
454 const ConstantSInt *CS = cast<ConstantSInt>(C);
456 // Calculate 0111111111..11111
457 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
458 int64_t Val = INT64_MAX; // All ones
459 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
460 return CS->getValue() == Val-1;
463 // isMinValuePlusOne - return true if this is Min+1
464 static bool isMinValuePlusOne(const ConstantInt *C) {
465 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
466 return CU->getValue() == 1;
468 const ConstantSInt *CS = cast<ConstantSInt>(C);
470 // Calculate 1111111111000000000000
471 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
472 int64_t Val = -1; // All ones
473 Val <<= TypeBits-1; // Shift over to the right spot
474 return CS->getValue() == Val+1;
478 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
479 bool Changed = SimplifyCommutative(I);
480 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
482 // and X, X = X and X, 0 == 0
483 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
484 return ReplaceInstUsesWith(I, Op1);
487 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
488 if (RHS->isAllOnesValue())
489 return ReplaceInstUsesWith(I, Op0);
491 Value *Op0NotVal = dyn_castNotVal(Op0);
492 Value *Op1NotVal = dyn_castNotVal(Op1);
494 // (~A & ~B) == (~(A | B)) - Demorgan's Law
495 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
496 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
497 Op1NotVal,I.getName()+".demorgan",
499 WorkList.push_back(Or);
500 return BinaryOperator::createNot(Or);
503 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
504 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
506 return Changed ? &I : 0;
511 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
512 bool Changed = SimplifyCommutative(I);
513 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
515 // or X, X = X or X, 0 == X
516 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
517 return ReplaceInstUsesWith(I, Op0);
520 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
521 if (RHS->isAllOnesValue())
522 return ReplaceInstUsesWith(I, Op1);
524 Value *Op0NotVal = dyn_castNotVal(Op0);
525 Value *Op1NotVal = dyn_castNotVal(Op1);
527 if (Op1 == Op0NotVal) // ~A | A == -1
528 return ReplaceInstUsesWith(I,
529 ConstantIntegral::getAllOnesValue(I.getType()));
531 if (Op0 == Op1NotVal) // A | ~A == -1
532 return ReplaceInstUsesWith(I,
533 ConstantIntegral::getAllOnesValue(I.getType()));
535 // (~A | ~B) == (~(A & B)) - Demorgan's Law
536 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
537 Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
538 Op1NotVal,I.getName()+".demorgan",
540 WorkList.push_back(And);
541 return BinaryOperator::createNot(And);
544 return Changed ? &I : 0;
549 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
550 bool Changed = SimplifyCommutative(I);
551 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
555 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
557 if (ConstantIntegral *Op1C = dyn_cast<ConstantIntegral>(Op1)) {
559 if (Op1C->isNullValue())
560 return ReplaceInstUsesWith(I, Op0);
562 // Is this a "NOT" instruction?
563 if (Op1C->isAllOnesValue()) {
564 // xor (xor X, -1), -1 = not (not X) = X
565 if (Value *X = dyn_castNotVal(Op0))
566 return ReplaceInstUsesWith(I, X);
568 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
569 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0))
570 if (SCI->use_size() == 1)
571 return new SetCondInst(SCI->getInverseCondition(),
572 SCI->getOperand(0), SCI->getOperand(1));
576 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
578 return ReplaceInstUsesWith(I,
579 ConstantIntegral::getAllOnesValue(I.getType()));
581 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
583 return ReplaceInstUsesWith(I,
584 ConstantIntegral::getAllOnesValue(I.getType()));
586 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
587 if (Op1I->getOpcode() == Instruction::Or)
588 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
589 cast<BinaryOperator>(Op1I)->swapOperands();
592 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
597 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
598 if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
599 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
600 cast<BinaryOperator>(Op0I)->swapOperands();
601 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
602 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
603 WorkList.push_back(cast<Instruction>(NotB));
604 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
609 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
610 if (Constant *C1 = dyn_castMaskingAnd(Op0))
611 if (Constant *C2 = dyn_castMaskingAnd(Op1))
612 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
613 return BinaryOperator::create(Instruction::Or, Op0, Op1);
615 return Changed ? &I : 0;
618 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
619 static Constant *AddOne(ConstantInt *C) {
620 Constant *Result = ConstantExpr::get(Instruction::Add, C,
621 ConstantInt::get(C->getType(), 1));
622 assert(Result && "Constant folding integer addition failed!");
625 static Constant *SubOne(ConstantInt *C) {
626 Constant *Result = ConstantExpr::get(Instruction::Sub, C,
627 ConstantInt::get(C->getType(), 1));
628 assert(Result && "Constant folding integer addition failed!");
632 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
633 // true when both operands are equal...
635 static bool isTrueWhenEqual(Instruction &I) {
636 return I.getOpcode() == Instruction::SetEQ ||
637 I.getOpcode() == Instruction::SetGE ||
638 I.getOpcode() == Instruction::SetLE;
641 Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
642 bool Changed = SimplifyCommutative(I);
643 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
644 const Type *Ty = Op0->getType();
648 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
650 // setcc <global*>, 0 - Global value addresses are never null!
651 if (isa<GlobalValue>(Op0) && isa<ConstantPointerNull>(Op1))
652 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
654 // setcc's with boolean values can always be turned into bitwise operations
655 if (Ty == Type::BoolTy) {
656 // If this is <, >, or !=, we can change this into a simple xor instruction
657 if (!isTrueWhenEqual(I))
658 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
660 // Otherwise we need to make a temporary intermediate instruction and insert
661 // it into the instruction stream. This is what we are after:
663 // seteq bool %A, %B -> ~(A^B)
664 // setle bool %A, %B -> ~A | B
665 // setge bool %A, %B -> A | ~B
667 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
668 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
670 InsertNewInstBefore(Xor, I);
671 return BinaryOperator::createNot(Xor, I.getName());
674 // Handle the setXe cases...
675 assert(I.getOpcode() == Instruction::SetGE ||
676 I.getOpcode() == Instruction::SetLE);
678 if (I.getOpcode() == Instruction::SetGE)
679 std::swap(Op0, Op1); // Change setge -> setle
681 // Now we just have the SetLE case.
682 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
683 InsertNewInstBefore(Not, I);
684 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
687 // Check to see if we are doing one of many comparisons against constant
688 // integers at the end of their ranges...
690 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
691 if (CI->isNullValue()) {
692 if (I.getOpcode() == Instruction::SetNE)
693 return new CastInst(Op0, Type::BoolTy, I.getName());
694 else if (I.getOpcode() == Instruction::SetEQ) {
695 // seteq X, 0 -> not (cast X to bool)
696 Instruction *Val = new CastInst(Op0, Type::BoolTy, I.getName()+".not");
697 InsertNewInstBefore(Val, I);
698 return BinaryOperator::createNot(Val, I.getName());
702 // Check to see if we are comparing against the minimum or maximum value...
703 if (CI->isMinValue()) {
704 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
705 return ReplaceInstUsesWith(I, ConstantBool::False);
706 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
707 return ReplaceInstUsesWith(I, ConstantBool::True);
708 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
709 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
710 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
711 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
713 } else if (CI->isMaxValue()) {
714 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
715 return ReplaceInstUsesWith(I, ConstantBool::False);
716 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
717 return ReplaceInstUsesWith(I, ConstantBool::True);
718 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
719 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
720 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
721 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
723 // Comparing against a value really close to min or max?
724 } else if (isMinValuePlusOne(CI)) {
725 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
726 return BinaryOperator::create(Instruction::SetEQ, Op0,
727 SubOne(CI), I.getName());
728 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
729 return BinaryOperator::create(Instruction::SetNE, Op0,
730 SubOne(CI), I.getName());
732 } else if (isMaxValueMinusOne(CI)) {
733 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
734 return BinaryOperator::create(Instruction::SetEQ, Op0,
735 AddOne(CI), I.getName());
736 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
737 return BinaryOperator::create(Instruction::SetNE, Op0,
738 AddOne(CI), I.getName());
742 return Changed ? &I : 0;
747 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
748 assert(I.getOperand(1)->getType() == Type::UByteTy);
749 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
751 // shl X, 0 == X and shr X, 0 == X
752 // shl 0, X == 0 and shr 0, X == 0
753 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
754 Op0 == Constant::getNullValue(Op0->getType()))
755 return ReplaceInstUsesWith(I, Op0);
757 // If this is a shift of a shift, see if we can fold the two together...
758 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0)) {
759 if (isa<Constant>(Op1) && isa<Constant>(Op0SI->getOperand(1))) {
760 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(Op0SI->getOperand(1));
761 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
762 unsigned ShiftAmt2 = cast<ConstantUInt>(Op1)->getValue();
764 // Check for (A << c1) << c2 and (A >> c1) >> c2
765 if (I.getOpcode() == Op0SI->getOpcode()) {
766 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
767 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
768 ConstantUInt::get(Type::UByteTy, Amt));
771 if (I.getType()->isUnsigned()) { // Check for (A << c1) >> c2 or visaversa
772 // Calculate bitmask for what gets shifted off the edge...
773 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
774 if (I.getOpcode() == Instruction::Shr)
775 C = ConstantExpr::getShift(Instruction::Shr, C, ShiftAmt1C);
777 C = ConstantExpr::getShift(Instruction::Shl, C, ShiftAmt1C);
780 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
781 C, Op0SI->getOperand(0)->getName()+".mask",&I);
782 WorkList.push_back(Mask);
784 // Figure out what flavor of shift we should use...
785 if (ShiftAmt1 == ShiftAmt2)
786 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
787 else if (ShiftAmt1 < ShiftAmt2) {
788 return new ShiftInst(I.getOpcode(), Mask,
789 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
791 return new ShiftInst(Op0SI->getOpcode(), Mask,
792 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
798 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr of
801 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
802 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
803 if (CUI->getValue() >= TypeBits &&
804 (!Op0->getType()->isSigned() || I.getOpcode() == Instruction::Shl))
805 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
807 // Check to see if we are shifting left by 1. If so, turn it into an add
809 if (I.getOpcode() == Instruction::Shl && CUI->equalsInt(1))
810 // Convert 'shl int %X, 1' to 'add int %X, %X'
811 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
815 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
816 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
817 if (I.getOpcode() == Instruction::Shr && CSI->isAllOnesValue())
818 return ReplaceInstUsesWith(I, CSI);
824 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
827 static inline bool isEliminableCastOfCast(const CastInst &CI,
828 const CastInst *CSrc) {
829 assert(CI.getOperand(0) == CSrc);
830 const Type *SrcTy = CSrc->getOperand(0)->getType();
831 const Type *MidTy = CSrc->getType();
832 const Type *DstTy = CI.getType();
834 // It is legal to eliminate the instruction if casting A->B->A if the sizes
835 // are identical and the bits don't get reinterpreted (for example
836 // int->float->int would not be allowed)
837 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
840 // Allow free casting and conversion of sizes as long as the sign doesn't
842 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
843 unsigned SrcSize = SrcTy->getPrimitiveSize();
844 unsigned MidSize = MidTy->getPrimitiveSize();
845 unsigned DstSize = DstTy->getPrimitiveSize();
847 // Cases where we are monotonically decreasing the size of the type are
848 // always ok, regardless of what sign changes are going on.
850 if (SrcSize >= MidSize && MidSize >= DstSize)
853 // Cases where the source and destination type are the same, but the middle
854 // type is bigger are noops.
856 if (SrcSize == DstSize && MidSize > SrcSize)
859 // If we are monotonically growing, things are more complex.
861 if (SrcSize <= MidSize && MidSize <= DstSize) {
862 // We have eight combinations of signedness to worry about. Here's the
864 static const int SignTable[8] = {
865 // CODE, SrcSigned, MidSigned, DstSigned, Comment
866 1, // U U U Always ok
867 1, // U U S Always ok
868 3, // U S U Ok iff SrcSize != MidSize
869 3, // U S S Ok iff SrcSize != MidSize
871 2, // S U S Ok iff MidSize == DstSize
872 1, // S S U Always ok
873 1, // S S S Always ok
876 // Choose an action based on the current entry of the signtable that this
877 // cast of cast refers to...
878 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
879 switch (SignTable[Row]) {
880 case 0: return false; // Never ok
881 case 1: return true; // Always ok
882 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
883 case 3: // Ok iff SrcSize != MidSize
884 return SrcSize != MidSize || SrcTy == Type::BoolTy;
885 default: assert(0 && "Bad entry in sign table!");
890 // Otherwise, we cannot succeed. Specifically we do not want to allow things
891 // like: short -> ushort -> uint, because this can create wrong results if
892 // the input short is negative!
898 // CastInst simplification
900 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
901 // If the user is casting a value to the same type, eliminate this cast
903 if (CI.getType() == CI.getOperand(0)->getType())
904 return ReplaceInstUsesWith(CI, CI.getOperand(0));
906 // If casting the result of another cast instruction, try to eliminate this
909 if (CastInst *CSrc = dyn_cast<CastInst>(CI.getOperand(0))) {
910 if (isEliminableCastOfCast(CI, CSrc)) {
911 // This instruction now refers directly to the cast's src operand. This
912 // has a good chance of making CSrc dead.
913 CI.setOperand(0, CSrc->getOperand(0));
917 // If this is an A->B->A cast, and we are dealing with integral types, try
918 // to convert this into a logical 'and' instruction.
920 if (CSrc->getOperand(0)->getType() == CI.getType() &&
921 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
922 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
923 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
924 assert(CSrc->getType() != Type::ULongTy &&
925 "Cannot have type bigger than ulong!");
926 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
927 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
928 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
936 // CallInst simplification
938 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
939 if (transformConstExprCastCall(&CI)) return 0;
943 // InvokeInst simplification
945 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
946 if (transformConstExprCastCall(&II)) return 0;
950 // getPromotedType - Return the specified type promoted as it would be to pass
951 // though a va_arg area...
952 static const Type *getPromotedType(const Type *Ty) {
953 switch (Ty->getPrimitiveID()) {
954 case Type::SByteTyID:
955 case Type::ShortTyID: return Type::IntTy;
956 case Type::UByteTyID:
957 case Type::UShortTyID: return Type::UIntTy;
958 case Type::FloatTyID: return Type::DoubleTy;
963 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
964 // attempt to move the cast to the arguments of the call/invoke.
966 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
967 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
968 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
969 if (CE->getOpcode() != Instruction::Cast ||
970 !isa<ConstantPointerRef>(CE->getOperand(0)))
972 ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
973 if (!isa<Function>(CPR->getValue())) return false;
974 Function *Callee = cast<Function>(CPR->getValue());
975 Instruction *Caller = CS.getInstruction();
977 // Okay, this is a cast from a function to a different type. Unless doing so
978 // would cause a type conversion of one of our arguments, change this call to
979 // be a direct call with arguments casted to the appropriate types.
981 const FunctionType *FT = Callee->getFunctionType();
982 const Type *OldRetTy = Caller->getType();
984 if (Callee->isExternal() &&
985 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()))
986 return false; // Cannot transform this return value...
988 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
989 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
991 CallSite::arg_iterator AI = CS.arg_begin();
992 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
993 const Type *ParamTy = FT->getParamType(i);
994 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
995 if (Callee->isExternal() && !isConvertible) return false;
998 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
999 Callee->isExternal())
1000 return false; // Do not delete arguments unless we have a function body...
1002 // Okay, we decided that this is a safe thing to do: go ahead and start
1003 // inserting cast instructions as necessary...
1004 std::vector<Value*> Args;
1005 Args.reserve(NumActualArgs);
1007 AI = CS.arg_begin();
1008 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1009 const Type *ParamTy = FT->getParamType(i);
1010 if ((*AI)->getType() == ParamTy) {
1011 Args.push_back(*AI);
1013 Instruction *Cast = new CastInst(*AI, ParamTy, "tmp");
1014 InsertNewInstBefore(Cast, *Caller);
1015 Args.push_back(Cast);
1019 // If the function takes more arguments than the call was taking, add them
1021 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1022 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1024 // If we are removing arguments to the function, emit an obnoxious warning...
1025 if (FT->getNumParams() < NumActualArgs)
1026 if (!FT->isVarArg()) {
1027 std::cerr << "WARNING: While resolving call to function '"
1028 << Callee->getName() << "' arguments were dropped!\n";
1030 // Add all of the arguments in their promoted form to the arg list...
1031 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1032 const Type *PTy = getPromotedType((*AI)->getType());
1033 if (PTy != (*AI)->getType()) {
1034 // Must promote to pass through va_arg area!
1035 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
1036 InsertNewInstBefore(Cast, *Caller);
1037 Args.push_back(Cast);
1039 Args.push_back(*AI);
1044 if (FT->getReturnType() == Type::VoidTy)
1045 Caller->setName(""); // Void type should not have a name...
1048 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1049 NC = new InvokeInst(Callee, II->getNormalDest(), II->getExceptionalDest(),
1050 Args, Caller->getName(), Caller);
1052 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
1055 // Insert a cast of the return type as necessary...
1057 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
1058 if (NV->getType() != Type::VoidTy) {
1059 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
1060 InsertNewInstBefore(NC, *Caller);
1061 AddUsesToWorkList(*Caller);
1063 NV = Constant::getNullValue(Caller->getType());
1067 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
1068 Caller->replaceAllUsesWith(NV);
1069 Caller->getParent()->getInstList().erase(Caller);
1070 removeFromWorkList(Caller);
1076 // PHINode simplification
1078 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
1079 // If the PHI node only has one incoming value, eliminate the PHI node...
1080 if (PN.getNumIncomingValues() == 1)
1081 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
1083 // Otherwise if all of the incoming values are the same for the PHI, replace
1084 // the PHI node with the incoming value.
1087 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1088 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
1089 if (InVal && PN.getIncomingValue(i) != InVal)
1090 return 0; // Not the same, bail out.
1092 InVal = PN.getIncomingValue(i);
1094 // The only case that could cause InVal to be null is if we have a PHI node
1095 // that only has entries for itself. In this case, there is no entry into the
1096 // loop, so kill the PHI.
1098 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
1100 // All of the incoming values are the same, replace the PHI node now.
1101 return ReplaceInstUsesWith(PN, InVal);
1105 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1106 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
1107 // If so, eliminate the noop.
1108 if ((GEP.getNumOperands() == 2 &&
1109 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
1110 GEP.getNumOperands() == 1)
1111 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
1113 // Combine Indices - If the source pointer to this getelementptr instruction
1114 // is a getelementptr instruction, combine the indices of the two
1115 // getelementptr instructions into a single instruction.
1117 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
1118 std::vector<Value *> Indices;
1120 // Can we combine the two pointer arithmetics offsets?
1121 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
1122 isa<Constant>(GEP.getOperand(1))) {
1123 // Replace: gep (gep %P, long C1), long C2, ...
1124 // With: gep %P, long (C1+C2), ...
1125 Value *Sum = ConstantExpr::get(Instruction::Add,
1126 cast<Constant>(Src->getOperand(1)),
1127 cast<Constant>(GEP.getOperand(1)));
1128 assert(Sum && "Constant folding of longs failed!?");
1129 GEP.setOperand(0, Src->getOperand(0));
1130 GEP.setOperand(1, Sum);
1131 AddUsesToWorkList(*Src); // Reduce use count of Src
1133 } else if (Src->getNumOperands() == 2) {
1134 // Replace: gep (gep %P, long B), long A, ...
1135 // With: T = long A+B; gep %P, T, ...
1137 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
1139 Src->getName()+".sum", &GEP);
1140 GEP.setOperand(0, Src->getOperand(0));
1141 GEP.setOperand(1, Sum);
1142 WorkList.push_back(cast<Instruction>(Sum));
1144 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
1145 Src->getNumOperands() != 1) {
1146 // Otherwise we can do the fold if the first index of the GEP is a zero
1147 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
1148 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
1149 } else if (Src->getOperand(Src->getNumOperands()-1) ==
1150 Constant::getNullValue(Type::LongTy)) {
1151 // If the src gep ends with a constant array index, merge this get into
1152 // it, even if we have a non-zero array index.
1153 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
1154 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
1157 if (!Indices.empty())
1158 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
1160 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
1161 // GEP of global variable. If all of the indices for this GEP are
1162 // constants, we can promote this to a constexpr instead of an instruction.
1164 // Scan for nonconstants...
1165 std::vector<Constant*> Indices;
1166 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1167 for (; I != E && isa<Constant>(*I); ++I)
1168 Indices.push_back(cast<Constant>(*I));
1170 if (I == E) { // If they are all constants...
1172 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1174 // Replace all uses of the GEP with the new constexpr...
1175 return ReplaceInstUsesWith(GEP, CE);
1182 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1183 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1184 if (AI.isArrayAllocation()) // Check C != 1
1185 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1186 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
1187 AllocationInst *New = 0;
1189 // Create and insert the replacement instruction...
1190 if (isa<MallocInst>(AI))
1191 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
1193 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
1194 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
1197 // Scan to the end of the allocation instructions, to skip over a block of
1198 // allocas if possible...
1200 BasicBlock::iterator It = New;
1201 while (isa<AllocationInst>(*It)) ++It;
1203 // Now that I is pointing to the first non-allocation-inst in the block,
1204 // insert our getelementptr instruction...
1206 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1207 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1209 // Now make everything use the getelementptr instead of the original
1211 ReplaceInstUsesWith(AI, V);
1217 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1218 // Change br (not X), label True, label False to: br X, label False, True
1219 if (BI.isConditional() && !isa<Constant>(BI.getCondition()))
1220 if (Value *V = dyn_castNotVal(BI.getCondition())) {
1221 BasicBlock *TrueDest = BI.getSuccessor(0);
1222 BasicBlock *FalseDest = BI.getSuccessor(1);
1223 // Swap Destinations and condition...
1225 BI.setSuccessor(0, FalseDest);
1226 BI.setSuccessor(1, TrueDest);
1233 void InstCombiner::removeFromWorkList(Instruction *I) {
1234 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1238 bool InstCombiner::runOnFunction(Function &F) {
1239 bool Changed = false;
1241 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
1243 while (!WorkList.empty()) {
1244 Instruction *I = WorkList.back(); // Get an instruction from the worklist
1245 WorkList.pop_back();
1247 // Check to see if we can DCE or ConstantPropagate the instruction...
1248 // Check to see if we can DIE the instruction...
1249 if (isInstructionTriviallyDead(I)) {
1250 // Add operands to the worklist...
1251 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1252 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1253 WorkList.push_back(Op);
1256 BasicBlock::iterator BBI = I;
1257 if (dceInstruction(BBI)) {
1258 removeFromWorkList(I);
1263 // Instruction isn't dead, see if we can constant propagate it...
1264 if (Constant *C = ConstantFoldInstruction(I)) {
1265 // Add operands to the worklist...
1266 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1267 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1268 WorkList.push_back(Op);
1269 ReplaceInstUsesWith(*I, C);
1272 BasicBlock::iterator BBI = I;
1273 if (dceInstruction(BBI)) {
1274 removeFromWorkList(I);
1279 // Now that we have an instruction, try combining it to simplify it...
1280 if (Instruction *Result = visit(*I)) {
1282 // Should we replace the old instruction with a new one?
1284 // Instructions can end up on the worklist more than once. Make sure
1285 // we do not process an instruction that has been deleted.
1286 removeFromWorkList(I);
1287 ReplaceInstWithInst(I, Result);
1289 BasicBlock::iterator II = I;
1291 // If the instruction was modified, it's possible that it is now dead.
1292 // if so, remove it.
1293 if (dceInstruction(II)) {
1294 // Instructions may end up in the worklist more than once. Erase them
1296 removeFromWorkList(I);
1302 WorkList.push_back(Result);
1303 AddUsesToWorkList(*Result);
1312 Pass *createInstructionCombiningPass() {
1313 return new InstCombiner();