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 // This pass guarantees that the following canonicalizations are performed on
17 // 1. If a binary operator has a constant operand, it is moved to the RHS
18 // 2. Bitwise operators with constant operands are always grouped so that
19 // shifts are performed first, then or's, then and's, then xor's.
20 // 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
21 // 4. All SetCC instructions on boolean values are replaced with logical ops
22 // 5. add X, X is represented as (X*2) => (X << 1)
23 // 6. Multiplies with a power-of-two constant argument are transformed into
25 // N. This list is incomplete
27 //===----------------------------------------------------------------------===//
29 #include "llvm/Transforms/Scalar.h"
30 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
31 #include "llvm/Transforms/Utils/Local.h"
32 #include "llvm/Instructions.h"
33 #include "llvm/Pass.h"
34 #include "llvm/Constants.h"
35 #include "llvm/ConstantHandling.h"
36 #include "llvm/DerivedTypes.h"
37 #include "llvm/GlobalVariable.h"
38 #include "llvm/Support/InstIterator.h"
39 #include "llvm/Support/InstVisitor.h"
40 #include "llvm/Support/CallSite.h"
41 #include "Support/Statistic.h"
45 Statistic<> NumCombined ("instcombine", "Number of insts combined");
46 Statistic<> NumConstProp("instcombine", "Number of constant folds");
47 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
49 class InstCombiner : public FunctionPass,
50 public InstVisitor<InstCombiner, Instruction*> {
51 // Worklist of all of the instructions that need to be simplified.
52 std::vector<Instruction*> WorkList;
54 void AddUsesToWorkList(Instruction &I) {
55 // The instruction was simplified, add all users of the instruction to
56 // the work lists because they might get more simplified now...
58 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
60 WorkList.push_back(cast<Instruction>(*UI));
63 // removeFromWorkList - remove all instances of I from the worklist.
64 void removeFromWorkList(Instruction *I);
66 virtual bool runOnFunction(Function &F);
68 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
72 // Visitation implementation - Implement instruction combining for different
73 // instruction types. The semantics are as follows:
75 // null - No change was made
76 // I - Change was made, I is still valid, I may be dead though
77 // otherwise - Change was made, replace I with returned instruction
79 Instruction *visitAdd(BinaryOperator &I);
80 Instruction *visitSub(BinaryOperator &I);
81 Instruction *visitMul(BinaryOperator &I);
82 Instruction *visitDiv(BinaryOperator &I);
83 Instruction *visitRem(BinaryOperator &I);
84 Instruction *visitAnd(BinaryOperator &I);
85 Instruction *visitOr (BinaryOperator &I);
86 Instruction *visitXor(BinaryOperator &I);
87 Instruction *visitSetCondInst(BinaryOperator &I);
88 Instruction *visitShiftInst(ShiftInst &I);
89 Instruction *visitCastInst(CastInst &CI);
90 Instruction *visitCallInst(CallInst &CI);
91 Instruction *visitInvokeInst(InvokeInst &II);
92 Instruction *visitPHINode(PHINode &PN);
93 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
94 Instruction *visitAllocationInst(AllocationInst &AI);
95 Instruction *visitLoadInst(LoadInst &LI);
96 Instruction *visitBranchInst(BranchInst &BI);
98 // visitInstruction - Specify what to return for unhandled instructions...
99 Instruction *visitInstruction(Instruction &I) { return 0; }
102 Instruction *visitCallSite(CallSite CS);
103 bool transformConstExprCastCall(CallSite CS);
105 // InsertNewInstBefore - insert an instruction New before instruction Old
106 // in the program. Add the new instruction to the worklist.
108 void InsertNewInstBefore(Instruction *New, Instruction &Old) {
109 assert(New && New->getParent() == 0 &&
110 "New instruction already inserted into a basic block!");
111 BasicBlock *BB = Old.getParent();
112 BB->getInstList().insert(&Old, New); // Insert inst
113 WorkList.push_back(New); // Add to worklist
117 // ReplaceInstUsesWith - This method is to be used when an instruction is
118 // found to be dead, replacable with another preexisting expression. Here
119 // we add all uses of I to the worklist, replace all uses of I with the new
120 // value, then return I, so that the inst combiner will know that I was
123 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
124 AddUsesToWorkList(I); // Add all modified instrs to worklist
125 I.replaceAllUsesWith(V);
129 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
130 /// InsertBefore instruction. This is specialized a bit to avoid inserting
131 /// casts that are known to not do anything...
133 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
134 Instruction *InsertBefore);
136 // SimplifyCommutative - This performs a few simplifications for commutative
138 bool SimplifyCommutative(BinaryOperator &I);
140 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
141 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
144 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
147 // getComplexity: Assign a complexity or rank value to LLVM Values...
148 // 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
149 static unsigned getComplexity(Value *V) {
150 if (isa<Instruction>(V)) {
151 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
155 if (isa<Argument>(V)) return 2;
156 return isa<Constant>(V) ? 0 : 1;
159 // isOnlyUse - Return true if this instruction will be deleted if we stop using
161 static bool isOnlyUse(Value *V) {
162 return V->use_size() == 1 || isa<Constant>(V);
165 // SimplifyCommutative - This performs a few simplifications for commutative
168 // 1. Order operands such that they are listed from right (least complex) to
169 // left (most complex). This puts constants before unary operators before
172 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
173 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
175 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
176 bool Changed = false;
177 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
178 Changed = !I.swapOperands();
180 if (!I.isAssociative()) return Changed;
181 Instruction::BinaryOps Opcode = I.getOpcode();
182 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
183 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
184 if (isa<Constant>(I.getOperand(1))) {
185 Constant *Folded = ConstantExpr::get(I.getOpcode(),
186 cast<Constant>(I.getOperand(1)),
187 cast<Constant>(Op->getOperand(1)));
188 I.setOperand(0, Op->getOperand(0));
189 I.setOperand(1, Folded);
191 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
192 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
193 isOnlyUse(Op) && isOnlyUse(Op1)) {
194 Constant *C1 = cast<Constant>(Op->getOperand(1));
195 Constant *C2 = cast<Constant>(Op1->getOperand(1));
197 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
198 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
199 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
202 WorkList.push_back(New);
203 I.setOperand(0, New);
204 I.setOperand(1, Folded);
211 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
212 // if the LHS is a constant zero (which is the 'negate' form).
214 static inline Value *dyn_castNegVal(Value *V) {
215 if (BinaryOperator::isNeg(V))
216 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
218 // Constants can be considered to be negated values if they can be folded...
219 if (Constant *C = dyn_cast<Constant>(V))
220 return ConstantExpr::get(Instruction::Sub,
221 Constant::getNullValue(V->getType()), C);
225 static inline Value *dyn_castNotVal(Value *V) {
226 if (BinaryOperator::isNot(V))
227 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
229 // Constants can be considered to be not'ed values...
230 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
231 return ConstantExpr::get(Instruction::Xor,
232 ConstantIntegral::getAllOnesValue(C->getType()),C);
236 // dyn_castFoldableMul - If this value is a multiply that can be folded into
237 // other computations (because it has a constant operand), return the
238 // non-constant operand of the multiply.
240 static inline Value *dyn_castFoldableMul(Value *V) {
241 if (V->use_size() == 1 && V->getType()->isInteger())
242 if (Instruction *I = dyn_cast<Instruction>(V))
243 if (I->getOpcode() == Instruction::Mul)
244 if (isa<Constant>(I->getOperand(1)))
245 return I->getOperand(0);
249 // dyn_castMaskingAnd - If this value is an And instruction masking a value with
250 // a constant, return the constant being anded with.
252 template<class ValueType>
253 static inline Constant *dyn_castMaskingAnd(ValueType *V) {
254 if (Instruction *I = dyn_cast<Instruction>(V))
255 if (I->getOpcode() == Instruction::And)
256 return dyn_cast<Constant>(I->getOperand(1));
258 // If this is a constant, it acts just like we were masking with it.
259 return dyn_cast<Constant>(V);
262 // Log2 - Calculate the log base 2 for the specified value if it is exactly a
264 static unsigned Log2(uint64_t Val) {
265 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
268 if (Val & 1) return 0; // Multiple bits set?
276 /// AssociativeOpt - Perform an optimization on an associative operator. This
277 /// function is designed to check a chain of associative operators for a
278 /// potential to apply a certain optimization. Since the optimization may be
279 /// applicable if the expression was reassociated, this checks the chain, then
280 /// reassociates the expression as necessary to expose the optimization
281 /// opportunity. This makes use of a special Functor, which must define
282 /// 'shouldApply' and 'apply' methods.
284 template<typename Functor>
285 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
286 unsigned Opcode = Root.getOpcode();
287 Value *LHS = Root.getOperand(0);
289 // Quick check, see if the immediate LHS matches...
290 if (F.shouldApply(LHS))
291 return F.apply(Root);
293 // Otherwise, if the LHS is not of the same opcode as the root, return.
294 Instruction *LHSI = dyn_cast<Instruction>(LHS);
295 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->use_size() == 1) {
296 // Should we apply this transform to the RHS?
297 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
299 // If not to the RHS, check to see if we should apply to the LHS...
300 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
301 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
305 // If the functor wants to apply the optimization to the RHS of LHSI,
306 // reassociate the expression from ((? op A) op B) to (? op (A op B))
308 BasicBlock *BB = Root.getParent();
309 // All of the instructions have a single use and have no side-effects,
310 // because of this, we can pull them all into the current basic block.
311 if (LHSI->getParent() != BB) {
312 // Move all of the instructions from root to LHSI into the current
314 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
315 Instruction *LastUse = &Root;
316 while (TmpLHSI->getParent() == BB) {
318 TmpLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
321 // Loop over all of the instructions in other blocks, moving them into
323 Value *TmpLHS = TmpLHSI;
325 TmpLHSI = cast<Instruction>(TmpLHS);
326 // Remove from current block...
327 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
328 // Insert before the last instruction...
329 BB->getInstList().insert(LastUse, TmpLHSI);
330 TmpLHS = TmpLHSI->getOperand(0);
331 } while (TmpLHSI != LHSI);
334 // Now all of the instructions are in the current basic block, go ahead
335 // and perform the reassociation.
336 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
338 // First move the selected RHS to the LHS of the root...
339 Root.setOperand(0, LHSI->getOperand(1));
341 // Make what used to be the LHS of the root be the user of the root...
342 Value *ExtraOperand = TmpLHSI->getOperand(1);
343 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
344 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
345 BB->getInstList().remove(&Root); // Remove root from the BB
346 BB->getInstList().insert(TmpLHSI, &Root); // Insert root before TmpLHSI
348 // Now propagate the ExtraOperand down the chain of instructions until we
350 while (TmpLHSI != LHSI) {
351 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
352 Value *NextOp = NextLHSI->getOperand(1);
353 NextLHSI->setOperand(1, ExtraOperand);
355 ExtraOperand = NextOp;
358 // Now that the instructions are reassociated, have the functor perform
359 // the transformation...
360 return F.apply(Root);
363 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
369 // AddRHS - Implements: X + X --> X << 1
372 AddRHS(Value *rhs) : RHS(rhs) {}
373 bool shouldApply(Value *LHS) const { return LHS == RHS; }
374 Instruction *apply(BinaryOperator &Add) const {
375 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
376 ConstantInt::get(Type::UByteTy, 1));
380 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
382 struct AddMaskingAnd {
384 AddMaskingAnd(Constant *c) : C2(c) {}
385 bool shouldApply(Value *LHS) const {
386 if (Constant *C1 = dyn_castMaskingAnd(LHS))
387 return ConstantExpr::get(Instruction::And, C1, C2)->isNullValue();
390 Instruction *apply(BinaryOperator &Add) const {
391 return BinaryOperator::create(Instruction::Or, Add.getOperand(0),
398 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
399 bool Changed = SimplifyCommutative(I);
400 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
403 if (RHS == Constant::getNullValue(I.getType()))
404 return ReplaceInstUsesWith(I, LHS);
407 if (I.getType()->isInteger())
408 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
411 if (Value *V = dyn_castNegVal(LHS))
412 return BinaryOperator::create(Instruction::Sub, RHS, V);
415 if (!isa<Constant>(RHS))
416 if (Value *V = dyn_castNegVal(RHS))
417 return BinaryOperator::create(Instruction::Sub, LHS, V);
419 // X*C + X --> X * (C+1)
420 if (dyn_castFoldableMul(LHS) == RHS) {
422 ConstantExpr::get(Instruction::Add,
423 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
424 ConstantInt::get(I.getType(), 1));
425 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
428 // X + X*C --> X * (C+1)
429 if (dyn_castFoldableMul(RHS) == LHS) {
431 ConstantExpr::get(Instruction::Add,
432 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
433 ConstantInt::get(I.getType(), 1));
434 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
437 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
438 if (Constant *C2 = dyn_castMaskingAnd(RHS))
439 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
441 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
442 if (Instruction *ILHS = dyn_cast<Instruction>(LHS)) {
443 switch (ILHS->getOpcode()) {
444 case Instruction::Xor:
445 // ~X + C --> (C-1) - X
446 if (ConstantInt *XorRHS = dyn_cast<ConstantInt>(ILHS->getOperand(1)))
447 if (XorRHS->isAllOnesValue())
448 return BinaryOperator::create(Instruction::Sub,
449 *CRHS - *ConstantInt::get(I.getType(), 1),
450 ILHS->getOperand(0));
457 return Changed ? &I : 0;
460 // isSignBit - Return true if the value represented by the constant only has the
461 // highest order bit set.
462 static bool isSignBit(ConstantInt *CI) {
463 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
464 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
467 static unsigned getTypeSizeInBits(const Type *Ty) {
468 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
471 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
472 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
474 if (Op0 == Op1) // sub X, X -> 0
475 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
477 // If this is a 'B = x-(-A)', change to B = x+A...
478 if (Value *V = dyn_castNegVal(Op1))
479 return BinaryOperator::create(Instruction::Add, Op0, V);
481 // Replace (-1 - A) with (~A)...
482 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
483 if (C->isAllOnesValue())
484 return BinaryOperator::createNot(Op1);
486 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
487 if (Op1I->use_size() == 1) {
488 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
489 // is not used by anyone else...
491 if (Op1I->getOpcode() == Instruction::Sub) {
492 // Swap the two operands of the subexpr...
493 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
494 Op1I->setOperand(0, IIOp1);
495 Op1I->setOperand(1, IIOp0);
497 // Create the new top level add instruction...
498 return BinaryOperator::create(Instruction::Add, Op0, Op1);
501 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
503 if (Op1I->getOpcode() == Instruction::And &&
504 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
505 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
507 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
508 return BinaryOperator::create(Instruction::And, Op0, NewNot);
511 // X - X*C --> X * (1-C)
512 if (dyn_castFoldableMul(Op1I) == Op0) {
514 ConstantExpr::get(Instruction::Sub,
515 ConstantInt::get(I.getType(), 1),
516 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
517 assert(CP1 && "Couldn't constant fold 1-C?");
518 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
522 // X*C - X --> X * (C-1)
523 if (dyn_castFoldableMul(Op0) == Op1) {
525 ConstantExpr::get(Instruction::Sub,
526 cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
527 ConstantInt::get(I.getType(), 1));
528 assert(CP1 && "Couldn't constant fold C - 1?");
529 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
535 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
536 bool Changed = SimplifyCommutative(I);
537 Value *Op0 = I.getOperand(0);
539 // Simplify mul instructions with a constant RHS...
540 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
541 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
543 // ((X << C1)*C2) == (X * (C2 << C1))
544 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
545 if (SI->getOpcode() == Instruction::Shl)
546 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
547 return BinaryOperator::create(Instruction::Mul, SI->getOperand(0),
550 if (CI->isNullValue())
551 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
552 if (CI->equalsInt(1)) // X * 1 == X
553 return ReplaceInstUsesWith(I, Op0);
554 if (CI->isAllOnesValue()) // X * -1 == 0 - X
555 return BinaryOperator::createNeg(Op0, I.getName());
557 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
558 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
559 return new ShiftInst(Instruction::Shl, Op0,
560 ConstantUInt::get(Type::UByteTy, C));
562 ConstantFP *Op1F = cast<ConstantFP>(Op1);
563 if (Op1F->isNullValue())
564 return ReplaceInstUsesWith(I, Op1);
566 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
567 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
568 if (Op1F->getValue() == 1.0)
569 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
573 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
574 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
575 return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
577 return Changed ? &I : 0;
580 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
582 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
583 if (RHS->equalsInt(1))
584 return ReplaceInstUsesWith(I, I.getOperand(0));
586 // Check to see if this is an unsigned division with an exact power of 2,
587 // if so, convert to a right shift.
588 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
589 if (uint64_t Val = C->getValue()) // Don't break X / 0
590 if (uint64_t C = Log2(Val))
591 return new ShiftInst(Instruction::Shr, I.getOperand(0),
592 ConstantUInt::get(Type::UByteTy, C));
595 // 0 / X == 0, we don't need to preserve faults!
596 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
597 if (LHS->equalsInt(0))
598 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
604 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
605 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
606 if (RHS->equalsInt(1)) // X % 1 == 0
607 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
609 // Check to see if this is an unsigned remainder with an exact power of 2,
610 // if so, convert to a bitwise and.
611 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
612 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
614 return BinaryOperator::create(Instruction::And, I.getOperand(0),
615 ConstantUInt::get(I.getType(), Val-1));
618 // 0 % X == 0, we don't need to preserve faults!
619 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
620 if (LHS->equalsInt(0))
621 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
626 // isMaxValueMinusOne - return true if this is Max-1
627 static bool isMaxValueMinusOne(const ConstantInt *C) {
628 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
629 // Calculate -1 casted to the right type...
630 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
631 uint64_t Val = ~0ULL; // All ones
632 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
633 return CU->getValue() == Val-1;
636 const ConstantSInt *CS = cast<ConstantSInt>(C);
638 // Calculate 0111111111..11111
639 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
640 int64_t Val = INT64_MAX; // All ones
641 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
642 return CS->getValue() == Val-1;
645 // isMinValuePlusOne - return true if this is Min+1
646 static bool isMinValuePlusOne(const ConstantInt *C) {
647 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
648 return CU->getValue() == 1;
650 const ConstantSInt *CS = cast<ConstantSInt>(C);
652 // Calculate 1111111111000000000000
653 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
654 int64_t Val = -1; // All ones
655 Val <<= TypeBits-1; // Shift over to the right spot
656 return CS->getValue() == Val+1;
659 /// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
660 /// are carefully arranged to allow folding of expressions such as:
662 /// (A < B) | (A > B) --> (A != B)
664 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
665 /// represents that the comparison is true if A == B, and bit value '1' is true
668 static unsigned getSetCondCode(const SetCondInst *SCI) {
669 switch (SCI->getOpcode()) {
671 case Instruction::SetGT: return 1;
672 case Instruction::SetEQ: return 2;
673 case Instruction::SetGE: return 3;
674 case Instruction::SetLT: return 4;
675 case Instruction::SetNE: return 5;
676 case Instruction::SetLE: return 6;
679 assert(0 && "Invalid SetCC opcode!");
684 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
685 /// opcode and two operands into either a constant true or false, or a brand new
686 /// SetCC instruction.
687 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
689 case 0: return ConstantBool::False;
690 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
691 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
692 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
693 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
694 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
695 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
696 case 7: return ConstantBool::True;
697 default: assert(0 && "Illegal SetCCCode!"); return 0;
701 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
702 struct FoldSetCCLogical {
705 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
706 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
707 bool shouldApply(Value *V) const {
708 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
709 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
710 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
713 Instruction *apply(BinaryOperator &Log) const {
714 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
715 if (SCI->getOperand(0) != LHS) {
716 assert(SCI->getOperand(1) == LHS);
717 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
720 unsigned LHSCode = getSetCondCode(SCI);
721 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
723 switch (Log.getOpcode()) {
724 case Instruction::And: Code = LHSCode & RHSCode; break;
725 case Instruction::Or: Code = LHSCode | RHSCode; break;
726 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
727 default: assert(0 && "Illegal logical opcode!"); return 0;
730 Value *RV = getSetCCValue(Code, LHS, RHS);
731 if (Instruction *I = dyn_cast<Instruction>(RV))
733 // Otherwise, it's a constant boolean value...
734 return IC.ReplaceInstUsesWith(Log, RV);
739 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
740 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
741 // guaranteed to be either a shift instruction or a binary operator.
742 Instruction *InstCombiner::OptAndOp(Instruction *Op,
743 ConstantIntegral *OpRHS,
744 ConstantIntegral *AndRHS,
745 BinaryOperator &TheAnd) {
746 Value *X = Op->getOperand(0);
747 switch (Op->getOpcode()) {
748 case Instruction::Xor:
749 if ((*AndRHS & *OpRHS)->isNullValue()) {
750 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
751 return BinaryOperator::create(Instruction::And, X, AndRHS);
752 } else if (Op->use_size() == 1) {
753 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
754 std::string OpName = Op->getName(); Op->setName("");
755 Instruction *And = BinaryOperator::create(Instruction::And,
757 InsertNewInstBefore(And, TheAnd);
758 return BinaryOperator::create(Instruction::Xor, And, *AndRHS & *OpRHS);
761 case Instruction::Or:
762 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
763 if ((*AndRHS & *OpRHS)->isNullValue())
764 return BinaryOperator::create(Instruction::And, X, AndRHS);
766 Constant *Together = *AndRHS & *OpRHS;
767 if (Together == AndRHS) // (X | C) & C --> C
768 return ReplaceInstUsesWith(TheAnd, AndRHS);
770 if (Op->use_size() == 1 && Together != OpRHS) {
771 // (X | C1) & C2 --> (X | (C1&C2)) & C2
772 std::string Op0Name = Op->getName(); Op->setName("");
773 Instruction *Or = BinaryOperator::create(Instruction::Or, X,
775 InsertNewInstBefore(Or, TheAnd);
776 return BinaryOperator::create(Instruction::And, Or, AndRHS);
780 case Instruction::Add:
781 if (Op->use_size() == 1) {
782 // Adding a one to a single bit bit-field should be turned into an XOR
783 // of the bit. First thing to check is to see if this AND is with a
784 // single bit constant.
785 unsigned long long AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
787 // Clear bits that are not part of the constant.
788 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
790 // If there is only one bit set...
791 if ((AndRHSV & (AndRHSV-1)) == 0) {
792 // Ok, at this point, we know that we are masking the result of the
793 // ADD down to exactly one bit. If the constant we are adding has
794 // no bits set below this bit, then we can eliminate the ADD.
795 unsigned long long AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
797 // Check to see if any bits below the one bit set in AndRHSV are set.
798 if ((AddRHS & (AndRHSV-1)) == 0) {
799 // If not, the only thing that can effect the output of the AND is
800 // the bit specified by AndRHSV. If that bit is set, the effect of
801 // the XOR is to toggle the bit. If it is clear, then the ADD has
803 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
804 TheAnd.setOperand(0, X);
807 std::string Name = Op->getName(); Op->setName("");
808 // Pull the XOR out of the AND.
809 Instruction *NewAnd =
810 BinaryOperator::create(Instruction::And, X, AndRHS, Name);
811 InsertNewInstBefore(NewAnd, TheAnd);
812 return BinaryOperator::create(Instruction::Xor, NewAnd, AndRHS);
819 case Instruction::Shl: {
820 // We know that the AND will not produce any of the bits shifted in, so if
821 // the anded constant includes them, clear them now!
823 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
824 Constant *CI = *AndRHS & *(*AllOne << *OpRHS);
826 TheAnd.setOperand(1, CI);
831 case Instruction::Shr:
832 // We know that the AND will not produce any of the bits shifted in, so if
833 // the anded constant includes them, clear them now! This only applies to
834 // unsigned shifts, because a signed shr may bring in set bits!
836 if (AndRHS->getType()->isUnsigned()) {
837 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
838 Constant *CI = *AndRHS & *(*AllOne >> *OpRHS);
840 TheAnd.setOperand(1, CI);
850 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
851 bool Changed = SimplifyCommutative(I);
852 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
854 // and X, X = X and X, 0 == 0
855 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
856 return ReplaceInstUsesWith(I, Op1);
859 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
860 if (RHS->isAllOnesValue())
861 return ReplaceInstUsesWith(I, Op0);
863 // Optimize a variety of ((val OP C1) & C2) combinations...
864 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
865 Instruction *Op0I = cast<Instruction>(Op0);
866 Value *X = Op0I->getOperand(0);
867 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
868 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
873 Value *Op0NotVal = dyn_castNotVal(Op0);
874 Value *Op1NotVal = dyn_castNotVal(Op1);
876 // (~A & ~B) == (~(A | B)) - Demorgan's Law
877 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
878 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
879 Op1NotVal,I.getName()+".demorgan");
880 InsertNewInstBefore(Or, I);
881 return BinaryOperator::createNot(Or);
884 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
885 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
887 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
888 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
889 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
892 return Changed ? &I : 0;
897 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
898 bool Changed = SimplifyCommutative(I);
899 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
901 // or X, X = X or X, 0 == X
902 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
903 return ReplaceInstUsesWith(I, Op0);
906 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
907 if (RHS->isAllOnesValue())
908 return ReplaceInstUsesWith(I, Op1);
910 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
911 // (X & C1) | C2 --> (X | C2) & (C1|C2)
912 if (Op0I->getOpcode() == Instruction::And && isOnlyUse(Op0))
913 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
914 std::string Op0Name = Op0I->getName(); Op0I->setName("");
915 Instruction *Or = BinaryOperator::create(Instruction::Or,
916 Op0I->getOperand(0), RHS,
918 InsertNewInstBefore(Or, I);
919 return BinaryOperator::create(Instruction::And, Or, *RHS | *Op0CI);
922 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
923 if (Op0I->getOpcode() == Instruction::Xor && isOnlyUse(Op0))
924 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
925 std::string Op0Name = Op0I->getName(); Op0I->setName("");
926 Instruction *Or = BinaryOperator::create(Instruction::Or,
927 Op0I->getOperand(0), RHS,
929 InsertNewInstBefore(Or, I);
930 return BinaryOperator::create(Instruction::Xor, Or, *Op0CI & *~*RHS);
935 // (A & C1)|(A & C2) == A & (C1|C2)
936 if (Instruction *LHS = dyn_cast<BinaryOperator>(Op0))
937 if (Instruction *RHS = dyn_cast<BinaryOperator>(Op1))
938 if (LHS->getOperand(0) == RHS->getOperand(0))
939 if (Constant *C0 = dyn_castMaskingAnd(LHS))
940 if (Constant *C1 = dyn_castMaskingAnd(RHS))
941 return BinaryOperator::create(Instruction::And, LHS->getOperand(0),
944 Value *Op0NotVal = dyn_castNotVal(Op0);
945 Value *Op1NotVal = dyn_castNotVal(Op1);
947 if (Op1 == Op0NotVal) // ~A | A == -1
948 return ReplaceInstUsesWith(I,
949 ConstantIntegral::getAllOnesValue(I.getType()));
951 if (Op0 == Op1NotVal) // A | ~A == -1
952 return ReplaceInstUsesWith(I,
953 ConstantIntegral::getAllOnesValue(I.getType()));
955 // (~A | ~B) == (~(A & B)) - Demorgan's Law
956 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
957 Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
958 Op1NotVal,I.getName()+".demorgan",
960 WorkList.push_back(And);
961 return BinaryOperator::createNot(And);
964 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
965 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
966 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
969 return Changed ? &I : 0;
974 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
975 bool Changed = SimplifyCommutative(I);
976 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
980 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
982 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
984 if (RHS->isNullValue())
985 return ReplaceInstUsesWith(I, Op0);
987 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
988 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
989 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
990 if (RHS == ConstantBool::True && SCI->use_size() == 1)
991 return new SetCondInst(SCI->getInverseCondition(),
992 SCI->getOperand(0), SCI->getOperand(1));
994 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
995 if (Op0I->getOpcode() == Instruction::And) {
996 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
997 if ((*RHS & *Op0CI)->isNullValue())
998 return BinaryOperator::create(Instruction::Or, Op0, RHS);
999 } else if (Op0I->getOpcode() == Instruction::Or) {
1000 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1001 if ((*RHS & *Op0CI) == RHS)
1002 return BinaryOperator::create(Instruction::And, Op0, ~*RHS);
1007 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
1009 return ReplaceInstUsesWith(I,
1010 ConstantIntegral::getAllOnesValue(I.getType()));
1012 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
1014 return ReplaceInstUsesWith(I,
1015 ConstantIntegral::getAllOnesValue(I.getType()));
1017 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
1018 if (Op1I->getOpcode() == Instruction::Or)
1019 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1020 cast<BinaryOperator>(Op1I)->swapOperands();
1022 std::swap(Op0, Op1);
1023 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1025 std::swap(Op0, Op1);
1028 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
1029 if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
1030 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1031 cast<BinaryOperator>(Op0I)->swapOperands();
1032 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
1033 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
1034 WorkList.push_back(cast<Instruction>(NotB));
1035 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
1040 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
1041 if (Constant *C1 = dyn_castMaskingAnd(Op0))
1042 if (Constant *C2 = dyn_castMaskingAnd(Op1))
1043 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
1044 return BinaryOperator::create(Instruction::Or, Op0, Op1);
1046 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1047 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1048 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1051 return Changed ? &I : 0;
1054 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
1055 static Constant *AddOne(ConstantInt *C) {
1056 Constant *Result = ConstantExpr::get(Instruction::Add, C,
1057 ConstantInt::get(C->getType(), 1));
1058 assert(Result && "Constant folding integer addition failed!");
1061 static Constant *SubOne(ConstantInt *C) {
1062 Constant *Result = ConstantExpr::get(Instruction::Sub, C,
1063 ConstantInt::get(C->getType(), 1));
1064 assert(Result && "Constant folding integer addition failed!");
1068 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
1069 // true when both operands are equal...
1071 static bool isTrueWhenEqual(Instruction &I) {
1072 return I.getOpcode() == Instruction::SetEQ ||
1073 I.getOpcode() == Instruction::SetGE ||
1074 I.getOpcode() == Instruction::SetLE;
1077 Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
1078 bool Changed = SimplifyCommutative(I);
1079 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1080 const Type *Ty = Op0->getType();
1084 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
1086 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1087 if (isa<ConstantPointerNull>(Op1) &&
1088 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
1089 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1092 // setcc's with boolean values can always be turned into bitwise operations
1093 if (Ty == Type::BoolTy) {
1094 // If this is <, >, or !=, we can change this into a simple xor instruction
1095 if (!isTrueWhenEqual(I))
1096 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
1098 // Otherwise we need to make a temporary intermediate instruction and insert
1099 // it into the instruction stream. This is what we are after:
1101 // seteq bool %A, %B -> ~(A^B)
1102 // setle bool %A, %B -> ~A | B
1103 // setge bool %A, %B -> A | ~B
1105 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
1106 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
1108 InsertNewInstBefore(Xor, I);
1109 return BinaryOperator::createNot(Xor, I.getName());
1112 // Handle the setXe cases...
1113 assert(I.getOpcode() == Instruction::SetGE ||
1114 I.getOpcode() == Instruction::SetLE);
1116 if (I.getOpcode() == Instruction::SetGE)
1117 std::swap(Op0, Op1); // Change setge -> setle
1119 // Now we just have the SetLE case.
1120 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1121 InsertNewInstBefore(Not, I);
1122 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
1125 // Check to see if we are doing one of many comparisons against constant
1126 // integers at the end of their ranges...
1128 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1129 // Simplify seteq and setne instructions...
1130 if (I.getOpcode() == Instruction::SetEQ ||
1131 I.getOpcode() == Instruction::SetNE) {
1132 bool isSetNE = I.getOpcode() == Instruction::SetNE;
1134 // If the first operand is (and|or|xor) with a constant, and the second
1135 // operand is a constant, simplify a bit.
1136 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
1137 switch (BO->getOpcode()) {
1138 case Instruction::Add:
1139 if (CI->isNullValue()) {
1140 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1141 // efficiently invertible, or if the add has just this one use.
1142 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
1143 if (Value *NegVal = dyn_castNegVal(BOp1))
1144 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
1145 else if (Value *NegVal = dyn_castNegVal(BOp0))
1146 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
1147 else if (BO->use_size() == 1) {
1148 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
1150 InsertNewInstBefore(Neg, I);
1151 return new SetCondInst(I.getOpcode(), BOp0, Neg);
1155 case Instruction::Xor:
1156 // For the xor case, we can xor two constants together, eliminating
1157 // the explicit xor.
1158 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1159 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
1163 case Instruction::Sub:
1164 // Replace (([sub|xor] A, B) != 0) with (A != B)
1165 if (CI->isNullValue())
1166 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1170 case Instruction::Or:
1171 // If bits are being or'd in that are not present in the constant we
1172 // are comparing against, then the comparison could never succeed!
1173 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1174 if (!(*BOC & *~*CI)->isNullValue())
1175 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
1178 case Instruction::And:
1179 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1180 // If bits are being compared against that are and'd out, then the
1181 // comparison can never succeed!
1182 if (!(*CI & *~*BOC)->isNullValue())
1183 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
1185 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
1186 // to be a signed value as appropriate.
1187 if (isSignBit(BOC)) {
1188 Value *X = BO->getOperand(0);
1189 // If 'X' is not signed, insert a cast now...
1190 if (!BOC->getType()->isSigned()) {
1192 switch (BOC->getType()->getPrimitiveID()) {
1193 case Type::UByteTyID: DestTy = Type::SByteTy; break;
1194 case Type::UShortTyID: DestTy = Type::ShortTy; break;
1195 case Type::UIntTyID: DestTy = Type::IntTy; break;
1196 case Type::ULongTyID: DestTy = Type::LongTy; break;
1197 default: assert(0 && "Invalid unsigned integer type!"); abort();
1199 CastInst *NewCI = new CastInst(X,DestTy,X->getName()+".signed");
1200 InsertNewInstBefore(NewCI, I);
1203 return new SetCondInst(isSetNE ? Instruction::SetLT :
1204 Instruction::SetGE, X,
1205 Constant::getNullValue(X->getType()));
1213 // Check to see if we are comparing against the minimum or maximum value...
1214 if (CI->isMinValue()) {
1215 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1216 return ReplaceInstUsesWith(I, ConstantBool::False);
1217 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1218 return ReplaceInstUsesWith(I, ConstantBool::True);
1219 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
1220 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
1221 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
1222 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
1224 } else if (CI->isMaxValue()) {
1225 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1226 return ReplaceInstUsesWith(I, ConstantBool::False);
1227 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1228 return ReplaceInstUsesWith(I, ConstantBool::True);
1229 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
1230 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
1231 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
1232 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
1234 // Comparing against a value really close to min or max?
1235 } else if (isMinValuePlusOne(CI)) {
1236 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
1237 return BinaryOperator::create(Instruction::SetEQ, Op0,
1238 SubOne(CI), I.getName());
1239 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
1240 return BinaryOperator::create(Instruction::SetNE, Op0,
1241 SubOne(CI), I.getName());
1243 } else if (isMaxValueMinusOne(CI)) {
1244 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
1245 return BinaryOperator::create(Instruction::SetEQ, Op0,
1246 AddOne(CI), I.getName());
1247 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
1248 return BinaryOperator::create(Instruction::SetNE, Op0,
1249 AddOne(CI), I.getName());
1253 return Changed ? &I : 0;
1258 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
1259 assert(I.getOperand(1)->getType() == Type::UByteTy);
1260 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1261 bool isLeftShift = I.getOpcode() == Instruction::Shl;
1263 // shl X, 0 == X and shr X, 0 == X
1264 // shl 0, X == 0 and shr 0, X == 0
1265 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
1266 Op0 == Constant::getNullValue(Op0->getType()))
1267 return ReplaceInstUsesWith(I, Op0);
1269 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
1271 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1272 if (CSI->isAllOnesValue())
1273 return ReplaceInstUsesWith(I, CSI);
1275 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
1276 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
1277 // of a signed value.
1279 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
1280 if (CUI->getValue() >= TypeBits &&
1281 (!Op0->getType()->isSigned() || isLeftShift))
1282 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
1284 // ((X*C1) << C2) == (X * (C1 << C2))
1285 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
1286 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
1287 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
1288 return BinaryOperator::create(Instruction::Mul, BO->getOperand(0),
1292 // If the operand is an bitwise operator with a constant RHS, and the
1293 // shift is the only use, we can pull it out of the shift.
1294 if (Op0->use_size() == 1)
1295 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
1296 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
1297 bool isValid = true; // Valid only for And, Or, Xor
1298 bool highBitSet = false; // Transform if high bit of constant set?
1300 switch (Op0BO->getOpcode()) {
1301 default: isValid = false; break; // Do not perform transform!
1302 case Instruction::Or:
1303 case Instruction::Xor:
1306 case Instruction::And:
1311 // If this is a signed shift right, and the high bit is modified
1312 // by the logical operation, do not perform the transformation.
1313 // The highBitSet boolean indicates the value of the high bit of
1314 // the constant which would cause it to be modified for this
1317 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
1318 uint64_t Val = Op0C->getRawValue();
1319 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
1324 ConstantFoldShiftInstruction(I.getOpcode(), Op0C, CUI);
1326 Instruction *NewShift =
1327 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
1330 InsertNewInstBefore(NewShift, I);
1332 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
1337 // If this is a shift of a shift, see if we can fold the two together...
1338 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
1339 if (ConstantUInt *ShiftAmt1C =
1340 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
1341 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
1342 unsigned ShiftAmt2 = CUI->getValue();
1344 // Check for (A << c1) << c2 and (A >> c1) >> c2
1345 if (I.getOpcode() == Op0SI->getOpcode()) {
1346 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
1347 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
1348 ConstantUInt::get(Type::UByteTy, Amt));
1351 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
1352 // signed types, we can only support the (A >> c1) << c2 configuration,
1353 // because it can not turn an arbitrary bit of A into a sign bit.
1354 if (I.getType()->isUnsigned() || isLeftShift) {
1355 // Calculate bitmask for what gets shifted off the edge...
1356 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
1358 C = ConstantExpr::getShift(Instruction::Shl, C, ShiftAmt1C);
1360 C = ConstantExpr::getShift(Instruction::Shr, C, ShiftAmt1C);
1363 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
1364 C, Op0SI->getOperand(0)->getName()+".mask");
1365 InsertNewInstBefore(Mask, I);
1367 // Figure out what flavor of shift we should use...
1368 if (ShiftAmt1 == ShiftAmt2)
1369 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
1370 else if (ShiftAmt1 < ShiftAmt2) {
1371 return new ShiftInst(I.getOpcode(), Mask,
1372 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
1374 return new ShiftInst(Op0SI->getOpcode(), Mask,
1375 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
1385 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
1388 static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
1389 const Type *DstTy) {
1391 // It is legal to eliminate the instruction if casting A->B->A if the sizes
1392 // are identical and the bits don't get reinterpreted (for example
1393 // int->float->int would not be allowed)
1394 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
1397 // Allow free casting and conversion of sizes as long as the sign doesn't
1399 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
1400 unsigned SrcSize = SrcTy->getPrimitiveSize();
1401 unsigned MidSize = MidTy->getPrimitiveSize();
1402 unsigned DstSize = DstTy->getPrimitiveSize();
1404 // Cases where we are monotonically decreasing the size of the type are
1405 // always ok, regardless of what sign changes are going on.
1407 if (SrcSize >= MidSize && MidSize >= DstSize)
1410 // Cases where the source and destination type are the same, but the middle
1411 // type is bigger are noops.
1413 if (SrcSize == DstSize && MidSize > SrcSize)
1416 // If we are monotonically growing, things are more complex.
1418 if (SrcSize <= MidSize && MidSize <= DstSize) {
1419 // We have eight combinations of signedness to worry about. Here's the
1421 static const int SignTable[8] = {
1422 // CODE, SrcSigned, MidSigned, DstSigned, Comment
1423 1, // U U U Always ok
1424 1, // U U S Always ok
1425 3, // U S U Ok iff SrcSize != MidSize
1426 3, // U S S Ok iff SrcSize != MidSize
1427 0, // S U U Never ok
1428 2, // S U S Ok iff MidSize == DstSize
1429 1, // S S U Always ok
1430 1, // S S S Always ok
1433 // Choose an action based on the current entry of the signtable that this
1434 // cast of cast refers to...
1435 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
1436 switch (SignTable[Row]) {
1437 case 0: return false; // Never ok
1438 case 1: return true; // Always ok
1439 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
1440 case 3: // Ok iff SrcSize != MidSize
1441 return SrcSize != MidSize || SrcTy == Type::BoolTy;
1442 default: assert(0 && "Bad entry in sign table!");
1447 // Otherwise, we cannot succeed. Specifically we do not want to allow things
1448 // like: short -> ushort -> uint, because this can create wrong results if
1449 // the input short is negative!
1454 static bool ValueRequiresCast(const Value *V, const Type *Ty) {
1455 if (V->getType() == Ty || isa<Constant>(V)) return false;
1456 if (const CastInst *CI = dyn_cast<CastInst>(V))
1457 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty))
1462 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
1463 /// InsertBefore instruction. This is specialized a bit to avoid inserting
1464 /// casts that are known to not do anything...
1466 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
1467 Instruction *InsertBefore) {
1468 if (V->getType() == DestTy) return V;
1469 if (Constant *C = dyn_cast<Constant>(V))
1470 return ConstantExpr::getCast(C, DestTy);
1472 CastInst *CI = new CastInst(V, DestTy, V->getName());
1473 InsertNewInstBefore(CI, *InsertBefore);
1477 // CastInst simplification
1479 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
1480 Value *Src = CI.getOperand(0);
1482 // If the user is casting a value to the same type, eliminate this cast
1484 if (CI.getType() == Src->getType())
1485 return ReplaceInstUsesWith(CI, Src);
1487 // If casting the result of another cast instruction, try to eliminate this
1490 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
1491 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
1492 CSrc->getType(), CI.getType())) {
1493 // This instruction now refers directly to the cast's src operand. This
1494 // has a good chance of making CSrc dead.
1495 CI.setOperand(0, CSrc->getOperand(0));
1499 // If this is an A->B->A cast, and we are dealing with integral types, try
1500 // to convert this into a logical 'and' instruction.
1502 if (CSrc->getOperand(0)->getType() == CI.getType() &&
1503 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
1504 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
1505 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
1506 assert(CSrc->getType() != Type::ULongTy &&
1507 "Cannot have type bigger than ulong!");
1508 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
1509 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
1510 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
1515 // If casting the result of a getelementptr instruction with no offset, turn
1516 // this into a cast of the original pointer!
1518 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1519 bool AllZeroOperands = true;
1520 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1521 if (!isa<Constant>(GEP->getOperand(i)) ||
1522 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
1523 AllZeroOperands = false;
1526 if (AllZeroOperands) {
1527 CI.setOperand(0, GEP->getOperand(0));
1532 // If the source value is an instruction with only this use, we can attempt to
1533 // propagate the cast into the instruction. Also, only handle integral types
1535 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
1536 if (SrcI->use_size() == 1 && Src->getType()->isIntegral() &&
1537 CI.getType()->isInteger()) { // Don't mess with casts to bool here
1538 const Type *DestTy = CI.getType();
1539 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
1540 unsigned DestBitSize = getTypeSizeInBits(DestTy);
1542 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
1543 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
1545 switch (SrcI->getOpcode()) {
1546 case Instruction::Add:
1547 case Instruction::Mul:
1548 case Instruction::And:
1549 case Instruction::Or:
1550 case Instruction::Xor:
1551 // If we are discarding information, or just changing the sign, rewrite.
1552 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
1553 // Don't insert two casts if they cannot be eliminated. We allow two
1554 // casts to be inserted if the sizes are the same. This could only be
1555 // converting signedness, which is a noop.
1556 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy) ||
1557 !ValueRequiresCast(Op0, DestTy)) {
1558 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1559 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
1560 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
1561 ->getOpcode(), Op0c, Op1c);
1565 case Instruction::Shl:
1566 // Allow changing the sign of the source operand. Do not allow changing
1567 // the size of the shift, UNLESS the shift amount is a constant. We
1568 // mush not change variable sized shifts to a smaller size, because it
1569 // is undefined to shift more bits out than exist in the value.
1570 if (DestBitSize == SrcBitSize ||
1571 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
1572 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1573 return new ShiftInst(Instruction::Shl, Op0c, Op1);
1582 // CallInst simplification
1584 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
1585 return visitCallSite(&CI);
1588 // InvokeInst simplification
1590 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
1591 return visitCallSite(&II);
1594 // getPromotedType - Return the specified type promoted as it would be to pass
1595 // though a va_arg area...
1596 static const Type *getPromotedType(const Type *Ty) {
1597 switch (Ty->getPrimitiveID()) {
1598 case Type::SByteTyID:
1599 case Type::ShortTyID: return Type::IntTy;
1600 case Type::UByteTyID:
1601 case Type::UShortTyID: return Type::UIntTy;
1602 case Type::FloatTyID: return Type::DoubleTy;
1607 // visitCallSite - Improvements for call and invoke instructions.
1609 Instruction *InstCombiner::visitCallSite(CallSite CS) {
1610 bool Changed = false;
1612 // If the callee is a constexpr cast of a function, attempt to move the cast
1613 // to the arguments of the call/invoke.
1614 if (transformConstExprCastCall(CS)) return 0;
1616 Value *Callee = CS.getCalledValue();
1617 const PointerType *PTy = cast<PointerType>(Callee->getType());
1618 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
1619 if (FTy->isVarArg()) {
1620 // See if we can optimize any arguments passed through the varargs area of
1622 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
1623 E = CS.arg_end(); I != E; ++I)
1624 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
1625 // If this cast does not effect the value passed through the varargs
1626 // area, we can eliminate the use of the cast.
1627 Value *Op = CI->getOperand(0);
1628 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
1635 return Changed ? CS.getInstruction() : 0;
1638 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
1639 // attempt to move the cast to the arguments of the call/invoke.
1641 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
1642 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
1643 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
1644 if (CE->getOpcode() != Instruction::Cast ||
1645 !isa<ConstantPointerRef>(CE->getOperand(0)))
1647 ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
1648 if (!isa<Function>(CPR->getValue())) return false;
1649 Function *Callee = cast<Function>(CPR->getValue());
1650 Instruction *Caller = CS.getInstruction();
1652 // Okay, this is a cast from a function to a different type. Unless doing so
1653 // would cause a type conversion of one of our arguments, change this call to
1654 // be a direct call with arguments casted to the appropriate types.
1656 const FunctionType *FT = Callee->getFunctionType();
1657 const Type *OldRetTy = Caller->getType();
1659 if (Callee->isExternal() &&
1660 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()))
1661 return false; // Cannot transform this return value...
1663 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1664 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1666 CallSite::arg_iterator AI = CS.arg_begin();
1667 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1668 const Type *ParamTy = FT->getParamType(i);
1669 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
1670 if (Callee->isExternal() && !isConvertible) return false;
1673 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
1674 Callee->isExternal())
1675 return false; // Do not delete arguments unless we have a function body...
1677 // Okay, we decided that this is a safe thing to do: go ahead and start
1678 // inserting cast instructions as necessary...
1679 std::vector<Value*> Args;
1680 Args.reserve(NumActualArgs);
1682 AI = CS.arg_begin();
1683 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1684 const Type *ParamTy = FT->getParamType(i);
1685 if ((*AI)->getType() == ParamTy) {
1686 Args.push_back(*AI);
1688 Instruction *Cast = new CastInst(*AI, ParamTy, "tmp");
1689 InsertNewInstBefore(Cast, *Caller);
1690 Args.push_back(Cast);
1694 // If the function takes more arguments than the call was taking, add them
1696 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1697 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1699 // If we are removing arguments to the function, emit an obnoxious warning...
1700 if (FT->getNumParams() < NumActualArgs)
1701 if (!FT->isVarArg()) {
1702 std::cerr << "WARNING: While resolving call to function '"
1703 << Callee->getName() << "' arguments were dropped!\n";
1705 // Add all of the arguments in their promoted form to the arg list...
1706 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1707 const Type *PTy = getPromotedType((*AI)->getType());
1708 if (PTy != (*AI)->getType()) {
1709 // Must promote to pass through va_arg area!
1710 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
1711 InsertNewInstBefore(Cast, *Caller);
1712 Args.push_back(Cast);
1714 Args.push_back(*AI);
1719 if (FT->getReturnType() == Type::VoidTy)
1720 Caller->setName(""); // Void type should not have a name...
1723 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1724 NC = new InvokeInst(Callee, II->getNormalDest(), II->getExceptionalDest(),
1725 Args, Caller->getName(), Caller);
1727 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
1730 // Insert a cast of the return type as necessary...
1732 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
1733 if (NV->getType() != Type::VoidTy) {
1734 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
1735 InsertNewInstBefore(NC, *Caller);
1736 AddUsesToWorkList(*Caller);
1738 NV = Constant::getNullValue(Caller->getType());
1742 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
1743 Caller->replaceAllUsesWith(NV);
1744 Caller->getParent()->getInstList().erase(Caller);
1745 removeFromWorkList(Caller);
1751 // PHINode simplification
1753 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
1754 // If the PHI node only has one incoming value, eliminate the PHI node...
1755 if (PN.getNumIncomingValues() == 1)
1756 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
1758 // Otherwise if all of the incoming values are the same for the PHI, replace
1759 // the PHI node with the incoming value.
1762 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1763 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
1764 if (InVal && PN.getIncomingValue(i) != InVal)
1765 return 0; // Not the same, bail out.
1767 InVal = PN.getIncomingValue(i);
1769 // The only case that could cause InVal to be null is if we have a PHI node
1770 // that only has entries for itself. In this case, there is no entry into the
1771 // loop, so kill the PHI.
1773 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
1775 // All of the incoming values are the same, replace the PHI node now.
1776 return ReplaceInstUsesWith(PN, InVal);
1780 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1781 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
1782 // If so, eliminate the noop.
1783 if ((GEP.getNumOperands() == 2 &&
1784 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
1785 GEP.getNumOperands() == 1)
1786 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
1788 // Combine Indices - If the source pointer to this getelementptr instruction
1789 // is a getelementptr instruction, combine the indices of the two
1790 // getelementptr instructions into a single instruction.
1792 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
1793 std::vector<Value *> Indices;
1795 // Can we combine the two pointer arithmetics offsets?
1796 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
1797 isa<Constant>(GEP.getOperand(1))) {
1798 // Replace: gep (gep %P, long C1), long C2, ...
1799 // With: gep %P, long (C1+C2), ...
1800 Value *Sum = ConstantExpr::get(Instruction::Add,
1801 cast<Constant>(Src->getOperand(1)),
1802 cast<Constant>(GEP.getOperand(1)));
1803 assert(Sum && "Constant folding of longs failed!?");
1804 GEP.setOperand(0, Src->getOperand(0));
1805 GEP.setOperand(1, Sum);
1806 AddUsesToWorkList(*Src); // Reduce use count of Src
1808 } else if (Src->getNumOperands() == 2) {
1809 // Replace: gep (gep %P, long B), long A, ...
1810 // With: T = long A+B; gep %P, T, ...
1812 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
1814 Src->getName()+".sum", &GEP);
1815 GEP.setOperand(0, Src->getOperand(0));
1816 GEP.setOperand(1, Sum);
1817 WorkList.push_back(cast<Instruction>(Sum));
1819 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
1820 Src->getNumOperands() != 1) {
1821 // Otherwise we can do the fold if the first index of the GEP is a zero
1822 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
1823 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
1824 } else if (Src->getOperand(Src->getNumOperands()-1) ==
1825 Constant::getNullValue(Type::LongTy)) {
1826 // If the src gep ends with a constant array index, merge this get into
1827 // it, even if we have a non-zero array index.
1828 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
1829 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
1832 if (!Indices.empty())
1833 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
1835 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
1836 // GEP of global variable. If all of the indices for this GEP are
1837 // constants, we can promote this to a constexpr instead of an instruction.
1839 // Scan for nonconstants...
1840 std::vector<Constant*> Indices;
1841 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1842 for (; I != E && isa<Constant>(*I); ++I)
1843 Indices.push_back(cast<Constant>(*I));
1845 if (I == E) { // If they are all constants...
1847 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1849 // Replace all uses of the GEP with the new constexpr...
1850 return ReplaceInstUsesWith(GEP, CE);
1857 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1858 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1859 if (AI.isArrayAllocation()) // Check C != 1
1860 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1861 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
1862 AllocationInst *New = 0;
1864 // Create and insert the replacement instruction...
1865 if (isa<MallocInst>(AI))
1866 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
1868 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
1869 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
1872 // Scan to the end of the allocation instructions, to skip over a block of
1873 // allocas if possible...
1875 BasicBlock::iterator It = New;
1876 while (isa<AllocationInst>(*It)) ++It;
1878 // Now that I is pointing to the first non-allocation-inst in the block,
1879 // insert our getelementptr instruction...
1881 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1882 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1884 // Now make everything use the getelementptr instead of the original
1886 ReplaceInstUsesWith(AI, V);
1892 /// GetGEPGlobalInitializer - Given a constant, and a getelementptr
1893 /// constantexpr, return the constant value being addressed by the constant
1894 /// expression, or null if something is funny.
1896 static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
1897 if (CE->getOperand(1) != Constant::getNullValue(Type::LongTy))
1898 return 0; // Do not allow stepping over the value!
1900 // Loop over all of the operands, tracking down which value we are
1902 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
1903 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
1904 ConstantStruct *CS = cast<ConstantStruct>(C);
1905 if (CU->getValue() >= CS->getValues().size()) return 0;
1906 C = cast<Constant>(CS->getValues()[CU->getValue()]);
1907 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
1908 ConstantArray *CA = cast<ConstantArray>(C);
1909 if ((uint64_t)CS->getValue() >= CA->getValues().size()) return 0;
1910 C = cast<Constant>(CA->getValues()[CS->getValue()]);
1916 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
1917 Value *Op = LI.getOperand(0);
1918 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Op))
1919 Op = CPR->getValue();
1921 // Instcombine load (constant global) into the value loaded...
1922 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
1923 if (GV->isConstant() && !GV->isExternal())
1924 return ReplaceInstUsesWith(LI, GV->getInitializer());
1926 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
1927 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
1928 if (CE->getOpcode() == Instruction::GetElementPtr)
1929 if (ConstantPointerRef *G=dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
1930 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
1931 if (GV->isConstant() && !GV->isExternal())
1932 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
1933 return ReplaceInstUsesWith(LI, V);
1938 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1939 // Change br (not X), label True, label False to: br X, label False, True
1940 if (BI.isConditional() && !isa<Constant>(BI.getCondition()))
1941 if (Value *V = dyn_castNotVal(BI.getCondition())) {
1942 BasicBlock *TrueDest = BI.getSuccessor(0);
1943 BasicBlock *FalseDest = BI.getSuccessor(1);
1944 // Swap Destinations and condition...
1946 BI.setSuccessor(0, FalseDest);
1947 BI.setSuccessor(1, TrueDest);
1954 void InstCombiner::removeFromWorkList(Instruction *I) {
1955 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1959 bool InstCombiner::runOnFunction(Function &F) {
1960 bool Changed = false;
1962 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
1964 while (!WorkList.empty()) {
1965 Instruction *I = WorkList.back(); // Get an instruction from the worklist
1966 WorkList.pop_back();
1968 // Check to see if we can DCE or ConstantPropagate the instruction...
1969 // Check to see if we can DIE the instruction...
1970 if (isInstructionTriviallyDead(I)) {
1971 // Add operands to the worklist...
1972 if (I->getNumOperands() < 4)
1973 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1974 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1975 WorkList.push_back(Op);
1978 I->getParent()->getInstList().erase(I);
1979 removeFromWorkList(I);
1983 // Instruction isn't dead, see if we can constant propagate it...
1984 if (Constant *C = ConstantFoldInstruction(I)) {
1985 // Add operands to the worklist...
1986 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1987 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1988 WorkList.push_back(Op);
1989 ReplaceInstUsesWith(*I, C);
1992 I->getParent()->getInstList().erase(I);
1993 removeFromWorkList(I);
1997 // Now that we have an instruction, try combining it to simplify it...
1998 if (Instruction *Result = visit(*I)) {
2000 // Should we replace the old instruction with a new one?
2002 // Instructions can end up on the worklist more than once. Make sure
2003 // we do not process an instruction that has been deleted.
2004 removeFromWorkList(I);
2006 // Move the name to the new instruction first...
2007 std::string OldName = I->getName(); I->setName("");
2008 Result->setName(OldName);
2010 // Insert the new instruction into the basic block...
2011 BasicBlock *InstParent = I->getParent();
2012 InstParent->getInstList().insert(I, Result);
2014 // Everything uses the new instruction now...
2015 I->replaceAllUsesWith(Result);
2017 // Erase the old instruction.
2018 InstParent->getInstList().erase(I);
2020 BasicBlock::iterator II = I;
2022 // If the instruction was modified, it's possible that it is now dead.
2023 // if so, remove it.
2024 if (dceInstruction(II)) {
2025 // Instructions may end up in the worklist more than once. Erase them
2027 removeFromWorkList(I);
2033 WorkList.push_back(Result);
2034 AddUsesToWorkList(*Result);
2043 Pass *createInstructionCombiningPass() {
2044 return new InstCombiner();