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/Instructions.h"
22 #include "llvm/Pass.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Support/InstIterator.h"
25 #include "llvm/Support/InstVisitor.h"
26 #include "Support/Statistic.h"
30 Statistic<> NumCombined ("instcombine", "Number of insts combined");
31 Statistic<> NumConstProp("instcombine", "Number of constant folds");
32 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
34 class InstCombiner : public FunctionPass,
35 public InstVisitor<InstCombiner, Instruction*> {
36 // Worklist of all of the instructions that need to be simplified.
37 std::vector<Instruction*> WorkList;
39 void AddUsesToWorkList(Instruction &I) {
40 // The instruction was simplified, add all users of the instruction to
41 // the work lists because they might get more simplified now...
43 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
45 WorkList.push_back(cast<Instruction>(*UI));
48 // removeFromWorkList - remove all instances of I from the worklist.
49 void removeFromWorkList(Instruction *I);
51 virtual bool runOnFunction(Function &F);
53 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
57 // Visitation implementation - Implement instruction combining for different
58 // instruction types. The semantics are as follows:
60 // null - No change was made
61 // I - Change was made, I is still valid, I may be dead though
62 // otherwise - Change was made, replace I with returned instruction
64 Instruction *visitAdd(BinaryOperator &I);
65 Instruction *visitSub(BinaryOperator &I);
66 Instruction *visitMul(BinaryOperator &I);
67 Instruction *visitDiv(BinaryOperator &I);
68 Instruction *visitRem(BinaryOperator &I);
69 Instruction *visitAnd(BinaryOperator &I);
70 Instruction *visitOr (BinaryOperator &I);
71 Instruction *visitXor(BinaryOperator &I);
72 Instruction *visitSetCondInst(BinaryOperator &I);
73 Instruction *visitShiftInst(ShiftInst &I);
74 Instruction *visitCastInst(CastInst &CI);
75 Instruction *visitPHINode(PHINode &PN);
76 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
77 Instruction *visitAllocationInst(AllocationInst &AI);
79 // visitInstruction - Specify what to return for unhandled instructions...
80 Instruction *visitInstruction(Instruction &I) { return 0; }
82 // InsertNewInstBefore - insert an instruction New before instruction Old
83 // in the program. Add the new instruction to the worklist.
85 void InsertNewInstBefore(Instruction *New, Instruction &Old) {
86 assert(New && New->getParent() == 0 &&
87 "New instruction already inserted into a basic block!");
88 BasicBlock *BB = Old.getParent();
89 BB->getInstList().insert(&Old, New); // Insert inst
90 WorkList.push_back(New); // Add to worklist
93 // ReplaceInstUsesWith - This method is to be used when an instruction is
94 // found to be dead, replacable with another preexisting expression. Here
95 // we add all uses of I to the worklist, replace all uses of I with the new
96 // value, then return I, so that the inst combiner will know that I was
99 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
100 AddUsesToWorkList(I); // Add all modified instrs to worklist
101 I.replaceAllUsesWith(V);
105 // SimplifyCommutative - This performs a few simplifications for commutative
107 bool SimplifyCommutative(BinaryOperator &I);
111 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
114 // getComplexity: Assign a complexity or rank value to LLVM Values...
115 // 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
116 static unsigned getComplexity(Value *V) {
117 if (isa<Instruction>(V)) {
118 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
122 if (isa<Argument>(V)) return 2;
123 return isa<Constant>(V) ? 0 : 1;
126 // isOnlyUse - Return true if this instruction will be deleted if we stop using
128 static bool isOnlyUse(Value *V) {
129 return V->use_size() == 1 || isa<Constant>(V);
132 // SimplifyCommutative - This performs a few simplifications for commutative
135 // 1. Order operands such that they are listed from right (least complex) to
136 // left (most complex). This puts constants before unary operators before
139 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
140 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
142 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
143 bool Changed = false;
144 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
145 Changed = !I.swapOperands();
147 if (!I.isAssociative()) return Changed;
148 Instruction::BinaryOps Opcode = I.getOpcode();
149 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
150 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
151 if (isa<Constant>(I.getOperand(1))) {
152 Constant *Folded = ConstantFoldBinaryInstruction(I.getOpcode(),
153 cast<Constant>(I.getOperand(1)), cast<Constant>(Op->getOperand(1)));
154 assert(Folded && "Couldn't constant fold commutative operand?");
155 I.setOperand(0, Op->getOperand(0));
156 I.setOperand(1, Folded);
158 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
159 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
160 isOnlyUse(Op) && isOnlyUse(Op1)) {
161 Constant *C1 = cast<Constant>(Op->getOperand(1));
162 Constant *C2 = cast<Constant>(Op1->getOperand(1));
164 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
165 Constant *Folded = ConstantFoldBinaryInstruction(I.getOpcode(),C1,C2);
166 assert(Folded && "Couldn't constant fold commutative operand?");
167 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
170 WorkList.push_back(New);
171 I.setOperand(0, New);
172 I.setOperand(1, Folded);
179 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
180 // if the LHS is a constant zero (which is the 'negate' form).
182 static inline Value *dyn_castNegVal(Value *V) {
183 if (BinaryOperator::isNeg(V))
184 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
186 // Constants can be considered to be negated values if they can be folded...
187 if (Constant *C = dyn_cast<Constant>(V))
188 return *Constant::getNullValue(V->getType()) - *C;
192 static inline Value *dyn_castNotVal(Value *V) {
193 if (BinaryOperator::isNot(V))
194 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
196 // Constants can be considered to be not'ed values...
197 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
198 return *ConstantIntegral::getAllOnesValue(C->getType()) ^ *C;
202 // dyn_castFoldableMul - If this value is a multiply that can be folded into
203 // other computations (because it has a constant operand), return the
204 // non-constant operand of the multiply.
206 static inline Value *dyn_castFoldableMul(Value *V) {
207 if (V->use_size() == 1 && V->getType()->isInteger())
208 if (Instruction *I = dyn_cast<Instruction>(V))
209 if (I->getOpcode() == Instruction::Mul)
210 if (isa<Constant>(I->getOperand(1)))
211 return I->getOperand(0);
215 // dyn_castMaskingAnd - If this value is an And instruction masking a value with
216 // a constant, return the constant being anded with.
218 static inline Constant *dyn_castMaskingAnd(Value *V) {
219 if (Instruction *I = dyn_cast<Instruction>(V))
220 if (I->getOpcode() == Instruction::And)
221 return dyn_cast<Constant>(I->getOperand(1));
223 // If this is a constant, it acts just like we were masking with it.
224 return dyn_cast<Constant>(V);
227 // Log2 - Calculate the log base 2 for the specified value if it is exactly a
229 static unsigned Log2(uint64_t Val) {
230 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
233 if (Val & 1) return 0; // Multiple bits set?
240 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
241 bool Changed = SimplifyCommutative(I);
242 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
244 // Eliminate 'add int %X, 0'
245 if (RHS == Constant::getNullValue(I.getType()))
246 return ReplaceInstUsesWith(I, LHS);
249 if (Value *V = dyn_castNegVal(LHS))
250 return BinaryOperator::create(Instruction::Sub, RHS, V);
253 if (!isa<Constant>(RHS))
254 if (Value *V = dyn_castNegVal(RHS))
255 return BinaryOperator::create(Instruction::Sub, LHS, V);
257 // X*C + X --> X * (C+1)
258 if (dyn_castFoldableMul(LHS) == RHS) {
259 Constant *CP1 = *cast<Constant>(cast<Instruction>(LHS)->getOperand(1)) +
260 *ConstantInt::get(I.getType(), 1);
261 assert(CP1 && "Couldn't constant fold C + 1?");
262 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
265 // X + X*C --> X * (C+1)
266 if (dyn_castFoldableMul(RHS) == LHS) {
267 Constant *CP1 = *cast<Constant>(cast<Instruction>(RHS)->getOperand(1)) +
268 *ConstantInt::get(I.getType(), 1);
269 assert(CP1 && "Couldn't constant fold C + 1?");
270 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
273 // (A & C1)+(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
274 if (Constant *C1 = dyn_castMaskingAnd(LHS))
275 if (Constant *C2 = dyn_castMaskingAnd(RHS))
276 if ((*C1 & *C2)->isNullValue())
277 return BinaryOperator::create(Instruction::Or, LHS, RHS);
279 return Changed ? &I : 0;
282 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
283 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
285 if (Op0 == Op1) // sub X, X -> 0
286 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
288 // If this is a 'B = x-(-A)', change to B = x+A...
289 if (Value *V = dyn_castNegVal(Op1))
290 return BinaryOperator::create(Instruction::Add, Op0, V);
292 // Replace (-1 - A) with (~A)...
293 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
294 if (C->isAllOnesValue())
295 return BinaryOperator::createNot(Op1);
297 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
298 if (Op1I->use_size() == 1) {
299 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
300 // is not used by anyone else...
302 if (Op1I->getOpcode() == Instruction::Sub) {
303 // Swap the two operands of the subexpr...
304 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
305 Op1I->setOperand(0, IIOp1);
306 Op1I->setOperand(1, IIOp0);
308 // Create the new top level add instruction...
309 return BinaryOperator::create(Instruction::Add, Op0, Op1);
312 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
314 if (Op1I->getOpcode() == Instruction::And &&
315 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
316 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
318 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
319 return BinaryOperator::create(Instruction::And, Op0, NewNot);
322 // X - X*C --> X * (1-C)
323 if (dyn_castFoldableMul(Op1I) == Op0) {
324 Constant *CP1 = *ConstantInt::get(I.getType(), 1) -
325 *cast<Constant>(cast<Instruction>(Op1)->getOperand(1));
326 assert(CP1 && "Couldn't constant fold 1-C?");
327 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
331 // X*C - X --> X * (C-1)
332 if (dyn_castFoldableMul(Op0) == Op1) {
333 Constant *CP1 = *cast<Constant>(cast<Instruction>(Op0)->getOperand(1)) -
334 *ConstantInt::get(I.getType(), 1);
335 assert(CP1 && "Couldn't constant fold C - 1?");
336 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
342 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
343 bool Changed = SimplifyCommutative(I);
344 Value *Op0 = I.getOperand(0);
346 // Simplify mul instructions with a constant RHS...
347 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
348 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
349 const Type *Ty = CI->getType();
350 uint64_t Val = Ty->isSigned() ?
351 (uint64_t)cast<ConstantSInt>(CI)->getValue() :
352 cast<ConstantUInt>(CI)->getValue();
355 return ReplaceInstUsesWith(I, Op1); // Eliminate 'mul double %X, 0'
357 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul int %X, 1'
358 case 2: // Convert 'mul int %X, 2' to 'add int %X, %X'
359 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
362 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
363 return new ShiftInst(Instruction::Shl, Op0,
364 ConstantUInt::get(Type::UByteTy, C));
366 ConstantFP *Op1F = cast<ConstantFP>(Op1);
367 if (Op1F->isNullValue())
368 return ReplaceInstUsesWith(I, Op1);
370 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
371 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
372 if (Op1F->getValue() == 1.0)
373 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
377 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
378 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
379 return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
381 return Changed ? &I : 0;
384 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
386 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
387 if (RHS->equalsInt(1))
388 return ReplaceInstUsesWith(I, I.getOperand(0));
390 // Check to see if this is an unsigned division with an exact power of 2,
391 // if so, convert to a right shift.
392 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
393 if (uint64_t Val = C->getValue()) // Don't break X / 0
394 if (uint64_t C = Log2(Val))
395 return new ShiftInst(Instruction::Shr, I.getOperand(0),
396 ConstantUInt::get(Type::UByteTy, C));
399 // 0 / X == 0, we don't need to preserve faults!
400 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
401 if (LHS->equalsInt(0))
402 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
408 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
409 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
410 if (RHS->equalsInt(1)) // X % 1 == 0
411 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
413 // Check to see if this is an unsigned remainder with an exact power of 2,
414 // if so, convert to a bitwise and.
415 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
416 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
418 return BinaryOperator::create(Instruction::And, I.getOperand(0),
419 ConstantUInt::get(I.getType(), Val-1));
422 // 0 % X == 0, we don't need to preserve faults!
423 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
424 if (LHS->equalsInt(0))
425 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
430 // isMaxValueMinusOne - return true if this is Max-1
431 static bool isMaxValueMinusOne(const ConstantInt *C) {
432 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
433 // Calculate -1 casted to the right type...
434 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
435 uint64_t Val = ~0ULL; // All ones
436 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
437 return CU->getValue() == Val-1;
440 const ConstantSInt *CS = cast<ConstantSInt>(C);
442 // Calculate 0111111111..11111
443 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
444 int64_t Val = INT64_MAX; // All ones
445 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
446 return CS->getValue() == Val-1;
449 // isMinValuePlusOne - return true if this is Min+1
450 static bool isMinValuePlusOne(const ConstantInt *C) {
451 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
452 return CU->getValue() == 1;
454 const ConstantSInt *CS = cast<ConstantSInt>(C);
456 // Calculate 1111111111000000000000
457 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
458 int64_t Val = -1; // All ones
459 Val <<= TypeBits-1; // Shift over to the right spot
460 return CS->getValue() == Val+1;
464 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
465 bool Changed = SimplifyCommutative(I);
466 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
468 // and X, X = X and X, 0 == 0
469 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
470 return ReplaceInstUsesWith(I, Op1);
473 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
474 if (RHS->isAllOnesValue())
475 return ReplaceInstUsesWith(I, Op0);
477 Value *Op0NotVal = dyn_castNotVal(Op0);
478 Value *Op1NotVal = dyn_castNotVal(Op1);
480 // (~A & ~B) == (~(A | B)) - Demorgan's Law
481 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
482 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
483 Op1NotVal,I.getName()+".demorgan",
485 WorkList.push_back(Or);
486 return BinaryOperator::createNot(Or);
489 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
490 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
492 return Changed ? &I : 0;
497 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
498 bool Changed = SimplifyCommutative(I);
499 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
501 // or X, X = X or X, 0 == X
502 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
503 return ReplaceInstUsesWith(I, Op0);
506 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
507 if (RHS->isAllOnesValue())
508 return ReplaceInstUsesWith(I, Op1);
510 Value *Op0NotVal = dyn_castNotVal(Op0);
511 Value *Op1NotVal = dyn_castNotVal(Op1);
513 if (Op1 == Op0NotVal) // ~A | A == -1
514 return ReplaceInstUsesWith(I,
515 ConstantIntegral::getAllOnesValue(I.getType()));
517 if (Op0 == Op1NotVal) // A | ~A == -1
518 return ReplaceInstUsesWith(I,
519 ConstantIntegral::getAllOnesValue(I.getType()));
521 // (~A | ~B) == (~(A & B)) - Demorgan's Law
522 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
523 Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
524 Op1NotVal,I.getName()+".demorgan",
526 WorkList.push_back(And);
527 return BinaryOperator::createNot(And);
530 return Changed ? &I : 0;
535 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
536 bool Changed = SimplifyCommutative(I);
537 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
541 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
543 if (ConstantIntegral *Op1C = dyn_cast<ConstantIntegral>(Op1)) {
545 if (Op1C->isNullValue())
546 return ReplaceInstUsesWith(I, Op0);
548 // Is this a "NOT" instruction?
549 if (Op1C->isAllOnesValue()) {
550 // xor (xor X, -1), -1 = not (not X) = X
551 if (Value *X = dyn_castNotVal(Op0))
552 return ReplaceInstUsesWith(I, X);
554 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
555 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0))
556 if (SCI->use_size() == 1)
557 return new SetCondInst(SCI->getInverseCondition(),
558 SCI->getOperand(0), SCI->getOperand(1));
562 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
564 return ReplaceInstUsesWith(I,
565 ConstantIntegral::getAllOnesValue(I.getType()));
567 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
569 return ReplaceInstUsesWith(I,
570 ConstantIntegral::getAllOnesValue(I.getType()));
572 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
573 if (Op1I->getOpcode() == Instruction::Or)
574 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
575 cast<BinaryOperator>(Op1I)->swapOperands();
578 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
583 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
584 if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
585 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
586 cast<BinaryOperator>(Op0I)->swapOperands();
587 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
588 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
589 WorkList.push_back(cast<Instruction>(NotB));
590 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
595 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
596 if (Constant *C1 = dyn_castMaskingAnd(Op0))
597 if (Constant *C2 = dyn_castMaskingAnd(Op1))
598 if ((*C1 & *C2)->isNullValue())
599 return BinaryOperator::create(Instruction::Or, Op0, Op1);
601 return Changed ? &I : 0;
604 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
605 static Constant *AddOne(ConstantInt *C) {
606 Constant *Result = *C + *ConstantInt::get(C->getType(), 1);
607 assert(Result && "Constant folding integer addition failed!");
610 static Constant *SubOne(ConstantInt *C) {
611 Constant *Result = *C - *ConstantInt::get(C->getType(), 1);
612 assert(Result && "Constant folding integer addition failed!");
616 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
617 // true when both operands are equal...
619 static bool isTrueWhenEqual(Instruction &I) {
620 return I.getOpcode() == Instruction::SetEQ ||
621 I.getOpcode() == Instruction::SetGE ||
622 I.getOpcode() == Instruction::SetLE;
625 Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
626 bool Changed = SimplifyCommutative(I);
627 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
628 const Type *Ty = Op0->getType();
632 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
634 // setcc <global*>, 0 - Global value addresses are never null!
635 if (isa<GlobalValue>(Op0) && isa<ConstantPointerNull>(Op1))
636 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
638 // setcc's with boolean values can always be turned into bitwise operations
639 if (Ty == Type::BoolTy) {
640 // If this is <, >, or !=, we can change this into a simple xor instruction
641 if (!isTrueWhenEqual(I))
642 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
644 // Otherwise we need to make a temporary intermediate instruction and insert
645 // it into the instruction stream. This is what we are after:
647 // seteq bool %A, %B -> ~(A^B)
648 // setle bool %A, %B -> ~A | B
649 // setge bool %A, %B -> A | ~B
651 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
652 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
654 InsertNewInstBefore(Xor, I);
655 return BinaryOperator::createNot(Xor, I.getName());
658 // Handle the setXe cases...
659 assert(I.getOpcode() == Instruction::SetGE ||
660 I.getOpcode() == Instruction::SetLE);
662 if (I.getOpcode() == Instruction::SetGE)
663 std::swap(Op0, Op1); // Change setge -> setle
665 // Now we just have the SetLE case.
666 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
667 InsertNewInstBefore(Not, I);
668 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
671 // Check to see if we are doing one of many comparisons against constant
672 // integers at the end of their ranges...
674 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
675 // Check to see if we are comparing against the minimum or maximum value...
676 if (CI->isMinValue()) {
677 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
678 return ReplaceInstUsesWith(I, ConstantBool::False);
679 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
680 return ReplaceInstUsesWith(I, ConstantBool::True);
681 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
682 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
683 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
684 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
686 } else if (CI->isMaxValue()) {
687 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
688 return ReplaceInstUsesWith(I, ConstantBool::False);
689 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
690 return ReplaceInstUsesWith(I, ConstantBool::True);
691 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
692 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
693 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
694 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
696 // Comparing against a value really close to min or max?
697 } else if (isMinValuePlusOne(CI)) {
698 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
699 return BinaryOperator::create(Instruction::SetEQ, Op0,
700 SubOne(CI), I.getName());
701 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
702 return BinaryOperator::create(Instruction::SetNE, Op0,
703 SubOne(CI), I.getName());
705 } else if (isMaxValueMinusOne(CI)) {
706 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
707 return BinaryOperator::create(Instruction::SetEQ, Op0,
708 AddOne(CI), I.getName());
709 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
710 return BinaryOperator::create(Instruction::SetNE, Op0,
711 AddOne(CI), I.getName());
715 return Changed ? &I : 0;
720 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
721 assert(I.getOperand(1)->getType() == Type::UByteTy);
722 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
724 // shl X, 0 == X and shr X, 0 == X
725 // shl 0, X == 0 and shr 0, X == 0
726 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
727 Op0 == Constant::getNullValue(Op0->getType()))
728 return ReplaceInstUsesWith(I, Op0);
730 // If this is a shift of a shift, see if we can fold the two together...
731 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0)) {
732 if (isa<Constant>(Op1) && isa<Constant>(Op0SI->getOperand(1))) {
733 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(Op0SI->getOperand(1));
734 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
735 unsigned ShiftAmt2 = cast<ConstantUInt>(Op1)->getValue();
737 // Check for (A << c1) << c2 and (A >> c1) >> c2
738 if (I.getOpcode() == Op0SI->getOpcode()) {
739 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
740 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
741 ConstantUInt::get(Type::UByteTy, Amt));
744 if (I.getType()->isUnsigned()) { // Check for (A << c1) >> c2 or visaversa
745 // Calculate bitmask for what gets shifted off the edge...
746 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
747 if (I.getOpcode() == Instruction::Shr)
748 C = *C >> *ShiftAmt1C;
750 C = *C << *ShiftAmt1C;
751 assert(C && "Couldn't constant fold shift expression?");
754 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
755 C, Op0SI->getOperand(0)->getName()+".mask",&I);
756 WorkList.push_back(Mask);
758 // Figure out what flavor of shift we should use...
759 if (ShiftAmt1 == ShiftAmt2)
760 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
761 else if (ShiftAmt1 < ShiftAmt2) {
762 return new ShiftInst(I.getOpcode(), Mask,
763 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
765 return new ShiftInst(Op0SI->getOpcode(), Mask,
766 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
772 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr of
775 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
776 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
777 if (CUI->getValue() >= TypeBits &&
778 (!Op0->getType()->isSigned() || I.getOpcode() == Instruction::Shl))
779 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
781 // Check to see if we are shifting left by 1. If so, turn it into an add
783 if (I.getOpcode() == Instruction::Shl && CUI->equalsInt(1))
784 // Convert 'shl int %X, 1' to 'add int %X, %X'
785 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
789 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
790 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
791 if (I.getOpcode() == Instruction::Shr && CSI->isAllOnesValue())
792 return ReplaceInstUsesWith(I, CSI);
798 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
801 static inline bool isEliminableCastOfCast(const CastInst &CI,
802 const CastInst *CSrc) {
803 assert(CI.getOperand(0) == CSrc);
804 const Type *SrcTy = CSrc->getOperand(0)->getType();
805 const Type *MidTy = CSrc->getType();
806 const Type *DstTy = CI.getType();
808 // It is legal to eliminate the instruction if casting A->B->A if the sizes
809 // are identical and the bits don't get reinterpreted (for example
810 // int->float->int would not be allowed)
811 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
814 // Allow free casting and conversion of sizes as long as the sign doesn't
816 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
817 unsigned SrcSize = SrcTy->getPrimitiveSize();
818 unsigned MidSize = MidTy->getPrimitiveSize();
819 unsigned DstSize = DstTy->getPrimitiveSize();
821 // Cases where we are monotonically decreasing the size of the type are
822 // always ok, regardless of what sign changes are going on.
824 if (SrcSize >= MidSize && MidSize >= DstSize)
827 // Cases where the source and destination type are the same, but the middle
828 // type is bigger are noops.
830 if (SrcSize == DstSize && MidSize > SrcSize)
833 // If we are monotonically growing, things are more complex.
835 if (SrcSize <= MidSize && MidSize <= DstSize) {
836 // We have eight combinations of signedness to worry about. Here's the
838 static const int SignTable[8] = {
839 // CODE, SrcSigned, MidSigned, DstSigned, Comment
840 1, // U U U Always ok
841 1, // U U S Always ok
842 3, // U S U Ok iff SrcSize != MidSize
843 3, // U S S Ok iff SrcSize != MidSize
845 2, // S U S Ok iff MidSize == DstSize
846 1, // S S U Always ok
847 1, // S S S Always ok
850 // Choose an action based on the current entry of the signtable that this
851 // cast of cast refers to...
852 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
853 switch (SignTable[Row]) {
854 case 0: return false; // Never ok
855 case 1: return true; // Always ok
856 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
857 case 3: // Ok iff SrcSize != MidSize
858 return SrcSize != MidSize || SrcTy == Type::BoolTy;
859 default: assert(0 && "Bad entry in sign table!");
864 // Otherwise, we cannot succeed. Specifically we do not want to allow things
865 // like: short -> ushort -> uint, because this can create wrong results if
866 // the input short is negative!
872 // CastInst simplification
874 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
875 // If the user is casting a value to the same type, eliminate this cast
877 if (CI.getType() == CI.getOperand(0)->getType())
878 return ReplaceInstUsesWith(CI, CI.getOperand(0));
880 // If casting the result of another cast instruction, try to eliminate this
883 if (CastInst *CSrc = dyn_cast<CastInst>(CI.getOperand(0))) {
884 if (isEliminableCastOfCast(CI, CSrc)) {
885 // This instruction now refers directly to the cast's src operand. This
886 // has a good chance of making CSrc dead.
887 CI.setOperand(0, CSrc->getOperand(0));
891 // If this is an A->B->A cast, and we are dealing with integral types, try
892 // to convert this into a logical 'and' instruction.
894 if (CSrc->getOperand(0)->getType() == CI.getType() &&
895 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
896 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
897 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
898 assert(CSrc->getType() != Type::ULongTy &&
899 "Cannot have type bigger than ulong!");
900 unsigned AndValue = (1U << CSrc->getType()->getPrimitiveSize()*8)-1;
901 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
902 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
911 // PHINode simplification
913 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
914 // If the PHI node only has one incoming value, eliminate the PHI node...
915 if (PN.getNumIncomingValues() == 1)
916 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
918 // Otherwise if all of the incoming values are the same for the PHI, replace
919 // the PHI node with the incoming value.
922 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
923 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
924 if (InVal && PN.getIncomingValue(i) != InVal)
925 return 0; // Not the same, bail out.
927 InVal = PN.getIncomingValue(i);
929 // The only case that could cause InVal to be null is if we have a PHI node
930 // that only has entries for itself. In this case, there is no entry into the
931 // loop, so kill the PHI.
933 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
935 // All of the incoming values are the same, replace the PHI node now.
936 return ReplaceInstUsesWith(PN, InVal);
940 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
941 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
942 // If so, eliminate the noop.
943 if ((GEP.getNumOperands() == 2 &&
944 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
945 GEP.getNumOperands() == 1)
946 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
948 // Combine Indices - If the source pointer to this getelementptr instruction
949 // is a getelementptr instruction, combine the indices of the two
950 // getelementptr instructions into a single instruction.
952 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
953 std::vector<Value *> Indices;
955 // Can we combine the two pointer arithmetics offsets?
956 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
957 isa<Constant>(GEP.getOperand(1))) {
958 // Replace: gep (gep %P, long C1), long C2, ...
959 // With: gep %P, long (C1+C2), ...
960 Value *Sum = *cast<Constant>(Src->getOperand(1)) +
961 *cast<Constant>(GEP.getOperand(1));
962 assert(Sum && "Constant folding of longs failed!?");
963 GEP.setOperand(0, Src->getOperand(0));
964 GEP.setOperand(1, Sum);
965 AddUsesToWorkList(*Src); // Reduce use count of Src
967 } else if (Src->getNumOperands() == 2) {
968 // Replace: gep (gep %P, long B), long A, ...
969 // With: T = long A+B; gep %P, T, ...
971 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
973 Src->getName()+".sum", &GEP);
974 GEP.setOperand(0, Src->getOperand(0));
975 GEP.setOperand(1, Sum);
976 WorkList.push_back(cast<Instruction>(Sum));
978 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
979 Src->getNumOperands() != 1) {
980 // Otherwise we can do the fold if the first index of the GEP is a zero
981 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
982 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
983 } else if (Src->getOperand(Src->getNumOperands()-1) ==
984 Constant::getNullValue(Type::LongTy)) {
985 // If the src gep ends with a constant array index, merge this get into
986 // it, even if we have a non-zero array index.
987 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
988 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
991 if (!Indices.empty())
992 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
994 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
995 // GEP of global variable. If all of the indices for this GEP are
996 // constants, we can promote this to a constexpr instead of an instruction.
998 // Scan for nonconstants...
999 std::vector<Constant*> Indices;
1000 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1001 for (; I != E && isa<Constant>(*I); ++I)
1002 Indices.push_back(cast<Constant>(*I));
1004 if (I == E) { // If they are all constants...
1006 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1008 // Replace all uses of the GEP with the new constexpr...
1009 return ReplaceInstUsesWith(GEP, CE);
1016 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1017 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1018 if (AI.isArrayAllocation()) // Check C != 1
1019 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1020 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
1021 AllocationInst *New = 0;
1023 // Create and insert the replacement instruction...
1024 if (isa<MallocInst>(AI))
1025 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
1027 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
1028 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
1031 // Scan to the end of the allocation instructions, to skip over a block of
1032 // allocas if possible...
1034 BasicBlock::iterator It = New;
1035 while (isa<AllocationInst>(*It)) ++It;
1037 // Now that I is pointing to the first non-allocation-inst in the block,
1038 // insert our getelementptr instruction...
1040 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1041 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1043 // Now make everything use the getelementptr instead of the original
1045 ReplaceInstUsesWith(AI, V);
1053 void InstCombiner::removeFromWorkList(Instruction *I) {
1054 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1058 bool InstCombiner::runOnFunction(Function &F) {
1059 bool Changed = false;
1061 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
1063 while (!WorkList.empty()) {
1064 Instruction *I = WorkList.back(); // Get an instruction from the worklist
1065 WorkList.pop_back();
1067 // Check to see if we can DCE or ConstantPropagate the instruction...
1068 // Check to see if we can DIE the instruction...
1069 if (isInstructionTriviallyDead(I)) {
1070 // Add operands to the worklist...
1071 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1072 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1073 WorkList.push_back(Op);
1076 BasicBlock::iterator BBI = I;
1077 if (dceInstruction(BBI)) {
1078 removeFromWorkList(I);
1083 // Instruction isn't dead, see if we can constant propagate it...
1084 if (Constant *C = ConstantFoldInstruction(I)) {
1085 // Add operands to the worklist...
1086 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1087 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1088 WorkList.push_back(Op);
1089 ReplaceInstUsesWith(*I, C);
1092 BasicBlock::iterator BBI = I;
1093 if (dceInstruction(BBI)) {
1094 removeFromWorkList(I);
1099 // Now that we have an instruction, try combining it to simplify it...
1100 if (Instruction *Result = visit(*I)) {
1102 // Should we replace the old instruction with a new one?
1104 // Instructions can end up on the worklist more than once. Make sure
1105 // we do not process an instruction that has been deleted.
1106 removeFromWorkList(I);
1107 ReplaceInstWithInst(I, Result);
1109 BasicBlock::iterator II = I;
1111 // If the instruction was modified, it's possible that it is now dead.
1112 // if so, remove it.
1113 if (dceInstruction(II)) {
1114 // Instructions may end up in the worklist more than once. Erase them
1116 removeFromWorkList(I);
1122 WorkList.push_back(Result);
1123 AddUsesToWorkList(*Result);
1132 Pass *createInstructionCombiningPass() {
1133 return new InstCombiner();