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 bool transformConstExprCastCall(CallSite CS);
104 // InsertNewInstBefore - insert an instruction New before instruction Old
105 // in the program. Add the new instruction to the worklist.
107 void InsertNewInstBefore(Instruction *New, Instruction &Old) {
108 assert(New && New->getParent() == 0 &&
109 "New instruction already inserted into a basic block!");
110 BasicBlock *BB = Old.getParent();
111 BB->getInstList().insert(&Old, New); // Insert inst
112 WorkList.push_back(New); // Add to worklist
116 // ReplaceInstUsesWith - This method is to be used when an instruction is
117 // found to be dead, replacable with another preexisting expression. Here
118 // we add all uses of I to the worklist, replace all uses of I with the new
119 // value, then return I, so that the inst combiner will know that I was
122 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
123 AddUsesToWorkList(I); // Add all modified instrs to worklist
124 I.replaceAllUsesWith(V);
128 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
129 /// InsertBefore instruction. This is specialized a bit to avoid inserting
130 /// casts that are known to not do anything...
132 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
133 Instruction *InsertBefore);
135 // SimplifyCommutative - This performs a few simplifications for commutative
137 bool SimplifyCommutative(BinaryOperator &I);
139 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
140 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
143 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
146 // getComplexity: Assign a complexity or rank value to LLVM Values...
147 // 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
148 static unsigned getComplexity(Value *V) {
149 if (isa<Instruction>(V)) {
150 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
154 if (isa<Argument>(V)) return 2;
155 return isa<Constant>(V) ? 0 : 1;
158 // isOnlyUse - Return true if this instruction will be deleted if we stop using
160 static bool isOnlyUse(Value *V) {
161 return V->use_size() == 1 || isa<Constant>(V);
164 // SimplifyCommutative - This performs a few simplifications for commutative
167 // 1. Order operands such that they are listed from right (least complex) to
168 // left (most complex). This puts constants before unary operators before
171 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
172 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
174 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
175 bool Changed = false;
176 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
177 Changed = !I.swapOperands();
179 if (!I.isAssociative()) return Changed;
180 Instruction::BinaryOps Opcode = I.getOpcode();
181 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
182 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
183 if (isa<Constant>(I.getOperand(1))) {
184 Constant *Folded = ConstantExpr::get(I.getOpcode(),
185 cast<Constant>(I.getOperand(1)),
186 cast<Constant>(Op->getOperand(1)));
187 I.setOperand(0, Op->getOperand(0));
188 I.setOperand(1, Folded);
190 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
191 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
192 isOnlyUse(Op) && isOnlyUse(Op1)) {
193 Constant *C1 = cast<Constant>(Op->getOperand(1));
194 Constant *C2 = cast<Constant>(Op1->getOperand(1));
196 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
197 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
198 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
201 WorkList.push_back(New);
202 I.setOperand(0, New);
203 I.setOperand(1, Folded);
210 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
211 // if the LHS is a constant zero (which is the 'negate' form).
213 static inline Value *dyn_castNegVal(Value *V) {
214 if (BinaryOperator::isNeg(V))
215 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
217 // Constants can be considered to be negated values if they can be folded...
218 if (Constant *C = dyn_cast<Constant>(V))
219 return ConstantExpr::get(Instruction::Sub,
220 Constant::getNullValue(V->getType()), C);
224 static inline Value *dyn_castNotVal(Value *V) {
225 if (BinaryOperator::isNot(V))
226 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
228 // Constants can be considered to be not'ed values...
229 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
230 return ConstantExpr::get(Instruction::Xor,
231 ConstantIntegral::getAllOnesValue(C->getType()),C);
235 // dyn_castFoldableMul - If this value is a multiply that can be folded into
236 // other computations (because it has a constant operand), return the
237 // non-constant operand of the multiply.
239 static inline Value *dyn_castFoldableMul(Value *V) {
240 if (V->use_size() == 1 && V->getType()->isInteger())
241 if (Instruction *I = dyn_cast<Instruction>(V))
242 if (I->getOpcode() == Instruction::Mul)
243 if (isa<Constant>(I->getOperand(1)))
244 return I->getOperand(0);
248 // dyn_castMaskingAnd - If this value is an And instruction masking a value with
249 // a constant, return the constant being anded with.
251 template<class ValueType>
252 static inline Constant *dyn_castMaskingAnd(ValueType *V) {
253 if (Instruction *I = dyn_cast<Instruction>(V))
254 if (I->getOpcode() == Instruction::And)
255 return dyn_cast<Constant>(I->getOperand(1));
257 // If this is a constant, it acts just like we were masking with it.
258 return dyn_cast<Constant>(V);
261 // Log2 - Calculate the log base 2 for the specified value if it is exactly a
263 static unsigned Log2(uint64_t Val) {
264 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
267 if (Val & 1) return 0; // Multiple bits set?
275 /// AssociativeOpt - Perform an optimization on an associative operator. This
276 /// function is designed to check a chain of associative operators for a
277 /// potential to apply a certain optimization. Since the optimization may be
278 /// applicable if the expression was reassociated, this checks the chain, then
279 /// reassociates the expression as necessary to expose the optimization
280 /// opportunity. This makes use of a special Functor, which must define
281 /// 'shouldApply' and 'apply' methods.
283 template<typename Functor>
284 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
285 unsigned Opcode = Root.getOpcode();
286 Value *LHS = Root.getOperand(0);
288 // Quick check, see if the immediate LHS matches...
289 if (F.shouldApply(LHS))
290 return F.apply(Root);
292 // Otherwise, if the LHS is not of the same opcode as the root, return.
293 Instruction *LHSI = dyn_cast<Instruction>(LHS);
294 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->use_size() == 1) {
295 // Should we apply this transform to the RHS?
296 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
298 // If not to the RHS, check to see if we should apply to the LHS...
299 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
300 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
304 // If the functor wants to apply the optimization to the RHS of LHSI,
305 // reassociate the expression from ((? op A) op B) to (? op (A op B))
307 BasicBlock *BB = Root.getParent();
308 // All of the instructions have a single use and have no side-effects,
309 // because of this, we can pull them all into the current basic block.
310 if (LHSI->getParent() != BB) {
311 // Move all of the instructions from root to LHSI into the current
313 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
314 Instruction *LastUse = &Root;
315 while (TmpLHSI->getParent() == BB) {
317 TmpLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
320 // Loop over all of the instructions in other blocks, moving them into
322 Value *TmpLHS = TmpLHSI;
324 TmpLHSI = cast<Instruction>(TmpLHS);
325 // Remove from current block...
326 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
327 // Insert before the last instruction...
328 BB->getInstList().insert(LastUse, TmpLHSI);
329 TmpLHS = TmpLHSI->getOperand(0);
330 } while (TmpLHSI != LHSI);
333 // Now all of the instructions are in the current basic block, go ahead
334 // and perform the reassociation.
335 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
337 // First move the selected RHS to the LHS of the root...
338 Root.setOperand(0, LHSI->getOperand(1));
340 // Make what used to be the LHS of the root be the user of the root...
341 Value *ExtraOperand = TmpLHSI->getOperand(1);
342 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
343 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
344 BB->getInstList().remove(&Root); // Remove root from the BB
345 BB->getInstList().insert(TmpLHSI, &Root); // Insert root before TmpLHSI
347 // Now propagate the ExtraOperand down the chain of instructions until we
349 while (TmpLHSI != LHSI) {
350 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
351 Value *NextOp = NextLHSI->getOperand(1);
352 NextLHSI->setOperand(1, ExtraOperand);
354 ExtraOperand = NextOp;
357 // Now that the instructions are reassociated, have the functor perform
358 // the transformation...
359 return F.apply(Root);
362 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
368 // AddRHS - Implements: X + X --> X << 1
371 AddRHS(Value *rhs) : RHS(rhs) {}
372 bool shouldApply(Value *LHS) const { return LHS == RHS; }
373 Instruction *apply(BinaryOperator &Add) const {
374 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
375 ConstantInt::get(Type::UByteTy, 1));
379 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
381 struct AddMaskingAnd {
383 AddMaskingAnd(Constant *c) : C2(c) {}
384 bool shouldApply(Value *LHS) const {
385 if (Constant *C1 = dyn_castMaskingAnd(LHS))
386 return ConstantExpr::get(Instruction::And, C1, C2)->isNullValue();
389 Instruction *apply(BinaryOperator &Add) const {
390 return BinaryOperator::create(Instruction::Or, Add.getOperand(0),
397 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
398 bool Changed = SimplifyCommutative(I);
399 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
402 if (RHS == Constant::getNullValue(I.getType()))
403 return ReplaceInstUsesWith(I, LHS);
406 if (I.getType()->isInteger())
407 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
410 if (Value *V = dyn_castNegVal(LHS))
411 return BinaryOperator::create(Instruction::Sub, RHS, V);
414 if (!isa<Constant>(RHS))
415 if (Value *V = dyn_castNegVal(RHS))
416 return BinaryOperator::create(Instruction::Sub, LHS, V);
418 // X*C + X --> X * (C+1)
419 if (dyn_castFoldableMul(LHS) == RHS) {
421 ConstantExpr::get(Instruction::Add,
422 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
423 ConstantInt::get(I.getType(), 1));
424 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
427 // X + X*C --> X * (C+1)
428 if (dyn_castFoldableMul(RHS) == LHS) {
430 ConstantExpr::get(Instruction::Add,
431 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
432 ConstantInt::get(I.getType(), 1));
433 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
436 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
437 if (Constant *C2 = dyn_castMaskingAnd(RHS))
438 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
440 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
441 if (Instruction *ILHS = dyn_cast<Instruction>(LHS)) {
442 switch (ILHS->getOpcode()) {
443 case Instruction::Xor:
444 // ~X + C --> (C-1) - X
445 if (ConstantInt *XorRHS = dyn_cast<ConstantInt>(ILHS->getOperand(1)))
446 if (XorRHS->isAllOnesValue())
447 return BinaryOperator::create(Instruction::Sub,
448 *CRHS - *ConstantInt::get(I.getType(), 1),
449 ILHS->getOperand(0));
456 return Changed ? &I : 0;
459 // isSignBit - Return true if the value represented by the constant only has the
460 // highest order bit set.
461 static bool isSignBit(ConstantInt *CI) {
462 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
463 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
466 static unsigned getTypeSizeInBits(const Type *Ty) {
467 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
470 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
471 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
473 if (Op0 == Op1) // sub X, X -> 0
474 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
476 // If this is a 'B = x-(-A)', change to B = x+A...
477 if (Value *V = dyn_castNegVal(Op1))
478 return BinaryOperator::create(Instruction::Add, Op0, V);
480 // Replace (-1 - A) with (~A)...
481 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
482 if (C->isAllOnesValue())
483 return BinaryOperator::createNot(Op1);
485 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
486 if (Op1I->use_size() == 1) {
487 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
488 // is not used by anyone else...
490 if (Op1I->getOpcode() == Instruction::Sub) {
491 // Swap the two operands of the subexpr...
492 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
493 Op1I->setOperand(0, IIOp1);
494 Op1I->setOperand(1, IIOp0);
496 // Create the new top level add instruction...
497 return BinaryOperator::create(Instruction::Add, Op0, Op1);
500 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
502 if (Op1I->getOpcode() == Instruction::And &&
503 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
504 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
506 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
507 return BinaryOperator::create(Instruction::And, Op0, NewNot);
510 // X - X*C --> X * (1-C)
511 if (dyn_castFoldableMul(Op1I) == Op0) {
513 ConstantExpr::get(Instruction::Sub,
514 ConstantInt::get(I.getType(), 1),
515 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
516 assert(CP1 && "Couldn't constant fold 1-C?");
517 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
521 // X*C - X --> X * (C-1)
522 if (dyn_castFoldableMul(Op0) == Op1) {
524 ConstantExpr::get(Instruction::Sub,
525 cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
526 ConstantInt::get(I.getType(), 1));
527 assert(CP1 && "Couldn't constant fold C - 1?");
528 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
534 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
535 bool Changed = SimplifyCommutative(I);
536 Value *Op0 = I.getOperand(0);
538 // Simplify mul instructions with a constant RHS...
539 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
540 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
542 // ((X << C1)*C2) == (X * (C2 << C1))
543 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
544 if (SI->getOpcode() == Instruction::Shl)
545 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
546 return BinaryOperator::create(Instruction::Mul, SI->getOperand(0),
549 if (CI->isNullValue())
550 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
551 if (CI->equalsInt(1)) // X * 1 == X
552 return ReplaceInstUsesWith(I, Op0);
553 if (CI->isAllOnesValue()) // X * -1 == 0 - X
554 return BinaryOperator::createNeg(Op0, I.getName());
556 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
557 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
558 return new ShiftInst(Instruction::Shl, Op0,
559 ConstantUInt::get(Type::UByteTy, C));
561 ConstantFP *Op1F = cast<ConstantFP>(Op1);
562 if (Op1F->isNullValue())
563 return ReplaceInstUsesWith(I, Op1);
565 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
566 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
567 if (Op1F->getValue() == 1.0)
568 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
572 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
573 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
574 return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
576 return Changed ? &I : 0;
579 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
581 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
582 if (RHS->equalsInt(1))
583 return ReplaceInstUsesWith(I, I.getOperand(0));
585 // Check to see if this is an unsigned division with an exact power of 2,
586 // if so, convert to a right shift.
587 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
588 if (uint64_t Val = C->getValue()) // Don't break X / 0
589 if (uint64_t C = Log2(Val))
590 return new ShiftInst(Instruction::Shr, I.getOperand(0),
591 ConstantUInt::get(Type::UByteTy, C));
594 // 0 / X == 0, we don't need to preserve faults!
595 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
596 if (LHS->equalsInt(0))
597 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
603 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
604 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
605 if (RHS->equalsInt(1)) // X % 1 == 0
606 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
608 // Check to see if this is an unsigned remainder with an exact power of 2,
609 // if so, convert to a bitwise and.
610 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
611 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
613 return BinaryOperator::create(Instruction::And, I.getOperand(0),
614 ConstantUInt::get(I.getType(), Val-1));
617 // 0 % X == 0, we don't need to preserve faults!
618 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
619 if (LHS->equalsInt(0))
620 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
625 // isMaxValueMinusOne - return true if this is Max-1
626 static bool isMaxValueMinusOne(const ConstantInt *C) {
627 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
628 // Calculate -1 casted to the right type...
629 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
630 uint64_t Val = ~0ULL; // All ones
631 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
632 return CU->getValue() == Val-1;
635 const ConstantSInt *CS = cast<ConstantSInt>(C);
637 // Calculate 0111111111..11111
638 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
639 int64_t Val = INT64_MAX; // All ones
640 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
641 return CS->getValue() == Val-1;
644 // isMinValuePlusOne - return true if this is Min+1
645 static bool isMinValuePlusOne(const ConstantInt *C) {
646 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
647 return CU->getValue() == 1;
649 const ConstantSInt *CS = cast<ConstantSInt>(C);
651 // Calculate 1111111111000000000000
652 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
653 int64_t Val = -1; // All ones
654 Val <<= TypeBits-1; // Shift over to the right spot
655 return CS->getValue() == Val+1;
658 /// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
659 /// are carefully arranged to allow folding of expressions such as:
661 /// (A < B) | (A > B) --> (A != B)
663 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
664 /// represents that the comparison is true if A == B, and bit value '1' is true
667 static unsigned getSetCondCode(const SetCondInst *SCI) {
668 switch (SCI->getOpcode()) {
670 case Instruction::SetGT: return 1;
671 case Instruction::SetEQ: return 2;
672 case Instruction::SetGE: return 3;
673 case Instruction::SetLT: return 4;
674 case Instruction::SetNE: return 5;
675 case Instruction::SetLE: return 6;
678 assert(0 && "Invalid SetCC opcode!");
683 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
684 /// opcode and two operands into either a constant true or false, or a brand new
685 /// SetCC instruction.
686 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
688 case 0: return ConstantBool::False;
689 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
690 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
691 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
692 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
693 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
694 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
695 case 7: return ConstantBool::True;
696 default: assert(0 && "Illegal SetCCCode!"); return 0;
700 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
701 struct FoldSetCCLogical {
704 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
705 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
706 bool shouldApply(Value *V) const {
707 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
708 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
709 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
712 Instruction *apply(BinaryOperator &Log) const {
713 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
714 if (SCI->getOperand(0) != LHS) {
715 assert(SCI->getOperand(1) == LHS);
716 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
719 unsigned LHSCode = getSetCondCode(SCI);
720 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
722 switch (Log.getOpcode()) {
723 case Instruction::And: Code = LHSCode & RHSCode; break;
724 case Instruction::Or: Code = LHSCode | RHSCode; break;
725 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
726 default: assert(0 && "Illegal logical opcode!"); return 0;
729 Value *RV = getSetCCValue(Code, LHS, RHS);
730 if (Instruction *I = dyn_cast<Instruction>(RV))
732 // Otherwise, it's a constant boolean value...
733 return IC.ReplaceInstUsesWith(Log, RV);
738 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
739 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
740 // guaranteed to be either a shift instruction or a binary operator.
741 Instruction *InstCombiner::OptAndOp(Instruction *Op,
742 ConstantIntegral *OpRHS,
743 ConstantIntegral *AndRHS,
744 BinaryOperator &TheAnd) {
745 Value *X = Op->getOperand(0);
746 switch (Op->getOpcode()) {
747 case Instruction::Xor:
748 if ((*AndRHS & *OpRHS)->isNullValue()) {
749 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
750 return BinaryOperator::create(Instruction::And, X, AndRHS);
751 } else if (Op->use_size() == 1) {
752 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
753 std::string OpName = Op->getName(); Op->setName("");
754 Instruction *And = BinaryOperator::create(Instruction::And,
756 InsertNewInstBefore(And, TheAnd);
757 return BinaryOperator::create(Instruction::Xor, And, *AndRHS & *OpRHS);
760 case Instruction::Or:
761 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
762 if ((*AndRHS & *OpRHS)->isNullValue())
763 return BinaryOperator::create(Instruction::And, X, AndRHS);
765 Constant *Together = *AndRHS & *OpRHS;
766 if (Together == AndRHS) // (X | C) & C --> C
767 return ReplaceInstUsesWith(TheAnd, AndRHS);
769 if (Op->use_size() == 1 && Together != OpRHS) {
770 // (X | C1) & C2 --> (X | (C1&C2)) & C2
771 std::string Op0Name = Op->getName(); Op->setName("");
772 Instruction *Or = BinaryOperator::create(Instruction::Or, X,
774 InsertNewInstBefore(Or, TheAnd);
775 return BinaryOperator::create(Instruction::And, Or, AndRHS);
779 case Instruction::Add:
780 if (Op->use_size() == 1) {
781 // Adding a one to a single bit bit-field should be turned into an XOR
782 // of the bit. First thing to check is to see if this AND is with a
783 // single bit constant.
784 unsigned long long AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
786 // Clear bits that are not part of the constant.
787 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
789 // If there is only one bit set...
790 if ((AndRHSV & (AndRHSV-1)) == 0) {
791 // Ok, at this point, we know that we are masking the result of the
792 // ADD down to exactly one bit. If the constant we are adding has
793 // no bits set below this bit, then we can eliminate the ADD.
794 unsigned long long AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
796 // Check to see if any bits below the one bit set in AndRHSV are set.
797 if ((AddRHS & (AndRHSV-1)) == 0) {
798 // If not, the only thing that can effect the output of the AND is
799 // the bit specified by AndRHSV. If that bit is set, the effect of
800 // the XOR is to toggle the bit. If it is clear, then the ADD has
802 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
803 TheAnd.setOperand(0, X);
806 std::string Name = Op->getName(); Op->setName("");
807 // Pull the XOR out of the AND.
808 Instruction *NewAnd =
809 BinaryOperator::create(Instruction::And, X, AndRHS, Name);
810 InsertNewInstBefore(NewAnd, TheAnd);
811 return BinaryOperator::create(Instruction::Xor, NewAnd, AndRHS);
818 case Instruction::Shl: {
819 // We know that the AND will not produce any of the bits shifted in, so if
820 // the anded constant includes them, clear them now!
822 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
823 Constant *CI = *AndRHS & *(*AllOne << *OpRHS);
825 TheAnd.setOperand(1, CI);
830 case Instruction::Shr:
831 // We know that the AND will not produce any of the bits shifted in, so if
832 // the anded constant includes them, clear them now! This only applies to
833 // unsigned shifts, because a signed shr may bring in set bits!
835 if (AndRHS->getType()->isUnsigned()) {
836 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
837 Constant *CI = *AndRHS & *(*AllOne >> *OpRHS);
839 TheAnd.setOperand(1, CI);
849 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
850 bool Changed = SimplifyCommutative(I);
851 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
853 // and X, X = X and X, 0 == 0
854 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
855 return ReplaceInstUsesWith(I, Op1);
858 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
859 if (RHS->isAllOnesValue())
860 return ReplaceInstUsesWith(I, Op0);
862 // Optimize a variety of ((val OP C1) & C2) combinations...
863 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
864 Instruction *Op0I = cast<Instruction>(Op0);
865 Value *X = Op0I->getOperand(0);
866 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
867 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
872 Value *Op0NotVal = dyn_castNotVal(Op0);
873 Value *Op1NotVal = dyn_castNotVal(Op1);
875 // (~A & ~B) == (~(A | B)) - Demorgan's Law
876 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
877 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
878 Op1NotVal,I.getName()+".demorgan");
879 InsertNewInstBefore(Or, I);
880 return BinaryOperator::createNot(Or);
883 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
884 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
886 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
887 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
888 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
891 return Changed ? &I : 0;
896 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
897 bool Changed = SimplifyCommutative(I);
898 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
900 // or X, X = X or X, 0 == X
901 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
902 return ReplaceInstUsesWith(I, Op0);
905 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
906 if (RHS->isAllOnesValue())
907 return ReplaceInstUsesWith(I, Op1);
909 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
910 // (X & C1) | C2 --> (X | C2) & (C1|C2)
911 if (Op0I->getOpcode() == Instruction::And && isOnlyUse(Op0))
912 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
913 std::string Op0Name = Op0I->getName(); Op0I->setName("");
914 Instruction *Or = BinaryOperator::create(Instruction::Or,
915 Op0I->getOperand(0), RHS,
917 InsertNewInstBefore(Or, I);
918 return BinaryOperator::create(Instruction::And, Or, *RHS | *Op0CI);
921 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
922 if (Op0I->getOpcode() == Instruction::Xor && isOnlyUse(Op0))
923 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
924 std::string Op0Name = Op0I->getName(); Op0I->setName("");
925 Instruction *Or = BinaryOperator::create(Instruction::Or,
926 Op0I->getOperand(0), RHS,
928 InsertNewInstBefore(Or, I);
929 return BinaryOperator::create(Instruction::Xor, Or, *Op0CI & *~*RHS);
934 // (A & C1)|(A & C2) == A & (C1|C2)
935 if (Instruction *LHS = dyn_cast<BinaryOperator>(Op0))
936 if (Instruction *RHS = dyn_cast<BinaryOperator>(Op1))
937 if (LHS->getOperand(0) == RHS->getOperand(0))
938 if (Constant *C0 = dyn_castMaskingAnd(LHS))
939 if (Constant *C1 = dyn_castMaskingAnd(RHS))
940 return BinaryOperator::create(Instruction::And, LHS->getOperand(0),
943 Value *Op0NotVal = dyn_castNotVal(Op0);
944 Value *Op1NotVal = dyn_castNotVal(Op1);
946 if (Op1 == Op0NotVal) // ~A | A == -1
947 return ReplaceInstUsesWith(I,
948 ConstantIntegral::getAllOnesValue(I.getType()));
950 if (Op0 == Op1NotVal) // A | ~A == -1
951 return ReplaceInstUsesWith(I,
952 ConstantIntegral::getAllOnesValue(I.getType()));
954 // (~A | ~B) == (~(A & B)) - Demorgan's Law
955 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
956 Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
957 Op1NotVal,I.getName()+".demorgan",
959 WorkList.push_back(And);
960 return BinaryOperator::createNot(And);
963 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
964 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
965 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
968 return Changed ? &I : 0;
973 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
974 bool Changed = SimplifyCommutative(I);
975 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
979 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
981 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
983 if (RHS->isNullValue())
984 return ReplaceInstUsesWith(I, Op0);
986 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
987 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
988 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
989 if (RHS == ConstantBool::True && SCI->use_size() == 1)
990 return new SetCondInst(SCI->getInverseCondition(),
991 SCI->getOperand(0), SCI->getOperand(1));
993 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
994 if (Op0I->getOpcode() == Instruction::And) {
995 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
996 if ((*RHS & *Op0CI)->isNullValue())
997 return BinaryOperator::create(Instruction::Or, Op0, RHS);
998 } else if (Op0I->getOpcode() == Instruction::Or) {
999 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1000 if ((*RHS & *Op0CI) == RHS)
1001 return BinaryOperator::create(Instruction::And, Op0, ~*RHS);
1006 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
1008 return ReplaceInstUsesWith(I,
1009 ConstantIntegral::getAllOnesValue(I.getType()));
1011 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
1013 return ReplaceInstUsesWith(I,
1014 ConstantIntegral::getAllOnesValue(I.getType()));
1016 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
1017 if (Op1I->getOpcode() == Instruction::Or)
1018 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1019 cast<BinaryOperator>(Op1I)->swapOperands();
1021 std::swap(Op0, Op1);
1022 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1024 std::swap(Op0, Op1);
1027 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
1028 if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
1029 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1030 cast<BinaryOperator>(Op0I)->swapOperands();
1031 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
1032 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
1033 WorkList.push_back(cast<Instruction>(NotB));
1034 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
1039 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
1040 if (Constant *C1 = dyn_castMaskingAnd(Op0))
1041 if (Constant *C2 = dyn_castMaskingAnd(Op1))
1042 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
1043 return BinaryOperator::create(Instruction::Or, Op0, Op1);
1045 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1046 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1047 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1050 return Changed ? &I : 0;
1053 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
1054 static Constant *AddOne(ConstantInt *C) {
1055 Constant *Result = ConstantExpr::get(Instruction::Add, C,
1056 ConstantInt::get(C->getType(), 1));
1057 assert(Result && "Constant folding integer addition failed!");
1060 static Constant *SubOne(ConstantInt *C) {
1061 Constant *Result = ConstantExpr::get(Instruction::Sub, C,
1062 ConstantInt::get(C->getType(), 1));
1063 assert(Result && "Constant folding integer addition failed!");
1067 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
1068 // true when both operands are equal...
1070 static bool isTrueWhenEqual(Instruction &I) {
1071 return I.getOpcode() == Instruction::SetEQ ||
1072 I.getOpcode() == Instruction::SetGE ||
1073 I.getOpcode() == Instruction::SetLE;
1076 Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
1077 bool Changed = SimplifyCommutative(I);
1078 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1079 const Type *Ty = Op0->getType();
1083 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
1085 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1086 if (isa<ConstantPointerNull>(Op1) &&
1087 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
1088 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1091 // setcc's with boolean values can always be turned into bitwise operations
1092 if (Ty == Type::BoolTy) {
1093 // If this is <, >, or !=, we can change this into a simple xor instruction
1094 if (!isTrueWhenEqual(I))
1095 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
1097 // Otherwise we need to make a temporary intermediate instruction and insert
1098 // it into the instruction stream. This is what we are after:
1100 // seteq bool %A, %B -> ~(A^B)
1101 // setle bool %A, %B -> ~A | B
1102 // setge bool %A, %B -> A | ~B
1104 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
1105 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
1107 InsertNewInstBefore(Xor, I);
1108 return BinaryOperator::createNot(Xor, I.getName());
1111 // Handle the setXe cases...
1112 assert(I.getOpcode() == Instruction::SetGE ||
1113 I.getOpcode() == Instruction::SetLE);
1115 if (I.getOpcode() == Instruction::SetGE)
1116 std::swap(Op0, Op1); // Change setge -> setle
1118 // Now we just have the SetLE case.
1119 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1120 InsertNewInstBefore(Not, I);
1121 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
1124 // Check to see if we are doing one of many comparisons against constant
1125 // integers at the end of their ranges...
1127 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1128 // Simplify seteq and setne instructions...
1129 if (I.getOpcode() == Instruction::SetEQ ||
1130 I.getOpcode() == Instruction::SetNE) {
1131 bool isSetNE = I.getOpcode() == Instruction::SetNE;
1133 // If the first operand is (and|or|xor) with a constant, and the second
1134 // operand is a constant, simplify a bit.
1135 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
1136 switch (BO->getOpcode()) {
1137 case Instruction::Add:
1138 if (CI->isNullValue()) {
1139 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1140 // efficiently invertible, or if the add has just this one use.
1141 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
1142 if (Value *NegVal = dyn_castNegVal(BOp1))
1143 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
1144 else if (Value *NegVal = dyn_castNegVal(BOp0))
1145 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
1146 else if (BO->use_size() == 1) {
1147 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
1149 InsertNewInstBefore(Neg, I);
1150 return new SetCondInst(I.getOpcode(), BOp0, Neg);
1154 case Instruction::Xor:
1155 // For the xor case, we can xor two constants together, eliminating
1156 // the explicit xor.
1157 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1158 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
1162 case Instruction::Sub:
1163 // Replace (([sub|xor] A, B) != 0) with (A != B)
1164 if (CI->isNullValue())
1165 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1169 case Instruction::Or:
1170 // If bits are being or'd in that are not present in the constant we
1171 // are comparing against, then the comparison could never succeed!
1172 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1173 if (!(*BOC & *~*CI)->isNullValue())
1174 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
1177 case Instruction::And:
1178 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1179 // If bits are being compared against that are and'd out, then the
1180 // comparison can never succeed!
1181 if (!(*CI & *~*BOC)->isNullValue())
1182 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
1184 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
1185 // to be a signed value as appropriate.
1186 if (isSignBit(BOC)) {
1187 Value *X = BO->getOperand(0);
1188 // If 'X' is not signed, insert a cast now...
1189 if (!BOC->getType()->isSigned()) {
1191 switch (BOC->getType()->getPrimitiveID()) {
1192 case Type::UByteTyID: DestTy = Type::SByteTy; break;
1193 case Type::UShortTyID: DestTy = Type::ShortTy; break;
1194 case Type::UIntTyID: DestTy = Type::IntTy; break;
1195 case Type::ULongTyID: DestTy = Type::LongTy; break;
1196 default: assert(0 && "Invalid unsigned integer type!"); abort();
1198 CastInst *NewCI = new CastInst(X,DestTy,X->getName()+".signed");
1199 InsertNewInstBefore(NewCI, I);
1202 return new SetCondInst(isSetNE ? Instruction::SetLT :
1203 Instruction::SetGE, X,
1204 Constant::getNullValue(X->getType()));
1212 // Check to see if we are comparing against the minimum or maximum value...
1213 if (CI->isMinValue()) {
1214 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1215 return ReplaceInstUsesWith(I, ConstantBool::False);
1216 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1217 return ReplaceInstUsesWith(I, ConstantBool::True);
1218 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
1219 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
1220 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
1221 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
1223 } else if (CI->isMaxValue()) {
1224 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1225 return ReplaceInstUsesWith(I, ConstantBool::False);
1226 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1227 return ReplaceInstUsesWith(I, ConstantBool::True);
1228 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
1229 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
1230 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
1231 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
1233 // Comparing against a value really close to min or max?
1234 } else if (isMinValuePlusOne(CI)) {
1235 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
1236 return BinaryOperator::create(Instruction::SetEQ, Op0,
1237 SubOne(CI), I.getName());
1238 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
1239 return BinaryOperator::create(Instruction::SetNE, Op0,
1240 SubOne(CI), I.getName());
1242 } else if (isMaxValueMinusOne(CI)) {
1243 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
1244 return BinaryOperator::create(Instruction::SetEQ, Op0,
1245 AddOne(CI), I.getName());
1246 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
1247 return BinaryOperator::create(Instruction::SetNE, Op0,
1248 AddOne(CI), I.getName());
1252 return Changed ? &I : 0;
1257 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
1258 assert(I.getOperand(1)->getType() == Type::UByteTy);
1259 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1260 bool isLeftShift = I.getOpcode() == Instruction::Shl;
1262 // shl X, 0 == X and shr X, 0 == X
1263 // shl 0, X == 0 and shr 0, X == 0
1264 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
1265 Op0 == Constant::getNullValue(Op0->getType()))
1266 return ReplaceInstUsesWith(I, Op0);
1268 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
1270 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1271 if (CSI->isAllOnesValue())
1272 return ReplaceInstUsesWith(I, CSI);
1274 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
1275 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
1276 // of a signed value.
1278 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
1279 if (CUI->getValue() >= TypeBits &&
1280 (!Op0->getType()->isSigned() || isLeftShift))
1281 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
1283 // ((X*C1) << C2) == (X * (C1 << C2))
1284 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
1285 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
1286 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
1287 return BinaryOperator::create(Instruction::Mul, BO->getOperand(0),
1291 // If the operand is an bitwise operator with a constant RHS, and the
1292 // shift is the only use, we can pull it out of the shift.
1293 if (Op0->use_size() == 1)
1294 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
1295 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
1296 bool isValid = true; // Valid only for And, Or, Xor
1297 bool highBitSet = false; // Transform if high bit of constant set?
1299 switch (Op0BO->getOpcode()) {
1300 default: isValid = false; break; // Do not perform transform!
1301 case Instruction::Or:
1302 case Instruction::Xor:
1305 case Instruction::And:
1310 // If this is a signed shift right, and the high bit is modified
1311 // by the logical operation, do not perform the transformation.
1312 // The highBitSet boolean indicates the value of the high bit of
1313 // the constant which would cause it to be modified for this
1316 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
1317 uint64_t Val = Op0C->getRawValue();
1318 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
1323 ConstantFoldShiftInstruction(I.getOpcode(), Op0C, CUI);
1325 Instruction *NewShift =
1326 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
1329 InsertNewInstBefore(NewShift, I);
1331 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
1336 // If this is a shift of a shift, see if we can fold the two together...
1337 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
1338 if (ConstantUInt *ShiftAmt1C =
1339 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
1340 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
1341 unsigned ShiftAmt2 = CUI->getValue();
1343 // Check for (A << c1) << c2 and (A >> c1) >> c2
1344 if (I.getOpcode() == Op0SI->getOpcode()) {
1345 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
1346 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
1347 ConstantUInt::get(Type::UByteTy, Amt));
1350 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
1351 // signed types, we can only support the (A >> c1) << c2 configuration,
1352 // because it can not turn an arbitrary bit of A into a sign bit.
1353 if (I.getType()->isUnsigned() || isLeftShift) {
1354 // Calculate bitmask for what gets shifted off the edge...
1355 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
1357 C = ConstantExpr::getShift(Instruction::Shl, C, ShiftAmt1C);
1359 C = ConstantExpr::getShift(Instruction::Shr, C, ShiftAmt1C);
1362 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
1363 C, Op0SI->getOperand(0)->getName()+".mask");
1364 InsertNewInstBefore(Mask, I);
1366 // Figure out what flavor of shift we should use...
1367 if (ShiftAmt1 == ShiftAmt2)
1368 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
1369 else if (ShiftAmt1 < ShiftAmt2) {
1370 return new ShiftInst(I.getOpcode(), Mask,
1371 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
1373 return new ShiftInst(Op0SI->getOpcode(), Mask,
1374 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
1384 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
1387 static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
1388 const Type *DstTy) {
1390 // It is legal to eliminate the instruction if casting A->B->A if the sizes
1391 // are identical and the bits don't get reinterpreted (for example
1392 // int->float->int would not be allowed)
1393 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
1396 // Allow free casting and conversion of sizes as long as the sign doesn't
1398 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
1399 unsigned SrcSize = SrcTy->getPrimitiveSize();
1400 unsigned MidSize = MidTy->getPrimitiveSize();
1401 unsigned DstSize = DstTy->getPrimitiveSize();
1403 // Cases where we are monotonically decreasing the size of the type are
1404 // always ok, regardless of what sign changes are going on.
1406 if (SrcSize >= MidSize && MidSize >= DstSize)
1409 // Cases where the source and destination type are the same, but the middle
1410 // type is bigger are noops.
1412 if (SrcSize == DstSize && MidSize > SrcSize)
1415 // If we are monotonically growing, things are more complex.
1417 if (SrcSize <= MidSize && MidSize <= DstSize) {
1418 // We have eight combinations of signedness to worry about. Here's the
1420 static const int SignTable[8] = {
1421 // CODE, SrcSigned, MidSigned, DstSigned, Comment
1422 1, // U U U Always ok
1423 1, // U U S Always ok
1424 3, // U S U Ok iff SrcSize != MidSize
1425 3, // U S S Ok iff SrcSize != MidSize
1426 0, // S U U Never ok
1427 2, // S U S Ok iff MidSize == DstSize
1428 1, // S S U Always ok
1429 1, // S S S Always ok
1432 // Choose an action based on the current entry of the signtable that this
1433 // cast of cast refers to...
1434 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
1435 switch (SignTable[Row]) {
1436 case 0: return false; // Never ok
1437 case 1: return true; // Always ok
1438 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
1439 case 3: // Ok iff SrcSize != MidSize
1440 return SrcSize != MidSize || SrcTy == Type::BoolTy;
1441 default: assert(0 && "Bad entry in sign table!");
1446 // Otherwise, we cannot succeed. Specifically we do not want to allow things
1447 // like: short -> ushort -> uint, because this can create wrong results if
1448 // the input short is negative!
1453 static bool ValueRequiresCast(const Value *V, const Type *Ty) {
1454 if (V->getType() == Ty || isa<Constant>(V)) return false;
1455 if (const CastInst *CI = dyn_cast<CastInst>(V))
1456 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty))
1461 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
1462 /// InsertBefore instruction. This is specialized a bit to avoid inserting
1463 /// casts that are known to not do anything...
1465 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
1466 Instruction *InsertBefore) {
1467 if (V->getType() == DestTy) return V;
1468 if (Constant *C = dyn_cast<Constant>(V))
1469 return ConstantExpr::getCast(C, DestTy);
1471 CastInst *CI = new CastInst(V, DestTy, V->getName());
1472 InsertNewInstBefore(CI, *InsertBefore);
1476 // CastInst simplification
1478 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
1479 Value *Src = CI.getOperand(0);
1481 // If the user is casting a value to the same type, eliminate this cast
1483 if (CI.getType() == Src->getType())
1484 return ReplaceInstUsesWith(CI, Src);
1486 // If casting the result of another cast instruction, try to eliminate this
1489 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
1490 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
1491 CSrc->getType(), CI.getType())) {
1492 // This instruction now refers directly to the cast's src operand. This
1493 // has a good chance of making CSrc dead.
1494 CI.setOperand(0, CSrc->getOperand(0));
1498 // If this is an A->B->A cast, and we are dealing with integral types, try
1499 // to convert this into a logical 'and' instruction.
1501 if (CSrc->getOperand(0)->getType() == CI.getType() &&
1502 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
1503 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
1504 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
1505 assert(CSrc->getType() != Type::ULongTy &&
1506 "Cannot have type bigger than ulong!");
1507 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
1508 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
1509 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
1514 // If casting the result of a getelementptr instruction with no offset, turn
1515 // this into a cast of the original pointer!
1517 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1518 bool AllZeroOperands = true;
1519 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1520 if (!isa<Constant>(GEP->getOperand(i)) ||
1521 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
1522 AllZeroOperands = false;
1525 if (AllZeroOperands) {
1526 CI.setOperand(0, GEP->getOperand(0));
1531 // If the source value is an instruction with only this use, we can attempt to
1532 // propagate the cast into the instruction. Also, only handle integral types
1534 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
1535 if (SrcI->use_size() == 1 && Src->getType()->isIntegral() &&
1536 CI.getType()->isInteger()) { // Don't mess with casts to bool here
1537 const Type *DestTy = CI.getType();
1538 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
1539 unsigned DestBitSize = getTypeSizeInBits(DestTy);
1541 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
1542 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
1544 switch (SrcI->getOpcode()) {
1545 case Instruction::Add:
1546 case Instruction::Mul:
1547 case Instruction::And:
1548 case Instruction::Or:
1549 case Instruction::Xor:
1550 // If we are discarding information, or just changing the sign, rewrite.
1551 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
1552 // Don't insert two casts if they cannot be eliminated. We allow two
1553 // casts to be inserted if the sizes are the same. This could only be
1554 // converting signedness, which is a noop.
1555 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy) ||
1556 !ValueRequiresCast(Op0, DestTy)) {
1557 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1558 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
1559 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
1560 ->getOpcode(), Op0c, Op1c);
1564 case Instruction::Shl:
1565 // Allow changing the sign of the source operand. Do not allow changing
1566 // the size of the shift, UNLESS the shift amount is a constant. We
1567 // mush not change variable sized shifts to a smaller size, because it
1568 // is undefined to shift more bits out than exist in the value.
1569 if (DestBitSize == SrcBitSize ||
1570 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
1571 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1572 return new ShiftInst(Instruction::Shl, Op0c, Op1);
1581 // CallInst simplification
1583 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
1584 if (transformConstExprCastCall(&CI)) return 0;
1588 // InvokeInst simplification
1590 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
1591 if (transformConstExprCastCall(&II)) return 0;
1595 // getPromotedType - Return the specified type promoted as it would be to pass
1596 // though a va_arg area...
1597 static const Type *getPromotedType(const Type *Ty) {
1598 switch (Ty->getPrimitiveID()) {
1599 case Type::SByteTyID:
1600 case Type::ShortTyID: return Type::IntTy;
1601 case Type::UByteTyID:
1602 case Type::UShortTyID: return Type::UIntTy;
1603 case Type::FloatTyID: return Type::DoubleTy;
1608 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
1609 // attempt to move the cast to the arguments of the call/invoke.
1611 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
1612 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
1613 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
1614 if (CE->getOpcode() != Instruction::Cast ||
1615 !isa<ConstantPointerRef>(CE->getOperand(0)))
1617 ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
1618 if (!isa<Function>(CPR->getValue())) return false;
1619 Function *Callee = cast<Function>(CPR->getValue());
1620 Instruction *Caller = CS.getInstruction();
1622 // Okay, this is a cast from a function to a different type. Unless doing so
1623 // would cause a type conversion of one of our arguments, change this call to
1624 // be a direct call with arguments casted to the appropriate types.
1626 const FunctionType *FT = Callee->getFunctionType();
1627 const Type *OldRetTy = Caller->getType();
1629 if (Callee->isExternal() &&
1630 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()))
1631 return false; // Cannot transform this return value...
1633 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1634 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1636 CallSite::arg_iterator AI = CS.arg_begin();
1637 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1638 const Type *ParamTy = FT->getParamType(i);
1639 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
1640 if (Callee->isExternal() && !isConvertible) return false;
1643 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
1644 Callee->isExternal())
1645 return false; // Do not delete arguments unless we have a function body...
1647 // Okay, we decided that this is a safe thing to do: go ahead and start
1648 // inserting cast instructions as necessary...
1649 std::vector<Value*> Args;
1650 Args.reserve(NumActualArgs);
1652 AI = CS.arg_begin();
1653 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1654 const Type *ParamTy = FT->getParamType(i);
1655 if ((*AI)->getType() == ParamTy) {
1656 Args.push_back(*AI);
1658 Instruction *Cast = new CastInst(*AI, ParamTy, "tmp");
1659 InsertNewInstBefore(Cast, *Caller);
1660 Args.push_back(Cast);
1664 // If the function takes more arguments than the call was taking, add them
1666 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1667 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1669 // If we are removing arguments to the function, emit an obnoxious warning...
1670 if (FT->getNumParams() < NumActualArgs)
1671 if (!FT->isVarArg()) {
1672 std::cerr << "WARNING: While resolving call to function '"
1673 << Callee->getName() << "' arguments were dropped!\n";
1675 // Add all of the arguments in their promoted form to the arg list...
1676 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1677 const Type *PTy = getPromotedType((*AI)->getType());
1678 if (PTy != (*AI)->getType()) {
1679 // Must promote to pass through va_arg area!
1680 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
1681 InsertNewInstBefore(Cast, *Caller);
1682 Args.push_back(Cast);
1684 Args.push_back(*AI);
1689 if (FT->getReturnType() == Type::VoidTy)
1690 Caller->setName(""); // Void type should not have a name...
1693 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1694 NC = new InvokeInst(Callee, II->getNormalDest(), II->getExceptionalDest(),
1695 Args, Caller->getName(), Caller);
1697 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
1700 // Insert a cast of the return type as necessary...
1702 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
1703 if (NV->getType() != Type::VoidTy) {
1704 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
1705 InsertNewInstBefore(NC, *Caller);
1706 AddUsesToWorkList(*Caller);
1708 NV = Constant::getNullValue(Caller->getType());
1712 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
1713 Caller->replaceAllUsesWith(NV);
1714 Caller->getParent()->getInstList().erase(Caller);
1715 removeFromWorkList(Caller);
1721 // PHINode simplification
1723 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
1724 // If the PHI node only has one incoming value, eliminate the PHI node...
1725 if (PN.getNumIncomingValues() == 1)
1726 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
1728 // Otherwise if all of the incoming values are the same for the PHI, replace
1729 // the PHI node with the incoming value.
1732 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1733 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
1734 if (InVal && PN.getIncomingValue(i) != InVal)
1735 return 0; // Not the same, bail out.
1737 InVal = PN.getIncomingValue(i);
1739 // The only case that could cause InVal to be null is if we have a PHI node
1740 // that only has entries for itself. In this case, there is no entry into the
1741 // loop, so kill the PHI.
1743 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
1745 // All of the incoming values are the same, replace the PHI node now.
1746 return ReplaceInstUsesWith(PN, InVal);
1750 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1751 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
1752 // If so, eliminate the noop.
1753 if ((GEP.getNumOperands() == 2 &&
1754 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
1755 GEP.getNumOperands() == 1)
1756 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
1758 // Combine Indices - If the source pointer to this getelementptr instruction
1759 // is a getelementptr instruction, combine the indices of the two
1760 // getelementptr instructions into a single instruction.
1762 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
1763 std::vector<Value *> Indices;
1765 // Can we combine the two pointer arithmetics offsets?
1766 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
1767 isa<Constant>(GEP.getOperand(1))) {
1768 // Replace: gep (gep %P, long C1), long C2, ...
1769 // With: gep %P, long (C1+C2), ...
1770 Value *Sum = ConstantExpr::get(Instruction::Add,
1771 cast<Constant>(Src->getOperand(1)),
1772 cast<Constant>(GEP.getOperand(1)));
1773 assert(Sum && "Constant folding of longs failed!?");
1774 GEP.setOperand(0, Src->getOperand(0));
1775 GEP.setOperand(1, Sum);
1776 AddUsesToWorkList(*Src); // Reduce use count of Src
1778 } else if (Src->getNumOperands() == 2) {
1779 // Replace: gep (gep %P, long B), long A, ...
1780 // With: T = long A+B; gep %P, T, ...
1782 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
1784 Src->getName()+".sum", &GEP);
1785 GEP.setOperand(0, Src->getOperand(0));
1786 GEP.setOperand(1, Sum);
1787 WorkList.push_back(cast<Instruction>(Sum));
1789 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
1790 Src->getNumOperands() != 1) {
1791 // Otherwise we can do the fold if the first index of the GEP is a zero
1792 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
1793 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
1794 } else if (Src->getOperand(Src->getNumOperands()-1) ==
1795 Constant::getNullValue(Type::LongTy)) {
1796 // If the src gep ends with a constant array index, merge this get into
1797 // it, even if we have a non-zero array index.
1798 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
1799 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
1802 if (!Indices.empty())
1803 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
1805 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
1806 // GEP of global variable. If all of the indices for this GEP are
1807 // constants, we can promote this to a constexpr instead of an instruction.
1809 // Scan for nonconstants...
1810 std::vector<Constant*> Indices;
1811 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1812 for (; I != E && isa<Constant>(*I); ++I)
1813 Indices.push_back(cast<Constant>(*I));
1815 if (I == E) { // If they are all constants...
1817 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1819 // Replace all uses of the GEP with the new constexpr...
1820 return ReplaceInstUsesWith(GEP, CE);
1827 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1828 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1829 if (AI.isArrayAllocation()) // Check C != 1
1830 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1831 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
1832 AllocationInst *New = 0;
1834 // Create and insert the replacement instruction...
1835 if (isa<MallocInst>(AI))
1836 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
1838 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
1839 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
1842 // Scan to the end of the allocation instructions, to skip over a block of
1843 // allocas if possible...
1845 BasicBlock::iterator It = New;
1846 while (isa<AllocationInst>(*It)) ++It;
1848 // Now that I is pointing to the first non-allocation-inst in the block,
1849 // insert our getelementptr instruction...
1851 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1852 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1854 // Now make everything use the getelementptr instead of the original
1856 ReplaceInstUsesWith(AI, V);
1862 /// GetGEPGlobalInitializer - Given a constant, and a getelementptr
1863 /// constantexpr, return the constant value being addressed by the constant
1864 /// expression, or null if something is funny.
1866 static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
1867 if (CE->getOperand(1) != Constant::getNullValue(Type::LongTy))
1868 return 0; // Do not allow stepping over the value!
1870 // Loop over all of the operands, tracking down which value we are
1872 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
1873 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
1874 ConstantStruct *CS = cast<ConstantStruct>(C);
1875 if (CU->getValue() >= CS->getValues().size()) return 0;
1876 C = cast<Constant>(CS->getValues()[CU->getValue()]);
1877 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
1878 ConstantArray *CA = cast<ConstantArray>(C);
1879 if ((uint64_t)CS->getValue() >= CA->getValues().size()) return 0;
1880 C = cast<Constant>(CA->getValues()[CS->getValue()]);
1886 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
1887 Value *Op = LI.getOperand(0);
1888 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Op))
1889 Op = CPR->getValue();
1891 // Instcombine load (constant global) into the value loaded...
1892 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
1893 if (GV->isConstant() && !GV->isExternal())
1894 return ReplaceInstUsesWith(LI, GV->getInitializer());
1896 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
1897 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
1898 if (CE->getOpcode() == Instruction::GetElementPtr)
1899 if (ConstantPointerRef *G=dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
1900 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
1901 if (GV->isConstant() && !GV->isExternal())
1902 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
1903 return ReplaceInstUsesWith(LI, V);
1908 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1909 // Change br (not X), label True, label False to: br X, label False, True
1910 if (BI.isConditional() && !isa<Constant>(BI.getCondition()))
1911 if (Value *V = dyn_castNotVal(BI.getCondition())) {
1912 BasicBlock *TrueDest = BI.getSuccessor(0);
1913 BasicBlock *FalseDest = BI.getSuccessor(1);
1914 // Swap Destinations and condition...
1916 BI.setSuccessor(0, FalseDest);
1917 BI.setSuccessor(1, TrueDest);
1924 void InstCombiner::removeFromWorkList(Instruction *I) {
1925 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1929 bool InstCombiner::runOnFunction(Function &F) {
1930 bool Changed = false;
1932 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
1934 while (!WorkList.empty()) {
1935 Instruction *I = WorkList.back(); // Get an instruction from the worklist
1936 WorkList.pop_back();
1938 // Check to see if we can DCE or ConstantPropagate the instruction...
1939 // Check to see if we can DIE the instruction...
1940 if (isInstructionTriviallyDead(I)) {
1941 // Add operands to the worklist...
1942 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1943 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1944 WorkList.push_back(Op);
1947 BasicBlock::iterator BBI = I;
1948 if (dceInstruction(BBI)) {
1949 removeFromWorkList(I);
1954 // Instruction isn't dead, see if we can constant propagate it...
1955 if (Constant *C = ConstantFoldInstruction(I)) {
1956 // Add operands to the worklist...
1957 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1958 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1959 WorkList.push_back(Op);
1960 ReplaceInstUsesWith(*I, C);
1963 BasicBlock::iterator BBI = I;
1964 if (dceInstruction(BBI)) {
1965 removeFromWorkList(I);
1970 // Now that we have an instruction, try combining it to simplify it...
1971 if (Instruction *Result = visit(*I)) {
1973 // Should we replace the old instruction with a new one?
1975 // Instructions can end up on the worklist more than once. Make sure
1976 // we do not process an instruction that has been deleted.
1977 removeFromWorkList(I);
1978 ReplaceInstWithInst(I, Result);
1980 BasicBlock::iterator II = I;
1982 // If the instruction was modified, it's possible that it is now dead.
1983 // if so, remove it.
1984 if (dceInstruction(II)) {
1985 // Instructions may end up in the worklist more than once. Erase them
1987 removeFromWorkList(I);
1993 WorkList.push_back(Result);
1994 AddUsesToWorkList(*Result);
2003 Pass *createInstructionCombiningPass() {
2004 return new InstCombiner();