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 cannonicalizations are performed on
17 // 1. If a binary operator has a constant operand, it is moved to the RHS
18 // 2. Logical operators with constant operands are always grouped so that
19 // 'or's are performed first, 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 // N. This list is incomplete
24 //===----------------------------------------------------------------------===//
26 #include "llvm/Transforms/Scalar.h"
27 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
28 #include "llvm/Transforms/Utils/Local.h"
29 #include "llvm/Instructions.h"
30 #include "llvm/Pass.h"
31 #include "llvm/Constants.h"
32 #include "llvm/ConstantHandling.h"
33 #include "llvm/DerivedTypes.h"
34 #include "llvm/GlobalVariable.h"
35 #include "llvm/Support/InstIterator.h"
36 #include "llvm/Support/InstVisitor.h"
37 #include "llvm/Support/CallSite.h"
38 #include "Support/Statistic.h"
42 Statistic<> NumCombined ("instcombine", "Number of insts combined");
43 Statistic<> NumConstProp("instcombine", "Number of constant folds");
44 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
46 class InstCombiner : public FunctionPass,
47 public InstVisitor<InstCombiner, Instruction*> {
48 // Worklist of all of the instructions that need to be simplified.
49 std::vector<Instruction*> WorkList;
51 void AddUsesToWorkList(Instruction &I) {
52 // The instruction was simplified, add all users of the instruction to
53 // the work lists because they might get more simplified now...
55 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
57 WorkList.push_back(cast<Instruction>(*UI));
60 // removeFromWorkList - remove all instances of I from the worklist.
61 void removeFromWorkList(Instruction *I);
63 virtual bool runOnFunction(Function &F);
65 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
69 // Visitation implementation - Implement instruction combining for different
70 // instruction types. The semantics are as follows:
72 // null - No change was made
73 // I - Change was made, I is still valid, I may be dead though
74 // otherwise - Change was made, replace I with returned instruction
76 Instruction *visitAdd(BinaryOperator &I);
77 Instruction *visitSub(BinaryOperator &I);
78 Instruction *visitMul(BinaryOperator &I);
79 Instruction *visitDiv(BinaryOperator &I);
80 Instruction *visitRem(BinaryOperator &I);
81 Instruction *visitAnd(BinaryOperator &I);
82 Instruction *visitOr (BinaryOperator &I);
83 Instruction *visitXor(BinaryOperator &I);
84 Instruction *visitSetCondInst(BinaryOperator &I);
85 Instruction *visitShiftInst(ShiftInst &I);
86 Instruction *visitCastInst(CastInst &CI);
87 Instruction *visitCallInst(CallInst &CI);
88 Instruction *visitInvokeInst(InvokeInst &II);
89 Instruction *visitPHINode(PHINode &PN);
90 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
91 Instruction *visitAllocationInst(AllocationInst &AI);
92 Instruction *visitLoadInst(LoadInst &LI);
93 Instruction *visitBranchInst(BranchInst &BI);
95 // visitInstruction - Specify what to return for unhandled instructions...
96 Instruction *visitInstruction(Instruction &I) { return 0; }
99 bool transformConstExprCastCall(CallSite CS);
101 // InsertNewInstBefore - insert an instruction New before instruction Old
102 // in the program. Add the new instruction to the worklist.
104 void InsertNewInstBefore(Instruction *New, Instruction &Old) {
105 assert(New && New->getParent() == 0 &&
106 "New instruction already inserted into a basic block!");
107 BasicBlock *BB = Old.getParent();
108 BB->getInstList().insert(&Old, New); // Insert inst
109 WorkList.push_back(New); // Add to worklist
112 // ReplaceInstUsesWith - This method is to be used when an instruction is
113 // found to be dead, replacable with another preexisting expression. Here
114 // we add all uses of I to the worklist, replace all uses of I with the new
115 // value, then return I, so that the inst combiner will know that I was
118 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
119 AddUsesToWorkList(I); // Add all modified instrs to worklist
120 I.replaceAllUsesWith(V);
124 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
125 /// InsertBefore instruction. This is specialized a bit to avoid inserting
126 /// casts that are known to not do anything...
128 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
129 Instruction *InsertBefore);
131 // SimplifyCommutative - This performs a few simplifications for commutative
133 bool SimplifyCommutative(BinaryOperator &I);
136 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
139 // getComplexity: Assign a complexity or rank value to LLVM Values...
140 // 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
141 static unsigned getComplexity(Value *V) {
142 if (isa<Instruction>(V)) {
143 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
147 if (isa<Argument>(V)) return 2;
148 return isa<Constant>(V) ? 0 : 1;
151 // isOnlyUse - Return true if this instruction will be deleted if we stop using
153 static bool isOnlyUse(Value *V) {
154 return V->use_size() == 1 || isa<Constant>(V);
157 // SimplifyCommutative - This performs a few simplifications for commutative
160 // 1. Order operands such that they are listed from right (least complex) to
161 // left (most complex). This puts constants before unary operators before
164 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
165 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
167 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
168 bool Changed = false;
169 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
170 Changed = !I.swapOperands();
172 if (!I.isAssociative()) return Changed;
173 Instruction::BinaryOps Opcode = I.getOpcode();
174 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
175 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
176 if (isa<Constant>(I.getOperand(1))) {
177 Constant *Folded = ConstantExpr::get(I.getOpcode(),
178 cast<Constant>(I.getOperand(1)),
179 cast<Constant>(Op->getOperand(1)));
180 I.setOperand(0, Op->getOperand(0));
181 I.setOperand(1, Folded);
183 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
184 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
185 isOnlyUse(Op) && isOnlyUse(Op1)) {
186 Constant *C1 = cast<Constant>(Op->getOperand(1));
187 Constant *C2 = cast<Constant>(Op1->getOperand(1));
189 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
190 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
191 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
194 WorkList.push_back(New);
195 I.setOperand(0, New);
196 I.setOperand(1, Folded);
203 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
204 // if the LHS is a constant zero (which is the 'negate' form).
206 static inline Value *dyn_castNegVal(Value *V) {
207 if (BinaryOperator::isNeg(V))
208 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
210 // Constants can be considered to be negated values if they can be folded...
211 if (Constant *C = dyn_cast<Constant>(V))
212 return ConstantExpr::get(Instruction::Sub,
213 Constant::getNullValue(V->getType()), C);
217 static inline Value *dyn_castNotVal(Value *V) {
218 if (BinaryOperator::isNot(V))
219 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
221 // Constants can be considered to be not'ed values...
222 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
223 return ConstantExpr::get(Instruction::Xor,
224 ConstantIntegral::getAllOnesValue(C->getType()),C);
228 // dyn_castFoldableMul - If this value is a multiply that can be folded into
229 // other computations (because it has a constant operand), return the
230 // non-constant operand of the multiply.
232 static inline Value *dyn_castFoldableMul(Value *V) {
233 if (V->use_size() == 1 && V->getType()->isInteger())
234 if (Instruction *I = dyn_cast<Instruction>(V))
235 if (I->getOpcode() == Instruction::Mul)
236 if (isa<Constant>(I->getOperand(1)))
237 return I->getOperand(0);
241 // dyn_castMaskingAnd - If this value is an And instruction masking a value with
242 // a constant, return the constant being anded with.
244 template<class ValueType>
245 static inline Constant *dyn_castMaskingAnd(ValueType *V) {
246 if (Instruction *I = dyn_cast<Instruction>(V))
247 if (I->getOpcode() == Instruction::And)
248 return dyn_cast<Constant>(I->getOperand(1));
250 // If this is a constant, it acts just like we were masking with it.
251 return dyn_cast<Constant>(V);
254 // Log2 - Calculate the log base 2 for the specified value if it is exactly a
256 static unsigned Log2(uint64_t Val) {
257 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
260 if (Val & 1) return 0; // Multiple bits set?
267 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
268 bool Changed = SimplifyCommutative(I);
269 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
271 // Eliminate 'add int %X, 0'
272 if (RHS == Constant::getNullValue(I.getType()))
273 return ReplaceInstUsesWith(I, LHS);
276 if (Value *V = dyn_castNegVal(LHS))
277 return BinaryOperator::create(Instruction::Sub, RHS, V);
280 if (!isa<Constant>(RHS))
281 if (Value *V = dyn_castNegVal(RHS))
282 return BinaryOperator::create(Instruction::Sub, LHS, V);
284 // X*C + X --> X * (C+1)
285 if (dyn_castFoldableMul(LHS) == RHS) {
287 ConstantExpr::get(Instruction::Add,
288 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
289 ConstantInt::get(I.getType(), 1));
290 return BinaryOperator::create(Instruction::Mul, RHS, CP1);
293 // X + X*C --> X * (C+1)
294 if (dyn_castFoldableMul(RHS) == LHS) {
296 ConstantExpr::get(Instruction::Add,
297 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
298 ConstantInt::get(I.getType(), 1));
299 return BinaryOperator::create(Instruction::Mul, LHS, CP1);
302 // (A & C1)+(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
303 if (Constant *C1 = dyn_castMaskingAnd(LHS))
304 if (Constant *C2 = dyn_castMaskingAnd(RHS))
305 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
306 return BinaryOperator::create(Instruction::Or, LHS, RHS);
308 return Changed ? &I : 0;
311 // isSignBit - Return true if the value represented by the constant only has the
312 // highest order bit set.
313 static bool isSignBit(ConstantInt *CI) {
314 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
315 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
318 static unsigned getTypeSizeInBits(const Type *Ty) {
319 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
322 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
323 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
325 if (Op0 == Op1) // sub X, X -> 0
326 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
328 // If this is a 'B = x-(-A)', change to B = x+A...
329 if (Value *V = dyn_castNegVal(Op1))
330 return BinaryOperator::create(Instruction::Add, Op0, V);
332 // Replace (-1 - A) with (~A)...
333 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0))
334 if (C->isAllOnesValue())
335 return BinaryOperator::createNot(Op1);
337 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
338 if (Op1I->use_size() == 1) {
339 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
340 // is not used by anyone else...
342 if (Op1I->getOpcode() == Instruction::Sub) {
343 // Swap the two operands of the subexpr...
344 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
345 Op1I->setOperand(0, IIOp1);
346 Op1I->setOperand(1, IIOp0);
348 // Create the new top level add instruction...
349 return BinaryOperator::create(Instruction::Add, Op0, Op1);
352 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
354 if (Op1I->getOpcode() == Instruction::And &&
355 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
356 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
358 Instruction *NewNot = BinaryOperator::createNot(OtherOp, "B.not", &I);
359 return BinaryOperator::create(Instruction::And, Op0, NewNot);
362 // X - X*C --> X * (1-C)
363 if (dyn_castFoldableMul(Op1I) == Op0) {
365 ConstantExpr::get(Instruction::Sub,
366 ConstantInt::get(I.getType(), 1),
367 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
368 assert(CP1 && "Couldn't constant fold 1-C?");
369 return BinaryOperator::create(Instruction::Mul, Op0, CP1);
373 // X*C - X --> X * (C-1)
374 if (dyn_castFoldableMul(Op0) == Op1) {
376 ConstantExpr::get(Instruction::Sub,
377 cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
378 ConstantInt::get(I.getType(), 1));
379 assert(CP1 && "Couldn't constant fold C - 1?");
380 return BinaryOperator::create(Instruction::Mul, Op1, CP1);
386 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
387 bool Changed = SimplifyCommutative(I);
388 Value *Op0 = I.getOperand(0);
390 // Simplify mul instructions with a constant RHS...
391 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
392 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
393 const Type *Ty = CI->getType();
394 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
396 case -1: // X * -1 -> -X
397 return BinaryOperator::createNeg(Op0, I.getName());
399 return ReplaceInstUsesWith(I, Op1); // Eliminate 'mul double %X, 0'
401 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul int %X, 1'
402 case 2: // Convert 'mul int %X, 2' to 'add int %X, %X'
403 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
406 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
407 return new ShiftInst(Instruction::Shl, Op0,
408 ConstantUInt::get(Type::UByteTy, C));
410 ConstantFP *Op1F = cast<ConstantFP>(Op1);
411 if (Op1F->isNullValue())
412 return ReplaceInstUsesWith(I, Op1);
414 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
415 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
416 if (Op1F->getValue() == 1.0)
417 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
421 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
422 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
423 return BinaryOperator::create(Instruction::Mul, Op0v, Op1v);
425 return Changed ? &I : 0;
428 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
430 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
431 if (RHS->equalsInt(1))
432 return ReplaceInstUsesWith(I, I.getOperand(0));
434 // Check to see if this is an unsigned division with an exact power of 2,
435 // if so, convert to a right shift.
436 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
437 if (uint64_t Val = C->getValue()) // Don't break X / 0
438 if (uint64_t C = Log2(Val))
439 return new ShiftInst(Instruction::Shr, I.getOperand(0),
440 ConstantUInt::get(Type::UByteTy, C));
443 // 0 / X == 0, we don't need to preserve faults!
444 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
445 if (LHS->equalsInt(0))
446 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
452 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
453 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
454 if (RHS->equalsInt(1)) // X % 1 == 0
455 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
457 // Check to see if this is an unsigned remainder with an exact power of 2,
458 // if so, convert to a bitwise and.
459 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
460 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
462 return BinaryOperator::create(Instruction::And, I.getOperand(0),
463 ConstantUInt::get(I.getType(), Val-1));
466 // 0 % X == 0, we don't need to preserve faults!
467 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
468 if (LHS->equalsInt(0))
469 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
474 // isMaxValueMinusOne - return true if this is Max-1
475 static bool isMaxValueMinusOne(const ConstantInt *C) {
476 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
477 // Calculate -1 casted to the right type...
478 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
479 uint64_t Val = ~0ULL; // All ones
480 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
481 return CU->getValue() == Val-1;
484 const ConstantSInt *CS = cast<ConstantSInt>(C);
486 // Calculate 0111111111..11111
487 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
488 int64_t Val = INT64_MAX; // All ones
489 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
490 return CS->getValue() == Val-1;
493 // isMinValuePlusOne - return true if this is Min+1
494 static bool isMinValuePlusOne(const ConstantInt *C) {
495 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
496 return CU->getValue() == 1;
498 const ConstantSInt *CS = cast<ConstantSInt>(C);
500 // Calculate 1111111111000000000000
501 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
502 int64_t Val = -1; // All ones
503 Val <<= TypeBits-1; // Shift over to the right spot
504 return CS->getValue() == Val+1;
508 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
509 bool Changed = SimplifyCommutative(I);
510 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
512 // and X, X = X and X, 0 == 0
513 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
514 return ReplaceInstUsesWith(I, Op1);
517 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
518 if (RHS->isAllOnesValue())
519 return ReplaceInstUsesWith(I, Op0);
521 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
522 Value *X = Op0I->getOperand(0);
523 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
524 if (Op0I->getOpcode() == Instruction::Xor) {
525 if ((*RHS & *Op0CI)->isNullValue()) {
526 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
527 return BinaryOperator::create(Instruction::And, X, RHS);
528 } else if (isOnlyUse(Op0)) {
529 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
530 std::string Op0Name = Op0I->getName(); Op0I->setName("");
531 Instruction *And = BinaryOperator::create(Instruction::And,
533 InsertNewInstBefore(And, I);
534 return BinaryOperator::create(Instruction::Xor, And, *RHS & *Op0CI);
536 } else if (Op0I->getOpcode() == Instruction::Or) {
537 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
538 if ((*RHS & *Op0CI)->isNullValue())
539 return BinaryOperator::create(Instruction::And, X, RHS);
541 Constant *Together = *RHS & *Op0CI;
542 if (Together == RHS) // (X | C) & C --> C
543 return ReplaceInstUsesWith(I, RHS);
545 if (isOnlyUse(Op0)) {
546 if (Together != Op0CI) {
547 // (X | C1) & C2 --> (X | (C1&C2)) & C2
548 std::string Op0Name = Op0I->getName(); Op0I->setName("");
549 Instruction *Or = BinaryOperator::create(Instruction::Or, X,
551 InsertNewInstBefore(Or, I);
552 return BinaryOperator::create(Instruction::And, Or, RHS);
559 Value *Op0NotVal = dyn_castNotVal(Op0);
560 Value *Op1NotVal = dyn_castNotVal(Op1);
562 // (~A & ~B) == (~(A | B)) - Demorgan's Law
563 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
564 Instruction *Or = BinaryOperator::create(Instruction::Or, Op0NotVal,
565 Op1NotVal,I.getName()+".demorgan");
566 InsertNewInstBefore(Or, I);
567 return BinaryOperator::createNot(Or);
570 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
571 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
573 return Changed ? &I : 0;
578 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
579 bool Changed = SimplifyCommutative(I);
580 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
582 // or X, X = X or X, 0 == X
583 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
584 return ReplaceInstUsesWith(I, Op0);
587 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
588 if (RHS->isAllOnesValue())
589 return ReplaceInstUsesWith(I, Op1);
591 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
592 // (X & C1) | C2 --> (X | C2) & (C1|C2)
593 if (Op0I->getOpcode() == Instruction::And && isOnlyUse(Op0))
594 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
595 std::string Op0Name = Op0I->getName(); Op0I->setName("");
596 Instruction *Or = BinaryOperator::create(Instruction::Or,
597 Op0I->getOperand(0), RHS,
599 InsertNewInstBefore(Or, I);
600 return BinaryOperator::create(Instruction::And, Or, *RHS | *Op0CI);
603 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
604 if (Op0I->getOpcode() == Instruction::Xor && isOnlyUse(Op0))
605 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
606 std::string Op0Name = Op0I->getName(); Op0I->setName("");
607 Instruction *Or = BinaryOperator::create(Instruction::Or,
608 Op0I->getOperand(0), RHS,
610 InsertNewInstBefore(Or, I);
611 return BinaryOperator::create(Instruction::Xor, Or, *Op0CI & *~*RHS);
616 // (A & C1)|(A & C2) == A & (C1|C2)
617 if (Instruction *LHS = dyn_cast<BinaryOperator>(Op0))
618 if (Instruction *RHS = dyn_cast<BinaryOperator>(Op1))
619 if (LHS->getOperand(0) == RHS->getOperand(0))
620 if (Constant *C0 = dyn_castMaskingAnd(LHS))
621 if (Constant *C1 = dyn_castMaskingAnd(RHS))
622 return BinaryOperator::create(Instruction::And, LHS->getOperand(0),
625 Value *Op0NotVal = dyn_castNotVal(Op0);
626 Value *Op1NotVal = dyn_castNotVal(Op1);
628 if (Op1 == Op0NotVal) // ~A | A == -1
629 return ReplaceInstUsesWith(I,
630 ConstantIntegral::getAllOnesValue(I.getType()));
632 if (Op0 == Op1NotVal) // A | ~A == -1
633 return ReplaceInstUsesWith(I,
634 ConstantIntegral::getAllOnesValue(I.getType()));
636 // (~A | ~B) == (~(A & B)) - Demorgan's Law
637 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
638 Instruction *And = BinaryOperator::create(Instruction::And, Op0NotVal,
639 Op1NotVal,I.getName()+".demorgan",
641 WorkList.push_back(And);
642 return BinaryOperator::createNot(And);
645 return Changed ? &I : 0;
650 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
651 bool Changed = SimplifyCommutative(I);
652 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
656 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
658 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
660 if (RHS->isNullValue())
661 return ReplaceInstUsesWith(I, Op0);
663 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
664 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
665 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
666 if (RHS == ConstantBool::True && SCI->use_size() == 1)
667 return new SetCondInst(SCI->getInverseCondition(),
668 SCI->getOperand(0), SCI->getOperand(1));
670 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
671 if (Op0I->getOpcode() == Instruction::And) {
672 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
673 if ((*RHS & *Op0CI)->isNullValue())
674 return BinaryOperator::create(Instruction::Or, Op0, RHS);
675 } else if (Op0I->getOpcode() == Instruction::Or) {
676 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
677 if ((*RHS & *Op0CI) == RHS)
678 return BinaryOperator::create(Instruction::And, Op0, ~*RHS);
683 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
685 return ReplaceInstUsesWith(I,
686 ConstantIntegral::getAllOnesValue(I.getType()));
688 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
690 return ReplaceInstUsesWith(I,
691 ConstantIntegral::getAllOnesValue(I.getType()));
693 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
694 if (Op1I->getOpcode() == Instruction::Or)
695 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
696 cast<BinaryOperator>(Op1I)->swapOperands();
699 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
704 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
705 if (Op0I->getOpcode() == Instruction::Or && Op0I->use_size() == 1) {
706 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
707 cast<BinaryOperator>(Op0I)->swapOperands();
708 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
709 Value *NotB = BinaryOperator::createNot(Op1, Op1->getName()+".not", &I);
710 WorkList.push_back(cast<Instruction>(NotB));
711 return BinaryOperator::create(Instruction::And, Op0I->getOperand(0),
716 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1^C2 == 0
717 if (Constant *C1 = dyn_castMaskingAnd(Op0))
718 if (Constant *C2 = dyn_castMaskingAnd(Op1))
719 if (ConstantExpr::get(Instruction::And, C1, C2)->isNullValue())
720 return BinaryOperator::create(Instruction::Or, Op0, Op1);
722 return Changed ? &I : 0;
725 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
726 static Constant *AddOne(ConstantInt *C) {
727 Constant *Result = ConstantExpr::get(Instruction::Add, C,
728 ConstantInt::get(C->getType(), 1));
729 assert(Result && "Constant folding integer addition failed!");
732 static Constant *SubOne(ConstantInt *C) {
733 Constant *Result = ConstantExpr::get(Instruction::Sub, C,
734 ConstantInt::get(C->getType(), 1));
735 assert(Result && "Constant folding integer addition failed!");
739 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
740 // true when both operands are equal...
742 static bool isTrueWhenEqual(Instruction &I) {
743 return I.getOpcode() == Instruction::SetEQ ||
744 I.getOpcode() == Instruction::SetGE ||
745 I.getOpcode() == Instruction::SetLE;
748 Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
749 bool Changed = SimplifyCommutative(I);
750 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
751 const Type *Ty = Op0->getType();
755 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
757 // setcc <global*>, 0 - Global value addresses are never null!
758 if (isa<GlobalValue>(Op0) && isa<ConstantPointerNull>(Op1))
759 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
761 // setcc's with boolean values can always be turned into bitwise operations
762 if (Ty == Type::BoolTy) {
763 // If this is <, >, or !=, we can change this into a simple xor instruction
764 if (!isTrueWhenEqual(I))
765 return BinaryOperator::create(Instruction::Xor, Op0, Op1, I.getName());
767 // Otherwise we need to make a temporary intermediate instruction and insert
768 // it into the instruction stream. This is what we are after:
770 // seteq bool %A, %B -> ~(A^B)
771 // setle bool %A, %B -> ~A | B
772 // setge bool %A, %B -> A | ~B
774 if (I.getOpcode() == Instruction::SetEQ) { // seteq case
775 Instruction *Xor = BinaryOperator::create(Instruction::Xor, Op0, Op1,
777 InsertNewInstBefore(Xor, I);
778 return BinaryOperator::createNot(Xor, I.getName());
781 // Handle the setXe cases...
782 assert(I.getOpcode() == Instruction::SetGE ||
783 I.getOpcode() == Instruction::SetLE);
785 if (I.getOpcode() == Instruction::SetGE)
786 std::swap(Op0, Op1); // Change setge -> setle
788 // Now we just have the SetLE case.
789 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
790 InsertNewInstBefore(Not, I);
791 return BinaryOperator::create(Instruction::Or, Not, Op1, I.getName());
794 // Check to see if we are doing one of many comparisons against constant
795 // integers at the end of their ranges...
797 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
798 // Simplify seteq and setne instructions...
799 if (I.getOpcode() == Instruction::SetEQ ||
800 I.getOpcode() == Instruction::SetNE) {
801 bool isSetNE = I.getOpcode() == Instruction::SetNE;
803 if (CI->isNullValue()) { // Simplify [seteq|setne] X, 0
804 CastInst *Val = new CastInst(Op0, Type::BoolTy, I.getName()+".not");
805 if (isSetNE) return Val;
807 // seteq X, 0 -> not (cast X to bool)
808 InsertNewInstBefore(Val, I);
809 return BinaryOperator::createNot(Val, I.getName());
812 // If the first operand is (and|or|xor) with a constant, and the second
813 // operand is a constant, simplify a bit.
814 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
815 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1)))
816 if (BO->getOpcode() == Instruction::Or) {
817 // If bits are being or'd in that are not present in the constant we
818 // are comparing against, then the comparison could never succeed!
819 if (!(*BOC & *~*CI)->isNullValue())
820 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
821 } else if (BO->getOpcode() == Instruction::And) {
822 // If bits are being compared against that are and'd out, then the
823 // comparison can never succeed!
824 if (!(*CI & *~*BOC)->isNullValue())
825 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
826 } else if (BO->getOpcode() == Instruction::Xor) {
827 // For the xor case, we can always just xor the two constants
828 // together, potentially eliminating the explicit xor.
829 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
834 // Check to see if we are comparing against the minimum or maximum value...
835 if (CI->isMinValue()) {
836 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
837 return ReplaceInstUsesWith(I, ConstantBool::False);
838 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
839 return ReplaceInstUsesWith(I, ConstantBool::True);
840 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
841 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
842 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
843 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
845 } else if (CI->isMaxValue()) {
846 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
847 return ReplaceInstUsesWith(I, ConstantBool::False);
848 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
849 return ReplaceInstUsesWith(I, ConstantBool::True);
850 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
851 return BinaryOperator::create(Instruction::SetEQ, Op0,Op1, I.getName());
852 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
853 return BinaryOperator::create(Instruction::SetNE, Op0,Op1, I.getName());
855 // Comparing against a value really close to min or max?
856 } else if (isMinValuePlusOne(CI)) {
857 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
858 return BinaryOperator::create(Instruction::SetEQ, Op0,
859 SubOne(CI), I.getName());
860 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
861 return BinaryOperator::create(Instruction::SetNE, Op0,
862 SubOne(CI), I.getName());
864 } else if (isMaxValueMinusOne(CI)) {
865 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
866 return BinaryOperator::create(Instruction::SetEQ, Op0,
867 AddOne(CI), I.getName());
868 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
869 return BinaryOperator::create(Instruction::SetNE, Op0,
870 AddOne(CI), I.getName());
874 return Changed ? &I : 0;
879 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
880 assert(I.getOperand(1)->getType() == Type::UByteTy);
881 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
883 // shl X, 0 == X and shr X, 0 == X
884 // shl 0, X == 0 and shr 0, X == 0
885 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
886 Op0 == Constant::getNullValue(Op0->getType()))
887 return ReplaceInstUsesWith(I, Op0);
889 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
890 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
891 // of a signed value.
893 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
894 if (CUI->getValue() >= TypeBits &&
895 (!Op0->getType()->isSigned() || I.getOpcode() == Instruction::Shl))
896 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
898 // If this is a shift of a shift, see if we can fold the two together...
899 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0)) {
900 if (ConstantUInt *ShiftAmt1C =
901 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
902 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
903 unsigned ShiftAmt2 = CUI->getValue();
905 // Check for (A << c1) << c2 and (A >> c1) >> c2
906 if (I.getOpcode() == Op0SI->getOpcode()) {
907 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
908 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
909 ConstantUInt::get(Type::UByteTy, Amt));
912 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
913 // signed types, we can only support the (A >> c1) << c2 configuration,
914 // because it can not turn an arbitrary bit of A into a sign bit.
915 if (I.getType()->isUnsigned() || I.getOpcode() == Instruction::Shl) {
916 // Calculate bitmask for what gets shifted off the edge...
917 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
918 if (I.getOpcode() == Instruction::Shr)
919 C = ConstantExpr::getShift(Instruction::Shr, C, ShiftAmt1C);
921 C = ConstantExpr::getShift(Instruction::Shl, C, ShiftAmt1C);
924 BinaryOperator::create(Instruction::And, Op0SI->getOperand(0),
925 C, Op0SI->getOperand(0)->getName()+".mask");
926 InsertNewInstBefore(Mask, I);
928 // Figure out what flavor of shift we should use...
929 if (ShiftAmt1 == ShiftAmt2)
930 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
931 else if (ShiftAmt1 < ShiftAmt2) {
932 return new ShiftInst(I.getOpcode(), Mask,
933 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
935 return new ShiftInst(Op0SI->getOpcode(), Mask,
936 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
942 // Check to see if we are shifting left by 1. If so, turn it into an add
944 if (I.getOpcode() == Instruction::Shl && CUI->equalsInt(1))
945 // Convert 'shl int %X, 1' to 'add int %X, %X'
946 return BinaryOperator::create(Instruction::Add, Op0, Op0, I.getName());
949 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
950 if (I.getOpcode() == Instruction::Shr)
951 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
952 if (CSI->isAllOnesValue())
953 return ReplaceInstUsesWith(I, CSI);
959 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
962 static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
965 // It is legal to eliminate the instruction if casting A->B->A if the sizes
966 // are identical and the bits don't get reinterpreted (for example
967 // int->float->int would not be allowed)
968 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
971 // Allow free casting and conversion of sizes as long as the sign doesn't
973 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
974 unsigned SrcSize = SrcTy->getPrimitiveSize();
975 unsigned MidSize = MidTy->getPrimitiveSize();
976 unsigned DstSize = DstTy->getPrimitiveSize();
978 // Cases where we are monotonically decreasing the size of the type are
979 // always ok, regardless of what sign changes are going on.
981 if (SrcSize >= MidSize && MidSize >= DstSize)
984 // Cases where the source and destination type are the same, but the middle
985 // type is bigger are noops.
987 if (SrcSize == DstSize && MidSize > SrcSize)
990 // If we are monotonically growing, things are more complex.
992 if (SrcSize <= MidSize && MidSize <= DstSize) {
993 // We have eight combinations of signedness to worry about. Here's the
995 static const int SignTable[8] = {
996 // CODE, SrcSigned, MidSigned, DstSigned, Comment
997 1, // U U U Always ok
998 1, // U U S Always ok
999 3, // U S U Ok iff SrcSize != MidSize
1000 3, // U S S Ok iff SrcSize != MidSize
1001 0, // S U U Never ok
1002 2, // S U S Ok iff MidSize == DstSize
1003 1, // S S U Always ok
1004 1, // S S S Always ok
1007 // Choose an action based on the current entry of the signtable that this
1008 // cast of cast refers to...
1009 unsigned Row = SrcTy->isSigned()*4+MidTy->isSigned()*2+DstTy->isSigned();
1010 switch (SignTable[Row]) {
1011 case 0: return false; // Never ok
1012 case 1: return true; // Always ok
1013 case 2: return MidSize == DstSize; // Ok iff MidSize == DstSize
1014 case 3: // Ok iff SrcSize != MidSize
1015 return SrcSize != MidSize || SrcTy == Type::BoolTy;
1016 default: assert(0 && "Bad entry in sign table!");
1021 // Otherwise, we cannot succeed. Specifically we do not want to allow things
1022 // like: short -> ushort -> uint, because this can create wrong results if
1023 // the input short is negative!
1028 static bool ValueRequiresCast(const Value *V, const Type *Ty) {
1029 if (V->getType() == Ty || isa<Constant>(V)) return false;
1030 if (const CastInst *CI = dyn_cast<CastInst>(V))
1031 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty))
1036 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
1037 /// InsertBefore instruction. This is specialized a bit to avoid inserting
1038 /// casts that are known to not do anything...
1040 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
1041 Instruction *InsertBefore) {
1042 if (V->getType() == DestTy) return V;
1043 if (Constant *C = dyn_cast<Constant>(V))
1044 return ConstantExpr::getCast(C, DestTy);
1046 CastInst *CI = new CastInst(V, DestTy, V->getName());
1047 InsertNewInstBefore(CI, *InsertBefore);
1051 // CastInst simplification
1053 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
1054 Value *Src = CI.getOperand(0);
1056 // If the user is casting a value to the same type, eliminate this cast
1058 if (CI.getType() == Src->getType())
1059 return ReplaceInstUsesWith(CI, Src);
1061 // If casting the result of another cast instruction, try to eliminate this
1064 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
1065 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
1066 CSrc->getType(), CI.getType())) {
1067 // This instruction now refers directly to the cast's src operand. This
1068 // has a good chance of making CSrc dead.
1069 CI.setOperand(0, CSrc->getOperand(0));
1073 // If this is an A->B->A cast, and we are dealing with integral types, try
1074 // to convert this into a logical 'and' instruction.
1076 if (CSrc->getOperand(0)->getType() == CI.getType() &&
1077 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
1078 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
1079 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
1080 assert(CSrc->getType() != Type::ULongTy &&
1081 "Cannot have type bigger than ulong!");
1082 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
1083 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
1084 return BinaryOperator::create(Instruction::And, CSrc->getOperand(0),
1089 // If casting the result of a getelementptr instruction with no offset, turn
1090 // this into a cast of the original pointer!
1092 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
1093 bool AllZeroOperands = true;
1094 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1095 if (!isa<Constant>(GEP->getOperand(i)) ||
1096 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
1097 AllZeroOperands = false;
1100 if (AllZeroOperands) {
1101 CI.setOperand(0, GEP->getOperand(0));
1106 // If this is a cast to bool (which is effectively a "!=0" test), then we can
1107 // perform a few optimizations...
1109 if (CI.getType() == Type::BoolTy) {
1110 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Src)) {
1111 Value *Op0 = BO->getOperand(0), *Op1 = BO->getOperand(1);
1113 switch (BO->getOpcode()) {
1114 case Instruction::Sub:
1115 case Instruction::Xor:
1116 // Replace (cast ([sub|xor] A, B) to bool) with (setne A, B)
1117 return new SetCondInst(Instruction::SetNE, Op0, Op1);
1119 // Replace (cast (add A, B) to bool) with (setne A, -B) if B is
1120 // efficiently invertible, or if the add has just this one use.
1121 case Instruction::Add:
1122 if (Value *NegVal = dyn_castNegVal(Op1))
1123 return new SetCondInst(Instruction::SetNE, Op0, NegVal);
1124 else if (Value *NegVal = dyn_castNegVal(Op0))
1125 return new SetCondInst(Instruction::SetNE, NegVal, Op1);
1126 else if (BO->use_size() == 1) {
1127 Instruction *Neg = BinaryOperator::createNeg(Op1, BO->getName());
1129 InsertNewInstBefore(Neg, CI);
1130 return new SetCondInst(Instruction::SetNE, Op0, Neg);
1134 case Instruction::And:
1135 // Replace (cast (and X, (1 << size(X)-1)) to bool) with x < 0,
1136 // converting X to be a signed value as appropriate. Don't worry about
1137 // bool values, as they will be optimized other ways if they occur in
1138 // this configuration.
1139 if (ConstantInt *CInt = dyn_cast<ConstantInt>(Op1))
1140 if (isSignBit(CInt)) {
1141 // If 'X' is not signed, insert a cast now...
1142 if (!CInt->getType()->isSigned()) {
1144 switch (CInt->getType()->getPrimitiveID()) {
1145 case Type::UByteTyID: DestTy = Type::SByteTy; break;
1146 case Type::UShortTyID: DestTy = Type::ShortTy; break;
1147 case Type::UIntTyID: DestTy = Type::IntTy; break;
1148 case Type::ULongTyID: DestTy = Type::LongTy; break;
1149 default: assert(0 && "Invalid unsigned integer type!"); abort();
1151 CastInst *NewCI = new CastInst(Op0, DestTy,
1152 Op0->getName()+".signed");
1153 InsertNewInstBefore(NewCI, CI);
1156 return new SetCondInst(Instruction::SetLT, Op0,
1157 Constant::getNullValue(Op0->getType()));
1165 // If the source value is an instruction with only this use, we can attempt to
1166 // propagate the cast into the instruction. Also, only handle integral types
1168 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
1169 if (SrcI->use_size() == 1 && Src->getType()->isIntegral() &&
1170 CI.getType()->isInteger()) { // Don't mess with casts to bool here
1171 const Type *DestTy = CI.getType();
1172 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
1173 unsigned DestBitSize = getTypeSizeInBits(DestTy);
1175 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
1176 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
1178 switch (SrcI->getOpcode()) {
1179 case Instruction::Add:
1180 case Instruction::Mul:
1181 case Instruction::And:
1182 case Instruction::Or:
1183 case Instruction::Xor:
1184 // If we are discarding information, or just changing the sign, rewrite.
1185 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
1186 // Don't insert two casts if they cannot be eliminated. We allow two
1187 // casts to be inserted if the sizes are the same. This could only be
1188 // converting signedness, which is a noop.
1189 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy) ||
1190 !ValueRequiresCast(Op0, DestTy)) {
1191 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1192 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
1193 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
1194 ->getOpcode(), Op0c, Op1c);
1198 case Instruction::Shl:
1199 // Allow changing the sign of the source operand. Do not allow changing
1200 // the size of the shift, UNLESS the shift amount is a constant. We
1201 // mush not change variable sized shifts to a smaller size, because it
1202 // is undefined to shift more bits out than exist in the value.
1203 if (DestBitSize == SrcBitSize ||
1204 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
1205 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
1206 return new ShiftInst(Instruction::Shl, Op0c, Op1);
1215 // CallInst simplification
1217 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
1218 if (transformConstExprCastCall(&CI)) return 0;
1222 // InvokeInst simplification
1224 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
1225 if (transformConstExprCastCall(&II)) return 0;
1229 // getPromotedType - Return the specified type promoted as it would be to pass
1230 // though a va_arg area...
1231 static const Type *getPromotedType(const Type *Ty) {
1232 switch (Ty->getPrimitiveID()) {
1233 case Type::SByteTyID:
1234 case Type::ShortTyID: return Type::IntTy;
1235 case Type::UByteTyID:
1236 case Type::UShortTyID: return Type::UIntTy;
1237 case Type::FloatTyID: return Type::DoubleTy;
1242 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
1243 // attempt to move the cast to the arguments of the call/invoke.
1245 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
1246 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
1247 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
1248 if (CE->getOpcode() != Instruction::Cast ||
1249 !isa<ConstantPointerRef>(CE->getOperand(0)))
1251 ConstantPointerRef *CPR = cast<ConstantPointerRef>(CE->getOperand(0));
1252 if (!isa<Function>(CPR->getValue())) return false;
1253 Function *Callee = cast<Function>(CPR->getValue());
1254 Instruction *Caller = CS.getInstruction();
1256 // Okay, this is a cast from a function to a different type. Unless doing so
1257 // would cause a type conversion of one of our arguments, change this call to
1258 // be a direct call with arguments casted to the appropriate types.
1260 const FunctionType *FT = Callee->getFunctionType();
1261 const Type *OldRetTy = Caller->getType();
1263 if (Callee->isExternal() &&
1264 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()))
1265 return false; // Cannot transform this return value...
1267 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
1268 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
1270 CallSite::arg_iterator AI = CS.arg_begin();
1271 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
1272 const Type *ParamTy = FT->getParamType(i);
1273 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
1274 if (Callee->isExternal() && !isConvertible) return false;
1277 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
1278 Callee->isExternal())
1279 return false; // Do not delete arguments unless we have a function body...
1281 // Okay, we decided that this is a safe thing to do: go ahead and start
1282 // inserting cast instructions as necessary...
1283 std::vector<Value*> Args;
1284 Args.reserve(NumActualArgs);
1286 AI = CS.arg_begin();
1287 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
1288 const Type *ParamTy = FT->getParamType(i);
1289 if ((*AI)->getType() == ParamTy) {
1290 Args.push_back(*AI);
1292 Instruction *Cast = new CastInst(*AI, ParamTy, "tmp");
1293 InsertNewInstBefore(Cast, *Caller);
1294 Args.push_back(Cast);
1298 // If the function takes more arguments than the call was taking, add them
1300 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
1301 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
1303 // If we are removing arguments to the function, emit an obnoxious warning...
1304 if (FT->getNumParams() < NumActualArgs)
1305 if (!FT->isVarArg()) {
1306 std::cerr << "WARNING: While resolving call to function '"
1307 << Callee->getName() << "' arguments were dropped!\n";
1309 // Add all of the arguments in their promoted form to the arg list...
1310 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
1311 const Type *PTy = getPromotedType((*AI)->getType());
1312 if (PTy != (*AI)->getType()) {
1313 // Must promote to pass through va_arg area!
1314 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
1315 InsertNewInstBefore(Cast, *Caller);
1316 Args.push_back(Cast);
1318 Args.push_back(*AI);
1323 if (FT->getReturnType() == Type::VoidTy)
1324 Caller->setName(""); // Void type should not have a name...
1327 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
1328 NC = new InvokeInst(Callee, II->getNormalDest(), II->getExceptionalDest(),
1329 Args, Caller->getName(), Caller);
1331 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
1334 // Insert a cast of the return type as necessary...
1336 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
1337 if (NV->getType() != Type::VoidTy) {
1338 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
1339 InsertNewInstBefore(NC, *Caller);
1340 AddUsesToWorkList(*Caller);
1342 NV = Constant::getNullValue(Caller->getType());
1346 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
1347 Caller->replaceAllUsesWith(NV);
1348 Caller->getParent()->getInstList().erase(Caller);
1349 removeFromWorkList(Caller);
1355 // PHINode simplification
1357 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
1358 // If the PHI node only has one incoming value, eliminate the PHI node...
1359 if (PN.getNumIncomingValues() == 1)
1360 return ReplaceInstUsesWith(PN, PN.getIncomingValue(0));
1362 // Otherwise if all of the incoming values are the same for the PHI, replace
1363 // the PHI node with the incoming value.
1366 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
1367 if (PN.getIncomingValue(i) != &PN) // Not the PHI node itself...
1368 if (InVal && PN.getIncomingValue(i) != InVal)
1369 return 0; // Not the same, bail out.
1371 InVal = PN.getIncomingValue(i);
1373 // The only case that could cause InVal to be null is if we have a PHI node
1374 // that only has entries for itself. In this case, there is no entry into the
1375 // loop, so kill the PHI.
1377 if (InVal == 0) InVal = Constant::getNullValue(PN.getType());
1379 // All of the incoming values are the same, replace the PHI node now.
1380 return ReplaceInstUsesWith(PN, InVal);
1384 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
1385 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
1386 // If so, eliminate the noop.
1387 if ((GEP.getNumOperands() == 2 &&
1388 GEP.getOperand(1) == Constant::getNullValue(Type::LongTy)) ||
1389 GEP.getNumOperands() == 1)
1390 return ReplaceInstUsesWith(GEP, GEP.getOperand(0));
1392 // Combine Indices - If the source pointer to this getelementptr instruction
1393 // is a getelementptr instruction, combine the indices of the two
1394 // getelementptr instructions into a single instruction.
1396 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(GEP.getOperand(0))) {
1397 std::vector<Value *> Indices;
1399 // Can we combine the two pointer arithmetics offsets?
1400 if (Src->getNumOperands() == 2 && isa<Constant>(Src->getOperand(1)) &&
1401 isa<Constant>(GEP.getOperand(1))) {
1402 // Replace: gep (gep %P, long C1), long C2, ...
1403 // With: gep %P, long (C1+C2), ...
1404 Value *Sum = ConstantExpr::get(Instruction::Add,
1405 cast<Constant>(Src->getOperand(1)),
1406 cast<Constant>(GEP.getOperand(1)));
1407 assert(Sum && "Constant folding of longs failed!?");
1408 GEP.setOperand(0, Src->getOperand(0));
1409 GEP.setOperand(1, Sum);
1410 AddUsesToWorkList(*Src); // Reduce use count of Src
1412 } else if (Src->getNumOperands() == 2) {
1413 // Replace: gep (gep %P, long B), long A, ...
1414 // With: T = long A+B; gep %P, T, ...
1416 Value *Sum = BinaryOperator::create(Instruction::Add, Src->getOperand(1),
1418 Src->getName()+".sum", &GEP);
1419 GEP.setOperand(0, Src->getOperand(0));
1420 GEP.setOperand(1, Sum);
1421 WorkList.push_back(cast<Instruction>(Sum));
1423 } else if (*GEP.idx_begin() == Constant::getNullValue(Type::LongTy) &&
1424 Src->getNumOperands() != 1) {
1425 // Otherwise we can do the fold if the first index of the GEP is a zero
1426 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end());
1427 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
1428 } else if (Src->getOperand(Src->getNumOperands()-1) ==
1429 Constant::getNullValue(Type::LongTy)) {
1430 // If the src gep ends with a constant array index, merge this get into
1431 // it, even if we have a non-zero array index.
1432 Indices.insert(Indices.end(), Src->idx_begin(), Src->idx_end()-1);
1433 Indices.insert(Indices.end(), GEP.idx_begin(), GEP.idx_end());
1436 if (!Indices.empty())
1437 return new GetElementPtrInst(Src->getOperand(0), Indices, GEP.getName());
1439 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(GEP.getOperand(0))) {
1440 // GEP of global variable. If all of the indices for this GEP are
1441 // constants, we can promote this to a constexpr instead of an instruction.
1443 // Scan for nonconstants...
1444 std::vector<Constant*> Indices;
1445 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
1446 for (; I != E && isa<Constant>(*I); ++I)
1447 Indices.push_back(cast<Constant>(*I));
1449 if (I == E) { // If they are all constants...
1451 ConstantExpr::getGetElementPtr(ConstantPointerRef::get(GV), Indices);
1453 // Replace all uses of the GEP with the new constexpr...
1454 return ReplaceInstUsesWith(GEP, CE);
1461 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
1462 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
1463 if (AI.isArrayAllocation()) // Check C != 1
1464 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
1465 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
1466 AllocationInst *New = 0;
1468 // Create and insert the replacement instruction...
1469 if (isa<MallocInst>(AI))
1470 New = new MallocInst(NewTy, 0, AI.getName(), &AI);
1472 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
1473 New = new AllocaInst(NewTy, 0, AI.getName(), &AI);
1476 // Scan to the end of the allocation instructions, to skip over a block of
1477 // allocas if possible...
1479 BasicBlock::iterator It = New;
1480 while (isa<AllocationInst>(*It)) ++It;
1482 // Now that I is pointing to the first non-allocation-inst in the block,
1483 // insert our getelementptr instruction...
1485 std::vector<Value*> Idx(2, Constant::getNullValue(Type::LongTy));
1486 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
1488 // Now make everything use the getelementptr instead of the original
1490 ReplaceInstUsesWith(AI, V);
1496 /// GetGEPGlobalInitializer - Given a constant, and a getelementptr
1497 /// constantexpr, return the constant value being addressed by the constant
1498 /// expression, or null if something is funny.
1500 static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
1501 if (CE->getOperand(1) != Constant::getNullValue(Type::LongTy))
1502 return 0; // Do not allow stepping over the value!
1504 // Loop over all of the operands, tracking down which value we are
1506 for (unsigned i = 2, e = CE->getNumOperands(); i != e; ++i)
1507 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(CE->getOperand(i))) {
1508 ConstantStruct *CS = cast<ConstantStruct>(C);
1509 if (CU->getValue() >= CS->getValues().size()) return 0;
1510 C = cast<Constant>(CS->getValues()[CU->getValue()]);
1511 } else if (ConstantSInt *CS = dyn_cast<ConstantSInt>(CE->getOperand(i))) {
1512 ConstantArray *CA = cast<ConstantArray>(C);
1513 if ((uint64_t)CS->getValue() >= CA->getValues().size()) return 0;
1514 C = cast<Constant>(CA->getValues()[CS->getValue()]);
1520 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
1521 Value *Op = LI.getOperand(0);
1522 if (ConstantPointerRef *CPR = dyn_cast<ConstantPointerRef>(Op))
1523 Op = CPR->getValue();
1525 // Instcombine load (constant global) into the value loaded...
1526 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
1527 if (GV->isConstant() && !GV->isExternal())
1528 return ReplaceInstUsesWith(LI, GV->getInitializer());
1530 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
1531 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
1532 if (CE->getOpcode() == Instruction::GetElementPtr)
1533 if (ConstantPointerRef *G=dyn_cast<ConstantPointerRef>(CE->getOperand(0)))
1534 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getValue()))
1535 if (GV->isConstant() && !GV->isExternal())
1536 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
1537 return ReplaceInstUsesWith(LI, V);
1542 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
1543 // Change br (not X), label True, label False to: br X, label False, True
1544 if (BI.isConditional() && !isa<Constant>(BI.getCondition()))
1545 if (Value *V = dyn_castNotVal(BI.getCondition())) {
1546 BasicBlock *TrueDest = BI.getSuccessor(0);
1547 BasicBlock *FalseDest = BI.getSuccessor(1);
1548 // Swap Destinations and condition...
1550 BI.setSuccessor(0, FalseDest);
1551 BI.setSuccessor(1, TrueDest);
1558 void InstCombiner::removeFromWorkList(Instruction *I) {
1559 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
1563 bool InstCombiner::runOnFunction(Function &F) {
1564 bool Changed = false;
1566 WorkList.insert(WorkList.end(), inst_begin(F), inst_end(F));
1568 while (!WorkList.empty()) {
1569 Instruction *I = WorkList.back(); // Get an instruction from the worklist
1570 WorkList.pop_back();
1572 // Check to see if we can DCE or ConstantPropagate the instruction...
1573 // Check to see if we can DIE the instruction...
1574 if (isInstructionTriviallyDead(I)) {
1575 // Add operands to the worklist...
1576 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1577 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1578 WorkList.push_back(Op);
1581 BasicBlock::iterator BBI = I;
1582 if (dceInstruction(BBI)) {
1583 removeFromWorkList(I);
1588 // Instruction isn't dead, see if we can constant propagate it...
1589 if (Constant *C = ConstantFoldInstruction(I)) {
1590 // Add operands to the worklist...
1591 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1592 if (Instruction *Op = dyn_cast<Instruction>(I->getOperand(i)))
1593 WorkList.push_back(Op);
1594 ReplaceInstUsesWith(*I, C);
1597 BasicBlock::iterator BBI = I;
1598 if (dceInstruction(BBI)) {
1599 removeFromWorkList(I);
1604 // Now that we have an instruction, try combining it to simplify it...
1605 if (Instruction *Result = visit(*I)) {
1607 // Should we replace the old instruction with a new one?
1609 // Instructions can end up on the worklist more than once. Make sure
1610 // we do not process an instruction that has been deleted.
1611 removeFromWorkList(I);
1612 ReplaceInstWithInst(I, Result);
1614 BasicBlock::iterator II = I;
1616 // If the instruction was modified, it's possible that it is now dead.
1617 // if so, remove it.
1618 if (dceInstruction(II)) {
1619 // Instructions may end up in the worklist more than once. Erase them
1621 removeFromWorkList(I);
1627 WorkList.push_back(Result);
1628 AddUsesToWorkList(*Result);
1637 Pass *createInstructionCombiningPass() {
1638 return new InstCombiner();