1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions. This pass does not modify the CFG This pass is where algebraic
12 // simplification happens.
14 // This pass combines things like:
20 // This is a simple worklist driven algorithm.
22 // This pass guarantees that the following canonicalizations are performed on
24 // 1. If a binary operator has a constant operand, it is moved to the RHS
25 // 2. Bitwise operators with constant operands are always grouped so that
26 // shifts are performed first, then or's, then and's, then xor's.
27 // 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All SetCC instructions on boolean values are replaced with logical ops
29 // 5. add X, X is represented as (X*2) => (X << 1)
30 // 6. Multiplies with a power-of-two constant argument are transformed into
32 // N. This list is incomplete
34 //===----------------------------------------------------------------------===//
36 #include "llvm/Transforms/Scalar.h"
37 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
38 #include "llvm/Transforms/Utils/Local.h"
39 #include "llvm/Instructions.h"
40 #include "llvm/Pass.h"
41 #include "llvm/Constants.h"
42 #include "llvm/ConstantHandling.h"
43 #include "llvm/DerivedTypes.h"
44 #include "llvm/GlobalVariable.h"
45 #include "llvm/Support/InstIterator.h"
46 #include "llvm/Support/InstVisitor.h"
47 #include "llvm/Support/CallSite.h"
48 #include "Support/Statistic.h"
52 Statistic<> NumCombined ("instcombine", "Number of insts combined");
53 Statistic<> NumConstProp("instcombine", "Number of constant folds");
54 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
56 class InstCombiner : public FunctionPass,
57 public InstVisitor<InstCombiner, Instruction*> {
58 // Worklist of all of the instructions that need to be simplified.
59 std::vector<Instruction*> WorkList;
61 void AddUsesToWorkList(Instruction &I) {
62 // The instruction was simplified, add all users of the instruction to
63 // the work lists because they might get more simplified now...
65 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
67 WorkList.push_back(cast<Instruction>(*UI));
70 // removeFromWorkList - remove all instances of I from the worklist.
71 void removeFromWorkList(Instruction *I);
73 virtual bool runOnFunction(Function &F);
75 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
79 // Visitation implementation - Implement instruction combining for different
80 // instruction types. The semantics are as follows:
82 // null - No change was made
83 // I - Change was made, I is still valid, I may be dead though
84 // otherwise - Change was made, replace I with returned instruction
86 Instruction *visitAdd(BinaryOperator &I);
87 Instruction *visitSub(BinaryOperator &I);
88 Instruction *visitMul(BinaryOperator &I);
89 Instruction *visitDiv(BinaryOperator &I);
90 Instruction *visitRem(BinaryOperator &I);
91 Instruction *visitAnd(BinaryOperator &I);
92 Instruction *visitOr (BinaryOperator &I);
93 Instruction *visitXor(BinaryOperator &I);
94 Instruction *visitSetCondInst(BinaryOperator &I);
95 Instruction *visitShiftInst(ShiftInst &I);
96 Instruction *visitCastInst(CastInst &CI);
97 Instruction *visitCallInst(CallInst &CI);
98 Instruction *visitInvokeInst(InvokeInst &II);
99 Instruction *visitPHINode(PHINode &PN);
100 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
101 Instruction *visitAllocationInst(AllocationInst &AI);
102 Instruction *visitLoadInst(LoadInst &LI);
103 Instruction *visitBranchInst(BranchInst &BI);
105 // visitInstruction - Specify what to return for unhandled instructions...
106 Instruction *visitInstruction(Instruction &I) { return 0; }
109 Instruction *visitCallSite(CallSite CS);
110 bool transformConstExprCastCall(CallSite CS);
112 // InsertNewInstBefore - insert an instruction New before instruction Old
113 // in the program. Add the new instruction to the worklist.
115 void InsertNewInstBefore(Instruction *New, Instruction &Old) {
116 assert(New && New->getParent() == 0 &&
117 "New instruction already inserted into a basic block!");
118 BasicBlock *BB = Old.getParent();
119 BB->getInstList().insert(&Old, New); // Insert inst
120 WorkList.push_back(New); // Add to worklist
124 // ReplaceInstUsesWith - This method is to be used when an instruction is
125 // found to be dead, replacable with another preexisting expression. Here
126 // we add all uses of I to the worklist, replace all uses of I with the new
127 // value, then return I, so that the inst combiner will know that I was
130 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
131 AddUsesToWorkList(I); // Add all modified instrs to worklist
132 I.replaceAllUsesWith(V);
136 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
137 /// InsertBefore instruction. This is specialized a bit to avoid inserting
138 /// casts that are known to not do anything...
140 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
141 Instruction *InsertBefore);
143 // SimplifyCommutative - This performs a few simplifications for commutative
145 bool SimplifyCommutative(BinaryOperator &I);
147 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
148 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
151 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
154 // getComplexity: Assign a complexity or rank value to LLVM Values...
155 // 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
156 static unsigned getComplexity(Value *V) {
157 if (isa<Instruction>(V)) {
158 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
162 if (isa<Argument>(V)) return 2;
163 return isa<Constant>(V) ? 0 : 1;
166 // isOnlyUse - Return true if this instruction will be deleted if we stop using
168 static bool isOnlyUse(Value *V) {
169 return V->hasOneUse() || isa<Constant>(V);
172 // SimplifyCommutative - This performs a few simplifications for commutative
175 // 1. Order operands such that they are listed from right (least complex) to
176 // left (most complex). This puts constants before unary operators before
179 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
180 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
182 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
183 bool Changed = false;
184 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
185 Changed = !I.swapOperands();
187 if (!I.isAssociative()) return Changed;
188 Instruction::BinaryOps Opcode = I.getOpcode();
189 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
190 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
191 if (isa<Constant>(I.getOperand(1))) {
192 Constant *Folded = ConstantExpr::get(I.getOpcode(),
193 cast<Constant>(I.getOperand(1)),
194 cast<Constant>(Op->getOperand(1)));
195 I.setOperand(0, Op->getOperand(0));
196 I.setOperand(1, Folded);
198 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
199 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
200 isOnlyUse(Op) && isOnlyUse(Op1)) {
201 Constant *C1 = cast<Constant>(Op->getOperand(1));
202 Constant *C2 = cast<Constant>(Op1->getOperand(1));
204 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
205 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
206 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
209 WorkList.push_back(New);
210 I.setOperand(0, New);
211 I.setOperand(1, Folded);
218 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
219 // if the LHS is a constant zero (which is the 'negate' form).
221 static inline Value *dyn_castNegVal(Value *V) {
222 if (BinaryOperator::isNeg(V))
223 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
225 // Constants can be considered to be negated values if they can be folded...
226 if (Constant *C = dyn_cast<Constant>(V))
227 return ConstantExpr::get(Instruction::Sub,
228 Constant::getNullValue(V->getType()), C);
232 static inline Value *dyn_castNotVal(Value *V) {
233 if (BinaryOperator::isNot(V))
234 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
236 // Constants can be considered to be not'ed values...
237 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
238 return ConstantExpr::get(Instruction::Xor,
239 ConstantIntegral::getAllOnesValue(C->getType()),C);
243 // dyn_castFoldableMul - If this value is a multiply that can be folded into
244 // other computations (because it has a constant operand), return the
245 // non-constant operand of the multiply.
247 static inline Value *dyn_castFoldableMul(Value *V) {
248 if (V->hasOneUse() && V->getType()->isInteger())
249 if (Instruction *I = dyn_cast<Instruction>(V))
250 if (I->getOpcode() == Instruction::Mul)
251 if (isa<Constant>(I->getOperand(1)))
252 return I->getOperand(0);
256 // dyn_castMaskingAnd - If this value is an And instruction masking a value with
257 // a constant, return the constant being anded with.
259 template<class ValueType>
260 static inline Constant *dyn_castMaskingAnd(ValueType *V) {
261 if (Instruction *I = dyn_cast<Instruction>(V))
262 if (I->getOpcode() == Instruction::And)
263 return dyn_cast<Constant>(I->getOperand(1));
265 // If this is a constant, it acts just like we were masking with it.
266 return dyn_cast<Constant>(V);
269 // Log2 - Calculate the log base 2 for the specified value if it is exactly a
271 static unsigned Log2(uint64_t Val) {
272 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
275 if (Val & 1) return 0; // Multiple bits set?
283 /// AssociativeOpt - Perform an optimization on an associative operator. This
284 /// function is designed to check a chain of associative operators for a
285 /// potential to apply a certain optimization. Since the optimization may be
286 /// applicable if the expression was reassociated, this checks the chain, then
287 /// reassociates the expression as necessary to expose the optimization
288 /// opportunity. This makes use of a special Functor, which must define
289 /// 'shouldApply' and 'apply' methods.
291 template<typename Functor>
292 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
293 unsigned Opcode = Root.getOpcode();
294 Value *LHS = Root.getOperand(0);
296 // Quick check, see if the immediate LHS matches...
297 if (F.shouldApply(LHS))
298 return F.apply(Root);
300 // Otherwise, if the LHS is not of the same opcode as the root, return.
301 Instruction *LHSI = dyn_cast<Instruction>(LHS);
302 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
303 // Should we apply this transform to the RHS?
304 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
306 // If not to the RHS, check to see if we should apply to the LHS...
307 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
308 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
312 // If the functor wants to apply the optimization to the RHS of LHSI,
313 // reassociate the expression from ((? op A) op B) to (? op (A op B))
315 BasicBlock *BB = Root.getParent();
316 // All of the instructions have a single use and have no side-effects,
317 // because of this, we can pull them all into the current basic block.
318 if (LHSI->getParent() != BB) {
319 // Move all of the instructions from root to LHSI into the current
321 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
322 Instruction *LastUse = &Root;
323 while (TmpLHSI->getParent() == BB) {
325 TmpLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
328 // Loop over all of the instructions in other blocks, moving them into
330 Value *TmpLHS = TmpLHSI;
332 TmpLHSI = cast<Instruction>(TmpLHS);
333 // Remove from current block...
334 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
335 // Insert before the last instruction...
336 BB->getInstList().insert(LastUse, TmpLHSI);
337 TmpLHS = TmpLHSI->getOperand(0);
338 } while (TmpLHSI != LHSI);
341 // Now all of the instructions are in the current basic block, go ahead
342 // and perform the reassociation.
343 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
345 // First move the selected RHS to the LHS of the root...
346 Root.setOperand(0, LHSI->getOperand(1));
348 // Make what used to be the LHS of the root be the user of the root...
349 Value *ExtraOperand = TmpLHSI->getOperand(1);
350 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
351 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
352 BB->getInstList().remove(&Root); // Remove root from the BB
353 BB->getInstList().insert(TmpLHSI, &Root); // Insert root before TmpLHSI
355 // Now propagate the ExtraOperand down the chain of instructions until we
357 while (TmpLHSI != LHSI) {
358 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
359 Value *NextOp = NextLHSI->getOperand(1);
360 NextLHSI->setOperand(1, ExtraOperand);
362 ExtraOperand = NextOp;
365 // Now that the instructions are reassociated, have the functor perform
366 // the transformation...
367 return F.apply(Root);
370 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
376 // AddRHS - Implements: X + X --> X << 1
379 AddRHS(Value *rhs) : RHS(rhs) {}
380 bool shouldApply(Value *LHS) const { return LHS == RHS; }
381 Instruction *apply(BinaryOperator &Add) const {
382 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
383 ConstantInt::get(Type::UByteTy, 1));
387 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
389 struct AddMaskingAnd {
391 AddMaskingAnd(Constant *c) : C2(c) {}
392 bool shouldApply(Value *LHS) const {
393 if (Constant *C1 = dyn_castMaskingAnd(LHS))
394 return ConstantExpr::get(Instruction::And, C1, C2)->isNullValue();
397 Instruction *apply(BinaryOperator &Add) const {
398 return BinaryOperator::create(Instruction::Or, Add.getOperand(0),
405 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
406 bool Changed = SimplifyCommutative(I);
407 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
410 if (RHS == Constant::getNullValue(I.getType()))
411 return ReplaceInstUsesWith(I, LHS);
414 if (I.getType()->isInteger())
415 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
418 if (Value *V = dyn_castNegVal(LHS))
419 return BinaryOperator::create(Instruction::Sub, RHS, V);
422 if (!isa<Constant>(RHS))
423 if (Value *V = dyn_castNegVal(RHS))
424 return BinaryOperator::create(Instruction::Sub, LHS, V);
426 // X*C + X --> X * (C+1)
427 if (dyn_castFoldableMul(LHS) == RHS) {
429 ConstantExpr::get(Instruction::Add,
430 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
431 ConstantInt::get(I.getType(), 1));
432 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
435 // X + X*C --> X * (C+1)
436 if (dyn_castFoldableMul(RHS) == LHS) {
438 ConstantExpr::get(Instruction::Add,
439 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
440 ConstantInt::get(I.getType(), 1));
441 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
444 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
445 if (Constant *C2 = dyn_castMaskingAnd(RHS))
446 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
448 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
449 if (Instruction *ILHS = dyn_cast<Instruction>(LHS)) {
450 switch (ILHS->getOpcode()) {
451 case Instruction::Xor:
452 // ~X + C --> (C-1) - X
453 if (ConstantInt *XorRHS = dyn_cast<ConstantInt>(ILHS->getOperand(1)))
454 if (XorRHS->isAllOnesValue())
455 return BinaryOperator::create(Instruction::Sub,
456 *CRHS - *ConstantInt::get(I.getType(), 1),
457 ILHS->getOperand(0));
464 return Changed ? &I : 0;
467 // isSignBit - Return true if the value represented by the constant only has the
468 // highest order bit set.
469 static bool isSignBit(ConstantInt *CI) {
470 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
471 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
474 static unsigned getTypeSizeInBits(const Type *Ty) {
475 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
478 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
479 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
481 if (Op0 == Op1) // sub X, X -> 0
482 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
484 // If this is a 'B = x-(-A)', change to B = x+A...
485 if (Value *V = dyn_castNegVal(Op1))
486 return BinaryOperator::create(Instruction::Add, Op0, V);
488 // Replace (-1 - A) with (~A)...
489 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
490 if (C->isAllOnesValue())
491 return BinaryOperator::createNot(Op1);
493 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
494 if (Op1I->hasOneUse()) {
495 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
496 // is not used by anyone else...
498 if (Op1I->getOpcode() == Instruction::Sub) {
499 // Swap the two operands of the subexpr...
500 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
501 Op1I->setOperand(0, IIOp1);
502 Op1I->setOperand(1, IIOp0);
504 // Create the new top level add instruction...
505 return BinaryOperator::create(Instruction::Add, Op0, Op1);
508 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
510 if (Op1I->getOpcode() == Instruction::And &&
511 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
512 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
514 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
515 return BinaryOperator::create(Instruction::And, Op0, NewNot);
518 // X - X*C --> X * (1-C)
519 if (dyn_castFoldableMul(Op1I) == Op0) {
521 ConstantExpr::get(Instruction::Sub,
522 ConstantInt::get(I.getType(), 1),
523 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
524 assert(CP1 && "Couldn't constant fold 1-C?");
525 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
529 // X*C - X --> X * (C-1)
530 if (dyn_castFoldableMul(Op0) == Op1) {
532 ConstantExpr::get(Instruction::Sub,
533 cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
534 ConstantInt::get(I.getType(), 1));
535 assert(CP1 && "Couldn't constant fold C - 1?");
536 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
542 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
543 bool Changed = SimplifyCommutative(I);
544 Value *Op0 = I.getOperand(0);
546 // Simplify mul instructions with a constant RHS...
547 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
548 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
550 // ((X << C1)*C2) == (X * (C2 << C1))
551 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
552 if (SI->getOpcode() == Instruction::Shl)
553 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
554 return BinaryOperator::create(Instruction::Mul, SI->getOperand(0),
557 if (CI->isNullValue())
558 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
559 if (CI->equalsInt(1)) // X * 1 == X
560 return ReplaceInstUsesWith(I, Op0);
561 if (CI->isAllOnesValue()) // X * -1 == 0 - X
562 return BinaryOperator::createNeg(Op0, I.getName());
564 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
565 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
566 return new ShiftInst(Instruction::Shl, Op0,
567 ConstantUInt::get(Type::UByteTy, C));
569 ConstantFP *Op1F = cast<ConstantFP>(Op1);
570 if (Op1F->isNullValue())
571 return ReplaceInstUsesWith(I, Op1);
573 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
574 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
575 if (Op1F->getValue() == 1.0)
576 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
580 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
581 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
582 return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
584 return Changed ? &I : 0;
587 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
589 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
590 if (RHS->equalsInt(1))
591 return ReplaceInstUsesWith(I, I.getOperand(0));
593 // Check to see if this is an unsigned division with an exact power of 2,
594 // if so, convert to a right shift.
595 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
596 if (uint64_t Val = C->getValue()) // Don't break X / 0
597 if (uint64_t C = Log2(Val))
598 return new ShiftInst(Instruction::Shr, I.getOperand(0),
599 ConstantUInt::get(Type::UByteTy, C));
602 // 0 / X == 0, we don't need to preserve faults!
603 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
604 if (LHS->equalsInt(0))
605 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
611 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
612 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
613 if (RHS->equalsInt(1)) // X % 1 == 0
614 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
616 // Check to see if this is an unsigned remainder with an exact power of 2,
617 // if so, convert to a bitwise and.
618 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
619 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
621 return BinaryOperator::create(Instruction::And, I.getOperand(0),
622 ConstantUInt::get(I.getType(), Val-1));
625 // 0 % X == 0, we don't need to preserve faults!
626 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
627 if (LHS->equalsInt(0))
628 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
633 // isMaxValueMinusOne - return true if this is Max-1
634 static bool isMaxValueMinusOne(const ConstantInt *C) {
635 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
636 // Calculate -1 casted to the right type...
637 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
638 uint64_t Val = ~0ULL; // All ones
639 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
640 return CU->getValue() == Val-1;
643 const ConstantSInt *CS = cast<ConstantSInt>(C);
645 // Calculate 0111111111..11111
646 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
647 int64_t Val = INT64_MAX; // All ones
648 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
649 return CS->getValue() == Val-1;
652 // isMinValuePlusOne - return true if this is Min+1
653 static bool isMinValuePlusOne(const ConstantInt *C) {
654 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
655 return CU->getValue() == 1;
657 const ConstantSInt *CS = cast<ConstantSInt>(C);
659 // Calculate 1111111111000000000000
660 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
661 int64_t Val = -1; // All ones
662 Val <<= TypeBits-1; // Shift over to the right spot
663 return CS->getValue() == Val+1;
666 /// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
667 /// are carefully arranged to allow folding of expressions such as:
669 /// (A < B) | (A > B) --> (A != B)
671 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
672 /// represents that the comparison is true if A == B, and bit value '1' is true
675 static unsigned getSetCondCode(const SetCondInst *SCI) {
676 switch (SCI->getOpcode()) {
678 case Instruction::SetGT: return 1;
679 case Instruction::SetEQ: return 2;
680 case Instruction::SetGE: return 3;
681 case Instruction::SetLT: return 4;
682 case Instruction::SetNE: return 5;
683 case Instruction::SetLE: return 6;
686 assert(0 && "Invalid SetCC opcode!");
691 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
692 /// opcode and two operands into either a constant true or false, or a brand new
693 /// SetCC instruction.
694 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
696 case 0: return ConstantBool::False;
697 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
698 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
699 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
700 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
701 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
702 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
703 case 7: return ConstantBool::True;
704 default: assert(0 && "Illegal SetCCCode!"); return 0;
708 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
709 struct FoldSetCCLogical {
712 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
713 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
714 bool shouldApply(Value *V) const {
715 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
716 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
717 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
720 Instruction *apply(BinaryOperator &Log) const {
721 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
722 if (SCI->getOperand(0) != LHS) {
723 assert(SCI->getOperand(1) == LHS);
724 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
727 unsigned LHSCode = getSetCondCode(SCI);
728 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
730 switch (Log.getOpcode()) {
731 case Instruction::And: Code = LHSCode & RHSCode; break;
732 case Instruction::Or: Code = LHSCode | RHSCode; break;
733 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
734 default: assert(0 && "Illegal logical opcode!"); return 0;
737 Value *RV = getSetCCValue(Code, LHS, RHS);
738 if (Instruction *I = dyn_cast<Instruction>(RV))
740 // Otherwise, it's a constant boolean value...
741 return IC.ReplaceInstUsesWith(Log, RV);
746 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
747 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
748 // guaranteed to be either a shift instruction or a binary operator.
749 Instruction *InstCombiner::OptAndOp(Instruction *Op,
750 ConstantIntegral *OpRHS,
751 ConstantIntegral *AndRHS,
752 BinaryOperator &TheAnd) {
753 Value *X = Op->getOperand(0);
754 switch (Op->getOpcode()) {
755 case Instruction::Xor:
756 if ((*AndRHS & *OpRHS)->isNullValue()) {
757 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
758 return BinaryOperator::create(Instruction::And, X, AndRHS);
759 } else if (Op->hasOneUse()) {
760 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
761 std::string OpName = Op->getName(); Op->setName("");
762 Instruction *And = BinaryOperator::create(Instruction::And,
764 InsertNewInstBefore(And, TheAnd);
765 return BinaryOperator::create(Instruction::Xor, And, *AndRHS & *OpRHS);
768 case Instruction::Or:
769 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
770 if ((*AndRHS & *OpRHS)->isNullValue())
771 return BinaryOperator::create(Instruction::And, X, AndRHS);
773 Constant *Together = *AndRHS & *OpRHS;
774 if (Together == AndRHS) // (X | C) & C --> C
775 return ReplaceInstUsesWith(TheAnd, AndRHS);
777 if (Op->hasOneUse() && Together != OpRHS) {
778 // (X | C1) & C2 --> (X | (C1&C2)) & C2
779 std::string Op0Name = Op->getName(); Op->setName("");
780 Instruction *Or = BinaryOperator::create(Instruction::Or, X,
782 InsertNewInstBefore(Or, TheAnd);
783 return BinaryOperator::create(Instruction::And, Or, AndRHS);
787 case Instruction::Add:
788 if (Op->hasOneUse()) {
789 // Adding a one to a single bit bit-field should be turned into an XOR
790 // of the bit. First thing to check is to see if this AND is with a
791 // single bit constant.
792 unsigned long long AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
794 // Clear bits that are not part of the constant.
795 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
797 // If there is only one bit set...
798 if ((AndRHSV & (AndRHSV-1)) == 0) {
799 // Ok, at this point, we know that we are masking the result of the
800 // ADD down to exactly one bit. If the constant we are adding has
801 // no bits set below this bit, then we can eliminate the ADD.
802 unsigned long long AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
804 // Check to see if any bits below the one bit set in AndRHSV are set.
805 if ((AddRHS & (AndRHSV-1)) == 0) {
806 // If not, the only thing that can effect the output of the AND is
807 // the bit specified by AndRHSV. If that bit is set, the effect of
808 // the XOR is to toggle the bit. If it is clear, then the ADD has
810 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
811 TheAnd.setOperand(0, X);
814 std::string Name = Op->getName(); Op->setName("");
815 // Pull the XOR out of the AND.
816 Instruction *NewAnd =
817 BinaryOperator::create(Instruction::And, X, AndRHS, Name);
818 InsertNewInstBefore(NewAnd, TheAnd);
819 return BinaryOperator::create(Instruction::Xor, NewAnd, AndRHS);
826 case Instruction::Shl: {
827 // We know that the AND will not produce any of the bits shifted in, so if
828 // the anded constant includes them, clear them now!
830 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
831 Constant *CI = *AndRHS & *(*AllOne << *OpRHS);
833 TheAnd.setOperand(1, CI);
838 case Instruction::Shr:
839 // We know that the AND will not produce any of the bits shifted in, so if
840 // the anded constant includes them, clear them now! This only applies to
841 // unsigned shifts, because a signed shr may bring in set bits!
843 if (AndRHS->getType()->isUnsigned()) {
844 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
845 Constant *CI = *AndRHS & *(*AllOne >> *OpRHS);
847 TheAnd.setOperand(1, CI);
857 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
858 bool Changed = SimplifyCommutative(I);
859 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
861 // and X, X = X and X, 0 == 0
862 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
863 return ReplaceInstUsesWith(I, Op1);
866 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
867 if (RHS->isAllOnesValue())
868 return ReplaceInstUsesWith(I, Op0);
870 // Optimize a variety of ((val OP C1) & C2) combinations...
871 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
872 Instruction *Op0I = cast<Instruction>(Op0);
873 Value *X = Op0I->getOperand(0);
874 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
875 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
880 Value *Op0NotVal = dyn_castNotVal(Op0);
881 Value *Op1NotVal = dyn_castNotVal(Op1);
883 // (~A & ~B) == (~(A | B)) - Demorgan's Law
884 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
885 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
886 Op1NotVal,I.getName()+".demorgan");
887 InsertNewInstBefore(Or, I);
888 return BinaryOperator::createNot(Or);
891 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
892 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
894 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
895 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
896 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
899 return Changed ? &I : 0;
904 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
905 bool Changed = SimplifyCommutative(I);
906 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
908 // or X, X = X or X, 0 == X
909 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
910 return ReplaceInstUsesWith(I, Op0);
913 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
914 if (RHS->isAllOnesValue())
915 return ReplaceInstUsesWith(I, Op1);
917 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
918 // (X & C1) | C2 --> (X | C2) & (C1|C2)
919 if (Op0I->getOpcode() == Instruction::And && isOnlyUse(Op0))
920 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
921 std::string Op0Name = Op0I->getName(); Op0I->setName("");
922 Instruction *Or = BinaryOperator::create(Instruction::Or,
923 Op0I->getOperand(0), RHS,
925 InsertNewInstBefore(Or, I);
926 return BinaryOperator::create(Instruction::And, Or, *RHS | *Op0CI);
929 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
930 if (Op0I->getOpcode() == Instruction::Xor && isOnlyUse(Op0))
931 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
932 std::string Op0Name = Op0I->getName(); Op0I->setName("");
933 Instruction *Or = BinaryOperator::create(Instruction::Or,
934 Op0I->getOperand(0), RHS,
936 InsertNewInstBefore(Or, I);
937 return BinaryOperator::create(Instruction::Xor, Or, *Op0CI & *~*RHS);
942 // (A & C1)|(A & C2) == A & (C1|C2)
943 if (Instruction *LHS = dyn_cast<BinaryOperator>(Op0))
944 if (Instruction *RHS = dyn_cast<BinaryOperator>(Op1))
945 if (LHS->getOperand(0) == RHS->getOperand(0))
946 if (Constant *C0 = dyn_castMaskingAnd(LHS))
947 if (Constant *C1 = dyn_castMaskingAnd(RHS))
948 return BinaryOperator::create(Instruction::And, LHS->getOperand(0),
951 Value *Op0NotVal = dyn_castNotVal(Op0);
952 Value *Op1NotVal = dyn_castNotVal(Op1);
954 if (Op1 == Op0NotVal) // ~A | A == -1
955 return ReplaceInstUsesWith(I,
956 ConstantIntegral::getAllOnesValue(I.getType()));
958 if (Op0 == Op1NotVal) // A | ~A == -1
959 return ReplaceInstUsesWith(I,
960 ConstantIntegral::getAllOnesValue(I.getType()));
962 // (~A | ~B) == (~(A & B)) - Demorgan's Law
963 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
964 Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
965 Op1NotVal,I.getName()+".demorgan",
967 WorkList.push_back(And);
968 return BinaryOperator::createNot(And);
971 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
972 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
973 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
976 return Changed ? &I : 0;
981 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
982 bool Changed = SimplifyCommutative(I);
983 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
987 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
989 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
991 if (RHS->isNullValue())
992 return ReplaceInstUsesWith(I, Op0);
994 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
995 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
996 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
997 if (RHS == ConstantBool::True && SCI->hasOneUse())
998 return new SetCondInst(SCI->getInverseCondition(),
999 SCI->getOperand(0), SCI->getOperand(1));
1001 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1002 if (Op0I->getOpcode() == Instruction::And) {
1003 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
1004 if ((*RHS & *Op0CI)->isNullValue())
1005 return BinaryOperator::create(Instruction::Or, Op0, RHS);
1006 } else if (Op0I->getOpcode() == Instruction::Or) {
1007 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1008 if ((*RHS & *Op0CI) == RHS)
1009 return BinaryOperator::create(Instruction::And, Op0, ~*RHS);
1014 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
1016 return ReplaceInstUsesWith(I,
1017 ConstantIntegral::getAllOnesValue(I.getType()));
1019 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
1021 return ReplaceInstUsesWith(I,
1022 ConstantIntegral::getAllOnesValue(I.getType()));
1024 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
1025 if (Op1I->getOpcode() == Instruction::Or)
1026 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1027 cast<BinaryOperator>(Op1I)->swapOperands();
1029 std::swap(Op0, Op1);
1030 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1032 std::swap(Op0, Op1);
1035 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
1036 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
1037 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1038 cast<BinaryOperator>(Op0I)->swapOperands();
1039 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
1040 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
1041 WorkList.push_back(cast<Instruction>(NotB));
1042 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
1047 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
1048 if (Constant *C1 = dyn_castMaskingAnd(Op0))
1049 if (Constant *C2 = dyn_castMaskingAnd(Op1))
1050 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
1051 return BinaryOperator::create(Instruction::Or, Op0, Op1);
1053 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1054 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1055 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1058 return Changed ? &I : 0;
1061 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
1062 static Constant *AddOne(ConstantInt *C) {
1063 Constant *Result = ConstantExpr::get(Instruction::Add, C,
1064 ConstantInt::get(C->getType(), 1));
1065 assert(Result && "Constant folding integer addition failed!");
1068 static Constant *SubOne(ConstantInt *C) {
1069 Constant *Result = ConstantExpr::get(Instruction::Sub, C,
1070 ConstantInt::get(C->getType(), 1));
1071 assert(Result && "Constant folding integer addition failed!");
1075 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
1076 // true when both operands are equal...
1078 static bool isTrueWhenEqual(Instruction &I) {
1079 return I.getOpcode() == Instruction::SetEQ ||
1080 I.getOpcode() == Instruction::SetGE ||
1081 I.getOpcode() == Instruction::SetLE;
1084 Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
1085 bool Changed = SimplifyCommutative(I);
1086 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1087 const Type *Ty = Op0->getType();
1091 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
1093 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1094 if (isa<ConstantPointerNull>(Op1) &&
1095 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
1096 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1099 // setcc's with boolean values can always be turned into bitwise operations
1100 if (Ty == Type::BoolTy) {
1101 // If this is <, >, or !=, we can change this into a simple xor instruction
1102 if (!isTrueWhenEqual(I))
1103 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
1105 // Otherwise we need to make a temporary intermediate instruction and insert
1106 // it into the instruction stream. This is what we are after:
1108 // seteq bool %A, %B -> ~(A^B)
1109 // setle bool %A, %B -> ~A | B
1110 // setge bool %A, %B -> A | ~B
1112 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
1113 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
1115 InsertNewInstBefore(Xor, I);
1116 return BinaryOperator::createNot(Xor, I.getName());
1119 // Handle the setXe cases...
1120 assert(I.getOpcode() == Instruction::SetGE ||
1121 I.getOpcode() == Instruction::SetLE);
1123 if (I.getOpcode() == Instruction::SetGE)
1124 std::swap(Op0, Op1); // Change setge -> setle
1126 // Now we just have the SetLE case.
1127 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1128 InsertNewInstBefore(Not, I);
1129 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
1132 // Check to see if we are doing one of many comparisons against constant
1133 // integers at the end of their ranges...
1135 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1136 // Simplify seteq and setne instructions...
1137 if (I.getOpcode() == Instruction::SetEQ ||
1138 I.getOpcode() == Instruction::SetNE) {
1139 bool isSetNE = I.getOpcode() == Instruction::SetNE;
1141 // If the first operand is (and|or|xor) with a constant, and the second
1142 // operand is a constant, simplify a bit.
1143 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
1144 switch (BO->getOpcode()) {
1145 case Instruction::Add:
1146 if (CI->isNullValue()) {
1147 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1148 // efficiently invertible, or if the add has just this one use.
1149 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
1150 if (Value *NegVal = dyn_castNegVal(BOp1))
1151 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
1152 else if (Value *NegVal = dyn_castNegVal(BOp0))
1153 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
1154 else if (BO->hasOneUse()) {
1155 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
1157 InsertNewInstBefore(Neg, I);
1158 return new SetCondInst(I.getOpcode(), BOp0, Neg);
1162 case Instruction::Xor:
1163 // For the xor case, we can xor two constants together, eliminating
1164 // the explicit xor.
1165 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1166 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
1170 case Instruction::Sub:
1171 // Replace (([sub|xor] A, B) != 0) with (A != B)
1172 if (CI->isNullValue())
1173 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1177 case Instruction::Or:
1178 // If bits are being or'd in that are not present in the constant we
1179 // are comparing against, then the comparison could never succeed!
1180 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1181 if (!(*BOC & *~*CI)->isNullValue())
1182 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
1185 case Instruction::And:
1186 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1187 // If bits are being compared against that are and'd out, then the
1188 // comparison can never succeed!
1189 if (!(*CI & *~*BOC)->isNullValue())
1190 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
1192 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
1193 // to be a signed value as appropriate.
1194 if (isSignBit(BOC)) {
1195 Value *X = BO->getOperand(0);
1196 // If 'X' is not signed, insert a cast now...
1197 if (!BOC->getType()->isSigned()) {
1199 switch (BOC->getType()->getPrimitiveID()) {
1200 case Type::UByteTyID: DestTy = Type::SByteTy; break;
1201 case Type::UShortTyID: DestTy = Type::ShortTy; break;
1202 case Type::UIntTyID: DestTy = Type::IntTy; break;
1203 case Type::ULongTyID: DestTy = Type::LongTy; break;
1204 default: assert(0 && "Invalid unsigned integer type!"); abort();
1206 CastInst *NewCI = new CastInst(X,DestTy,X->getName()+".signed");
1207 InsertNewInstBefore(NewCI, I);
1210 return new SetCondInst(isSetNE ? Instruction::SetLT :
1211 Instruction::SetGE, X,
1212 Constant::getNullValue(X->getType()));
1220 // Check to see if we are comparing against the minimum or maximum value...
1221 if (CI->isMinValue()) {
1222 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1223 return ReplaceInstUsesWith(I, ConstantBool::False);
1224 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1225 return ReplaceInstUsesWith(I, ConstantBool::True);
1226 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
1227 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
1228 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
1229 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
1231 } else if (CI->isMaxValue()) {
1232 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1233 return ReplaceInstUsesWith(I, ConstantBool::False);
1234 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1235 return ReplaceInstUsesWith(I, ConstantBool::True);
1236 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
1237 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
1238 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
1239 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
1241 // Comparing against a value really close to min or max?
1242 } else if (isMinValuePlusOne(CI)) {
1243 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
1244 return BinaryOperator::create(Instruction::SetEQ, Op0,
1245 SubOne(CI), I.getName());
1246 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
1247 return BinaryOperator::create(Instruction::SetNE, Op0,
1248 SubOne(CI), I.getName());
1250 } else if (isMaxValueMinusOne(CI)) {
1251 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
1252 return BinaryOperator::create(Instruction::SetEQ, Op0,
1253 AddOne(CI), I.getName());
1254 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
1255 return BinaryOperator::create(Instruction::SetNE, Op0,
1256 AddOne(CI), I.getName());
1260 return Changed ? &I : 0;
1265 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
1266 assert(I.getOperand(1)->getType() == Type::UByteTy);
1267 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1268 bool isLeftShift = I.getOpcode() == Instruction::Shl;
1270 // shl X, 0 == X and shr X, 0 == X
1271 // shl 0, X == 0 and shr 0, X == 0
1272 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
1273 Op0 == Constant::getNullValue(Op0->getType()))
1274 return ReplaceInstUsesWith(I, Op0);
1276 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
1278 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1279 if (CSI->isAllOnesValue())
1280 return ReplaceInstUsesWith(I, CSI);
1282 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
1283 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
1284 // of a signed value.
1286 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
1287 if (CUI->getValue() >= TypeBits &&
1288 (!Op0->getType()->isSigned() || isLeftShift))
1289 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
1291 // ((X*C1) << C2) == (X * (C1 << C2))
1292 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
1293 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
1294 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
1295 return BinaryOperator::create(Instruction::Mul, BO->getOperand(0),
1299 // If the operand is an bitwise operator with a constant RHS, and the
1300 // shift is the only use, we can pull it out of the shift.
1301 if (Op0->hasOneUse())
1302 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
1303 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
1304 bool isValid = true; // Valid only for And, Or, Xor
1305 bool highBitSet = false; // Transform if high bit of constant set?
1307 switch (Op0BO->getOpcode()) {
1308 default: isValid = false; break; // Do not perform transform!
1309 case Instruction::Or:
1310 case Instruction::Xor:
1313 case Instruction::And:
1318 // If this is a signed shift right, and the high bit is modified
1319 // by the logical operation, do not perform the transformation.
1320 // The highBitSet boolean indicates the value of the high bit of
1321 // the constant which would cause it to be modified for this
1324 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
1325 uint64_t Val = Op0C->getRawValue();
1326 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
1331 ConstantFoldShiftInstruction(I.getOpcode(), Op0C, CUI);
1333 Instruction *NewShift =
1334 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
1337 InsertNewInstBefore(NewShift, I);
1339 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
1344 // If this is a shift of a shift, see if we can fold the two together...
1345 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
1346 if (ConstantUInt *ShiftAmt1C =
1347 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
1348 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
1349 unsigned ShiftAmt2 = CUI->getValue();
1351 // Check for (A << c1) << c2 and (A >> c1) >> c2
1352 if (I.getOpcode() == Op0SI->getOpcode()) {
1353 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
1354 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
1355 ConstantUInt::get(Type::UByteTy, Amt));
1358 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
1359 // signed types, we can only support the (A >> c1) << c2 configuration,
1360 // because it can not turn an arbitrary bit of A into a sign bit.
1361 if (I.getType()->isUnsigned() || isLeftShift) {
1362 // Calculate bitmask for what gets shifted off the edge...
1363 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
1365 C = ConstantExpr::getShift(Instruction::Shl, C, ShiftAmt1C);
1367 C = ConstantExpr::getShift(Instruction::Shr, C, ShiftAmt1C);
1370 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
1371 C, Op0SI->getOperand(0)->getName()+".mask");
1372 InsertNewInstBefore(Mask, I);
1374 // Figure out what flavor of shift we should use...
1375 if (ShiftAmt1 == ShiftAmt2)
1376 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
1377 else if (ShiftAmt1 < ShiftAmt2) {
1378 return new ShiftInst(I.getOpcode(), Mask,
1379 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
1381 return new ShiftInst(Op0SI->getOpcode(), Mask,
1382 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
1392 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
1395 static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
1396 const Type *DstTy) {
1398 // It is legal to eliminate the instruction if casting A->B->A if the sizes
1399 // are identical and the bits don't get reinterpreted (for example
1400 // int->float->int would not be allowed)
1401 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
1404 // Allow free casting and conversion of sizes as long as the sign doesn't
1406 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
1407 unsigned SrcSize = SrcTy->getPrimitiveSize();
1408 unsigned MidSize = MidTy->getPrimitiveSize();
1409 unsigned DstSize = DstTy->getPrimitiveSize();
1411 // Cases where we are monotonically decreasing the size of the type are
1412 // always ok, regardless of what sign changes are going on.
1414 if (SrcSize >= MidSize && MidSize >= DstSize)
1417 // Cases where the source and destination type are the same, but the middle
1418 // type is bigger are noops.
1420 if (SrcSize == DstSize && MidSize > SrcSize)
1423 // If we are monotonically growing, things are more complex.
1425 if (SrcSize <= MidSize && MidSize <= DstSize) {
1426 // We have eight combinations of signedness to worry about. Here's the
1428 static const int SignTable[8] = {
1429 // CODE, SrcSigned, MidSigned, DstSigned, Comment
1430 1, // U U U Always ok
1431 1, // U U S Always ok
1432 3, // U S U Ok iff SrcSize != MidSize
1433 3, // U S S Ok iff SrcSize != MidSize
1434 0, // S U U Never ok
1435 2, // S U S Ok iff MidSize == DstSize
1436 1, // S S U Always ok
1437 1, // S S S Always ok
1440 // Choose an action based on the current entry of the signtable that this
1441 // cast of cast refers to...
1442 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
1443 switch (SignTable[Row]) {
1444 case 0: return false; // Never ok
1445 case 1: return true; // Always ok
1446 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
1447 case 3: // Ok iff SrcSize != MidSize
1448 return SrcSize != MidSize || SrcTy == Type::BoolTy;
1449 default: assert(0 && "Bad entry in sign table!");
1454 // Otherwise, we cannot succeed. Specifically we do not want to allow things
1455 // like: short -> ushort -> uint, because this can create wrong results if
1456 // the input short is negative!
1461 static bool ValueRequiresCast(const Value *V, const Type *Ty) {
1462 if (V->getType() == Ty || isa<Constant>(V)) return false;
1463 if (const CastInst *CI = dyn_cast<CastInst>(V))
1464 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty))
1469 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
1470 /// InsertBefore instruction. This is specialized a bit to avoid inserting
1471 /// casts that are known to not do anything...
1473 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
1474 Instruction *InsertBefore) {
1475 if (V->getType() == DestTy) return V;
1476 if (Constant *C = dyn_cast<Constant>(V))
1477 return ConstantExpr::getCast(C, DestTy);
1479 CastInst *CI = new CastInst(V, DestTy, V->getName());
1480 InsertNewInstBefore(CI, *InsertBefore);
1484 // CastInst simplification
1486 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
1487 Value *Src = CI.getOperand(0);
1489 // If the user is casting a value to the same type, eliminate this cast
1491 if (CI.getType() == Src->getType())
1492 return ReplaceInstUsesWith(CI, Src);
1494 // If casting the result of another cast instruction, try to eliminate this
1497 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
1498 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
1499 CSrc->getType(), CI.getType())) {
1500 // This instruction now refers directly to the cast's src operand. This
1501 // has a good chance of making CSrc dead.
1502 CI.setOperand(0, CSrc->getOperand(0));
1506 // If this is an A->B->A cast, and we are dealing with integral types, try
1507 // to convert this into a logical 'and' instruction.
1509 if (CSrc->getOperand(0)->getType() == CI.getType() &&
1510 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
1511 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
1512 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
1513 assert(CSrc->getType() != Type::ULongTy &&
1514 "Cannot have type bigger than ulong!");
1515 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
1516 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
1517 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
1522 // If casting the result of a getelementptr instruction with no offset, turn
1523 // this into a cast of the original pointer!
1525 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1526 bool AllZeroOperands = true;
1527 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1528 if (!isa<Constant>(GEP->getOperand(i)) ||
1529 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
1530 AllZeroOperands = false;
1533 if (AllZeroOperands) {
1534 CI.setOperand(0, GEP->getOperand(0));
1539 // If the source value is an instruction with only this use, we can attempt to
1540 // propagate the cast into the instruction. Also, only handle integral types
1542 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
1543 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
1544 CI.getType()->isInteger()) { // Don't mess with casts to bool here
1545 const Type *DestTy = CI.getType();
1546 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
1547 unsigned DestBitSize = getTypeSizeInBits(DestTy);
1549 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
1550 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
1552 switch (SrcI->getOpcode()) {
1553 case Instruction::Add:
1554 case Instruction::Mul:
1555 case Instruction::And:
1556 case Instruction::Or:
1557 case Instruction::Xor:
1558 // If we are discarding information, or just changing the sign, rewrite.
1559 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
1560 // Don't insert two casts if they cannot be eliminated. We allow two
1561 // casts to be inserted if the sizes are the same. This could only be
1562 // converting signedness, which is a noop.
1563 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy) ||
1564 !ValueRequiresCast(Op0, DestTy)) {
1565 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1566 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
1567 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
1568 ->getOpcode(), Op0c, Op1c);
1572 case Instruction::Shl:
1573 // Allow changing the sign of the source operand. Do not allow changing
1574 // the size of the shift, UNLESS the shift amount is a constant. We
1575 // mush not change variable sized shifts to a smaller size, because it
1576 // is undefined to shift more bits out than exist in the value.
1577 if (DestBitSize == SrcBitSize ||
1578 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
1579 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1580 return new ShiftInst(Instruction::Shl, Op0c, Op1);
1589 // CallInst simplification
1591 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
1592 return visitCallSite(&CI);
1595 // InvokeInst simplification
1597 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
1598 return visitCallSite(&II);
1601 // getPromotedType - Return the specified type promoted as it would be to pass
1602 // though a va_arg area...
1603 static const Type *getPromotedType(const Type *Ty) {
1604 switch (Ty->getPrimitiveID()) {
1605 case Type::SByteTyID:
1606 case Type::ShortTyID: return Type::IntTy;
1607 case Type::UByteTyID:
1608 case Type::UShortTyID: return Type::UIntTy;
1609 case Type::FloatTyID: return Type::DoubleTy;
1614 // visitCallSite - Improvements for call and invoke instructions.
1616 Instruction *InstCombiner::visitCallSite(CallSite CS) {
1617 bool Changed = false;
1619 // If the callee is a constexpr cast of a function, attempt to move the cast
1620 // to the arguments of the call/invoke.
1621 if (transformConstExprCastCall(CS)) return 0;
1623 Value *Callee = CS.getCalledValue();
1624 const PointerType *PTy = cast<PointerType>(Callee->getType());
1625 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1626 if (FTy->isVarArg()) {
1627 // See if we can optimize any arguments passed through the varargs area of
1629 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
1630 E = CS.arg_end(); I != E; ++I)
1631 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
1632 // If this cast does not effect the value passed through the varargs
1633 // area, we can eliminate the use of the cast.
1634 Value *Op = CI->getOperand(0);
1635 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
1642 return Changed ? CS.getInstruction() : 0;
1645 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
1646 // attempt to move the cast to the arguments of the call/invoke.
1648 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
1649 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
1650 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
1651 if (CE->getOpcode() != Instruction::Cast ||
1652 !isa<ConstantPointerRef>(CE->getOperand(0)))
1654 ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
1655 if (!isa<Function>(CPR->getValue())) return false;
1656 Function *Callee = cast<Function>(CPR->getValue());
1657 Instruction *Caller = CS.getInstruction();
1659 // Okay, this is a cast from a function to a different type. Unless doing so
1660 // would cause a type conversion of one of our arguments, change this call to
1661 // be a direct call with arguments casted to the appropriate types.
1663 const FunctionType *FT = Callee->getFunctionType();
1664 const Type *OldRetTy = Caller->getType();
1666 if (Callee->isExternal() &&
1667 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()))
1668 return false; // Cannot transform this return value...
1670 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1671 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1673 CallSite::arg_iterator AI = CS.arg_begin();
1674 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1675 const Type *ParamTy = FT->getParamType(i);
1676 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
1677 if (Callee->isExternal() && !isConvertible) return false;
1680 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
1681 Callee->isExternal())
1682 return false; // Do not delete arguments unless we have a function body...
1684 // Okay, we decided that this is a safe thing to do: go ahead and start
1685 // inserting cast instructions as necessary...
1686 std::vector<Value*> Args;
1687 Args.reserve(NumActualArgs);
1689 AI = CS.arg_begin();
1690 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1691 const Type *ParamTy = FT->getParamType(i);
1692 if ((*AI)->getType() == ParamTy) {
1693 Args.push_back(*AI);
1695 Instruction *Cast = new CastInst(*AI, ParamTy, "tmp");
1696 InsertNewInstBefore(Cast, *Caller);
1697 Args.push_back(Cast);
1701 // If the function takes more arguments than the call was taking, add them
1703 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1704 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1706 // If we are removing arguments to the function, emit an obnoxious warning...
1707 if (FT->getNumParams() < NumActualArgs)
1708 if (!FT->isVarArg()) {
1709 std::cerr << "WARNING: While resolving call to function '"
1710 << Callee->getName() << "' arguments were dropped!\n";
1712 // Add all of the arguments in their promoted form to the arg list...
1713 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1714 const Type *PTy = getPromotedType((*AI)->getType());
1715 if (PTy != (*AI)->getType()) {
1716 // Must promote to pass through va_arg area!
1717 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
1718 InsertNewInstBefore(Cast, *Caller);
1719 Args.push_back(Cast);
1721 Args.push_back(*AI);
1726 if (FT->getReturnType() == Type::VoidTy)
1727 Caller->setName(""); // Void type should not have a name...
1730 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1731 NC = new InvokeInst(Callee, II->getNormalDest(), II->getExceptionalDest(),
1732 Args, Caller->getName(), Caller);
1734 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
1737 // Insert a cast of the return type as necessary...
1739 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
1740 if (NV->getType() != Type::VoidTy) {
1741 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
1742 InsertNewInstBefore(NC, *Caller);
1743 AddUsesToWorkList(*Caller);
1745 NV = Constant::getNullValue(Caller->getType());
1749 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
1750 Caller->replaceAllUsesWith(NV);
1751 Caller->getParent()->getInstList().erase(Caller);
1752 removeFromWorkList(Caller);
1758 // PHINode simplification
1760 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
1761 // If the PHI node only has one incoming value, eliminate the PHI node...
1762 if (PN.getNumIncomingValues() == 1)
1763 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
1765 // Otherwise if all of the incoming values are the same for the PHI, replace
1766 // the PHI node with the incoming value.
1769 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1770 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
1771 if (InVal && PN.getIncomingValue(i) != InVal)
1772 return 0; // Not the same, bail out.
1774 InVal = PN.getIncomingValue(i);
1776 // The only case that could cause InVal to be null is if we have a PHI node
1777 // that only has entries for itself. In this case, there is no entry into the
1778 // loop, so kill the PHI.
1780 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
1782 // All of the incoming values are the same, replace the PHI node now.
1783 return ReplaceInstUsesWith(PN, InVal);
1787 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1788 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
1789 // If so, eliminate the noop.
1790 if ((GEP.getNumOperands() == 2 &&
1791 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
1792 GEP.getNumOperands() == 1)
1793 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
1795 // Combine Indices - If the source pointer to this getelementptr instruction
1796 // is a getelementptr instruction, combine the indices of the two
1797 // getelementptr instructions into a single instruction.
1799 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
1800 std::vector<Value *> Indices;
1802 // Can we combine the two pointer arithmetics offsets?
1803 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
1804 isa<Constant>(GEP.getOperand(1))) {
1805 // Replace: gep (gep %P, long C1), long C2, ...
1806 // With: gep %P, long (C1+C2), ...
1807 Value *Sum = ConstantExpr::get(Instruction::Add,
1808 cast<Constant>(Src->getOperand(1)),
1809 cast<Constant>(GEP.getOperand(1)));
1810 assert(Sum && "Constant folding of longs failed!?");
1811 GEP.setOperand(0, Src->getOperand(0));
1812 GEP.setOperand(1, Sum);
1813 AddUsesToWorkList(*Src); // Reduce use count of Src
1815 } else if (Src->getNumOperands() == 2) {
1816 // Replace: gep (gep %P, long B), long A, ...
1817 // With: T = long A+B; gep %P, T, ...
1819 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
1821 Src->getName()+".sum", &GEP);
1822 GEP.setOperand(0, Src->getOperand(0));
1823 GEP.setOperand(1, Sum);
1824 WorkList.push_back(cast<Instruction>(Sum));
1826 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
1827 Src->getNumOperands() != 1) {
1828 // Otherwise we can do the fold if the first index of the GEP is a zero
1829 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
1830 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
1831 } else if (Src->getOperand(Src->getNumOperands()-1) ==
1832 Constant::getNullValue(Type::LongTy)) {
1833 // If the src gep ends with a constant array index, merge this get into
1834 // it, even if we have a non-zero array index.
1835 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
1836 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
1839 if (!Indices.empty())
1840 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
1842 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
1843 // GEP of global variable. If all of the indices for this GEP are
1844 // constants, we can promote this to a constexpr instead of an instruction.
1846 // Scan for nonconstants...
1847 std::vector<Constant*> Indices;
1848 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1849 for (; I != E && isa<Constant>(*I); ++I)
1850 Indices.push_back(cast<Constant>(*I));
1852 if (I == E) { // If they are all constants...
1854 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1856 // Replace all uses of the GEP with the new constexpr...
1857 return ReplaceInstUsesWith(GEP, CE);
1864 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1865 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1866 if (AI.isArrayAllocation()) // Check C != 1
1867 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1868 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
1869 AllocationInst *New = 0;
1871 // Create and insert the replacement instruction...
1872 if (isa<MallocInst>(AI))
1873 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
1875 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
1876 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
1879 // Scan to the end of the allocation instructions, to skip over a block of
1880 // allocas if possible...
1882 BasicBlock::iterator It = New;
1883 while (isa<AllocationInst>(*It)) ++It;
1885 // Now that I is pointing to the first non-allocation-inst in the block,
1886 // insert our getelementptr instruction...
1888 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1889 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1891 // Now make everything use the getelementptr instead of the original
1893 ReplaceInstUsesWith(AI, V);
1899 /// GetGEPGlobalInitializer - Given a constant, and a getelementptr
1900 /// constantexpr, return the constant value being addressed by the constant
1901 /// expression, or null if something is funny.
1903 static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
1904 if (CE->getOperand(1) != Constant::getNullValue(Type::LongTy))
1905 return 0; // Do not allow stepping over the value!
1907 // Loop over all of the operands, tracking down which value we are
1909 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
1910 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
1911 ConstantStruct *CS = cast<ConstantStruct>(C);
1912 if (CU->getValue() >= CS->getValues().size()) return 0;
1913 C = cast<Constant>(CS->getValues()[CU->getValue()]);
1914 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
1915 ConstantArray *CA = cast<ConstantArray>(C);
1916 if ((uint64_t)CS->getValue() >= CA->getValues().size()) return 0;
1917 C = cast<Constant>(CA->getValues()[CS->getValue()]);
1923 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
1924 Value *Op = LI.getOperand(0);
1925 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Op))
1926 Op = CPR->getValue();
1928 // Instcombine load (constant global) into the value loaded...
1929 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
1930 if (GV->isConstant() && !GV->isExternal())
1931 return ReplaceInstUsesWith(LI, GV->getInitializer());
1933 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
1934 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
1935 if (CE->getOpcode() == Instruction::GetElementPtr)
1936 if (ConstantPointerRef *G=dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
1937 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
1938 if (GV->isConstant() && !GV->isExternal())
1939 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
1940 return ReplaceInstUsesWith(LI, V);
1945 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1946 // Change br (not X), label True, label False to: br X, label False, True
1947 if (BI.isConditional() && !isa<Constant>(BI.getCondition()))
1948 if (Value *V = dyn_castNotVal(BI.getCondition())) {
1949 BasicBlock *TrueDest = BI.getSuccessor(0);
1950 BasicBlock *FalseDest = BI.getSuccessor(1);
1951 // Swap Destinations and condition...
1953 BI.setSuccessor(0, FalseDest);
1954 BI.setSuccessor(1, TrueDest);
1961 void InstCombiner::removeFromWorkList(Instruction *I) {
1962 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1966 bool InstCombiner::runOnFunction(Function &F) {
1967 bool Changed = false;
1969 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
1971 while (!WorkList.empty()) {
1972 Instruction *I = WorkList.back(); // Get an instruction from the worklist
1973 WorkList.pop_back();
1975 // Check to see if we can DCE or ConstantPropagate the instruction...
1976 // Check to see if we can DIE the instruction...
1977 if (isInstructionTriviallyDead(I)) {
1978 // Add operands to the worklist...
1979 if (I->getNumOperands() < 4)
1980 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1981 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1982 WorkList.push_back(Op);
1985 I->getParent()->getInstList().erase(I);
1986 removeFromWorkList(I);
1990 // Instruction isn't dead, see if we can constant propagate it...
1991 if (Constant *C = ConstantFoldInstruction(I)) {
1992 // Add operands to the worklist...
1993 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1994 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1995 WorkList.push_back(Op);
1996 ReplaceInstUsesWith(*I, C);
1999 I->getParent()->getInstList().erase(I);
2000 removeFromWorkList(I);
2004 // Now that we have an instruction, try combining it to simplify it...
2005 if (Instruction *Result = visit(*I)) {
2007 // Should we replace the old instruction with a new one?
2009 // Instructions can end up on the worklist more than once. Make sure
2010 // we do not process an instruction that has been deleted.
2011 removeFromWorkList(I);
2013 // Move the name to the new instruction first...
2014 std::string OldName = I->getName(); I->setName("");
2015 Result->setName(OldName);
2017 // Insert the new instruction into the basic block...
2018 BasicBlock *InstParent = I->getParent();
2019 InstParent->getInstList().insert(I, Result);
2021 // Everything uses the new instruction now...
2022 I->replaceAllUsesWith(Result);
2024 // Erase the old instruction.
2025 InstParent->getInstList().erase(I);
2027 BasicBlock::iterator II = I;
2029 // If the instruction was modified, it's possible that it is now dead.
2030 // if so, remove it.
2031 if (dceInstruction(II)) {
2032 // Instructions may end up in the worklist more than once. Erase them
2034 removeFromWorkList(I);
2040 WorkList.push_back(Result);
2041 AddUsesToWorkList(*Result);
2050 Pass *createInstructionCombiningPass() {
2051 return new InstCombiner();