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);
140 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
143 // getComplexity: Assign a complexity or rank value to LLVM Values...
144 // 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
145 static unsigned getComplexity(Value *V) {
146 if (isa<Instruction>(V)) {
147 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
151 if (isa<Argument>(V)) return 2;
152 return isa<Constant>(V) ? 0 : 1;
155 // isOnlyUse - Return true if this instruction will be deleted if we stop using
157 static bool isOnlyUse(Value *V) {
158 return V->use_size() == 1 || isa<Constant>(V);
161 // SimplifyCommutative - This performs a few simplifications for commutative
164 // 1. Order operands such that they are listed from right (least complex) to
165 // left (most complex). This puts constants before unary operators before
168 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
169 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
171 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
172 bool Changed = false;
173 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
174 Changed = !I.swapOperands();
176 if (!I.isAssociative()) return Changed;
177 Instruction::BinaryOps Opcode = I.getOpcode();
178 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
179 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
180 if (isa<Constant>(I.getOperand(1))) {
181 Constant *Folded = ConstantExpr::get(I.getOpcode(),
182 cast<Constant>(I.getOperand(1)),
183 cast<Constant>(Op->getOperand(1)));
184 I.setOperand(0, Op->getOperand(0));
185 I.setOperand(1, Folded);
187 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
188 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
189 isOnlyUse(Op) && isOnlyUse(Op1)) {
190 Constant *C1 = cast<Constant>(Op->getOperand(1));
191 Constant *C2 = cast<Constant>(Op1->getOperand(1));
193 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
194 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
195 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
198 WorkList.push_back(New);
199 I.setOperand(0, New);
200 I.setOperand(1, Folded);
207 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
208 // if the LHS is a constant zero (which is the 'negate' form).
210 static inline Value *dyn_castNegVal(Value *V) {
211 if (BinaryOperator::isNeg(V))
212 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
214 // Constants can be considered to be negated values if they can be folded...
215 if (Constant *C = dyn_cast<Constant>(V))
216 return ConstantExpr::get(Instruction::Sub,
217 Constant::getNullValue(V->getType()), C);
221 static inline Value *dyn_castNotVal(Value *V) {
222 if (BinaryOperator::isNot(V))
223 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
225 // Constants can be considered to be not'ed values...
226 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
227 return ConstantExpr::get(Instruction::Xor,
228 ConstantIntegral::getAllOnesValue(C->getType()),C);
232 // dyn_castFoldableMul - If this value is a multiply that can be folded into
233 // other computations (because it has a constant operand), return the
234 // non-constant operand of the multiply.
236 static inline Value *dyn_castFoldableMul(Value *V) {
237 if (V->use_size() == 1 && V->getType()->isInteger())
238 if (Instruction *I = dyn_cast<Instruction>(V))
239 if (I->getOpcode() == Instruction::Mul)
240 if (isa<Constant>(I->getOperand(1)))
241 return I->getOperand(0);
245 // dyn_castMaskingAnd - If this value is an And instruction masking a value with
246 // a constant, return the constant being anded with.
248 template<class ValueType>
249 static inline Constant *dyn_castMaskingAnd(ValueType *V) {
250 if (Instruction *I = dyn_cast<Instruction>(V))
251 if (I->getOpcode() == Instruction::And)
252 return dyn_cast<Constant>(I->getOperand(1));
254 // If this is a constant, it acts just like we were masking with it.
255 return dyn_cast<Constant>(V);
258 // Log2 - Calculate the log base 2 for the specified value if it is exactly a
260 static unsigned Log2(uint64_t Val) {
261 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
264 if (Val & 1) return 0; // Multiple bits set?
272 /// AssociativeOpt - Perform an optimization on an associative operator. This
273 /// function is designed to check a chain of associative operators for a
274 /// potential to apply a certain optimization. Since the optimization may be
275 /// applicable if the expression was reassociated, this checks the chain, then
276 /// reassociates the expression as necessary to expose the optimization
277 /// opportunity. This makes use of a special Functor, which must define
278 /// 'shouldApply' and 'apply' methods.
280 template<typename Functor>
281 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
282 unsigned Opcode = Root.getOpcode();
283 Value *LHS = Root.getOperand(0);
285 // Quick check, see if the immediate LHS matches...
286 if (F.shouldApply(LHS))
287 return F.apply(Root);
289 // Otherwise, if the LHS is not of the same opcode as the root, return.
290 Instruction *LHSI = dyn_cast<Instruction>(LHS);
291 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->use_size() == 1) {
292 // Should we apply this transform to the RHS?
293 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
295 // If not to the RHS, check to see if we should apply to the LHS...
296 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
297 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
301 // If the functor wants to apply the optimization to the RHS of LHSI,
302 // reassociate the expression from ((? op A) op B) to (? op (A op B))
304 BasicBlock *BB = Root.getParent();
305 // All of the instructions have a single use and have no side-effects,
306 // because of this, we can pull them all into the current basic block.
307 if (LHSI->getParent() != BB) {
308 // Move all of the instructions from root to LHSI into the current
310 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
311 Instruction *LastUse = &Root;
312 while (TmpLHSI->getParent() == BB) {
314 TmpLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
317 // Loop over all of the instructions in other blocks, moving them into
319 Value *TmpLHS = TmpLHSI;
321 TmpLHSI = cast<Instruction>(TmpLHS);
322 // Remove from current block...
323 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
324 // Insert before the last instruction...
325 BB->getInstList().insert(LastUse, TmpLHSI);
326 TmpLHS = TmpLHSI->getOperand(0);
327 } while (TmpLHSI != LHSI);
330 // Now all of the instructions are in the current basic block, go ahead
331 // and perform the reassociation.
332 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
334 // First move the selected RHS to the LHS of the root...
335 Root.setOperand(0, LHSI->getOperand(1));
337 // Make what used to be the LHS of the root be the user of the root...
338 Value *ExtraOperand = TmpLHSI->getOperand(1);
339 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
340 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
341 BB->getInstList().remove(&Root); // Remove root from the BB
342 BB->getInstList().insert(TmpLHSI, &Root); // Insert root before TmpLHSI
344 // Now propagate the ExtraOperand down the chain of instructions until we
346 while (TmpLHSI != LHSI) {
347 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
348 Value *NextOp = NextLHSI->getOperand(1);
349 NextLHSI->setOperand(1, ExtraOperand);
351 ExtraOperand = NextOp;
354 // Now that the instructions are reassociated, have the functor perform
355 // the transformation...
356 return F.apply(Root);
359 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
365 // AddRHS - Implements: X + X --> X << 1
368 AddRHS(Value *rhs) : RHS(rhs) {}
369 bool shouldApply(Value *LHS) const { return LHS == RHS; }
370 Instruction *apply(BinaryOperator &Add) const {
371 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
372 ConstantInt::get(Type::UByteTy, 1));
376 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
378 struct AddMaskingAnd {
380 AddMaskingAnd(Constant *c) : C2(c) {}
381 bool shouldApply(Value *LHS) const {
382 if (Constant *C1 = dyn_castMaskingAnd(LHS))
383 return ConstantExpr::get(Instruction::And, C1, C2)->isNullValue();
386 Instruction *apply(BinaryOperator &Add) const {
387 return BinaryOperator::create(Instruction::Or, Add.getOperand(0),
394 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
395 bool Changed = SimplifyCommutative(I);
396 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
399 if (RHS == Constant::getNullValue(I.getType()))
400 return ReplaceInstUsesWith(I, LHS);
403 if (I.getType()->isInteger())
404 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
407 if (Value *V = dyn_castNegVal(LHS))
408 return BinaryOperator::create(Instruction::Sub, RHS, V);
411 if (!isa<Constant>(RHS))
412 if (Value *V = dyn_castNegVal(RHS))
413 return BinaryOperator::create(Instruction::Sub, LHS, V);
415 // X*C + X --> X * (C+1)
416 if (dyn_castFoldableMul(LHS) == RHS) {
418 ConstantExpr::get(Instruction::Add,
419 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
420 ConstantInt::get(I.getType(), 1));
421 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
424 // X + X*C --> X * (C+1)
425 if (dyn_castFoldableMul(RHS) == LHS) {
427 ConstantExpr::get(Instruction::Add,
428 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
429 ConstantInt::get(I.getType(), 1));
430 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
433 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
434 if (Constant *C2 = dyn_castMaskingAnd(RHS))
435 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
437 return Changed ? &I : 0;
440 // isSignBit - Return true if the value represented by the constant only has the
441 // highest order bit set.
442 static bool isSignBit(ConstantInt *CI) {
443 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
444 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
447 static unsigned getTypeSizeInBits(const Type *Ty) {
448 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
451 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
452 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
454 if (Op0 == Op1) // sub X, X -> 0
455 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
457 // If this is a 'B = x-(-A)', change to B = x+A...
458 if (Value *V = dyn_castNegVal(Op1))
459 return BinaryOperator::create(Instruction::Add, Op0, V);
461 // Replace (-1 - A) with (~A)...
462 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
463 if (C->isAllOnesValue())
464 return BinaryOperator::createNot(Op1);
466 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
467 if (Op1I->use_size() == 1) {
468 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
469 // is not used by anyone else...
471 if (Op1I->getOpcode() == Instruction::Sub) {
472 // Swap the two operands of the subexpr...
473 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
474 Op1I->setOperand(0, IIOp1);
475 Op1I->setOperand(1, IIOp0);
477 // Create the new top level add instruction...
478 return BinaryOperator::create(Instruction::Add, Op0, Op1);
481 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
483 if (Op1I->getOpcode() == Instruction::And &&
484 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
485 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
487 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
488 return BinaryOperator::create(Instruction::And, Op0, NewNot);
491 // X - X*C --> X * (1-C)
492 if (dyn_castFoldableMul(Op1I) == Op0) {
494 ConstantExpr::get(Instruction::Sub,
495 ConstantInt::get(I.getType(), 1),
496 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
497 assert(CP1 && "Couldn't constant fold 1-C?");
498 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
502 // X*C - X --> X * (C-1)
503 if (dyn_castFoldableMul(Op0) == Op1) {
505 ConstantExpr::get(Instruction::Sub,
506 cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
507 ConstantInt::get(I.getType(), 1));
508 assert(CP1 && "Couldn't constant fold C - 1?");
509 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
515 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
516 bool Changed = SimplifyCommutative(I);
517 Value *Op0 = I.getOperand(0);
519 // Simplify mul instructions with a constant RHS...
520 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
521 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
523 // ((X << C1)*C2) == (X * (C2 << C1))
524 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
525 if (SI->getOpcode() == Instruction::Shl)
526 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
527 return BinaryOperator::create(Instruction::Mul, SI->getOperand(0),
530 const Type *Ty = CI->getType();
531 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
533 case -1: // X * -1 -> -X
534 return BinaryOperator::createNeg(Op0, I.getName());
536 return ReplaceInstUsesWith(I, Op1); // Eliminate 'mul double %X, 0'
538 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul int %X, 1'
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);
723 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
724 bool Changed = SimplifyCommutative(I);
725 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
727 // and X, X = X and X, 0 == 0
728 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
729 return ReplaceInstUsesWith(I, Op1);
732 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
733 if (RHS->isAllOnesValue())
734 return ReplaceInstUsesWith(I, Op0);
736 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
737 Value *X = Op0I->getOperand(0);
738 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
739 if (Op0I->getOpcode() == Instruction::Xor) {
740 if ((*RHS & *Op0CI)->isNullValue()) {
741 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
742 return BinaryOperator::create(Instruction::And, X, RHS);
743 } else if (isOnlyUse(Op0)) {
744 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
745 std::string Op0Name = Op0I->getName(); Op0I->setName("");
746 Instruction *And = BinaryOperator::create(Instruction::And,
748 InsertNewInstBefore(And, I);
749 return BinaryOperator::create(Instruction::Xor, And, *RHS & *Op0CI);
751 } else if (Op0I->getOpcode() == Instruction::Or) {
752 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
753 if ((*RHS & *Op0CI)->isNullValue())
754 return BinaryOperator::create(Instruction::And, X, RHS);
756 Constant *Together = *RHS & *Op0CI;
757 if (Together == RHS) // (X | C) & C --> C
758 return ReplaceInstUsesWith(I, RHS);
760 if (isOnlyUse(Op0)) {
761 if (Together != Op0CI) {
762 // (X | C1) & C2 --> (X | (C1&C2)) & C2
763 std::string Op0Name = Op0I->getName(); Op0I->setName("");
764 Instruction *Or = BinaryOperator::create(Instruction::Or, X,
766 InsertNewInstBefore(Or, I);
767 return BinaryOperator::create(Instruction::And, Or, RHS);
774 Value *Op0NotVal = dyn_castNotVal(Op0);
775 Value *Op1NotVal = dyn_castNotVal(Op1);
777 // (~A & ~B) == (~(A | B)) - Demorgan's Law
778 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
779 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
780 Op1NotVal,I.getName()+".demorgan");
781 InsertNewInstBefore(Or, I);
782 return BinaryOperator::createNot(Or);
785 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
786 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
788 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
789 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
790 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
793 return Changed ? &I : 0;
798 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
799 bool Changed = SimplifyCommutative(I);
800 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
802 // or X, X = X or X, 0 == X
803 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
804 return ReplaceInstUsesWith(I, Op0);
807 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
808 if (RHS->isAllOnesValue())
809 return ReplaceInstUsesWith(I, Op1);
811 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
812 // (X & C1) | C2 --> (X | C2) & (C1|C2)
813 if (Op0I->getOpcode() == Instruction::And && isOnlyUse(Op0))
814 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
815 std::string Op0Name = Op0I->getName(); Op0I->setName("");
816 Instruction *Or = BinaryOperator::create(Instruction::Or,
817 Op0I->getOperand(0), RHS,
819 InsertNewInstBefore(Or, I);
820 return BinaryOperator::create(Instruction::And, Or, *RHS | *Op0CI);
823 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
824 if (Op0I->getOpcode() == Instruction::Xor && isOnlyUse(Op0))
825 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
826 std::string Op0Name = Op0I->getName(); Op0I->setName("");
827 Instruction *Or = BinaryOperator::create(Instruction::Or,
828 Op0I->getOperand(0), RHS,
830 InsertNewInstBefore(Or, I);
831 return BinaryOperator::create(Instruction::Xor, Or, *Op0CI & *~*RHS);
836 // (A & C1)|(A & C2) == A & (C1|C2)
837 if (Instruction *LHS = dyn_cast<BinaryOperator>(Op0))
838 if (Instruction *RHS = dyn_cast<BinaryOperator>(Op1))
839 if (LHS->getOperand(0) == RHS->getOperand(0))
840 if (Constant *C0 = dyn_castMaskingAnd(LHS))
841 if (Constant *C1 = dyn_castMaskingAnd(RHS))
842 return BinaryOperator::create(Instruction::And, LHS->getOperand(0),
845 Value *Op0NotVal = dyn_castNotVal(Op0);
846 Value *Op1NotVal = dyn_castNotVal(Op1);
848 if (Op1 == Op0NotVal) // ~A | A == -1
849 return ReplaceInstUsesWith(I,
850 ConstantIntegral::getAllOnesValue(I.getType()));
852 if (Op0 == Op1NotVal) // A | ~A == -1
853 return ReplaceInstUsesWith(I,
854 ConstantIntegral::getAllOnesValue(I.getType()));
856 // (~A | ~B) == (~(A & B)) - Demorgan's Law
857 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
858 Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
859 Op1NotVal,I.getName()+".demorgan",
861 WorkList.push_back(And);
862 return BinaryOperator::createNot(And);
865 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
866 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
867 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
870 return Changed ? &I : 0;
875 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
876 bool Changed = SimplifyCommutative(I);
877 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
881 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
883 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
885 if (RHS->isNullValue())
886 return ReplaceInstUsesWith(I, Op0);
888 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
889 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
890 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
891 if (RHS == ConstantBool::True && SCI->use_size() == 1)
892 return new SetCondInst(SCI->getInverseCondition(),
893 SCI->getOperand(0), SCI->getOperand(1));
895 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
896 if (Op0I->getOpcode() == Instruction::And) {
897 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
898 if ((*RHS & *Op0CI)->isNullValue())
899 return BinaryOperator::create(Instruction::Or, Op0, RHS);
900 } else if (Op0I->getOpcode() == Instruction::Or) {
901 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
902 if ((*RHS & *Op0CI) == RHS)
903 return BinaryOperator::create(Instruction::And, Op0, ~*RHS);
908 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
910 return ReplaceInstUsesWith(I,
911 ConstantIntegral::getAllOnesValue(I.getType()));
913 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
915 return ReplaceInstUsesWith(I,
916 ConstantIntegral::getAllOnesValue(I.getType()));
918 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
919 if (Op1I->getOpcode() == Instruction::Or)
920 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
921 cast<BinaryOperator>(Op1I)->swapOperands();
924 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
929 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
930 if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
931 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
932 cast<BinaryOperator>(Op0I)->swapOperands();
933 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
934 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
935 WorkList.push_back(cast<Instruction>(NotB));
936 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
941 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
942 if (Constant *C1 = dyn_castMaskingAnd(Op0))
943 if (Constant *C2 = dyn_castMaskingAnd(Op1))
944 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
945 return BinaryOperator::create(Instruction::Or, Op0, Op1);
947 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
948 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
949 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
952 return Changed ? &I : 0;
955 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
956 static Constant *AddOne(ConstantInt *C) {
957 Constant *Result = ConstantExpr::get(Instruction::Add, C,
958 ConstantInt::get(C->getType(), 1));
959 assert(Result && "Constant folding integer addition failed!");
962 static Constant *SubOne(ConstantInt *C) {
963 Constant *Result = ConstantExpr::get(Instruction::Sub, C,
964 ConstantInt::get(C->getType(), 1));
965 assert(Result && "Constant folding integer addition failed!");
969 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
970 // true when both operands are equal...
972 static bool isTrueWhenEqual(Instruction &I) {
973 return I.getOpcode() == Instruction::SetEQ ||
974 I.getOpcode() == Instruction::SetGE ||
975 I.getOpcode() == Instruction::SetLE;
978 Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
979 bool Changed = SimplifyCommutative(I);
980 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
981 const Type *Ty = Op0->getType();
985 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
987 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
988 if (isa<ConstantPointerNull>(Op1) &&
989 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
990 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
993 // setcc's with boolean values can always be turned into bitwise operations
994 if (Ty == Type::BoolTy) {
995 // If this is <, >, or !=, we can change this into a simple xor instruction
996 if (!isTrueWhenEqual(I))
997 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
999 // Otherwise we need to make a temporary intermediate instruction and insert
1000 // it into the instruction stream. This is what we are after:
1002 // seteq bool %A, %B -> ~(A^B)
1003 // setle bool %A, %B -> ~A | B
1004 // setge bool %A, %B -> A | ~B
1006 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
1007 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
1009 InsertNewInstBefore(Xor, I);
1010 return BinaryOperator::createNot(Xor, I.getName());
1013 // Handle the setXe cases...
1014 assert(I.getOpcode() == Instruction::SetGE ||
1015 I.getOpcode() == Instruction::SetLE);
1017 if (I.getOpcode() == Instruction::SetGE)
1018 std::swap(Op0, Op1); // Change setge -> setle
1020 // Now we just have the SetLE case.
1021 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1022 InsertNewInstBefore(Not, I);
1023 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
1026 // Check to see if we are doing one of many comparisons against constant
1027 // integers at the end of their ranges...
1029 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1030 // Simplify seteq and setne instructions...
1031 if (I.getOpcode() == Instruction::SetEQ ||
1032 I.getOpcode() == Instruction::SetNE) {
1033 bool isSetNE = I.getOpcode() == Instruction::SetNE;
1035 // If the first operand is (and|or|xor) with a constant, and the second
1036 // operand is a constant, simplify a bit.
1037 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
1038 switch (BO->getOpcode()) {
1039 case Instruction::Add:
1040 if (CI->isNullValue()) {
1041 // Replace ((add A, B) != 0) with (A != -B) if A or B is
1042 // efficiently invertible, or if the add has just this one use.
1043 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
1044 if (Value *NegVal = dyn_castNegVal(BOp1))
1045 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
1046 else if (Value *NegVal = dyn_castNegVal(BOp0))
1047 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
1048 else if (BO->use_size() == 1) {
1049 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
1051 InsertNewInstBefore(Neg, I);
1052 return new SetCondInst(I.getOpcode(), BOp0, Neg);
1056 case Instruction::Xor:
1057 // For the xor case, we can xor two constants together, eliminating
1058 // the explicit xor.
1059 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1060 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
1064 case Instruction::Sub:
1065 // Replace (([sub|xor] A, B) != 0) with (A != B)
1066 if (CI->isNullValue())
1067 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
1071 case Instruction::Or:
1072 // If bits are being or'd in that are not present in the constant we
1073 // are comparing against, then the comparison could never succeed!
1074 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
1075 if (!(*BOC & *~*CI)->isNullValue())
1076 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
1079 case Instruction::And:
1080 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
1081 // If bits are being compared against that are and'd out, then the
1082 // comparison can never succeed!
1083 if (!(*CI & *~*BOC)->isNullValue())
1084 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
1086 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
1087 // to be a signed value as appropriate.
1088 if (isSignBit(BOC)) {
1089 Value *X = BO->getOperand(0);
1090 // If 'X' is not signed, insert a cast now...
1091 if (!BOC->getType()->isSigned()) {
1093 switch (BOC->getType()->getPrimitiveID()) {
1094 case Type::UByteTyID: DestTy = Type::SByteTy; break;
1095 case Type::UShortTyID: DestTy = Type::ShortTy; break;
1096 case Type::UIntTyID: DestTy = Type::IntTy; break;
1097 case Type::ULongTyID: DestTy = Type::LongTy; break;
1098 default: assert(0 && "Invalid unsigned integer type!"); abort();
1100 CastInst *NewCI = new CastInst(X,DestTy,X->getName()+".signed");
1101 InsertNewInstBefore(NewCI, I);
1104 return new SetCondInst(isSetNE ? Instruction::SetLT :
1105 Instruction::SetGE, X,
1106 Constant::getNullValue(X->getType()));
1114 // Check to see if we are comparing against the minimum or maximum value...
1115 if (CI->isMinValue()) {
1116 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1117 return ReplaceInstUsesWith(I, ConstantBool::False);
1118 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1119 return ReplaceInstUsesWith(I, ConstantBool::True);
1120 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
1121 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
1122 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
1123 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
1125 } else if (CI->isMaxValue()) {
1126 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1127 return ReplaceInstUsesWith(I, ConstantBool::False);
1128 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1129 return ReplaceInstUsesWith(I, ConstantBool::True);
1130 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
1131 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
1132 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
1133 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
1135 // Comparing against a value really close to min or max?
1136 } else if (isMinValuePlusOne(CI)) {
1137 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
1138 return BinaryOperator::create(Instruction::SetEQ, Op0,
1139 SubOne(CI), I.getName());
1140 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
1141 return BinaryOperator::create(Instruction::SetNE, Op0,
1142 SubOne(CI), I.getName());
1144 } else if (isMaxValueMinusOne(CI)) {
1145 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
1146 return BinaryOperator::create(Instruction::SetEQ, Op0,
1147 AddOne(CI), I.getName());
1148 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
1149 return BinaryOperator::create(Instruction::SetNE, Op0,
1150 AddOne(CI), I.getName());
1154 return Changed ? &I : 0;
1159 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
1160 assert(I.getOperand(1)->getType() == Type::UByteTy);
1161 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1162 bool isLeftShift = I.getOpcode() == Instruction::Shl;
1164 // shl X, 0 == X and shr X, 0 == X
1165 // shl 0, X == 0 and shr 0, X == 0
1166 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
1167 Op0 == Constant::getNullValue(Op0->getType()))
1168 return ReplaceInstUsesWith(I, Op0);
1170 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
1172 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1173 if (CSI->isAllOnesValue())
1174 return ReplaceInstUsesWith(I, CSI);
1176 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
1177 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
1178 // of a signed value.
1180 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
1181 if (CUI->getValue() >= TypeBits &&
1182 (!Op0->getType()->isSigned() || isLeftShift))
1183 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
1185 // ((X*C1) << C2) == (X * (C1 << C2))
1186 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
1187 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
1188 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
1189 return BinaryOperator::create(Instruction::Mul, BO->getOperand(0),
1193 // If the operand is an bitwise operator with a constant RHS, and the
1194 // shift is the only use, we can pull it out of the shift.
1195 if (Op0->use_size() == 1)
1196 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
1197 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
1198 bool isValid = true; // Valid only for And, Or, Xor
1199 bool highBitSet = false; // Transform if high bit of constant set?
1201 switch (Op0BO->getOpcode()) {
1202 default: isValid = false; break; // Do not perform transform!
1203 case Instruction::Or:
1204 case Instruction::Xor:
1207 case Instruction::And:
1212 // If this is a signed shift right, and the high bit is modified
1213 // by the logical operation, do not perform the transformation.
1214 // The highBitSet boolean indicates the value of the high bit of
1215 // the constant which would cause it to be modified for this
1218 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
1219 uint64_t Val = Op0C->getRawValue();
1220 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
1225 ConstantFoldShiftInstruction(I.getOpcode(), Op0C, CUI);
1227 Instruction *NewShift =
1228 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
1231 InsertNewInstBefore(NewShift, I);
1233 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
1238 // If this is a shift of a shift, see if we can fold the two together...
1239 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
1240 if (ConstantUInt *ShiftAmt1C =
1241 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
1242 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
1243 unsigned ShiftAmt2 = CUI->getValue();
1245 // Check for (A << c1) << c2 and (A >> c1) >> c2
1246 if (I.getOpcode() == Op0SI->getOpcode()) {
1247 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
1248 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
1249 ConstantUInt::get(Type::UByteTy, Amt));
1252 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
1253 // signed types, we can only support the (A >> c1) << c2 configuration,
1254 // because it can not turn an arbitrary bit of A into a sign bit.
1255 if (I.getType()->isUnsigned() || isLeftShift) {
1256 // Calculate bitmask for what gets shifted off the edge...
1257 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
1259 C = ConstantExpr::getShift(Instruction::Shl, C, ShiftAmt1C);
1261 C = ConstantExpr::getShift(Instruction::Shr, C, ShiftAmt1C);
1264 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
1265 C, Op0SI->getOperand(0)->getName()+".mask");
1266 InsertNewInstBefore(Mask, I);
1268 // Figure out what flavor of shift we should use...
1269 if (ShiftAmt1 == ShiftAmt2)
1270 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
1271 else if (ShiftAmt1 < ShiftAmt2) {
1272 return new ShiftInst(I.getOpcode(), Mask,
1273 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
1275 return new ShiftInst(Op0SI->getOpcode(), Mask,
1276 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
1286 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
1289 static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
1290 const Type *DstTy) {
1292 // It is legal to eliminate the instruction if casting A->B->A if the sizes
1293 // are identical and the bits don't get reinterpreted (for example
1294 // int->float->int would not be allowed)
1295 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
1298 // Allow free casting and conversion of sizes as long as the sign doesn't
1300 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
1301 unsigned SrcSize = SrcTy->getPrimitiveSize();
1302 unsigned MidSize = MidTy->getPrimitiveSize();
1303 unsigned DstSize = DstTy->getPrimitiveSize();
1305 // Cases where we are monotonically decreasing the size of the type are
1306 // always ok, regardless of what sign changes are going on.
1308 if (SrcSize >= MidSize && MidSize >= DstSize)
1311 // Cases where the source and destination type are the same, but the middle
1312 // type is bigger are noops.
1314 if (SrcSize == DstSize && MidSize > SrcSize)
1317 // If we are monotonically growing, things are more complex.
1319 if (SrcSize <= MidSize && MidSize <= DstSize) {
1320 // We have eight combinations of signedness to worry about. Here's the
1322 static const int SignTable[8] = {
1323 // CODE, SrcSigned, MidSigned, DstSigned, Comment
1324 1, // U U U Always ok
1325 1, // U U S Always ok
1326 3, // U S U Ok iff SrcSize != MidSize
1327 3, // U S S Ok iff SrcSize != MidSize
1328 0, // S U U Never ok
1329 2, // S U S Ok iff MidSize == DstSize
1330 1, // S S U Always ok
1331 1, // S S S Always ok
1334 // Choose an action based on the current entry of the signtable that this
1335 // cast of cast refers to...
1336 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
1337 switch (SignTable[Row]) {
1338 case 0: return false; // Never ok
1339 case 1: return true; // Always ok
1340 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
1341 case 3: // Ok iff SrcSize != MidSize
1342 return SrcSize != MidSize || SrcTy == Type::BoolTy;
1343 default: assert(0 && "Bad entry in sign table!");
1348 // Otherwise, we cannot succeed. Specifically we do not want to allow things
1349 // like: short -> ushort -> uint, because this can create wrong results if
1350 // the input short is negative!
1355 static bool ValueRequiresCast(const Value *V, const Type *Ty) {
1356 if (V->getType() == Ty || isa<Constant>(V)) return false;
1357 if (const CastInst *CI = dyn_cast<CastInst>(V))
1358 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty))
1363 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
1364 /// InsertBefore instruction. This is specialized a bit to avoid inserting
1365 /// casts that are known to not do anything...
1367 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
1368 Instruction *InsertBefore) {
1369 if (V->getType() == DestTy) return V;
1370 if (Constant *C = dyn_cast<Constant>(V))
1371 return ConstantExpr::getCast(C, DestTy);
1373 CastInst *CI = new CastInst(V, DestTy, V->getName());
1374 InsertNewInstBefore(CI, *InsertBefore);
1378 // CastInst simplification
1380 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
1381 Value *Src = CI.getOperand(0);
1383 // If the user is casting a value to the same type, eliminate this cast
1385 if (CI.getType() == Src->getType())
1386 return ReplaceInstUsesWith(CI, Src);
1388 // If casting the result of another cast instruction, try to eliminate this
1391 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
1392 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
1393 CSrc->getType(), CI.getType())) {
1394 // This instruction now refers directly to the cast's src operand. This
1395 // has a good chance of making CSrc dead.
1396 CI.setOperand(0, CSrc->getOperand(0));
1400 // If this is an A->B->A cast, and we are dealing with integral types, try
1401 // to convert this into a logical 'and' instruction.
1403 if (CSrc->getOperand(0)->getType() == CI.getType() &&
1404 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
1405 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
1406 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
1407 assert(CSrc->getType() != Type::ULongTy &&
1408 "Cannot have type bigger than ulong!");
1409 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
1410 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
1411 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
1416 // If casting the result of a getelementptr instruction with no offset, turn
1417 // this into a cast of the original pointer!
1419 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1420 bool AllZeroOperands = true;
1421 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1422 if (!isa<Constant>(GEP->getOperand(i)) ||
1423 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
1424 AllZeroOperands = false;
1427 if (AllZeroOperands) {
1428 CI.setOperand(0, GEP->getOperand(0));
1433 // If the source value is an instruction with only this use, we can attempt to
1434 // propagate the cast into the instruction. Also, only handle integral types
1436 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
1437 if (SrcI->use_size() == 1 && Src->getType()->isIntegral() &&
1438 CI.getType()->isInteger()) { // Don't mess with casts to bool here
1439 const Type *DestTy = CI.getType();
1440 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
1441 unsigned DestBitSize = getTypeSizeInBits(DestTy);
1443 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
1444 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
1446 switch (SrcI->getOpcode()) {
1447 case Instruction::Add:
1448 case Instruction::Mul:
1449 case Instruction::And:
1450 case Instruction::Or:
1451 case Instruction::Xor:
1452 // If we are discarding information, or just changing the sign, rewrite.
1453 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
1454 // Don't insert two casts if they cannot be eliminated. We allow two
1455 // casts to be inserted if the sizes are the same. This could only be
1456 // converting signedness, which is a noop.
1457 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy) ||
1458 !ValueRequiresCast(Op0, DestTy)) {
1459 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1460 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
1461 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
1462 ->getOpcode(), Op0c, Op1c);
1466 case Instruction::Shl:
1467 // Allow changing the sign of the source operand. Do not allow changing
1468 // the size of the shift, UNLESS the shift amount is a constant. We
1469 // mush not change variable sized shifts to a smaller size, because it
1470 // is undefined to shift more bits out than exist in the value.
1471 if (DestBitSize == SrcBitSize ||
1472 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
1473 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1474 return new ShiftInst(Instruction::Shl, Op0c, Op1);
1483 // CallInst simplification
1485 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
1486 if (transformConstExprCastCall(&CI)) return 0;
1490 // InvokeInst simplification
1492 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
1493 if (transformConstExprCastCall(&II)) return 0;
1497 // getPromotedType - Return the specified type promoted as it would be to pass
1498 // though a va_arg area...
1499 static const Type *getPromotedType(const Type *Ty) {
1500 switch (Ty->getPrimitiveID()) {
1501 case Type::SByteTyID:
1502 case Type::ShortTyID: return Type::IntTy;
1503 case Type::UByteTyID:
1504 case Type::UShortTyID: return Type::UIntTy;
1505 case Type::FloatTyID: return Type::DoubleTy;
1510 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
1511 // attempt to move the cast to the arguments of the call/invoke.
1513 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
1514 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
1515 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
1516 if (CE->getOpcode() != Instruction::Cast ||
1517 !isa<ConstantPointerRef>(CE->getOperand(0)))
1519 ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
1520 if (!isa<Function>(CPR->getValue())) return false;
1521 Function *Callee = cast<Function>(CPR->getValue());
1522 Instruction *Caller = CS.getInstruction();
1524 // Okay, this is a cast from a function to a different type. Unless doing so
1525 // would cause a type conversion of one of our arguments, change this call to
1526 // be a direct call with arguments casted to the appropriate types.
1528 const FunctionType *FT = Callee->getFunctionType();
1529 const Type *OldRetTy = Caller->getType();
1531 if (Callee->isExternal() &&
1532 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()))
1533 return false; // Cannot transform this return value...
1535 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1536 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1538 CallSite::arg_iterator AI = CS.arg_begin();
1539 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1540 const Type *ParamTy = FT->getParamType(i);
1541 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
1542 if (Callee->isExternal() && !isConvertible) return false;
1545 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
1546 Callee->isExternal())
1547 return false; // Do not delete arguments unless we have a function body...
1549 // Okay, we decided that this is a safe thing to do: go ahead and start
1550 // inserting cast instructions as necessary...
1551 std::vector<Value*> Args;
1552 Args.reserve(NumActualArgs);
1554 AI = CS.arg_begin();
1555 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1556 const Type *ParamTy = FT->getParamType(i);
1557 if ((*AI)->getType() == ParamTy) {
1558 Args.push_back(*AI);
1560 Instruction *Cast = new CastInst(*AI, ParamTy, "tmp");
1561 InsertNewInstBefore(Cast, *Caller);
1562 Args.push_back(Cast);
1566 // If the function takes more arguments than the call was taking, add them
1568 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1569 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1571 // If we are removing arguments to the function, emit an obnoxious warning...
1572 if (FT->getNumParams() < NumActualArgs)
1573 if (!FT->isVarArg()) {
1574 std::cerr << "WARNING: While resolving call to function '"
1575 << Callee->getName() << "' arguments were dropped!\n";
1577 // Add all of the arguments in their promoted form to the arg list...
1578 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1579 const Type *PTy = getPromotedType((*AI)->getType());
1580 if (PTy != (*AI)->getType()) {
1581 // Must promote to pass through va_arg area!
1582 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
1583 InsertNewInstBefore(Cast, *Caller);
1584 Args.push_back(Cast);
1586 Args.push_back(*AI);
1591 if (FT->getReturnType() == Type::VoidTy)
1592 Caller->setName(""); // Void type should not have a name...
1595 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1596 NC = new InvokeInst(Callee, II->getNormalDest(), II->getExceptionalDest(),
1597 Args, Caller->getName(), Caller);
1599 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
1602 // Insert a cast of the return type as necessary...
1604 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
1605 if (NV->getType() != Type::VoidTy) {
1606 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
1607 InsertNewInstBefore(NC, *Caller);
1608 AddUsesToWorkList(*Caller);
1610 NV = Constant::getNullValue(Caller->getType());
1614 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
1615 Caller->replaceAllUsesWith(NV);
1616 Caller->getParent()->getInstList().erase(Caller);
1617 removeFromWorkList(Caller);
1623 // PHINode simplification
1625 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
1626 // If the PHI node only has one incoming value, eliminate the PHI node...
1627 if (PN.getNumIncomingValues() == 1)
1628 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
1630 // Otherwise if all of the incoming values are the same for the PHI, replace
1631 // the PHI node with the incoming value.
1634 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1635 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
1636 if (InVal && PN.getIncomingValue(i) != InVal)
1637 return 0; // Not the same, bail out.
1639 InVal = PN.getIncomingValue(i);
1641 // The only case that could cause InVal to be null is if we have a PHI node
1642 // that only has entries for itself. In this case, there is no entry into the
1643 // loop, so kill the PHI.
1645 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
1647 // All of the incoming values are the same, replace the PHI node now.
1648 return ReplaceInstUsesWith(PN, InVal);
1652 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1653 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
1654 // If so, eliminate the noop.
1655 if ((GEP.getNumOperands() == 2 &&
1656 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
1657 GEP.getNumOperands() == 1)
1658 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
1660 // Combine Indices - If the source pointer to this getelementptr instruction
1661 // is a getelementptr instruction, combine the indices of the two
1662 // getelementptr instructions into a single instruction.
1664 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
1665 std::vector<Value *> Indices;
1667 // Can we combine the two pointer arithmetics offsets?
1668 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
1669 isa<Constant>(GEP.getOperand(1))) {
1670 // Replace: gep (gep %P, long C1), long C2, ...
1671 // With: gep %P, long (C1+C2), ...
1672 Value *Sum = ConstantExpr::get(Instruction::Add,
1673 cast<Constant>(Src->getOperand(1)),
1674 cast<Constant>(GEP.getOperand(1)));
1675 assert(Sum && "Constant folding of longs failed!?");
1676 GEP.setOperand(0, Src->getOperand(0));
1677 GEP.setOperand(1, Sum);
1678 AddUsesToWorkList(*Src); // Reduce use count of Src
1680 } else if (Src->getNumOperands() == 2) {
1681 // Replace: gep (gep %P, long B), long A, ...
1682 // With: T = long A+B; gep %P, T, ...
1684 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
1686 Src->getName()+".sum", &GEP);
1687 GEP.setOperand(0, Src->getOperand(0));
1688 GEP.setOperand(1, Sum);
1689 WorkList.push_back(cast<Instruction>(Sum));
1691 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
1692 Src->getNumOperands() != 1) {
1693 // Otherwise we can do the fold if the first index of the GEP is a zero
1694 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
1695 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
1696 } else if (Src->getOperand(Src->getNumOperands()-1) ==
1697 Constant::getNullValue(Type::LongTy)) {
1698 // If the src gep ends with a constant array index, merge this get into
1699 // it, even if we have a non-zero array index.
1700 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
1701 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
1704 if (!Indices.empty())
1705 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
1707 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
1708 // GEP of global variable. If all of the indices for this GEP are
1709 // constants, we can promote this to a constexpr instead of an instruction.
1711 // Scan for nonconstants...
1712 std::vector<Constant*> Indices;
1713 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1714 for (; I != E && isa<Constant>(*I); ++I)
1715 Indices.push_back(cast<Constant>(*I));
1717 if (I == E) { // If they are all constants...
1719 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1721 // Replace all uses of the GEP with the new constexpr...
1722 return ReplaceInstUsesWith(GEP, CE);
1729 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1730 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1731 if (AI.isArrayAllocation()) // Check C != 1
1732 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1733 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
1734 AllocationInst *New = 0;
1736 // Create and insert the replacement instruction...
1737 if (isa<MallocInst>(AI))
1738 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
1740 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
1741 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
1744 // Scan to the end of the allocation instructions, to skip over a block of
1745 // allocas if possible...
1747 BasicBlock::iterator It = New;
1748 while (isa<AllocationInst>(*It)) ++It;
1750 // Now that I is pointing to the first non-allocation-inst in the block,
1751 // insert our getelementptr instruction...
1753 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1754 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1756 // Now make everything use the getelementptr instead of the original
1758 ReplaceInstUsesWith(AI, V);
1764 /// GetGEPGlobalInitializer - Given a constant, and a getelementptr
1765 /// constantexpr, return the constant value being addressed by the constant
1766 /// expression, or null if something is funny.
1768 static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
1769 if (CE->getOperand(1) != Constant::getNullValue(Type::LongTy))
1770 return 0; // Do not allow stepping over the value!
1772 // Loop over all of the operands, tracking down which value we are
1774 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
1775 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
1776 ConstantStruct *CS = cast<ConstantStruct>(C);
1777 if (CU->getValue() >= CS->getValues().size()) return 0;
1778 C = cast<Constant>(CS->getValues()[CU->getValue()]);
1779 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
1780 ConstantArray *CA = cast<ConstantArray>(C);
1781 if ((uint64_t)CS->getValue() >= CA->getValues().size()) return 0;
1782 C = cast<Constant>(CA->getValues()[CS->getValue()]);
1788 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
1789 Value *Op = LI.getOperand(0);
1790 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Op))
1791 Op = CPR->getValue();
1793 // Instcombine load (constant global) into the value loaded...
1794 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
1795 if (GV->isConstant() && !GV->isExternal())
1796 return ReplaceInstUsesWith(LI, GV->getInitializer());
1798 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
1799 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
1800 if (CE->getOpcode() == Instruction::GetElementPtr)
1801 if (ConstantPointerRef *G=dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
1802 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
1803 if (GV->isConstant() && !GV->isExternal())
1804 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
1805 return ReplaceInstUsesWith(LI, V);
1810 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1811 // Change br (not X), label True, label False to: br X, label False, True
1812 if (BI.isConditional() && !isa<Constant>(BI.getCondition()))
1813 if (Value *V = dyn_castNotVal(BI.getCondition())) {
1814 BasicBlock *TrueDest = BI.getSuccessor(0);
1815 BasicBlock *FalseDest = BI.getSuccessor(1);
1816 // Swap Destinations and condition...
1818 BI.setSuccessor(0, FalseDest);
1819 BI.setSuccessor(1, TrueDest);
1826 void InstCombiner::removeFromWorkList(Instruction *I) {
1827 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1831 bool InstCombiner::runOnFunction(Function &F) {
1832 bool Changed = false;
1834 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
1836 while (!WorkList.empty()) {
1837 Instruction *I = WorkList.back(); // Get an instruction from the worklist
1838 WorkList.pop_back();
1840 // Check to see if we can DCE or ConstantPropagate the instruction...
1841 // Check to see if we can DIE the instruction...
1842 if (isInstructionTriviallyDead(I)) {
1843 // Add operands to the worklist...
1844 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1845 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1846 WorkList.push_back(Op);
1849 BasicBlock::iterator BBI = I;
1850 if (dceInstruction(BBI)) {
1851 removeFromWorkList(I);
1856 // Instruction isn't dead, see if we can constant propagate it...
1857 if (Constant *C = ConstantFoldInstruction(I)) {
1858 // Add operands to the worklist...
1859 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1860 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1861 WorkList.push_back(Op);
1862 ReplaceInstUsesWith(*I, C);
1865 BasicBlock::iterator BBI = I;
1866 if (dceInstruction(BBI)) {
1867 removeFromWorkList(I);
1872 // Now that we have an instruction, try combining it to simplify it...
1873 if (Instruction *Result = visit(*I)) {
1875 // Should we replace the old instruction with a new one?
1877 // Instructions can end up on the worklist more than once. Make sure
1878 // we do not process an instruction that has been deleted.
1879 removeFromWorkList(I);
1880 ReplaceInstWithInst(I, Result);
1882 BasicBlock::iterator II = I;
1884 // If the instruction was modified, it's possible that it is now dead.
1885 // if so, remove it.
1886 if (dceInstruction(II)) {
1887 // Instructions may end up in the worklist more than once. Erase them
1889 removeFromWorkList(I);
1895 WorkList.push_back(Result);
1896 AddUsesToWorkList(*Result);
1905 Pass *createInstructionCombiningPass() {
1906 return new InstCombiner();