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/DerivedTypes.h"
27 #include "llvm/Support/InstIterator.h"
28 #include "llvm/Support/InstVisitor.h"
29 #include "Support/Statistic.h"
33 Statistic<> NumCombined ("instcombine", "Number of insts combined");
34 Statistic<> NumConstProp("instcombine", "Number of constant folds");
35 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
37 class InstCombiner : public FunctionPass,
38 public InstVisitor<InstCombiner, Instruction*> {
39 // Worklist of all of the instructions that need to be simplified.
40 std::vector<Instruction*> WorkList;
42 void AddUsesToWorkList(Instruction &I) {
43 // The instruction was simplified, add all users of the instruction to
44 // the work lists because they might get more simplified now...
46 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
48 WorkList.push_back(cast<Instruction>(*UI));
51 // removeFromWorkList - remove all instances of I from the worklist.
52 void removeFromWorkList(Instruction *I);
54 virtual bool runOnFunction(Function &F);
56 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
60 // Visitation implementation - Implement instruction combining for different
61 // instruction types. The semantics are as follows:
63 // null - No change was made
64 // I - Change was made, I is still valid, I may be dead though
65 // otherwise - Change was made, replace I with returned instruction
67 Instruction *visitAdd(BinaryOperator &I);
68 Instruction *visitSub(BinaryOperator &I);
69 Instruction *visitMul(BinaryOperator &I);
70 Instruction *visitDiv(BinaryOperator &I);
71 Instruction *visitRem(BinaryOperator &I);
72 Instruction *visitAnd(BinaryOperator &I);
73 Instruction *visitOr (BinaryOperator &I);
74 Instruction *visitXor(BinaryOperator &I);
75 Instruction *visitSetCondInst(BinaryOperator &I);
76 Instruction *visitShiftInst(ShiftInst &I);
77 Instruction *visitCastInst(CastInst &CI);
78 Instruction *visitPHINode(PHINode &PN);
79 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
80 Instruction *visitAllocationInst(AllocationInst &AI);
82 // visitInstruction - Specify what to return for unhandled instructions...
83 Instruction *visitInstruction(Instruction &I) { return 0; }
85 // InsertNewInstBefore - insert an instruction New before instruction Old
86 // in the program. Add the new instruction to the worklist.
88 void InsertNewInstBefore(Instruction *New, Instruction &Old) {
89 assert(New && New->getParent() == 0 &&
90 "New instruction already inserted into a basic block!");
91 BasicBlock *BB = Old.getParent();
92 BB->getInstList().insert(&Old, New); // Insert inst
93 WorkList.push_back(New); // Add to worklist
96 // ReplaceInstUsesWith - This method is to be used when an instruction is
97 // found to be dead, replacable with another preexisting expression. Here
98 // we add all uses of I to the worklist, replace all uses of I with the new
99 // value, then return I, so that the inst combiner will know that I was
102 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
103 AddUsesToWorkList(I); // Add all modified instrs to worklist
104 I.replaceAllUsesWith(V);
108 // SimplifyCommutative - This performs a few simplifications for commutative
110 bool SimplifyCommutative(BinaryOperator &I);
114 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
117 // getComplexity: Assign a complexity or rank value to LLVM Values...
118 // 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
119 static unsigned getComplexity(Value *V) {
120 if (isa<Instruction>(V)) {
121 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
125 if (isa<Argument>(V)) return 2;
126 return isa<Constant>(V) ? 0 : 1;
129 // isOnlyUse - Return true if this instruction will be deleted if we stop using
131 static bool isOnlyUse(Value *V) {
132 return V->use_size() == 1 || isa<Constant>(V);
135 // SimplifyCommutative - This performs a few simplifications for commutative
138 // 1. Order operands such that they are listed from right (least complex) to
139 // left (most complex). This puts constants before unary operators before
142 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
143 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
145 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
146 bool Changed = false;
147 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
148 Changed = !I.swapOperands();
150 if (!I.isAssociative()) return Changed;
151 Instruction::BinaryOps Opcode = I.getOpcode();
152 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
153 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
154 if (isa<Constant>(I.getOperand(1))) {
155 Constant *Folded = ConstantFoldBinaryInstruction(I.getOpcode(),
156 cast<Constant>(I.getOperand(1)), cast<Constant>(Op->getOperand(1)));
157 assert(Folded && "Couldn't constant fold commutative operand?");
158 I.setOperand(0, Op->getOperand(0));
159 I.setOperand(1, Folded);
161 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
162 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
163 isOnlyUse(Op) && isOnlyUse(Op1)) {
164 Constant *C1 = cast<Constant>(Op->getOperand(1));
165 Constant *C2 = cast<Constant>(Op1->getOperand(1));
167 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
168 Constant *Folded = ConstantFoldBinaryInstruction(I.getOpcode(),C1,C2);
169 assert(Folded && "Couldn't constant fold commutative operand?");
170 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
173 WorkList.push_back(New);
174 I.setOperand(0, New);
175 I.setOperand(1, Folded);
182 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
183 // if the LHS is a constant zero (which is the 'negate' form).
185 static inline Value *dyn_castNegVal(Value *V) {
186 if (BinaryOperator::isNeg(V))
187 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
189 // Constants can be considered to be negated values if they can be folded...
190 if (Constant *C = dyn_cast<Constant>(V))
191 return *Constant::getNullValue(V->getType()) - *C;
195 static inline Value *dyn_castNotVal(Value *V) {
196 if (BinaryOperator::isNot(V))
197 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
199 // Constants can be considered to be not'ed values...
200 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
201 return *ConstantIntegral::getAllOnesValue(C->getType()) ^ *C;
205 // dyn_castFoldableMul - If this value is a multiply that can be folded into
206 // other computations (because it has a constant operand), return the
207 // non-constant operand of the multiply.
209 static inline Value *dyn_castFoldableMul(Value *V) {
210 if (V->use_size() == 1 && V->getType()->isInteger())
211 if (Instruction *I = dyn_cast<Instruction>(V))
212 if (I->getOpcode() == Instruction::Mul)
213 if (isa<Constant>(I->getOperand(1)))
214 return I->getOperand(0);
218 // dyn_castMaskingAnd - If this value is an And instruction masking a value with
219 // a constant, return the constant being anded with.
221 static inline Constant *dyn_castMaskingAnd(Value *V) {
222 if (Instruction *I = dyn_cast<Instruction>(V))
223 if (I->getOpcode() == Instruction::And)
224 return dyn_cast<Constant>(I->getOperand(1));
226 // If this is a constant, it acts just like we were masking with it.
227 return dyn_cast<Constant>(V);
230 // Log2 - Calculate the log base 2 for the specified value if it is exactly a
232 static unsigned Log2(uint64_t Val) {
233 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
236 if (Val & 1) return 0; // Multiple bits set?
243 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
244 bool Changed = SimplifyCommutative(I);
245 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
247 // Eliminate 'add int %X, 0'
248 if (RHS == Constant::getNullValue(I.getType()))
249 return ReplaceInstUsesWith(I, LHS);
252 if (Value *V = dyn_castNegVal(LHS))
253 return BinaryOperator::create(Instruction::Sub, RHS, V);
256 if (!isa<Constant>(RHS))
257 if (Value *V = dyn_castNegVal(RHS))
258 return BinaryOperator::create(Instruction::Sub, LHS, V);
260 // X*C + X --> X * (C+1)
261 if (dyn_castFoldableMul(LHS) == RHS) {
262 Constant *CP1 = *cast<Constant>(cast<Instruction>(LHS)->getOperand(1)) +
263 *ConstantInt::get(I.getType(), 1);
264 assert(CP1 && "Couldn't constant fold C + 1?");
265 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
268 // X + X*C --> X * (C+1)
269 if (dyn_castFoldableMul(RHS) == LHS) {
270 Constant *CP1 = *cast<Constant>(cast<Instruction>(RHS)->getOperand(1)) +
271 *ConstantInt::get(I.getType(), 1);
272 assert(CP1 && "Couldn't constant fold C + 1?");
273 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
276 // (A & C1)+(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
277 if (Constant *C1 = dyn_castMaskingAnd(LHS))
278 if (Constant *C2 = dyn_castMaskingAnd(RHS))
279 if ((*C1 & *C2)->isNullValue())
280 return BinaryOperator::create(Instruction::Or, LHS, RHS);
282 return Changed ? &I : 0;
285 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
286 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
288 if (Op0 == Op1) // sub X, X -> 0
289 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
291 // If this is a 'B = x-(-A)', change to B = x+A...
292 if (Value *V = dyn_castNegVal(Op1))
293 return BinaryOperator::create(Instruction::Add, Op0, V);
295 // Replace (-1 - A) with (~A)...
296 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
297 if (C->isAllOnesValue())
298 return BinaryOperator::createNot(Op1);
300 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
301 if (Op1I->use_size() == 1) {
302 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
303 // is not used by anyone else...
305 if (Op1I->getOpcode() == Instruction::Sub) {
306 // Swap the two operands of the subexpr...
307 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
308 Op1I->setOperand(0, IIOp1);
309 Op1I->setOperand(1, IIOp0);
311 // Create the new top level add instruction...
312 return BinaryOperator::create(Instruction::Add, Op0, Op1);
315 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
317 if (Op1I->getOpcode() == Instruction::And &&
318 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
319 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
321 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
322 return BinaryOperator::create(Instruction::And, Op0, NewNot);
325 // X - X*C --> X * (1-C)
326 if (dyn_castFoldableMul(Op1I) == Op0) {
327 Constant *CP1 = *ConstantInt::get(I.getType(), 1) -
328 *cast<Constant>(cast<Instruction>(Op1)->getOperand(1));
329 assert(CP1 && "Couldn't constant fold 1-C?");
330 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
334 // X*C - X --> X * (C-1)
335 if (dyn_castFoldableMul(Op0) == Op1) {
336 Constant *CP1 = *cast<Constant>(cast<Instruction>(Op0)->getOperand(1)) -
337 *ConstantInt::get(I.getType(), 1);
338 assert(CP1 && "Couldn't constant fold C - 1?");
339 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
345 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
346 bool Changed = SimplifyCommutative(I);
347 Value *Op0 = I.getOperand(0);
349 // Simplify mul instructions with a constant RHS...
350 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
351 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
352 const Type *Ty = CI->getType();
353 uint64_t Val = Ty->isSigned() ?
354 (uint64_t)cast<ConstantSInt>(CI)->getValue() :
355 cast<ConstantUInt>(CI)->getValue();
358 return ReplaceInstUsesWith(I, Op1); // Eliminate 'mul double %X, 0'
360 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul int %X, 1'
361 case 2: // Convert 'mul int %X, 2' to 'add int %X, %X'
362 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
365 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
366 return new ShiftInst(Instruction::Shl, Op0,
367 ConstantUInt::get(Type::UByteTy, C));
369 ConstantFP *Op1F = cast<ConstantFP>(Op1);
370 if (Op1F->isNullValue())
371 return ReplaceInstUsesWith(I, Op1);
373 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
374 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
375 if (Op1F->getValue() == 1.0)
376 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
380 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
381 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
382 return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
384 return Changed ? &I : 0;
387 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
389 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
390 if (RHS->equalsInt(1))
391 return ReplaceInstUsesWith(I, I.getOperand(0));
393 // Check to see if this is an unsigned division with an exact power of 2,
394 // if so, convert to a right shift.
395 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
396 if (uint64_t Val = C->getValue()) // Don't break X / 0
397 if (uint64_t C = Log2(Val))
398 return new ShiftInst(Instruction::Shr, I.getOperand(0),
399 ConstantUInt::get(Type::UByteTy, C));
402 // 0 / X == 0, we don't need to preserve faults!
403 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
404 if (LHS->equalsInt(0))
405 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
411 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
412 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
413 if (RHS->equalsInt(1)) // X % 1 == 0
414 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
416 // Check to see if this is an unsigned remainder with an exact power of 2,
417 // if so, convert to a bitwise and.
418 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
419 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
421 return BinaryOperator::create(Instruction::And, I.getOperand(0),
422 ConstantUInt::get(I.getType(), Val-1));
425 // 0 % X == 0, we don't need to preserve faults!
426 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
427 if (LHS->equalsInt(0))
428 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
433 // isMaxValueMinusOne - return true if this is Max-1
434 static bool isMaxValueMinusOne(const ConstantInt *C) {
435 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
436 // Calculate -1 casted to the right type...
437 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
438 uint64_t Val = ~0ULL; // All ones
439 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
440 return CU->getValue() == Val-1;
443 const ConstantSInt *CS = cast<ConstantSInt>(C);
445 // Calculate 0111111111..11111
446 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
447 int64_t Val = INT64_MAX; // All ones
448 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
449 return CS->getValue() == Val-1;
452 // isMinValuePlusOne - return true if this is Min+1
453 static bool isMinValuePlusOne(const ConstantInt *C) {
454 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
455 return CU->getValue() == 1;
457 const ConstantSInt *CS = cast<ConstantSInt>(C);
459 // Calculate 1111111111000000000000
460 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
461 int64_t Val = -1; // All ones
462 Val <<= TypeBits-1; // Shift over to the right spot
463 return CS->getValue() == Val+1;
467 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
468 bool Changed = SimplifyCommutative(I);
469 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
471 // and X, X = X and X, 0 == 0
472 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
473 return ReplaceInstUsesWith(I, Op1);
476 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
477 if (RHS->isAllOnesValue())
478 return ReplaceInstUsesWith(I, Op0);
480 Value *Op0NotVal = dyn_castNotVal(Op0);
481 Value *Op1NotVal = dyn_castNotVal(Op1);
483 // (~A & ~B) == (~(A | B)) - Demorgan's Law
484 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
485 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
486 Op1NotVal,I.getName()+".demorgan",
488 WorkList.push_back(Or);
489 return BinaryOperator::createNot(Or);
492 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
493 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
495 return Changed ? &I : 0;
500 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
501 bool Changed = SimplifyCommutative(I);
502 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
504 // or X, X = X or X, 0 == X
505 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
506 return ReplaceInstUsesWith(I, Op0);
509 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1))
510 if (RHS->isAllOnesValue())
511 return ReplaceInstUsesWith(I, Op1);
513 Value *Op0NotVal = dyn_castNotVal(Op0);
514 Value *Op1NotVal = dyn_castNotVal(Op1);
516 if (Op1 == Op0NotVal) // ~A | A == -1
517 return ReplaceInstUsesWith(I,
518 ConstantIntegral::getAllOnesValue(I.getType()));
520 if (Op0 == Op1NotVal) // A | ~A == -1
521 return ReplaceInstUsesWith(I,
522 ConstantIntegral::getAllOnesValue(I.getType()));
524 // (~A | ~B) == (~(A & B)) - Demorgan's Law
525 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
526 Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
527 Op1NotVal,I.getName()+".demorgan",
529 WorkList.push_back(And);
530 return BinaryOperator::createNot(And);
533 return Changed ? &I : 0;
538 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
539 bool Changed = SimplifyCommutative(I);
540 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
544 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
546 if (ConstantIntegral *Op1C = dyn_cast<ConstantIntegral>(Op1)) {
548 if (Op1C->isNullValue())
549 return ReplaceInstUsesWith(I, Op0);
551 // Is this a "NOT" instruction?
552 if (Op1C->isAllOnesValue()) {
553 // xor (xor X, -1), -1 = not (not X) = X
554 if (Value *X = dyn_castNotVal(Op0))
555 return ReplaceInstUsesWith(I, X);
557 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
558 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0))
559 if (SCI->use_size() == 1)
560 return new SetCondInst(SCI->getInverseCondition(),
561 SCI->getOperand(0), SCI->getOperand(1));
565 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
567 return ReplaceInstUsesWith(I,
568 ConstantIntegral::getAllOnesValue(I.getType()));
570 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
572 return ReplaceInstUsesWith(I,
573 ConstantIntegral::getAllOnesValue(I.getType()));
575 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
576 if (Op1I->getOpcode() == Instruction::Or)
577 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
578 cast<BinaryOperator>(Op1I)->swapOperands();
581 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
586 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
587 if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
588 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
589 cast<BinaryOperator>(Op0I)->swapOperands();
590 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
591 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
592 WorkList.push_back(cast<Instruction>(NotB));
593 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
598 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
599 if (Constant *C1 = dyn_castMaskingAnd(Op0))
600 if (Constant *C2 = dyn_castMaskingAnd(Op1))
601 if ((*C1 & *C2)->isNullValue())
602 return BinaryOperator::create(Instruction::Or, Op0, Op1);
604 return Changed ? &I : 0;
607 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
608 static Constant *AddOne(ConstantInt *C) {
609 Constant *Result = *C + *ConstantInt::get(C->getType(), 1);
610 assert(Result && "Constant folding integer addition failed!");
613 static Constant *SubOne(ConstantInt *C) {
614 Constant *Result = *C - *ConstantInt::get(C->getType(), 1);
615 assert(Result && "Constant folding integer addition failed!");
619 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
620 // true when both operands are equal...
622 static bool isTrueWhenEqual(Instruction &I) {
623 return I.getOpcode() == Instruction::SetEQ ||
624 I.getOpcode() == Instruction::SetGE ||
625 I.getOpcode() == Instruction::SetLE;
628 Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
629 bool Changed = SimplifyCommutative(I);
630 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
631 const Type *Ty = Op0->getType();
635 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
637 // setcc <global*>, 0 - Global value addresses are never null!
638 if (isa<GlobalValue>(Op0) && isa<ConstantPointerNull>(Op1))
639 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
641 // setcc's with boolean values can always be turned into bitwise operations
642 if (Ty == Type::BoolTy) {
643 // If this is <, >, or !=, we can change this into a simple xor instruction
644 if (!isTrueWhenEqual(I))
645 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
647 // Otherwise we need to make a temporary intermediate instruction and insert
648 // it into the instruction stream. This is what we are after:
650 // seteq bool %A, %B -> ~(A^B)
651 // setle bool %A, %B -> ~A | B
652 // setge bool %A, %B -> A | ~B
654 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
655 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
657 InsertNewInstBefore(Xor, I);
658 return BinaryOperator::createNot(Xor, I.getName());
661 // Handle the setXe cases...
662 assert(I.getOpcode() == Instruction::SetGE ||
663 I.getOpcode() == Instruction::SetLE);
665 if (I.getOpcode() == Instruction::SetGE)
666 std::swap(Op0, Op1); // Change setge -> setle
668 // Now we just have the SetLE case.
669 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
670 InsertNewInstBefore(Not, I);
671 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
674 // Check to see if we are doing one of many comparisons against constant
675 // integers at the end of their ranges...
677 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
678 // Check to see if we are comparing against the minimum or maximum value...
679 if (CI->isMinValue()) {
680 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
681 return ReplaceInstUsesWith(I, ConstantBool::False);
682 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
683 return ReplaceInstUsesWith(I, ConstantBool::True);
684 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
685 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
686 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
687 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
689 } else if (CI->isMaxValue()) {
690 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
691 return ReplaceInstUsesWith(I, ConstantBool::False);
692 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
693 return ReplaceInstUsesWith(I, ConstantBool::True);
694 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
695 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
696 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
697 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
699 // Comparing against a value really close to min or max?
700 } else if (isMinValuePlusOne(CI)) {
701 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
702 return BinaryOperator::create(Instruction::SetEQ, Op0,
703 SubOne(CI), I.getName());
704 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
705 return BinaryOperator::create(Instruction::SetNE, Op0,
706 SubOne(CI), I.getName());
708 } else if (isMaxValueMinusOne(CI)) {
709 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
710 return BinaryOperator::create(Instruction::SetEQ, Op0,
711 AddOne(CI), I.getName());
712 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
713 return BinaryOperator::create(Instruction::SetNE, Op0,
714 AddOne(CI), I.getName());
718 return Changed ? &I : 0;
723 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
724 assert(I.getOperand(1)->getType() == Type::UByteTy);
725 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
727 // shl X, 0 == X and shr X, 0 == X
728 // shl 0, X == 0 and shr 0, X == 0
729 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
730 Op0 == Constant::getNullValue(Op0->getType()))
731 return ReplaceInstUsesWith(I, Op0);
733 // If this is a shift of a shift, see if we can fold the two together...
734 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0)) {
735 if (isa<Constant>(Op1) && isa<Constant>(Op0SI->getOperand(1))) {
736 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(Op0SI->getOperand(1));
737 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
738 unsigned ShiftAmt2 = cast<ConstantUInt>(Op1)->getValue();
740 // Check for (A << c1) << c2 and (A >> c1) >> c2
741 if (I.getOpcode() == Op0SI->getOpcode()) {
742 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
743 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
744 ConstantUInt::get(Type::UByteTy, Amt));
747 if (I.getType()->isUnsigned()) { // Check for (A << c1) >> c2 or visaversa
748 // Calculate bitmask for what gets shifted off the edge...
749 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
750 if (I.getOpcode() == Instruction::Shr)
751 C = *C >> *ShiftAmt1C;
753 C = *C << *ShiftAmt1C;
754 assert(C && "Couldn't constant fold shift expression?");
757 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
758 C, Op0SI->getOperand(0)->getName()+".mask",&I);
759 WorkList.push_back(Mask);
761 // Figure out what flavor of shift we should use...
762 if (ShiftAmt1 == ShiftAmt2)
763 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
764 else if (ShiftAmt1 < ShiftAmt2) {
765 return new ShiftInst(I.getOpcode(), Mask,
766 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
768 return new ShiftInst(Op0SI->getOpcode(), Mask,
769 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
775 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr of
778 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
779 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
780 if (CUI->getValue() >= TypeBits &&
781 (!Op0->getType()->isSigned() || I.getOpcode() == Instruction::Shl))
782 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
784 // Check to see if we are shifting left by 1. If so, turn it into an add
786 if (I.getOpcode() == Instruction::Shl && CUI->equalsInt(1))
787 // Convert 'shl int %X, 1' to 'add int %X, %X'
788 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
792 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
793 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
794 if (I.getOpcode() == Instruction::Shr && CSI->isAllOnesValue())
795 return ReplaceInstUsesWith(I, CSI);
801 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
804 static inline bool isEliminableCastOfCast(const CastInst &CI,
805 const CastInst *CSrc) {
806 assert(CI.getOperand(0) == CSrc);
807 const Type *SrcTy = CSrc->getOperand(0)->getType();
808 const Type *MidTy = CSrc->getType();
809 const Type *DstTy = CI.getType();
811 // It is legal to eliminate the instruction if casting A->B->A if the sizes
812 // are identical and the bits don't get reinterpreted (for example
813 // int->float->int would not be allowed)
814 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
817 // Allow free casting and conversion of sizes as long as the sign doesn't
819 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
820 unsigned SrcSize = SrcTy->getPrimitiveSize();
821 unsigned MidSize = MidTy->getPrimitiveSize();
822 unsigned DstSize = DstTy->getPrimitiveSize();
824 // Cases where we are monotonically decreasing the size of the type are
825 // always ok, regardless of what sign changes are going on.
827 if (SrcSize >= MidSize && MidSize >= DstSize)
830 // Cases where the source and destination type are the same, but the middle
831 // type is bigger are noops.
833 if (SrcSize == DstSize && MidSize > SrcSize)
836 // If we are monotonically growing, things are more complex.
838 if (SrcSize <= MidSize && MidSize <= DstSize) {
839 // We have eight combinations of signedness to worry about. Here's the
841 static const int SignTable[8] = {
842 // CODE, SrcSigned, MidSigned, DstSigned, Comment
843 1, // U U U Always ok
844 1, // U U S Always ok
845 3, // U S U Ok iff SrcSize != MidSize
846 3, // U S S Ok iff SrcSize != MidSize
848 2, // S U S Ok iff MidSize == DstSize
849 1, // S S U Always ok
850 1, // S S S Always ok
853 // Choose an action based on the current entry of the signtable that this
854 // cast of cast refers to...
855 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
856 switch (SignTable[Row]) {
857 case 0: return false; // Never ok
858 case 1: return true; // Always ok
859 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
860 case 3: // Ok iff SrcSize != MidSize
861 return SrcSize != MidSize || SrcTy == Type::BoolTy;
862 default: assert(0 && "Bad entry in sign table!");
867 // Otherwise, we cannot succeed. Specifically we do not want to allow things
868 // like: short -> ushort -> uint, because this can create wrong results if
869 // the input short is negative!
875 // CastInst simplification
877 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
878 // If the user is casting a value to the same type, eliminate this cast
880 if (CI.getType() == CI.getOperand(0)->getType())
881 return ReplaceInstUsesWith(CI, CI.getOperand(0));
883 // If casting the result of another cast instruction, try to eliminate this
886 if (CastInst *CSrc = dyn_cast<CastInst>(CI.getOperand(0))) {
887 if (isEliminableCastOfCast(CI, CSrc)) {
888 // This instruction now refers directly to the cast's src operand. This
889 // has a good chance of making CSrc dead.
890 CI.setOperand(0, CSrc->getOperand(0));
894 // If this is an A->B->A cast, and we are dealing with integral types, try
895 // to convert this into a logical 'and' instruction.
897 if (CSrc->getOperand(0)->getType() == CI.getType() &&
898 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
899 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
900 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
901 assert(CSrc->getType() != Type::ULongTy &&
902 "Cannot have type bigger than ulong!");
903 unsigned AndValue = (1U << CSrc->getType()->getPrimitiveSize()*8)-1;
904 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
905 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
914 // PHINode simplification
916 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
917 // If the PHI node only has one incoming value, eliminate the PHI node...
918 if (PN.getNumIncomingValues() == 1)
919 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
921 // Otherwise if all of the incoming values are the same for the PHI, replace
922 // the PHI node with the incoming value.
925 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
926 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
927 if (InVal && PN.getIncomingValue(i) != InVal)
928 return 0; // Not the same, bail out.
930 InVal = PN.getIncomingValue(i);
932 // The only case that could cause InVal to be null is if we have a PHI node
933 // that only has entries for itself. In this case, there is no entry into the
934 // loop, so kill the PHI.
936 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
938 // All of the incoming values are the same, replace the PHI node now.
939 return ReplaceInstUsesWith(PN, InVal);
943 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
944 // Is it 'getelementptr %P, uint 0' or 'getelementptr %P'
945 // If so, eliminate the noop.
946 if ((GEP.getNumOperands() == 2 &&
947 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
948 GEP.getNumOperands() == 1)
949 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
951 // Combine Indices - If the source pointer to this getelementptr instruction
952 // is a getelementptr instruction, combine the indices of the two
953 // getelementptr instructions into a single instruction.
955 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
956 std::vector<Value *> Indices;
958 // Can we combine the two pointer arithmetics offsets?
959 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
960 isa<Constant>(GEP.getOperand(1))) {
961 // Replace: gep (gep %P, long C1), long C2, ...
962 // With: gep %P, long (C1+C2), ...
963 Value *Sum = *cast<Constant>(Src->getOperand(1)) +
964 *cast<Constant>(GEP.getOperand(1));
965 assert(Sum && "Constant folding of longs failed!?");
966 GEP.setOperand(0, Src->getOperand(0));
967 GEP.setOperand(1, Sum);
968 AddUsesToWorkList(*Src); // Reduce use count of Src
970 } else if (Src->getNumOperands() == 2 && Src->use_size() == 1) {
971 // Replace: gep (gep %P, long B), long A, ...
972 // With: T = long A+B; gep %P, T, ...
974 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
976 Src->getName()+".sum", &GEP);
977 GEP.setOperand(0, Src->getOperand(0));
978 GEP.setOperand(1, Sum);
979 WorkList.push_back(cast<Instruction>(Sum));
981 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
982 Src->getNumOperands() != 1) {
983 // Otherwise we can do the fold if the first index of the GEP is a zero
984 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
985 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
986 } else if (Src->getOperand(Src->getNumOperands()-1) ==
987 Constant::getNullValue(Type::LongTy)) {
988 // If the src gep ends with a constant array index, merge this get into
989 // it, even if we have a non-zero array index.
990 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
991 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
994 if (!Indices.empty())
995 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
997 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
998 // GEP of global variable. If all of the indices for this GEP are
999 // constants, we can promote this to a constexpr instead of an instruction.
1001 // Scan for nonconstants...
1002 std::vector<Constant*> Indices;
1003 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1004 for (; I != E && isa<Constant>(*I); ++I)
1005 Indices.push_back(cast<Constant>(*I));
1007 if (I == E) { // If they are all constants...
1009 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1011 // Replace all uses of the GEP with the new constexpr...
1012 return ReplaceInstUsesWith(GEP, CE);
1019 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1020 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1021 if (AI.isArrayAllocation()) // Check C != 1
1022 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1023 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
1024 AllocationInst *New = 0;
1026 // Create and insert the replacement instruction...
1027 if (isa<MallocInst>(AI))
1028 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
1030 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
1031 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
1034 // Scan to the end of the allocation instructions, to skip over a block of
1035 // allocas if possible...
1037 BasicBlock::iterator It = New;
1038 while (isa<AllocationInst>(*It)) ++It;
1040 // Now that I is pointing to the first non-allocation-inst in the block,
1041 // insert our getelementptr instruction...
1043 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1044 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1046 // Now make everything use the getelementptr instead of the original
1048 ReplaceInstUsesWith(AI, V);
1056 void InstCombiner::removeFromWorkList(Instruction *I) {
1057 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1061 bool InstCombiner::runOnFunction(Function &F) {
1062 bool Changed = false;
1064 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
1066 while (!WorkList.empty()) {
1067 Instruction *I = WorkList.back(); // Get an instruction from the worklist
1068 WorkList.pop_back();
1070 // Check to see if we can DCE or ConstantPropagate the instruction...
1071 // Check to see if we can DIE the instruction...
1072 if (isInstructionTriviallyDead(I)) {
1073 // Add operands to the worklist...
1074 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1075 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1076 WorkList.push_back(Op);
1079 BasicBlock::iterator BBI = I;
1080 if (dceInstruction(BBI)) {
1081 removeFromWorkList(I);
1086 // Instruction isn't dead, see if we can constant propagate it...
1087 if (Constant *C = ConstantFoldInstruction(I)) {
1088 // Add operands to the worklist...
1089 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1090 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1091 WorkList.push_back(Op);
1092 ReplaceInstUsesWith(*I, C);
1095 BasicBlock::iterator BBI = I;
1096 if (dceInstruction(BBI)) {
1097 removeFromWorkList(I);
1102 // Now that we have an instruction, try combining it to simplify it...
1103 if (Instruction *Result = visit(*I)) {
1105 // Should we replace the old instruction with a new one?
1107 // Instructions can end up on the worklist more than once. Make sure
1108 // we do not process an instruction that has been deleted.
1109 removeFromWorkList(I);
1110 ReplaceInstWithInst(I, Result);
1112 BasicBlock::iterator II = I;
1114 // If the instruction was modified, it's possible that it is now dead.
1115 // if so, remove it.
1116 if (dceInstruction(II)) {
1117 // Instructions may end up in the worklist more than once. Erase them
1119 removeFromWorkList(I);
1125 WorkList.push_back(Result);
1126 AddUsesToWorkList(*Result);
1135 Pass *createInstructionCombiningPass() {
1136 return new InstCombiner();