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 return Changed ? &I : 0;
443 // isSignBit - Return true if the value represented by the constant only has the
444 // highest order bit set.
445 static bool isSignBit(ConstantInt *CI) {
446 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
447 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
450 static unsigned getTypeSizeInBits(const Type *Ty) {
451 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
454 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
455 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
457 if (Op0 == Op1) // sub X, X -> 0
458 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
460 // If this is a 'B = x-(-A)', change to B = x+A...
461 if (Value *V = dyn_castNegVal(Op1))
462 return BinaryOperator::create(Instruction::Add, Op0, V);
464 // Replace (-1 - A) with (~A)...
465 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
466 if (C->isAllOnesValue())
467 return BinaryOperator::createNot(Op1);
469 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
470 if (Op1I->use_size() == 1) {
471 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
472 // is not used by anyone else...
474 if (Op1I->getOpcode() == Instruction::Sub) {
475 // Swap the two operands of the subexpr...
476 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
477 Op1I->setOperand(0, IIOp1);
478 Op1I->setOperand(1, IIOp0);
480 // Create the new top level add instruction...
481 return BinaryOperator::create(Instruction::Add, Op0, Op1);
484 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
486 if (Op1I->getOpcode() == Instruction::And &&
487 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
488 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
490 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
491 return BinaryOperator::create(Instruction::And, Op0, NewNot);
494 // X - X*C --> X * (1-C)
495 if (dyn_castFoldableMul(Op1I) == Op0) {
497 ConstantExpr::get(Instruction::Sub,
498 ConstantInt::get(I.getType(), 1),
499 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
500 assert(CP1 && "Couldn't constant fold 1-C?");
501 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
505 // X*C - X --> X * (C-1)
506 if (dyn_castFoldableMul(Op0) == Op1) {
508 ConstantExpr::get(Instruction::Sub,
509 cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
510 ConstantInt::get(I.getType(), 1));
511 assert(CP1 && "Couldn't constant fold C - 1?");
512 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
518 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
519 bool Changed = SimplifyCommutative(I);
520 Value *Op0 = I.getOperand(0);
522 // Simplify mul instructions with a constant RHS...
523 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
524 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
526 // ((X << C1)*C2) == (X * (C2 << C1))
527 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
528 if (SI->getOpcode() == Instruction::Shl)
529 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
530 return BinaryOperator::create(Instruction::Mul, SI->getOperand(0),
533 if (CI->isNullValue())
534 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
535 if (CI->equalsInt(1)) // X * 1 == X
536 return ReplaceInstUsesWith(I, Op0);
537 if (CI->isAllOnesValue()) // X * -1 == 0 - X
538 return BinaryOperator::createNeg(Op0, I.getName());
540 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
541 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
542 return new ShiftInst(Instruction::Shl, Op0,
543 ConstantUInt::get(Type::UByteTy, C));
545 ConstantFP *Op1F = cast<ConstantFP>(Op1);
546 if (Op1F->isNullValue())
547 return ReplaceInstUsesWith(I, Op1);
549 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
550 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
551 if (Op1F->getValue() == 1.0)
552 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
556 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
557 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
558 return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
560 return Changed ? &I : 0;
563 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
565 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
566 if (RHS->equalsInt(1))
567 return ReplaceInstUsesWith(I, I.getOperand(0));
569 // Check to see if this is an unsigned division with an exact power of 2,
570 // if so, convert to a right shift.
571 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
572 if (uint64_t Val = C->getValue()) // Don't break X / 0
573 if (uint64_t C = Log2(Val))
574 return new ShiftInst(Instruction::Shr, I.getOperand(0),
575 ConstantUInt::get(Type::UByteTy, C));
578 // 0 / X == 0, we don't need to preserve faults!
579 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
580 if (LHS->equalsInt(0))
581 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
587 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
588 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
589 if (RHS->equalsInt(1)) // X % 1 == 0
590 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
592 // Check to see if this is an unsigned remainder with an exact power of 2,
593 // if so, convert to a bitwise and.
594 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
595 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
597 return BinaryOperator::create(Instruction::And, I.getOperand(0),
598 ConstantUInt::get(I.getType(), Val-1));
601 // 0 % X == 0, we don't need to preserve faults!
602 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
603 if (LHS->equalsInt(0))
604 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
609 // isMaxValueMinusOne - return true if this is Max-1
610 static bool isMaxValueMinusOne(const ConstantInt *C) {
611 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
612 // Calculate -1 casted to the right type...
613 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
614 uint64_t Val = ~0ULL; // All ones
615 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
616 return CU->getValue() == Val-1;
619 const ConstantSInt *CS = cast<ConstantSInt>(C);
621 // Calculate 0111111111..11111
622 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
623 int64_t Val = INT64_MAX; // All ones
624 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
625 return CS->getValue() == Val-1;
628 // isMinValuePlusOne - return true if this is Min+1
629 static bool isMinValuePlusOne(const ConstantInt *C) {
630 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
631 return CU->getValue() == 1;
633 const ConstantSInt *CS = cast<ConstantSInt>(C);
635 // Calculate 1111111111000000000000
636 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
637 int64_t Val = -1; // All ones
638 Val <<= TypeBits-1; // Shift over to the right spot
639 return CS->getValue() == Val+1;
642 /// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
643 /// are carefully arranged to allow folding of expressions such as:
645 /// (A < B) | (A > B) --> (A != B)
647 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
648 /// represents that the comparison is true if A == B, and bit value '1' is true
651 static unsigned getSetCondCode(const SetCondInst *SCI) {
652 switch (SCI->getOpcode()) {
654 case Instruction::SetGT: return 1;
655 case Instruction::SetEQ: return 2;
656 case Instruction::SetGE: return 3;
657 case Instruction::SetLT: return 4;
658 case Instruction::SetNE: return 5;
659 case Instruction::SetLE: return 6;
662 assert(0 && "Invalid SetCC opcode!");
667 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
668 /// opcode and two operands into either a constant true or false, or a brand new
669 /// SetCC instruction.
670 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
672 case 0: return ConstantBool::False;
673 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
674 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
675 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
676 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
677 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
678 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
679 case 7: return ConstantBool::True;
680 default: assert(0 && "Illegal SetCCCode!"); return 0;
684 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
685 struct FoldSetCCLogical {
688 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
689 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
690 bool shouldApply(Value *V) const {
691 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
692 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
693 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
696 Instruction *apply(BinaryOperator &Log) const {
697 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
698 if (SCI->getOperand(0) != LHS) {
699 assert(SCI->getOperand(1) == LHS);
700 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
703 unsigned LHSCode = getSetCondCode(SCI);
704 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
706 switch (Log.getOpcode()) {
707 case Instruction::And: Code = LHSCode & RHSCode; break;
708 case Instruction::Or: Code = LHSCode | RHSCode; break;
709 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
710 default: assert(0 && "Illegal logical opcode!");
713 Value *RV = getSetCCValue(Code, LHS, RHS);
714 if (Instruction *I = dyn_cast<Instruction>(RV))
716 // Otherwise, it's a constant boolean value...
717 return IC.ReplaceInstUsesWith(Log, RV);
722 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
723 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
724 // guaranteed to be either a shift instruction or a binary operator.
725 Instruction *InstCombiner::OptAndOp(Instruction *Op,
726 ConstantIntegral *OpRHS,
727 ConstantIntegral *AndRHS,
728 BinaryOperator &TheAnd) {
729 Value *X = Op->getOperand(0);
730 switch (Op->getOpcode()) {
731 case Instruction::Xor:
732 if ((*AndRHS & *OpRHS)->isNullValue()) {
733 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
734 return BinaryOperator::create(Instruction::And, X, AndRHS);
735 } else if (Op->use_size() == 1) {
736 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
737 std::string OpName = Op->getName(); Op->setName("");
738 Instruction *And = BinaryOperator::create(Instruction::And,
740 InsertNewInstBefore(And, TheAnd);
741 return BinaryOperator::create(Instruction::Xor, And, *AndRHS & *OpRHS);
744 case Instruction::Or:
745 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
746 if ((*AndRHS & *OpRHS)->isNullValue())
747 return BinaryOperator::create(Instruction::And, X, AndRHS);
749 Constant *Together = *AndRHS & *OpRHS;
750 if (Together == AndRHS) // (X | C) & C --> C
751 return ReplaceInstUsesWith(TheAnd, AndRHS);
753 if (Op->use_size() == 1 && Together != OpRHS) {
754 // (X | C1) & C2 --> (X | (C1&C2)) & C2
755 std::string Op0Name = Op->getName(); Op->setName("");
756 Instruction *Or = BinaryOperator::create(Instruction::Or, X,
758 InsertNewInstBefore(Or, TheAnd);
759 return BinaryOperator::create(Instruction::And, Or, AndRHS);
763 case Instruction::Add:
764 if (Op->use_size() == 1) {
765 // Adding a one to a single bit bit-field should be turned into an XOR
766 // of the bit. First thing to check is to see if this AND is with a
767 // single bit constant.
768 unsigned long long AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
770 // Clear bits that are not part of the constant.
771 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
773 // If there is only one bit set...
774 if ((AndRHSV & (AndRHSV-1)) == 0) {
775 // Ok, at this point, we know that we are masking the result of the
776 // ADD down to exactly one bit. If the constant we are adding has
777 // no bits set below this bit, then we can eliminate the ADD.
778 unsigned long long AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
780 // Check to see if any bits below the one bit set in AndRHSV are set.
781 if ((AddRHS & (AndRHSV-1)) == 0) {
782 // If not, the only thing that can effect the output of the AND is
783 // the bit specified by AndRHSV. If that bit is set, the effect of
784 // the XOR is to toggle the bit. If it is clear, then the ADD has
786 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
787 TheAnd.setOperand(0, X);
790 std::string Name = Op->getName(); Op->setName("");
791 // Pull the XOR out of the AND.
792 Instruction *NewAnd =
793 BinaryOperator::create(Instruction::And, X, AndRHS, Name);
794 InsertNewInstBefore(NewAnd, TheAnd);
795 return BinaryOperator::create(Instruction::Xor, NewAnd, AndRHS);
806 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
807 bool Changed = SimplifyCommutative(I);
808 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
810 // and X, X = X and X, 0 == 0
811 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
812 return ReplaceInstUsesWith(I, Op1);
815 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
816 if (RHS->isAllOnesValue())
817 return ReplaceInstUsesWith(I, Op0);
819 // Optimize a variety of ((val OP C1) & C2) combinations...
820 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
821 Instruction *Op0I = cast<Instruction>(Op0);
822 Value *X = Op0I->getOperand(0);
823 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
824 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
829 Value *Op0NotVal = dyn_castNotVal(Op0);
830 Value *Op1NotVal = dyn_castNotVal(Op1);
832 // (~A & ~B) == (~(A | B)) - Demorgan's Law
833 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
834 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
835 Op1NotVal,I.getName()+".demorgan");
836 InsertNewInstBefore(Or, I);
837 return BinaryOperator::createNot(Or);
840 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
841 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
843 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
844 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
845 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
848 return Changed ? &I : 0;
853 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
854 bool Changed = SimplifyCommutative(I);
855 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
857 // or X, X = X or X, 0 == X
858 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
859 return ReplaceInstUsesWith(I, Op0);
862 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
863 if (RHS->isAllOnesValue())
864 return ReplaceInstUsesWith(I, Op1);
866 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
867 // (X & C1) | C2 --> (X | C2) & (C1|C2)
868 if (Op0I->getOpcode() == Instruction::And && isOnlyUse(Op0))
869 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
870 std::string Op0Name = Op0I->getName(); Op0I->setName("");
871 Instruction *Or = BinaryOperator::create(Instruction::Or,
872 Op0I->getOperand(0), RHS,
874 InsertNewInstBefore(Or, I);
875 return BinaryOperator::create(Instruction::And, Or, *RHS | *Op0CI);
878 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
879 if (Op0I->getOpcode() == Instruction::Xor && isOnlyUse(Op0))
880 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
881 std::string Op0Name = Op0I->getName(); Op0I->setName("");
882 Instruction *Or = BinaryOperator::create(Instruction::Or,
883 Op0I->getOperand(0), RHS,
885 InsertNewInstBefore(Or, I);
886 return BinaryOperator::create(Instruction::Xor, Or, *Op0CI & *~*RHS);
891 // (A & C1)|(A & C2) == A & (C1|C2)
892 if (Instruction *LHS = dyn_cast<BinaryOperator>(Op0))
893 if (Instruction *RHS = dyn_cast<BinaryOperator>(Op1))
894 if (LHS->getOperand(0) == RHS->getOperand(0))
895 if (Constant *C0 = dyn_castMaskingAnd(LHS))
896 if (Constant *C1 = dyn_castMaskingAnd(RHS))
897 return BinaryOperator::create(Instruction::And, LHS->getOperand(0),
900 Value *Op0NotVal = dyn_castNotVal(Op0);
901 Value *Op1NotVal = dyn_castNotVal(Op1);
903 if (Op1 == Op0NotVal) // ~A | A == -1
904 return ReplaceInstUsesWith(I,
905 ConstantIntegral::getAllOnesValue(I.getType()));
907 if (Op0 == Op1NotVal) // A | ~A == -1
908 return ReplaceInstUsesWith(I,
909 ConstantIntegral::getAllOnesValue(I.getType()));
911 // (~A | ~B) == (~(A & B)) - Demorgan's Law
912 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
913 Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
914 Op1NotVal,I.getName()+".demorgan",
916 WorkList.push_back(And);
917 return BinaryOperator::createNot(And);
920 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
921 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
922 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
925 return Changed ? &I : 0;
930 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
931 bool Changed = SimplifyCommutative(I);
932 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
936 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
938 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
940 if (RHS->isNullValue())
941 return ReplaceInstUsesWith(I, Op0);
943 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
944 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
945 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
946 if (RHS == ConstantBool::True && SCI->use_size() == 1)
947 return new SetCondInst(SCI->getInverseCondition(),
948 SCI->getOperand(0), SCI->getOperand(1));
950 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
951 if (Op0I->getOpcode() == Instruction::And) {
952 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
953 if ((*RHS & *Op0CI)->isNullValue())
954 return BinaryOperator::create(Instruction::Or, Op0, RHS);
955 } else if (Op0I->getOpcode() == Instruction::Or) {
956 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
957 if ((*RHS & *Op0CI) == RHS)
958 return BinaryOperator::create(Instruction::And, Op0, ~*RHS);
963 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
965 return ReplaceInstUsesWith(I,
966 ConstantIntegral::getAllOnesValue(I.getType()));
968 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
970 return ReplaceInstUsesWith(I,
971 ConstantIntegral::getAllOnesValue(I.getType()));
973 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
974 if (Op1I->getOpcode() == Instruction::Or)
975 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
976 cast<BinaryOperator>(Op1I)->swapOperands();
979 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
984 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
985 if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
986 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
987 cast<BinaryOperator>(Op0I)->swapOperands();
988 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
989 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
990 WorkList.push_back(cast<Instruction>(NotB));
991 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
996 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
997 if (Constant *C1 = dyn_castMaskingAnd(Op0))
998 if (Constant *C2 = dyn_castMaskingAnd(Op1))
999 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
1000 return BinaryOperator::create(Instruction::Or, Op0, Op1);
1002 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1003 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1004 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1007 return Changed ? &I : 0;
1010 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
1011 static Constant *AddOne(ConstantInt *C) {
1012 Constant *Result = ConstantExpr::get(Instruction::Add, C,
1013 ConstantInt::get(C->getType(), 1));
1014 assert(Result && "Constant folding integer addition failed!");
1017 static Constant *SubOne(ConstantInt *C) {
1018 Constant *Result = ConstantExpr::get(Instruction::Sub, C,
1019 ConstantInt::get(C->getType(), 1));
1020 assert(Result && "Constant folding integer addition failed!");
1024 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
1025 // true when both operands are equal...
1027 static bool isTrueWhenEqual(Instruction &I) {
1028 return I.getOpcode() == Instruction::SetEQ ||
1029 I.getOpcode() == Instruction::SetGE ||
1030 I.getOpcode() == Instruction::SetLE;
1033 Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
1034 bool Changed = SimplifyCommutative(I);
1035 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1036 const Type *Ty = Op0->getType();
1040 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
1042 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1043 if (isa<ConstantPointerNull>(Op1) &&
1044 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
1045 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1048 // setcc's with boolean values can always be turned into bitwise operations
1049 if (Ty == Type::BoolTy) {
1050 // If this is <, >, or !=, we can change this into a simple xor instruction
1051 if (!isTrueWhenEqual(I))
1052 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
1054 // Otherwise we need to make a temporary intermediate instruction and insert
1055 // it into the instruction stream. This is what we are after:
1057 // seteq bool %A, %B -> ~(A^B)
1058 // setle bool %A, %B -> ~A | B
1059 // setge bool %A, %B -> A | ~B
1061 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
1062 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
1064 InsertNewInstBefore(Xor, I);
1065 return BinaryOperator::createNot(Xor, I.getName());
1068 // Handle the setXe cases...
1069 assert(I.getOpcode() == Instruction::SetGE ||
1070 I.getOpcode() == Instruction::SetLE);
1072 if (I.getOpcode() == Instruction::SetGE)
1073 std::swap(Op0, Op1); // Change setge -> setle
1075 // Now we just have the SetLE case.
1076 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1077 InsertNewInstBefore(Not, I);
1078 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
1081 // Check to see if we are doing one of many comparisons against constant
1082 // integers at the end of their ranges...
1084 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1085 // Simplify seteq and setne instructions...
1086 if (I.getOpcode() == Instruction::SetEQ ||
1087 I.getOpcode() == Instruction::SetNE) {
1088 bool isSetNE = I.getOpcode() == Instruction::SetNE;
1090 // If the first operand is (and|or|xor) with a constant, and the second
1091 // operand is a constant, simplify a bit.
1092 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
1093 switch (BO->getOpcode()) {
1094 case Instruction::Add:
1095 if (CI->isNullValue()) {
1096 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1097 // efficiently invertible, or if the add has just this one use.
1098 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
1099 if (Value *NegVal = dyn_castNegVal(BOp1))
1100 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
1101 else if (Value *NegVal = dyn_castNegVal(BOp0))
1102 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
1103 else if (BO->use_size() == 1) {
1104 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
1106 InsertNewInstBefore(Neg, I);
1107 return new SetCondInst(I.getOpcode(), BOp0, Neg);
1111 case Instruction::Xor:
1112 // For the xor case, we can xor two constants together, eliminating
1113 // the explicit xor.
1114 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1115 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
1119 case Instruction::Sub:
1120 // Replace (([sub|xor] A, B) != 0) with (A != B)
1121 if (CI->isNullValue())
1122 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1126 case Instruction::Or:
1127 // If bits are being or'd in that are not present in the constant we
1128 // are comparing against, then the comparison could never succeed!
1129 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1130 if (!(*BOC & *~*CI)->isNullValue())
1131 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
1134 case Instruction::And:
1135 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1136 // If bits are being compared against that are and'd out, then the
1137 // comparison can never succeed!
1138 if (!(*CI & *~*BOC)->isNullValue())
1139 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
1141 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
1142 // to be a signed value as appropriate.
1143 if (isSignBit(BOC)) {
1144 Value *X = BO->getOperand(0);
1145 // If 'X' is not signed, insert a cast now...
1146 if (!BOC->getType()->isSigned()) {
1148 switch (BOC->getType()->getPrimitiveID()) {
1149 case Type::UByteTyID: DestTy = Type::SByteTy; break;
1150 case Type::UShortTyID: DestTy = Type::ShortTy; break;
1151 case Type::UIntTyID: DestTy = Type::IntTy; break;
1152 case Type::ULongTyID: DestTy = Type::LongTy; break;
1153 default: assert(0 && "Invalid unsigned integer type!"); abort();
1155 CastInst *NewCI = new CastInst(X,DestTy,X->getName()+".signed");
1156 InsertNewInstBefore(NewCI, I);
1159 return new SetCondInst(isSetNE ? Instruction::SetLT :
1160 Instruction::SetGE, X,
1161 Constant::getNullValue(X->getType()));
1169 // Check to see if we are comparing against the minimum or maximum value...
1170 if (CI->isMinValue()) {
1171 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1172 return ReplaceInstUsesWith(I, ConstantBool::False);
1173 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1174 return ReplaceInstUsesWith(I, ConstantBool::True);
1175 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
1176 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
1177 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
1178 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
1180 } else if (CI->isMaxValue()) {
1181 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1182 return ReplaceInstUsesWith(I, ConstantBool::False);
1183 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1184 return ReplaceInstUsesWith(I, ConstantBool::True);
1185 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
1186 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
1187 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
1188 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
1190 // Comparing against a value really close to min or max?
1191 } else if (isMinValuePlusOne(CI)) {
1192 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
1193 return BinaryOperator::create(Instruction::SetEQ, Op0,
1194 SubOne(CI), I.getName());
1195 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
1196 return BinaryOperator::create(Instruction::SetNE, Op0,
1197 SubOne(CI), I.getName());
1199 } else if (isMaxValueMinusOne(CI)) {
1200 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
1201 return BinaryOperator::create(Instruction::SetEQ, Op0,
1202 AddOne(CI), I.getName());
1203 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
1204 return BinaryOperator::create(Instruction::SetNE, Op0,
1205 AddOne(CI), I.getName());
1209 return Changed ? &I : 0;
1214 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
1215 assert(I.getOperand(1)->getType() == Type::UByteTy);
1216 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1217 bool isLeftShift = I.getOpcode() == Instruction::Shl;
1219 // shl X, 0 == X and shr X, 0 == X
1220 // shl 0, X == 0 and shr 0, X == 0
1221 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
1222 Op0 == Constant::getNullValue(Op0->getType()))
1223 return ReplaceInstUsesWith(I, Op0);
1225 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
1227 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1228 if (CSI->isAllOnesValue())
1229 return ReplaceInstUsesWith(I, CSI);
1231 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
1232 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
1233 // of a signed value.
1235 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
1236 if (CUI->getValue() >= TypeBits &&
1237 (!Op0->getType()->isSigned() || isLeftShift))
1238 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
1240 // ((X*C1) << C2) == (X * (C1 << C2))
1241 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
1242 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
1243 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
1244 return BinaryOperator::create(Instruction::Mul, BO->getOperand(0),
1248 // If the operand is an bitwise operator with a constant RHS, and the
1249 // shift is the only use, we can pull it out of the shift.
1250 if (Op0->use_size() == 1)
1251 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
1252 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
1253 bool isValid = true; // Valid only for And, Or, Xor
1254 bool highBitSet = false; // Transform if high bit of constant set?
1256 switch (Op0BO->getOpcode()) {
1257 default: isValid = false; break; // Do not perform transform!
1258 case Instruction::Or:
1259 case Instruction::Xor:
1262 case Instruction::And:
1267 // If this is a signed shift right, and the high bit is modified
1268 // by the logical operation, do not perform the transformation.
1269 // The highBitSet boolean indicates the value of the high bit of
1270 // the constant which would cause it to be modified for this
1273 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
1274 uint64_t Val = Op0C->getRawValue();
1275 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
1280 ConstantFoldShiftInstruction(I.getOpcode(), Op0C, CUI);
1282 Instruction *NewShift =
1283 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
1286 InsertNewInstBefore(NewShift, I);
1288 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
1293 // If this is a shift of a shift, see if we can fold the two together...
1294 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
1295 if (ConstantUInt *ShiftAmt1C =
1296 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
1297 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
1298 unsigned ShiftAmt2 = CUI->getValue();
1300 // Check for (A << c1) << c2 and (A >> c1) >> c2
1301 if (I.getOpcode() == Op0SI->getOpcode()) {
1302 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
1303 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
1304 ConstantUInt::get(Type::UByteTy, Amt));
1307 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
1308 // signed types, we can only support the (A >> c1) << c2 configuration,
1309 // because it can not turn an arbitrary bit of A into a sign bit.
1310 if (I.getType()->isUnsigned() || isLeftShift) {
1311 // Calculate bitmask for what gets shifted off the edge...
1312 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
1314 C = ConstantExpr::getShift(Instruction::Shl, C, ShiftAmt1C);
1316 C = ConstantExpr::getShift(Instruction::Shr, C, ShiftAmt1C);
1319 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
1320 C, Op0SI->getOperand(0)->getName()+".mask");
1321 InsertNewInstBefore(Mask, I);
1323 // Figure out what flavor of shift we should use...
1324 if (ShiftAmt1 == ShiftAmt2)
1325 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
1326 else if (ShiftAmt1 < ShiftAmt2) {
1327 return new ShiftInst(I.getOpcode(), Mask,
1328 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
1330 return new ShiftInst(Op0SI->getOpcode(), Mask,
1331 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
1341 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
1344 static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
1345 const Type *DstTy) {
1347 // It is legal to eliminate the instruction if casting A->B->A if the sizes
1348 // are identical and the bits don't get reinterpreted (for example
1349 // int->float->int would not be allowed)
1350 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
1353 // Allow free casting and conversion of sizes as long as the sign doesn't
1355 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
1356 unsigned SrcSize = SrcTy->getPrimitiveSize();
1357 unsigned MidSize = MidTy->getPrimitiveSize();
1358 unsigned DstSize = DstTy->getPrimitiveSize();
1360 // Cases where we are monotonically decreasing the size of the type are
1361 // always ok, regardless of what sign changes are going on.
1363 if (SrcSize >= MidSize && MidSize >= DstSize)
1366 // Cases where the source and destination type are the same, but the middle
1367 // type is bigger are noops.
1369 if (SrcSize == DstSize && MidSize > SrcSize)
1372 // If we are monotonically growing, things are more complex.
1374 if (SrcSize <= MidSize && MidSize <= DstSize) {
1375 // We have eight combinations of signedness to worry about. Here's the
1377 static const int SignTable[8] = {
1378 // CODE, SrcSigned, MidSigned, DstSigned, Comment
1379 1, // U U U Always ok
1380 1, // U U S Always ok
1381 3, // U S U Ok iff SrcSize != MidSize
1382 3, // U S S Ok iff SrcSize != MidSize
1383 0, // S U U Never ok
1384 2, // S U S Ok iff MidSize == DstSize
1385 1, // S S U Always ok
1386 1, // S S S Always ok
1389 // Choose an action based on the current entry of the signtable that this
1390 // cast of cast refers to...
1391 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
1392 switch (SignTable[Row]) {
1393 case 0: return false; // Never ok
1394 case 1: return true; // Always ok
1395 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
1396 case 3: // Ok iff SrcSize != MidSize
1397 return SrcSize != MidSize || SrcTy == Type::BoolTy;
1398 default: assert(0 && "Bad entry in sign table!");
1403 // Otherwise, we cannot succeed. Specifically we do not want to allow things
1404 // like: short -> ushort -> uint, because this can create wrong results if
1405 // the input short is negative!
1410 static bool ValueRequiresCast(const Value *V, const Type *Ty) {
1411 if (V->getType() == Ty || isa<Constant>(V)) return false;
1412 if (const CastInst *CI = dyn_cast<CastInst>(V))
1413 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty))
1418 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
1419 /// InsertBefore instruction. This is specialized a bit to avoid inserting
1420 /// casts that are known to not do anything...
1422 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
1423 Instruction *InsertBefore) {
1424 if (V->getType() == DestTy) return V;
1425 if (Constant *C = dyn_cast<Constant>(V))
1426 return ConstantExpr::getCast(C, DestTy);
1428 CastInst *CI = new CastInst(V, DestTy, V->getName());
1429 InsertNewInstBefore(CI, *InsertBefore);
1433 // CastInst simplification
1435 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
1436 Value *Src = CI.getOperand(0);
1438 // If the user is casting a value to the same type, eliminate this cast
1440 if (CI.getType() == Src->getType())
1441 return ReplaceInstUsesWith(CI, Src);
1443 // If casting the result of another cast instruction, try to eliminate this
1446 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
1447 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
1448 CSrc->getType(), CI.getType())) {
1449 // This instruction now refers directly to the cast's src operand. This
1450 // has a good chance of making CSrc dead.
1451 CI.setOperand(0, CSrc->getOperand(0));
1455 // If this is an A->B->A cast, and we are dealing with integral types, try
1456 // to convert this into a logical 'and' instruction.
1458 if (CSrc->getOperand(0)->getType() == CI.getType() &&
1459 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
1460 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
1461 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
1462 assert(CSrc->getType() != Type::ULongTy &&
1463 "Cannot have type bigger than ulong!");
1464 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
1465 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
1466 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
1471 // If casting the result of a getelementptr instruction with no offset, turn
1472 // this into a cast of the original pointer!
1474 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1475 bool AllZeroOperands = true;
1476 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1477 if (!isa<Constant>(GEP->getOperand(i)) ||
1478 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
1479 AllZeroOperands = false;
1482 if (AllZeroOperands) {
1483 CI.setOperand(0, GEP->getOperand(0));
1488 // If the source value is an instruction with only this use, we can attempt to
1489 // propagate the cast into the instruction. Also, only handle integral types
1491 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
1492 if (SrcI->use_size() == 1 && Src->getType()->isIntegral() &&
1493 CI.getType()->isInteger()) { // Don't mess with casts to bool here
1494 const Type *DestTy = CI.getType();
1495 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
1496 unsigned DestBitSize = getTypeSizeInBits(DestTy);
1498 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
1499 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
1501 switch (SrcI->getOpcode()) {
1502 case Instruction::Add:
1503 case Instruction::Mul:
1504 case Instruction::And:
1505 case Instruction::Or:
1506 case Instruction::Xor:
1507 // If we are discarding information, or just changing the sign, rewrite.
1508 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
1509 // Don't insert two casts if they cannot be eliminated. We allow two
1510 // casts to be inserted if the sizes are the same. This could only be
1511 // converting signedness, which is a noop.
1512 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy) ||
1513 !ValueRequiresCast(Op0, DestTy)) {
1514 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1515 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
1516 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
1517 ->getOpcode(), Op0c, Op1c);
1521 case Instruction::Shl:
1522 // Allow changing the sign of the source operand. Do not allow changing
1523 // the size of the shift, UNLESS the shift amount is a constant. We
1524 // mush not change variable sized shifts to a smaller size, because it
1525 // is undefined to shift more bits out than exist in the value.
1526 if (DestBitSize == SrcBitSize ||
1527 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
1528 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1529 return new ShiftInst(Instruction::Shl, Op0c, Op1);
1538 // CallInst simplification
1540 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
1541 if (transformConstExprCastCall(&CI)) return 0;
1545 // InvokeInst simplification
1547 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
1548 if (transformConstExprCastCall(&II)) return 0;
1552 // getPromotedType - Return the specified type promoted as it would be to pass
1553 // though a va_arg area...
1554 static const Type *getPromotedType(const Type *Ty) {
1555 switch (Ty->getPrimitiveID()) {
1556 case Type::SByteTyID:
1557 case Type::ShortTyID: return Type::IntTy;
1558 case Type::UByteTyID:
1559 case Type::UShortTyID: return Type::UIntTy;
1560 case Type::FloatTyID: return Type::DoubleTy;
1565 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
1566 // attempt to move the cast to the arguments of the call/invoke.
1568 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
1569 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
1570 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
1571 if (CE->getOpcode() != Instruction::Cast ||
1572 !isa<ConstantPointerRef>(CE->getOperand(0)))
1574 ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
1575 if (!isa<Function>(CPR->getValue())) return false;
1576 Function *Callee = cast<Function>(CPR->getValue());
1577 Instruction *Caller = CS.getInstruction();
1579 // Okay, this is a cast from a function to a different type. Unless doing so
1580 // would cause a type conversion of one of our arguments, change this call to
1581 // be a direct call with arguments casted to the appropriate types.
1583 const FunctionType *FT = Callee->getFunctionType();
1584 const Type *OldRetTy = Caller->getType();
1586 if (Callee->isExternal() &&
1587 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()))
1588 return false; // Cannot transform this return value...
1590 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1591 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1593 CallSite::arg_iterator AI = CS.arg_begin();
1594 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1595 const Type *ParamTy = FT->getParamType(i);
1596 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
1597 if (Callee->isExternal() && !isConvertible) return false;
1600 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
1601 Callee->isExternal())
1602 return false; // Do not delete arguments unless we have a function body...
1604 // Okay, we decided that this is a safe thing to do: go ahead and start
1605 // inserting cast instructions as necessary...
1606 std::vector<Value*> Args;
1607 Args.reserve(NumActualArgs);
1609 AI = CS.arg_begin();
1610 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1611 const Type *ParamTy = FT->getParamType(i);
1612 if ((*AI)->getType() == ParamTy) {
1613 Args.push_back(*AI);
1615 Instruction *Cast = new CastInst(*AI, ParamTy, "tmp");
1616 InsertNewInstBefore(Cast, *Caller);
1617 Args.push_back(Cast);
1621 // If the function takes more arguments than the call was taking, add them
1623 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1624 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1626 // If we are removing arguments to the function, emit an obnoxious warning...
1627 if (FT->getNumParams() < NumActualArgs)
1628 if (!FT->isVarArg()) {
1629 std::cerr << "WARNING: While resolving call to function '"
1630 << Callee->getName() << "' arguments were dropped!\n";
1632 // Add all of the arguments in their promoted form to the arg list...
1633 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1634 const Type *PTy = getPromotedType((*AI)->getType());
1635 if (PTy != (*AI)->getType()) {
1636 // Must promote to pass through va_arg area!
1637 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
1638 InsertNewInstBefore(Cast, *Caller);
1639 Args.push_back(Cast);
1641 Args.push_back(*AI);
1646 if (FT->getReturnType() == Type::VoidTy)
1647 Caller->setName(""); // Void type should not have a name...
1650 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1651 NC = new InvokeInst(Callee, II->getNormalDest(), II->getExceptionalDest(),
1652 Args, Caller->getName(), Caller);
1654 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
1657 // Insert a cast of the return type as necessary...
1659 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
1660 if (NV->getType() != Type::VoidTy) {
1661 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
1662 InsertNewInstBefore(NC, *Caller);
1663 AddUsesToWorkList(*Caller);
1665 NV = Constant::getNullValue(Caller->getType());
1669 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
1670 Caller->replaceAllUsesWith(NV);
1671 Caller->getParent()->getInstList().erase(Caller);
1672 removeFromWorkList(Caller);
1678 // PHINode simplification
1680 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
1681 // If the PHI node only has one incoming value, eliminate the PHI node...
1682 if (PN.getNumIncomingValues() == 1)
1683 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
1685 // Otherwise if all of the incoming values are the same for the PHI, replace
1686 // the PHI node with the incoming value.
1689 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1690 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
1691 if (InVal && PN.getIncomingValue(i) != InVal)
1692 return 0; // Not the same, bail out.
1694 InVal = PN.getIncomingValue(i);
1696 // The only case that could cause InVal to be null is if we have a PHI node
1697 // that only has entries for itself. In this case, there is no entry into the
1698 // loop, so kill the PHI.
1700 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
1702 // All of the incoming values are the same, replace the PHI node now.
1703 return ReplaceInstUsesWith(PN, InVal);
1707 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1708 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
1709 // If so, eliminate the noop.
1710 if ((GEP.getNumOperands() == 2 &&
1711 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
1712 GEP.getNumOperands() == 1)
1713 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
1715 // Combine Indices - If the source pointer to this getelementptr instruction
1716 // is a getelementptr instruction, combine the indices of the two
1717 // getelementptr instructions into a single instruction.
1719 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
1720 std::vector<Value *> Indices;
1722 // Can we combine the two pointer arithmetics offsets?
1723 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
1724 isa<Constant>(GEP.getOperand(1))) {
1725 // Replace: gep (gep %P, long C1), long C2, ...
1726 // With: gep %P, long (C1+C2), ...
1727 Value *Sum = ConstantExpr::get(Instruction::Add,
1728 cast<Constant>(Src->getOperand(1)),
1729 cast<Constant>(GEP.getOperand(1)));
1730 assert(Sum && "Constant folding of longs failed!?");
1731 GEP.setOperand(0, Src->getOperand(0));
1732 GEP.setOperand(1, Sum);
1733 AddUsesToWorkList(*Src); // Reduce use count of Src
1735 } else if (Src->getNumOperands() == 2) {
1736 // Replace: gep (gep %P, long B), long A, ...
1737 // With: T = long A+B; gep %P, T, ...
1739 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
1741 Src->getName()+".sum", &GEP);
1742 GEP.setOperand(0, Src->getOperand(0));
1743 GEP.setOperand(1, Sum);
1744 WorkList.push_back(cast<Instruction>(Sum));
1746 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
1747 Src->getNumOperands() != 1) {
1748 // Otherwise we can do the fold if the first index of the GEP is a zero
1749 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
1750 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
1751 } else if (Src->getOperand(Src->getNumOperands()-1) ==
1752 Constant::getNullValue(Type::LongTy)) {
1753 // If the src gep ends with a constant array index, merge this get into
1754 // it, even if we have a non-zero array index.
1755 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
1756 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
1759 if (!Indices.empty())
1760 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
1762 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
1763 // GEP of global variable. If all of the indices for this GEP are
1764 // constants, we can promote this to a constexpr instead of an instruction.
1766 // Scan for nonconstants...
1767 std::vector<Constant*> Indices;
1768 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1769 for (; I != E && isa<Constant>(*I); ++I)
1770 Indices.push_back(cast<Constant>(*I));
1772 if (I == E) { // If they are all constants...
1774 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1776 // Replace all uses of the GEP with the new constexpr...
1777 return ReplaceInstUsesWith(GEP, CE);
1784 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1785 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1786 if (AI.isArrayAllocation()) // Check C != 1
1787 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1788 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
1789 AllocationInst *New = 0;
1791 // Create and insert the replacement instruction...
1792 if (isa<MallocInst>(AI))
1793 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
1795 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
1796 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
1799 // Scan to the end of the allocation instructions, to skip over a block of
1800 // allocas if possible...
1802 BasicBlock::iterator It = New;
1803 while (isa<AllocationInst>(*It)) ++It;
1805 // Now that I is pointing to the first non-allocation-inst in the block,
1806 // insert our getelementptr instruction...
1808 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1809 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1811 // Now make everything use the getelementptr instead of the original
1813 ReplaceInstUsesWith(AI, V);
1819 /// GetGEPGlobalInitializer - Given a constant, and a getelementptr
1820 /// constantexpr, return the constant value being addressed by the constant
1821 /// expression, or null if something is funny.
1823 static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
1824 if (CE->getOperand(1) != Constant::getNullValue(Type::LongTy))
1825 return 0; // Do not allow stepping over the value!
1827 // Loop over all of the operands, tracking down which value we are
1829 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
1830 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
1831 ConstantStruct *CS = cast<ConstantStruct>(C);
1832 if (CU->getValue() >= CS->getValues().size()) return 0;
1833 C = cast<Constant>(CS->getValues()[CU->getValue()]);
1834 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
1835 ConstantArray *CA = cast<ConstantArray>(C);
1836 if ((uint64_t)CS->getValue() >= CA->getValues().size()) return 0;
1837 C = cast<Constant>(CA->getValues()[CS->getValue()]);
1843 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
1844 Value *Op = LI.getOperand(0);
1845 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Op))
1846 Op = CPR->getValue();
1848 // Instcombine load (constant global) into the value loaded...
1849 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
1850 if (GV->isConstant() && !GV->isExternal())
1851 return ReplaceInstUsesWith(LI, GV->getInitializer());
1853 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
1854 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
1855 if (CE->getOpcode() == Instruction::GetElementPtr)
1856 if (ConstantPointerRef *G=dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
1857 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
1858 if (GV->isConstant() && !GV->isExternal())
1859 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
1860 return ReplaceInstUsesWith(LI, V);
1865 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1866 // Change br (not X), label True, label False to: br X, label False, True
1867 if (BI.isConditional() && !isa<Constant>(BI.getCondition()))
1868 if (Value *V = dyn_castNotVal(BI.getCondition())) {
1869 BasicBlock *TrueDest = BI.getSuccessor(0);
1870 BasicBlock *FalseDest = BI.getSuccessor(1);
1871 // Swap Destinations and condition...
1873 BI.setSuccessor(0, FalseDest);
1874 BI.setSuccessor(1, TrueDest);
1881 void InstCombiner::removeFromWorkList(Instruction *I) {
1882 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1886 bool InstCombiner::runOnFunction(Function &F) {
1887 bool Changed = false;
1889 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
1891 while (!WorkList.empty()) {
1892 Instruction *I = WorkList.back(); // Get an instruction from the worklist
1893 WorkList.pop_back();
1895 // Check to see if we can DCE or ConstantPropagate the instruction...
1896 // Check to see if we can DIE the instruction...
1897 if (isInstructionTriviallyDead(I)) {
1898 // Add operands to the worklist...
1899 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1900 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1901 WorkList.push_back(Op);
1904 BasicBlock::iterator BBI = I;
1905 if (dceInstruction(BBI)) {
1906 removeFromWorkList(I);
1911 // Instruction isn't dead, see if we can constant propagate it...
1912 if (Constant *C = ConstantFoldInstruction(I)) {
1913 // Add operands to the worklist...
1914 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1915 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1916 WorkList.push_back(Op);
1917 ReplaceInstUsesWith(*I, C);
1920 BasicBlock::iterator BBI = I;
1921 if (dceInstruction(BBI)) {
1922 removeFromWorkList(I);
1927 // Now that we have an instruction, try combining it to simplify it...
1928 if (Instruction *Result = visit(*I)) {
1930 // Should we replace the old instruction with a new one?
1932 // Instructions can end up on the worklist more than once. Make sure
1933 // we do not process an instruction that has been deleted.
1934 removeFromWorkList(I);
1935 ReplaceInstWithInst(I, Result);
1937 BasicBlock::iterator II = I;
1939 // If the instruction was modified, it's possible that it is now dead.
1940 // if so, remove it.
1941 if (dceInstruction(II)) {
1942 // Instructions may end up in the worklist more than once. Erase them
1944 removeFromWorkList(I);
1950 WorkList.push_back(Result);
1951 AddUsesToWorkList(*Result);
1960 Pass *createInstructionCombiningPass() {
1961 return new InstCombiner();