1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions. This pass does not modify the CFG This pass is where algebraic
12 // simplification happens.
14 // This pass combines things like:
20 // This is a simple worklist driven algorithm.
22 // This pass guarantees that the following canonicalizations are performed on
24 // 1. If a binary operator has a constant operand, it is moved to the RHS
25 // 2. Bitwise operators with constant operands are always grouped so that
26 // shifts are performed first, then or's, then and's, then xor's.
27 // 3. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All SetCC instructions on boolean values are replaced with logical ops
29 // 5. add X, X is represented as (X*2) => (X << 1)
30 // 6. Multiplies with a power-of-two constant argument are transformed into
32 // N. This list is incomplete
34 //===----------------------------------------------------------------------===//
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include "llvm/Support/CallSite.h"
46 #include "llvm/Support/GetElementPtrTypeIterator.h"
47 #include "llvm/Support/InstIterator.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "llvm/Support/PatternMatch.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/ADT/Statistic.h"
54 using namespace llvm::PatternMatch;
57 Statistic<> NumCombined ("instcombine", "Number of insts combined");
58 Statistic<> NumConstProp("instcombine", "Number of constant folds");
59 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
61 class InstCombiner : public FunctionPass,
62 public InstVisitor<InstCombiner, Instruction*> {
63 // Worklist of all of the instructions that need to be simplified.
64 std::vector<Instruction*> WorkList;
67 /// AddUsersToWorkList - When an instruction is simplified, add all users of
68 /// the instruction to the work lists because they might get more simplified
71 void AddUsersToWorkList(Instruction &I) {
72 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
74 WorkList.push_back(cast<Instruction>(*UI));
77 /// AddUsesToWorkList - When an instruction is simplified, add operands to
78 /// the work lists because they might get more simplified now.
80 void AddUsesToWorkList(Instruction &I) {
81 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
82 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
83 WorkList.push_back(Op);
86 // removeFromWorkList - remove all instances of I from the worklist.
87 void removeFromWorkList(Instruction *I);
89 virtual bool runOnFunction(Function &F);
91 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
92 AU.addRequired<TargetData>();
96 TargetData &getTargetData() const { return *TD; }
98 // Visitation implementation - Implement instruction combining for different
99 // instruction types. The semantics are as follows:
101 // null - No change was made
102 // I - Change was made, I is still valid, I may be dead though
103 // otherwise - Change was made, replace I with returned instruction
105 Instruction *visitAdd(BinaryOperator &I);
106 Instruction *visitSub(BinaryOperator &I);
107 Instruction *visitMul(BinaryOperator &I);
108 Instruction *visitDiv(BinaryOperator &I);
109 Instruction *visitRem(BinaryOperator &I);
110 Instruction *visitAnd(BinaryOperator &I);
111 Instruction *visitOr (BinaryOperator &I);
112 Instruction *visitXor(BinaryOperator &I);
113 Instruction *visitSetCondInst(BinaryOperator &I);
114 Instruction *visitShiftInst(ShiftInst &I);
115 Instruction *visitCastInst(CastInst &CI);
116 Instruction *visitSelectInst(SelectInst &CI);
117 Instruction *visitCallInst(CallInst &CI);
118 Instruction *visitInvokeInst(InvokeInst &II);
119 Instruction *visitPHINode(PHINode &PN);
120 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
121 Instruction *visitAllocationInst(AllocationInst &AI);
122 Instruction *visitFreeInst(FreeInst &FI);
123 Instruction *visitLoadInst(LoadInst &LI);
124 Instruction *visitBranchInst(BranchInst &BI);
125 Instruction *visitSwitchInst(SwitchInst &SI);
127 // visitInstruction - Specify what to return for unhandled instructions...
128 Instruction *visitInstruction(Instruction &I) { return 0; }
131 Instruction *visitCallSite(CallSite CS);
132 bool transformConstExprCastCall(CallSite CS);
135 // InsertNewInstBefore - insert an instruction New before instruction Old
136 // in the program. Add the new instruction to the worklist.
138 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
139 assert(New && New->getParent() == 0 &&
140 "New instruction already inserted into a basic block!");
141 BasicBlock *BB = Old.getParent();
142 BB->getInstList().insert(&Old, New); // Insert inst
143 WorkList.push_back(New); // Add to worklist
147 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
148 /// This also adds the cast to the worklist. Finally, this returns the
150 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
151 if (V->getType() == Ty) return V;
153 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
154 WorkList.push_back(C);
158 // ReplaceInstUsesWith - This method is to be used when an instruction is
159 // found to be dead, replacable with another preexisting expression. Here
160 // we add all uses of I to the worklist, replace all uses of I with the new
161 // value, then return I, so that the inst combiner will know that I was
164 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
165 AddUsersToWorkList(I); // Add all modified instrs to worklist
167 I.replaceAllUsesWith(V);
170 // If we are replacing the instruction with itself, this must be in a
171 // segment of unreachable code, so just clobber the instruction.
172 I.replaceAllUsesWith(UndefValue::get(I.getType()));
177 // EraseInstFromFunction - When dealing with an instruction that has side
178 // effects or produces a void value, we can't rely on DCE to delete the
179 // instruction. Instead, visit methods should return the value returned by
181 Instruction *EraseInstFromFunction(Instruction &I) {
182 assert(I.use_empty() && "Cannot erase instruction that is used!");
183 AddUsesToWorkList(I);
184 removeFromWorkList(&I);
185 I.getParent()->getInstList().erase(&I);
186 return 0; // Don't do anything with FI
191 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
192 /// InsertBefore instruction. This is specialized a bit to avoid inserting
193 /// casts that are known to not do anything...
195 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
196 Instruction *InsertBefore);
198 // SimplifyCommutative - This performs a few simplifications for commutative
200 bool SimplifyCommutative(BinaryOperator &I);
203 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
204 // PHI node as operand #0, see if we can fold the instruction into the PHI
205 // (which is only possible if all operands to the PHI are constants).
206 Instruction *FoldOpIntoPhi(Instruction &I);
208 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
209 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
211 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
212 bool Inside, Instruction &IB);
215 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
218 // getComplexity: Assign a complexity or rank value to LLVM Values...
219 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
220 static unsigned getComplexity(Value *V) {
221 if (isa<Instruction>(V)) {
222 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
226 if (isa<Argument>(V)) return 3;
227 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
230 // isOnlyUse - Return true if this instruction will be deleted if we stop using
232 static bool isOnlyUse(Value *V) {
233 return V->hasOneUse() || isa<Constant>(V);
236 // getPromotedType - Return the specified type promoted as it would be to pass
237 // though a va_arg area...
238 static const Type *getPromotedType(const Type *Ty) {
239 switch (Ty->getTypeID()) {
240 case Type::SByteTyID:
241 case Type::ShortTyID: return Type::IntTy;
242 case Type::UByteTyID:
243 case Type::UShortTyID: return Type::UIntTy;
244 case Type::FloatTyID: return Type::DoubleTy;
249 // SimplifyCommutative - This performs a few simplifications for commutative
252 // 1. Order operands such that they are listed from right (least complex) to
253 // left (most complex). This puts constants before unary operators before
256 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
257 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
259 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
260 bool Changed = false;
261 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
262 Changed = !I.swapOperands();
264 if (!I.isAssociative()) return Changed;
265 Instruction::BinaryOps Opcode = I.getOpcode();
266 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
267 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
268 if (isa<Constant>(I.getOperand(1))) {
269 Constant *Folded = ConstantExpr::get(I.getOpcode(),
270 cast<Constant>(I.getOperand(1)),
271 cast<Constant>(Op->getOperand(1)));
272 I.setOperand(0, Op->getOperand(0));
273 I.setOperand(1, Folded);
275 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
276 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
277 isOnlyUse(Op) && isOnlyUse(Op1)) {
278 Constant *C1 = cast<Constant>(Op->getOperand(1));
279 Constant *C2 = cast<Constant>(Op1->getOperand(1));
281 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
282 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
283 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
286 WorkList.push_back(New);
287 I.setOperand(0, New);
288 I.setOperand(1, Folded);
295 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
296 // if the LHS is a constant zero (which is the 'negate' form).
298 static inline Value *dyn_castNegVal(Value *V) {
299 if (BinaryOperator::isNeg(V))
300 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
302 // Constants can be considered to be negated values if they can be folded...
303 if (Constant *C = dyn_cast<Constant>(V))
304 return ConstantExpr::getNeg(C);
308 static inline Value *dyn_castNotVal(Value *V) {
309 if (BinaryOperator::isNot(V))
310 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
312 // Constants can be considered to be not'ed values...
313 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
314 return ConstantExpr::getNot(C);
318 // dyn_castFoldableMul - If this value is a multiply that can be folded into
319 // other computations (because it has a constant operand), return the
320 // non-constant operand of the multiply.
322 static inline Value *dyn_castFoldableMul(Value *V) {
323 if (V->hasOneUse() && V->getType()->isInteger())
324 if (Instruction *I = dyn_cast<Instruction>(V))
325 if (I->getOpcode() == Instruction::Mul)
326 if (isa<Constant>(I->getOperand(1)))
327 return I->getOperand(0);
331 // Log2 - Calculate the log base 2 for the specified value if it is exactly a
333 static unsigned Log2(uint64_t Val) {
334 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
337 if (Val & 1) return 0; // Multiple bits set?
344 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
345 static ConstantInt *AddOne(ConstantInt *C) {
346 return cast<ConstantInt>(ConstantExpr::getAdd(C,
347 ConstantInt::get(C->getType(), 1)));
349 static ConstantInt *SubOne(ConstantInt *C) {
350 return cast<ConstantInt>(ConstantExpr::getSub(C,
351 ConstantInt::get(C->getType(), 1)));
354 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
355 // true when both operands are equal...
357 static bool isTrueWhenEqual(Instruction &I) {
358 return I.getOpcode() == Instruction::SetEQ ||
359 I.getOpcode() == Instruction::SetGE ||
360 I.getOpcode() == Instruction::SetLE;
363 /// AssociativeOpt - Perform an optimization on an associative operator. This
364 /// function is designed to check a chain of associative operators for a
365 /// potential to apply a certain optimization. Since the optimization may be
366 /// applicable if the expression was reassociated, this checks the chain, then
367 /// reassociates the expression as necessary to expose the optimization
368 /// opportunity. This makes use of a special Functor, which must define
369 /// 'shouldApply' and 'apply' methods.
371 template<typename Functor>
372 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
373 unsigned Opcode = Root.getOpcode();
374 Value *LHS = Root.getOperand(0);
376 // Quick check, see if the immediate LHS matches...
377 if (F.shouldApply(LHS))
378 return F.apply(Root);
380 // Otherwise, if the LHS is not of the same opcode as the root, return.
381 Instruction *LHSI = dyn_cast<Instruction>(LHS);
382 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
383 // Should we apply this transform to the RHS?
384 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
386 // If not to the RHS, check to see if we should apply to the LHS...
387 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
388 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
392 // If the functor wants to apply the optimization to the RHS of LHSI,
393 // reassociate the expression from ((? op A) op B) to (? op (A op B))
395 BasicBlock *BB = Root.getParent();
397 // Now all of the instructions are in the current basic block, go ahead
398 // and perform the reassociation.
399 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
401 // First move the selected RHS to the LHS of the root...
402 Root.setOperand(0, LHSI->getOperand(1));
404 // Make what used to be the LHS of the root be the user of the root...
405 Value *ExtraOperand = TmpLHSI->getOperand(1);
406 if (&Root == TmpLHSI) {
407 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
410 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
411 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
412 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
413 BasicBlock::iterator ARI = &Root; ++ARI;
414 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
417 // Now propagate the ExtraOperand down the chain of instructions until we
419 while (TmpLHSI != LHSI) {
420 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
421 // Move the instruction to immediately before the chain we are
422 // constructing to avoid breaking dominance properties.
423 NextLHSI->getParent()->getInstList().remove(NextLHSI);
424 BB->getInstList().insert(ARI, NextLHSI);
427 Value *NextOp = NextLHSI->getOperand(1);
428 NextLHSI->setOperand(1, ExtraOperand);
430 ExtraOperand = NextOp;
433 // Now that the instructions are reassociated, have the functor perform
434 // the transformation...
435 return F.apply(Root);
438 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
444 // AddRHS - Implements: X + X --> X << 1
447 AddRHS(Value *rhs) : RHS(rhs) {}
448 bool shouldApply(Value *LHS) const { return LHS == RHS; }
449 Instruction *apply(BinaryOperator &Add) const {
450 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
451 ConstantInt::get(Type::UByteTy, 1));
455 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
457 struct AddMaskingAnd {
459 AddMaskingAnd(Constant *c) : C2(c) {}
460 bool shouldApply(Value *LHS) const {
462 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
463 ConstantExpr::getAnd(C1, C2)->isNullValue();
465 Instruction *apply(BinaryOperator &Add) const {
466 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
470 static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
472 // Figure out if the constant is the left or the right argument.
473 bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
474 Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
476 if (Constant *SOC = dyn_cast<Constant>(SO)) {
478 return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
479 return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
482 Value *Op0 = SO, *Op1 = ConstOperand;
486 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
487 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
488 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
489 New = new ShiftInst(SI->getOpcode(), Op0, Op1);
491 assert(0 && "Unknown binary instruction type!");
494 return IC->InsertNewInstBefore(New, BI);
498 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
499 /// node as operand #0, see if we can fold the instruction into the PHI (which
500 /// is only possible if all operands to the PHI are constants).
501 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
502 PHINode *PN = cast<PHINode>(I.getOperand(0));
503 if (!PN->hasOneUse()) return 0;
505 // Check to see if all of the operands of the PHI are constants. If not, we
506 // cannot do the transformation.
507 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
508 if (!isa<Constant>(PN->getIncomingValue(i)))
511 // Okay, we can do the transformation: create the new PHI node.
512 PHINode *NewPN = new PHINode(I.getType(), I.getName());
514 NewPN->op_reserve(PN->getNumOperands());
515 InsertNewInstBefore(NewPN, *PN);
517 // Next, add all of the operands to the PHI.
518 if (I.getNumOperands() == 2) {
519 Constant *C = cast<Constant>(I.getOperand(1));
520 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
521 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
522 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
523 PN->getIncomingBlock(i));
526 assert(isa<CastInst>(I) && "Unary op should be a cast!");
527 const Type *RetTy = I.getType();
528 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
529 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
530 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
531 PN->getIncomingBlock(i));
534 return ReplaceInstUsesWith(I, NewPN);
537 // FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
538 // constant as the other operand, try to fold the binary operator into the
540 static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
542 // Don't modify shared select instructions
543 if (!SI->hasOneUse()) return 0;
544 Value *TV = SI->getOperand(1);
545 Value *FV = SI->getOperand(2);
547 if (isa<Constant>(TV) || isa<Constant>(FV)) {
548 Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
549 Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
551 return new SelectInst(SI->getCondition(), SelectTrueVal,
557 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
558 bool Changed = SimplifyCommutative(I);
559 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
561 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
562 // X + undef -> undef
563 if (isa<UndefValue>(RHS))
564 return ReplaceInstUsesWith(I, RHS);
567 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
569 return ReplaceInstUsesWith(I, LHS);
571 // X + (signbit) --> X ^ signbit
572 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
573 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
574 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
575 if (Val == (1ULL << NumBits-1))
576 return BinaryOperator::createXor(LHS, RHS);
579 if (isa<PHINode>(LHS))
580 if (Instruction *NV = FoldOpIntoPhi(I))
585 if (I.getType()->isInteger()) {
586 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
590 if (Value *V = dyn_castNegVal(LHS))
591 return BinaryOperator::createSub(RHS, V);
594 if (!isa<Constant>(RHS))
595 if (Value *V = dyn_castNegVal(RHS))
596 return BinaryOperator::createSub(LHS, V);
598 // X*C + X --> X * (C+1)
599 if (dyn_castFoldableMul(LHS) == RHS) {
601 ConstantExpr::getAdd(
602 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
603 ConstantInt::get(I.getType(), 1));
604 return BinaryOperator::createMul(RHS, CP1);
607 // X + X*C --> X * (C+1)
608 if (dyn_castFoldableMul(RHS) == LHS) {
610 ConstantExpr::getAdd(
611 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
612 ConstantInt::get(I.getType(), 1));
613 return BinaryOperator::createMul(LHS, CP1);
616 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
618 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
619 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
621 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
623 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
624 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
625 return BinaryOperator::createSub(C, X);
628 // (X & FF00) + xx00 -> (X+xx00) & FF00
629 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
630 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
632 // See if all bits from the first bit set in the Add RHS up are included
633 // in the mask. First, get the rightmost bit.
634 uint64_t AddRHSV = CRHS->getRawValue();
636 // Form a mask of all bits from the lowest bit added through the top.
637 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
638 AddRHSHighBits &= (1ULL << C2->getType()->getPrimitiveSize()*8)-1;
640 // See if the and mask includes all of these bits.
641 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
643 if (AddRHSHighBits == AddRHSHighBitsAnd) {
644 // Okay, the xform is safe. Insert the new add pronto.
645 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
647 return BinaryOperator::createAnd(NewAdd, C2);
653 // Try to fold constant add into select arguments.
654 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
655 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
659 return Changed ? &I : 0;
662 // isSignBit - Return true if the value represented by the constant only has the
663 // highest order bit set.
664 static bool isSignBit(ConstantInt *CI) {
665 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
666 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
669 static unsigned getTypeSizeInBits(const Type *Ty) {
670 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
673 /// RemoveNoopCast - Strip off nonconverting casts from the value.
675 static Value *RemoveNoopCast(Value *V) {
676 if (CastInst *CI = dyn_cast<CastInst>(V)) {
677 const Type *CTy = CI->getType();
678 const Type *OpTy = CI->getOperand(0)->getType();
679 if (CTy->isInteger() && OpTy->isInteger()) {
680 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
681 return RemoveNoopCast(CI->getOperand(0));
682 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
683 return RemoveNoopCast(CI->getOperand(0));
688 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
689 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
691 if (Op0 == Op1) // sub X, X -> 0
692 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
694 // If this is a 'B = x-(-A)', change to B = x+A...
695 if (Value *V = dyn_castNegVal(Op1))
696 return BinaryOperator::createAdd(Op0, V);
698 if (isa<UndefValue>(Op0))
699 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
700 if (isa<UndefValue>(Op1))
701 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
703 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
704 // Replace (-1 - A) with (~A)...
705 if (C->isAllOnesValue())
706 return BinaryOperator::createNot(Op1);
708 // C - ~X == X + (1+C)
710 if (match(Op1, m_Not(m_Value(X))))
711 return BinaryOperator::createAdd(X,
712 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
713 // -((uint)X >> 31) -> ((int)X >> 31)
714 // -((int)X >> 31) -> ((uint)X >> 31)
715 if (C->isNullValue()) {
716 Value *NoopCastedRHS = RemoveNoopCast(Op1);
717 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
718 if (SI->getOpcode() == Instruction::Shr)
719 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
721 if (SI->getType()->isSigned())
722 NewTy = SI->getType()->getUnsignedVersion();
724 NewTy = SI->getType()->getSignedVersion();
725 // Check to see if we are shifting out everything but the sign bit.
726 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
727 // Ok, the transformation is safe. Insert a cast of the incoming
728 // value, then the new shift, then the new cast.
729 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
730 SI->getOperand(0)->getName());
731 Value *InV = InsertNewInstBefore(FirstCast, I);
732 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
734 if (NewShift->getType() == I.getType())
737 InV = InsertNewInstBefore(NewShift, I);
738 return new CastInst(NewShift, I.getType());
744 // Try to fold constant sub into select arguments.
745 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
746 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
749 if (isa<PHINode>(Op0))
750 if (Instruction *NV = FoldOpIntoPhi(I))
754 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
755 if (Op1I->hasOneUse()) {
756 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
757 // is not used by anyone else...
759 if (Op1I->getOpcode() == Instruction::Sub &&
760 !Op1I->getType()->isFloatingPoint()) {
761 // Swap the two operands of the subexpr...
762 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
763 Op1I->setOperand(0, IIOp1);
764 Op1I->setOperand(1, IIOp0);
766 // Create the new top level add instruction...
767 return BinaryOperator::createAdd(Op0, Op1);
770 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
772 if (Op1I->getOpcode() == Instruction::And &&
773 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
774 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
777 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
778 return BinaryOperator::createAnd(Op0, NewNot);
781 // -(X sdiv C) -> (X sdiv -C)
782 if (Op1I->getOpcode() == Instruction::Div)
783 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
784 if (CSI->getValue() == 0)
785 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
786 return BinaryOperator::createDiv(Op1I->getOperand(0),
787 ConstantExpr::getNeg(DivRHS));
789 // X - X*C --> X * (1-C)
790 if (dyn_castFoldableMul(Op1I) == Op0) {
792 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
793 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
794 assert(CP1 && "Couldn't constant fold 1-C?");
795 return BinaryOperator::createMul(Op0, CP1);
799 // X*C - X --> X * (C-1)
800 if (dyn_castFoldableMul(Op0) == Op1) {
802 ConstantExpr::getSub(cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
803 ConstantInt::get(I.getType(), 1));
804 assert(CP1 && "Couldn't constant fold C - 1?");
805 return BinaryOperator::createMul(Op1, CP1);
811 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
812 /// really just returns true if the most significant (sign) bit is set.
813 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
814 if (RHS->getType()->isSigned()) {
815 // True if source is LHS < 0 or LHS <= -1
816 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
817 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
819 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
820 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
821 // the size of the integer type.
822 if (Opcode == Instruction::SetGE)
823 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
824 if (Opcode == Instruction::SetGT)
825 return RHSC->getValue() ==
826 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
831 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
832 bool Changed = SimplifyCommutative(I);
833 Value *Op0 = I.getOperand(0);
835 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
836 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
838 // Simplify mul instructions with a constant RHS...
839 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
840 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
842 // ((X << C1)*C2) == (X * (C2 << C1))
843 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
844 if (SI->getOpcode() == Instruction::Shl)
845 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
846 return BinaryOperator::createMul(SI->getOperand(0),
847 ConstantExpr::getShl(CI, ShOp));
849 if (CI->isNullValue())
850 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
851 if (CI->equalsInt(1)) // X * 1 == X
852 return ReplaceInstUsesWith(I, Op0);
853 if (CI->isAllOnesValue()) // X * -1 == 0 - X
854 return BinaryOperator::createNeg(Op0, I.getName());
856 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
857 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
858 return new ShiftInst(Instruction::Shl, Op0,
859 ConstantUInt::get(Type::UByteTy, C));
860 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
861 if (Op1F->isNullValue())
862 return ReplaceInstUsesWith(I, Op1);
864 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
865 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
866 if (Op1F->getValue() == 1.0)
867 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
870 // Try to fold constant mul into select arguments.
871 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
872 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
875 if (isa<PHINode>(Op0))
876 if (Instruction *NV = FoldOpIntoPhi(I))
880 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
881 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
882 return BinaryOperator::createMul(Op0v, Op1v);
884 // If one of the operands of the multiply is a cast from a boolean value, then
885 // we know the bool is either zero or one, so this is a 'masking' multiply.
886 // See if we can simplify things based on how the boolean was originally
888 CastInst *BoolCast = 0;
889 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
890 if (CI->getOperand(0)->getType() == Type::BoolTy)
893 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
894 if (CI->getOperand(0)->getType() == Type::BoolTy)
897 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
898 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
899 const Type *SCOpTy = SCIOp0->getType();
901 // If the setcc is true iff the sign bit of X is set, then convert this
902 // multiply into a shift/and combination.
903 if (isa<ConstantInt>(SCIOp1) &&
904 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
905 // Shift the X value right to turn it into "all signbits".
906 Constant *Amt = ConstantUInt::get(Type::UByteTy,
907 SCOpTy->getPrimitiveSize()*8-1);
908 if (SCIOp0->getType()->isUnsigned()) {
909 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
910 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
911 SCIOp0->getName()), I);
915 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
916 BoolCast->getOperand(0)->getName()+
919 // If the multiply type is not the same as the source type, sign extend
920 // or truncate to the multiply type.
921 if (I.getType() != V->getType())
922 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
924 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
925 return BinaryOperator::createAnd(V, OtherOp);
930 return Changed ? &I : 0;
933 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
934 if (isa<UndefValue>(I.getOperand(0))) // undef / X -> 0
935 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
936 if (isa<UndefValue>(I.getOperand(1)))
937 return ReplaceInstUsesWith(I, I.getOperand(1)); // X / undef -> undef
939 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
941 if (RHS->equalsInt(1))
942 return ReplaceInstUsesWith(I, I.getOperand(0));
945 if (RHS->isAllOnesValue())
946 return BinaryOperator::createNeg(I.getOperand(0));
948 if (Instruction *LHS = dyn_cast<Instruction>(I.getOperand(0)))
949 if (LHS->getOpcode() == Instruction::Div)
950 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
951 // (X / C1) / C2 -> X / (C1*C2)
952 return BinaryOperator::createDiv(LHS->getOperand(0),
953 ConstantExpr::getMul(RHS, LHSRHS));
956 // Check to see if this is an unsigned division with an exact power of 2,
957 // if so, convert to a right shift.
958 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
959 if (uint64_t Val = C->getValue()) // Don't break X / 0
960 if (uint64_t C = Log2(Val))
961 return new ShiftInst(Instruction::Shr, I.getOperand(0),
962 ConstantUInt::get(Type::UByteTy, C));
965 if (RHS->getType()->isSigned())
966 if (Value *LHSNeg = dyn_castNegVal(I.getOperand(0)))
967 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
969 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
970 if (Instruction *NV = FoldOpIntoPhi(I))
974 // 0 / X == 0, we don't need to preserve faults!
975 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
976 if (LHS->equalsInt(0))
977 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
983 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
984 if (I.getType()->isSigned())
985 if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
986 if (!isa<ConstantSInt>(RHSNeg) ||
987 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
989 AddUsesToWorkList(I);
990 I.setOperand(1, RHSNeg);
994 if (isa<UndefValue>(I.getOperand(0))) // undef % X -> 0
995 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
996 if (isa<UndefValue>(I.getOperand(1)))
997 return ReplaceInstUsesWith(I, I.getOperand(1)); // X % undef -> undef
999 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
1000 if (RHS->equalsInt(1)) // X % 1 == 0
1001 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1003 // Check to see if this is an unsigned remainder with an exact power of 2,
1004 // if so, convert to a bitwise and.
1005 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1006 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
1007 if (!(Val & (Val-1))) // Power of 2
1008 return BinaryOperator::createAnd(I.getOperand(0),
1009 ConstantUInt::get(I.getType(), Val-1));
1010 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
1011 if (Instruction *NV = FoldOpIntoPhi(I))
1015 // 0 % X == 0, we don't need to preserve faults!
1016 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
1017 if (LHS->equalsInt(0))
1018 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1023 // isMaxValueMinusOne - return true if this is Max-1
1024 static bool isMaxValueMinusOne(const ConstantInt *C) {
1025 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1026 // Calculate -1 casted to the right type...
1027 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1028 uint64_t Val = ~0ULL; // All ones
1029 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1030 return CU->getValue() == Val-1;
1033 const ConstantSInt *CS = cast<ConstantSInt>(C);
1035 // Calculate 0111111111..11111
1036 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1037 int64_t Val = INT64_MAX; // All ones
1038 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1039 return CS->getValue() == Val-1;
1042 // isMinValuePlusOne - return true if this is Min+1
1043 static bool isMinValuePlusOne(const ConstantInt *C) {
1044 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1045 return CU->getValue() == 1;
1047 const ConstantSInt *CS = cast<ConstantSInt>(C);
1049 // Calculate 1111111111000000000000
1050 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1051 int64_t Val = -1; // All ones
1052 Val <<= TypeBits-1; // Shift over to the right spot
1053 return CS->getValue() == Val+1;
1056 // isOneBitSet - Return true if there is exactly one bit set in the specified
1058 static bool isOneBitSet(const ConstantInt *CI) {
1059 uint64_t V = CI->getRawValue();
1060 return V && (V & (V-1)) == 0;
1063 #if 0 // Currently unused
1064 // isLowOnes - Return true if the constant is of the form 0+1+.
1065 static bool isLowOnes(const ConstantInt *CI) {
1066 uint64_t V = CI->getRawValue();
1068 // There won't be bits set in parts that the type doesn't contain.
1069 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1071 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1072 return U && V && (U & V) == 0;
1076 // isHighOnes - Return true if the constant is of the form 1+0+.
1077 // This is the same as lowones(~X).
1078 static bool isHighOnes(const ConstantInt *CI) {
1079 uint64_t V = ~CI->getRawValue();
1081 // There won't be bits set in parts that the type doesn't contain.
1082 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1084 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1085 return U && V && (U & V) == 0;
1089 /// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1090 /// are carefully arranged to allow folding of expressions such as:
1092 /// (A < B) | (A > B) --> (A != B)
1094 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1095 /// represents that the comparison is true if A == B, and bit value '1' is true
1098 static unsigned getSetCondCode(const SetCondInst *SCI) {
1099 switch (SCI->getOpcode()) {
1101 case Instruction::SetGT: return 1;
1102 case Instruction::SetEQ: return 2;
1103 case Instruction::SetGE: return 3;
1104 case Instruction::SetLT: return 4;
1105 case Instruction::SetNE: return 5;
1106 case Instruction::SetLE: return 6;
1109 assert(0 && "Invalid SetCC opcode!");
1114 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
1115 /// opcode and two operands into either a constant true or false, or a brand new
1116 /// SetCC instruction.
1117 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1119 case 0: return ConstantBool::False;
1120 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1121 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1122 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1123 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1124 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1125 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1126 case 7: return ConstantBool::True;
1127 default: assert(0 && "Illegal SetCCCode!"); return 0;
1131 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1132 struct FoldSetCCLogical {
1135 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1136 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1137 bool shouldApply(Value *V) const {
1138 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1139 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1140 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1143 Instruction *apply(BinaryOperator &Log) const {
1144 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1145 if (SCI->getOperand(0) != LHS) {
1146 assert(SCI->getOperand(1) == LHS);
1147 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1150 unsigned LHSCode = getSetCondCode(SCI);
1151 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1153 switch (Log.getOpcode()) {
1154 case Instruction::And: Code = LHSCode & RHSCode; break;
1155 case Instruction::Or: Code = LHSCode | RHSCode; break;
1156 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
1157 default: assert(0 && "Illegal logical opcode!"); return 0;
1160 Value *RV = getSetCCValue(Code, LHS, RHS);
1161 if (Instruction *I = dyn_cast<Instruction>(RV))
1163 // Otherwise, it's a constant boolean value...
1164 return IC.ReplaceInstUsesWith(Log, RV);
1169 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1170 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1171 // guaranteed to be either a shift instruction or a binary operator.
1172 Instruction *InstCombiner::OptAndOp(Instruction *Op,
1173 ConstantIntegral *OpRHS,
1174 ConstantIntegral *AndRHS,
1175 BinaryOperator &TheAnd) {
1176 Value *X = Op->getOperand(0);
1177 Constant *Together = 0;
1178 if (!isa<ShiftInst>(Op))
1179 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
1181 switch (Op->getOpcode()) {
1182 case Instruction::Xor:
1183 if (Together->isNullValue()) {
1184 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
1185 return BinaryOperator::createAnd(X, AndRHS);
1186 } else if (Op->hasOneUse()) {
1187 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1188 std::string OpName = Op->getName(); Op->setName("");
1189 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
1190 InsertNewInstBefore(And, TheAnd);
1191 return BinaryOperator::createXor(And, Together);
1194 case Instruction::Or:
1195 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
1196 if (Together->isNullValue())
1197 return BinaryOperator::createAnd(X, AndRHS);
1199 if (Together == AndRHS) // (X | C) & C --> C
1200 return ReplaceInstUsesWith(TheAnd, AndRHS);
1202 if (Op->hasOneUse() && Together != OpRHS) {
1203 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1204 std::string Op0Name = Op->getName(); Op->setName("");
1205 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1206 InsertNewInstBefore(Or, TheAnd);
1207 return BinaryOperator::createAnd(Or, AndRHS);
1211 case Instruction::Add:
1212 if (Op->hasOneUse()) {
1213 // Adding a one to a single bit bit-field should be turned into an XOR
1214 // of the bit. First thing to check is to see if this AND is with a
1215 // single bit constant.
1216 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
1218 // Clear bits that are not part of the constant.
1219 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1221 // If there is only one bit set...
1222 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
1223 // Ok, at this point, we know that we are masking the result of the
1224 // ADD down to exactly one bit. If the constant we are adding has
1225 // no bits set below this bit, then we can eliminate the ADD.
1226 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
1228 // Check to see if any bits below the one bit set in AndRHSV are set.
1229 if ((AddRHS & (AndRHSV-1)) == 0) {
1230 // If not, the only thing that can effect the output of the AND is
1231 // the bit specified by AndRHSV. If that bit is set, the effect of
1232 // the XOR is to toggle the bit. If it is clear, then the ADD has
1234 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1235 TheAnd.setOperand(0, X);
1238 std::string Name = Op->getName(); Op->setName("");
1239 // Pull the XOR out of the AND.
1240 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
1241 InsertNewInstBefore(NewAnd, TheAnd);
1242 return BinaryOperator::createXor(NewAnd, AndRHS);
1249 case Instruction::Shl: {
1250 // We know that the AND will not produce any of the bits shifted in, so if
1251 // the anded constant includes them, clear them now!
1253 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1254 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1255 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1257 if (CI == ShlMask) { // Masking out bits that the shift already masks
1258 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1259 } else if (CI != AndRHS) { // Reducing bits set in and.
1260 TheAnd.setOperand(1, CI);
1265 case Instruction::Shr:
1266 // We know that the AND will not produce any of the bits shifted in, so if
1267 // the anded constant includes them, clear them now! This only applies to
1268 // unsigned shifts, because a signed shr may bring in set bits!
1270 if (AndRHS->getType()->isUnsigned()) {
1271 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1272 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1273 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1275 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1276 return ReplaceInstUsesWith(TheAnd, Op);
1277 } else if (CI != AndRHS) {
1278 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
1281 } else { // Signed shr.
1282 // See if this is shifting in some sign extension, then masking it out
1284 if (Op->hasOneUse()) {
1285 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1286 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1287 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1288 if (CI == AndRHS) { // Masking out bits shifted in.
1289 // Make the argument unsigned.
1290 Value *ShVal = Op->getOperand(0);
1291 ShVal = InsertCastBefore(ShVal,
1292 ShVal->getType()->getUnsignedVersion(),
1294 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1295 OpRHS, Op->getName()),
1297 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1298 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1301 return new CastInst(ShVal, Op->getType());
1311 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1312 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1313 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1314 /// insert new instructions.
1315 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1316 bool Inside, Instruction &IB) {
1317 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1318 "Lo is not <= Hi in range emission code!");
1320 if (Lo == Hi) // Trivially false.
1321 return new SetCondInst(Instruction::SetNE, V, V);
1322 if (cast<ConstantIntegral>(Lo)->isMinValue())
1323 return new SetCondInst(Instruction::SetLT, V, Hi);
1325 Constant *AddCST = ConstantExpr::getNeg(Lo);
1326 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1327 InsertNewInstBefore(Add, IB);
1328 // Convert to unsigned for the comparison.
1329 const Type *UnsType = Add->getType()->getUnsignedVersion();
1330 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1331 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1332 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1333 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1336 if (Lo == Hi) // Trivially true.
1337 return new SetCondInst(Instruction::SetEQ, V, V);
1339 Hi = SubOne(cast<ConstantInt>(Hi));
1340 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1341 return new SetCondInst(Instruction::SetGT, V, Hi);
1343 // Emit X-Lo > Hi-Lo-1
1344 Constant *AddCST = ConstantExpr::getNeg(Lo);
1345 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1346 InsertNewInstBefore(Add, IB);
1347 // Convert to unsigned for the comparison.
1348 const Type *UnsType = Add->getType()->getUnsignedVersion();
1349 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1350 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1351 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1352 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1356 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1357 bool Changed = SimplifyCommutative(I);
1358 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1360 if (isa<UndefValue>(Op1)) // X & undef -> 0
1361 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1363 // and X, X = X and X, 0 == 0
1364 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1365 return ReplaceInstUsesWith(I, Op1);
1368 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
1369 if (RHS->isAllOnesValue())
1370 return ReplaceInstUsesWith(I, Op0);
1372 // Optimize a variety of ((val OP C1) & C2) combinations...
1373 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1374 Instruction *Op0I = cast<Instruction>(Op0);
1375 Value *X = Op0I->getOperand(0);
1376 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1377 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1381 // Try to fold constant and into select arguments.
1382 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1383 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1385 if (isa<PHINode>(Op0))
1386 if (Instruction *NV = FoldOpIntoPhi(I))
1390 Value *Op0NotVal = dyn_castNotVal(Op0);
1391 Value *Op1NotVal = dyn_castNotVal(Op1);
1393 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1394 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1396 // (~A & ~B) == (~(A | B)) - De Morgan's Law
1397 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1398 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1399 I.getName()+".demorgan");
1400 InsertNewInstBefore(Or, I);
1401 return BinaryOperator::createNot(Or);
1404 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1405 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1406 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1409 Value *LHSVal, *RHSVal;
1410 ConstantInt *LHSCst, *RHSCst;
1411 Instruction::BinaryOps LHSCC, RHSCC;
1412 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1413 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1414 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1415 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1416 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1417 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1418 // Ensure that the larger constant is on the RHS.
1419 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1420 SetCondInst *LHS = cast<SetCondInst>(Op0);
1421 if (cast<ConstantBool>(Cmp)->getValue()) {
1422 std::swap(LHS, RHS);
1423 std::swap(LHSCst, RHSCst);
1424 std::swap(LHSCC, RHSCC);
1427 // At this point, we know we have have two setcc instructions
1428 // comparing a value against two constants and and'ing the result
1429 // together. Because of the above check, we know that we only have
1430 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1431 // FoldSetCCLogical check above), that the two constants are not
1433 assert(LHSCst != RHSCst && "Compares not folded above?");
1436 default: assert(0 && "Unknown integer condition code!");
1437 case Instruction::SetEQ:
1439 default: assert(0 && "Unknown integer condition code!");
1440 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1441 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1442 return ReplaceInstUsesWith(I, ConstantBool::False);
1443 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1444 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1445 return ReplaceInstUsesWith(I, LHS);
1447 case Instruction::SetNE:
1449 default: assert(0 && "Unknown integer condition code!");
1450 case Instruction::SetLT:
1451 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1452 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1453 break; // (X != 13 & X < 15) -> no change
1454 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1455 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1456 return ReplaceInstUsesWith(I, RHS);
1457 case Instruction::SetNE:
1458 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1459 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1460 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1461 LHSVal->getName()+".off");
1462 InsertNewInstBefore(Add, I);
1463 const Type *UnsType = Add->getType()->getUnsignedVersion();
1464 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1465 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1466 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1467 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1469 break; // (X != 13 & X != 15) -> no change
1472 case Instruction::SetLT:
1474 default: assert(0 && "Unknown integer condition code!");
1475 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1476 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1477 return ReplaceInstUsesWith(I, ConstantBool::False);
1478 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1479 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1480 return ReplaceInstUsesWith(I, LHS);
1482 case Instruction::SetGT:
1484 default: assert(0 && "Unknown integer condition code!");
1485 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1486 return ReplaceInstUsesWith(I, LHS);
1487 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1488 return ReplaceInstUsesWith(I, RHS);
1489 case Instruction::SetNE:
1490 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1491 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1492 break; // (X > 13 & X != 15) -> no change
1493 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1494 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
1500 return Changed ? &I : 0;
1503 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1504 bool Changed = SimplifyCommutative(I);
1505 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1507 if (isa<UndefValue>(Op1))
1508 return ReplaceInstUsesWith(I, // X | undef -> -1
1509 ConstantIntegral::getAllOnesValue(I.getType()));
1511 // or X, X = X or X, 0 == X
1512 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1513 return ReplaceInstUsesWith(I, Op0);
1516 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
1517 if (RHS->isAllOnesValue())
1518 return ReplaceInstUsesWith(I, Op1);
1520 ConstantInt *C1; Value *X;
1521 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1522 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1523 std::string Op0Name = Op0->getName(); Op0->setName("");
1524 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1525 InsertNewInstBefore(Or, I);
1526 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1529 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1530 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1531 std::string Op0Name = Op0->getName(); Op0->setName("");
1532 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1533 InsertNewInstBefore(Or, I);
1534 return BinaryOperator::createXor(Or,
1535 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
1538 // Try to fold constant and into select arguments.
1539 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1540 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1542 if (isa<PHINode>(Op0))
1543 if (Instruction *NV = FoldOpIntoPhi(I))
1547 // (A & C1)|(A & C2) == A & (C1|C2)
1548 Value *A, *B; ConstantInt *C1, *C2;
1549 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1550 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1551 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
1553 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1554 if (A == Op1) // ~A | A == -1
1555 return ReplaceInstUsesWith(I,
1556 ConstantIntegral::getAllOnesValue(I.getType()));
1561 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1563 return ReplaceInstUsesWith(I,
1564 ConstantIntegral::getAllOnesValue(I.getType()));
1566 // (~A | ~B) == (~(A & B)) - De Morgan's Law
1567 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1568 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1569 I.getName()+".demorgan"), I);
1570 return BinaryOperator::createNot(And);
1574 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
1575 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
1576 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1579 Value *LHSVal, *RHSVal;
1580 ConstantInt *LHSCst, *RHSCst;
1581 Instruction::BinaryOps LHSCC, RHSCC;
1582 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1583 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1584 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1585 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1586 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1587 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1588 // Ensure that the larger constant is on the RHS.
1589 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1590 SetCondInst *LHS = cast<SetCondInst>(Op0);
1591 if (cast<ConstantBool>(Cmp)->getValue()) {
1592 std::swap(LHS, RHS);
1593 std::swap(LHSCst, RHSCst);
1594 std::swap(LHSCC, RHSCC);
1597 // At this point, we know we have have two setcc instructions
1598 // comparing a value against two constants and or'ing the result
1599 // together. Because of the above check, we know that we only have
1600 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1601 // FoldSetCCLogical check above), that the two constants are not
1603 assert(LHSCst != RHSCst && "Compares not folded above?");
1606 default: assert(0 && "Unknown integer condition code!");
1607 case Instruction::SetEQ:
1609 default: assert(0 && "Unknown integer condition code!");
1610 case Instruction::SetEQ:
1611 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1612 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1613 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1614 LHSVal->getName()+".off");
1615 InsertNewInstBefore(Add, I);
1616 const Type *UnsType = Add->getType()->getUnsignedVersion();
1617 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1618 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1619 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1620 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1622 break; // (X == 13 | X == 15) -> no change
1624 case Instruction::SetGT:
1625 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1626 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1627 break; // (X == 13 | X > 15) -> no change
1628 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1629 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1630 return ReplaceInstUsesWith(I, RHS);
1633 case Instruction::SetNE:
1635 default: assert(0 && "Unknown integer condition code!");
1636 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1637 return ReplaceInstUsesWith(I, RHS);
1638 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1639 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1640 return ReplaceInstUsesWith(I, LHS);
1641 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1642 return ReplaceInstUsesWith(I, ConstantBool::True);
1645 case Instruction::SetLT:
1647 default: assert(0 && "Unknown integer condition code!");
1648 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1650 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1651 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
1652 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1653 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1654 return ReplaceInstUsesWith(I, RHS);
1657 case Instruction::SetGT:
1659 default: assert(0 && "Unknown integer condition code!");
1660 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1661 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1662 return ReplaceInstUsesWith(I, LHS);
1663 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1664 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1665 return ReplaceInstUsesWith(I, ConstantBool::True);
1670 return Changed ? &I : 0;
1673 // XorSelf - Implements: X ^ X --> 0
1676 XorSelf(Value *rhs) : RHS(rhs) {}
1677 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1678 Instruction *apply(BinaryOperator &Xor) const {
1684 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
1685 bool Changed = SimplifyCommutative(I);
1686 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1688 if (isa<UndefValue>(Op1))
1689 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
1691 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1692 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1693 assert(Result == &I && "AssociativeOpt didn't work?");
1694 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1697 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
1699 if (RHS->isNullValue())
1700 return ReplaceInstUsesWith(I, Op0);
1702 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1703 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
1704 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
1705 if (RHS == ConstantBool::True && SCI->hasOneUse())
1706 return new SetCondInst(SCI->getInverseCondition(),
1707 SCI->getOperand(0), SCI->getOperand(1));
1709 // ~(c-X) == X-c-1 == X+(-c-1)
1710 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1711 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
1712 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1713 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
1714 ConstantInt::get(I.getType(), 1));
1715 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
1718 // ~(~X & Y) --> (X | ~Y)
1719 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1720 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1721 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1723 BinaryOperator::createNot(Op0I->getOperand(1),
1724 Op0I->getOperand(1)->getName()+".not");
1725 InsertNewInstBefore(NotY, I);
1726 return BinaryOperator::createOr(Op0NotVal, NotY);
1730 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1731 switch (Op0I->getOpcode()) {
1732 case Instruction::Add:
1733 // ~(X-c) --> (-c-1)-X
1734 if (RHS->isAllOnesValue()) {
1735 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1736 return BinaryOperator::createSub(
1737 ConstantExpr::getSub(NegOp0CI,
1738 ConstantInt::get(I.getType(), 1)),
1739 Op0I->getOperand(0));
1742 case Instruction::And:
1743 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
1744 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1745 return BinaryOperator::createOr(Op0, RHS);
1747 case Instruction::Or:
1748 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1749 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
1750 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
1756 // Try to fold constant and into select arguments.
1757 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1758 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1760 if (isa<PHINode>(Op0))
1761 if (Instruction *NV = FoldOpIntoPhi(I))
1765 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
1767 return ReplaceInstUsesWith(I,
1768 ConstantIntegral::getAllOnesValue(I.getType()));
1770 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
1772 return ReplaceInstUsesWith(I,
1773 ConstantIntegral::getAllOnesValue(I.getType()));
1775 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
1776 if (Op1I->getOpcode() == Instruction::Or) {
1777 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1778 cast<BinaryOperator>(Op1I)->swapOperands();
1780 std::swap(Op0, Op1);
1781 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1783 std::swap(Op0, Op1);
1785 } else if (Op1I->getOpcode() == Instruction::Xor) {
1786 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1787 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1788 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1789 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1792 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
1793 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
1794 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1795 cast<BinaryOperator>(Op0I)->swapOperands();
1796 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
1797 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1798 Op1->getName()+".not"), I);
1799 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
1801 } else if (Op0I->getOpcode() == Instruction::Xor) {
1802 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1803 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1804 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1805 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1808 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1809 Value *A, *B; ConstantInt *C1, *C2;
1810 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1811 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
1812 ConstantExpr::getAnd(C1, C2)->isNullValue())
1813 return BinaryOperator::createOr(Op0, Op1);
1815 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1816 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1817 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1820 return Changed ? &I : 0;
1823 /// MulWithOverflow - Compute Result = In1*In2, returning true if the result
1824 /// overflowed for this type.
1825 static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1827 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
1828 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
1831 static bool isPositive(ConstantInt *C) {
1832 return cast<ConstantSInt>(C)->getValue() >= 0;
1835 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
1836 /// overflowed for this type.
1837 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1839 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
1841 if (In1->getType()->isUnsigned())
1842 return cast<ConstantUInt>(Result)->getValue() <
1843 cast<ConstantUInt>(In1)->getValue();
1844 if (isPositive(In1) != isPositive(In2))
1846 if (isPositive(In1))
1847 return cast<ConstantSInt>(Result)->getValue() <
1848 cast<ConstantSInt>(In1)->getValue();
1849 return cast<ConstantSInt>(Result)->getValue() >
1850 cast<ConstantSInt>(In1)->getValue();
1853 Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
1854 bool Changed = SimplifyCommutative(I);
1855 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1856 const Type *Ty = Op0->getType();
1860 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
1862 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
1863 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
1865 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1866 if (isa<ConstantPointerNull>(Op1) &&
1867 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
1868 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1871 // setcc's with boolean values can always be turned into bitwise operations
1872 if (Ty == Type::BoolTy) {
1873 switch (I.getOpcode()) {
1874 default: assert(0 && "Invalid setcc instruction!");
1875 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
1876 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
1877 InsertNewInstBefore(Xor, I);
1878 return BinaryOperator::createNot(Xor);
1880 case Instruction::SetNE:
1881 return BinaryOperator::createXor(Op0, Op1);
1883 case Instruction::SetGT:
1884 std::swap(Op0, Op1); // Change setgt -> setlt
1886 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
1887 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1888 InsertNewInstBefore(Not, I);
1889 return BinaryOperator::createAnd(Not, Op1);
1891 case Instruction::SetGE:
1892 std::swap(Op0, Op1); // Change setge -> setle
1894 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
1895 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1896 InsertNewInstBefore(Not, I);
1897 return BinaryOperator::createOr(Not, Op1);
1902 // See if we are doing a comparison between a constant and an instruction that
1903 // can be folded into the comparison.
1904 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1905 // Check to see if we are comparing against the minimum or maximum value...
1906 if (CI->isMinValue()) {
1907 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1908 return ReplaceInstUsesWith(I, ConstantBool::False);
1909 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1910 return ReplaceInstUsesWith(I, ConstantBool::True);
1911 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
1912 return BinaryOperator::createSetEQ(Op0, Op1);
1913 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
1914 return BinaryOperator::createSetNE(Op0, Op1);
1916 } else if (CI->isMaxValue()) {
1917 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1918 return ReplaceInstUsesWith(I, ConstantBool::False);
1919 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1920 return ReplaceInstUsesWith(I, ConstantBool::True);
1921 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
1922 return BinaryOperator::createSetEQ(Op0, Op1);
1923 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
1924 return BinaryOperator::createSetNE(Op0, Op1);
1926 // Comparing against a value really close to min or max?
1927 } else if (isMinValuePlusOne(CI)) {
1928 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
1929 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
1930 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
1931 return BinaryOperator::createSetNE(Op0, SubOne(CI));
1933 } else if (isMaxValueMinusOne(CI)) {
1934 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
1935 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
1936 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
1937 return BinaryOperator::createSetNE(Op0, AddOne(CI));
1940 // If we still have a setle or setge instruction, turn it into the
1941 // appropriate setlt or setgt instruction. Since the border cases have
1942 // already been handled above, this requires little checking.
1944 if (I.getOpcode() == Instruction::SetLE)
1945 return BinaryOperator::createSetLT(Op0, AddOne(CI));
1946 if (I.getOpcode() == Instruction::SetGE)
1947 return BinaryOperator::createSetGT(Op0, SubOne(CI));
1949 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
1950 switch (LHSI->getOpcode()) {
1951 case Instruction::PHI:
1952 if (Instruction *NV = FoldOpIntoPhi(I))
1955 case Instruction::And:
1956 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1957 LHSI->getOperand(0)->hasOneUse()) {
1958 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1959 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1960 // happens a LOT in code produced by the C front-end, for bitfield
1962 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
1963 ConstantUInt *ShAmt;
1964 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
1965 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1966 const Type *Ty = LHSI->getType();
1968 // We can fold this as long as we can't shift unknown bits
1969 // into the mask. This can only happen with signed shift
1970 // rights, as they sign-extend.
1972 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
1973 Shift->getType()->isUnsigned();
1975 // To test for the bad case of the signed shr, see if any
1976 // of the bits shifted in could be tested after the mask.
1977 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
1978 Ty->getPrimitiveSize()*8-ShAmt->getValue());
1980 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
1981 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
1987 if (Shift->getOpcode() == Instruction::Shl)
1988 NewCst = ConstantExpr::getUShr(CI, ShAmt);
1990 NewCst = ConstantExpr::getShl(CI, ShAmt);
1992 // Check to see if we are shifting out any of the bits being
1994 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
1995 // If we shifted bits out, the fold is not going to work out.
1996 // As a special case, check to see if this means that the
1997 // result is always true or false now.
1998 if (I.getOpcode() == Instruction::SetEQ)
1999 return ReplaceInstUsesWith(I, ConstantBool::False);
2000 if (I.getOpcode() == Instruction::SetNE)
2001 return ReplaceInstUsesWith(I, ConstantBool::True);
2003 I.setOperand(1, NewCst);
2004 Constant *NewAndCST;
2005 if (Shift->getOpcode() == Instruction::Shl)
2006 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2008 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2009 LHSI->setOperand(1, NewAndCST);
2010 LHSI->setOperand(0, Shift->getOperand(0));
2011 WorkList.push_back(Shift); // Shift is dead.
2012 AddUsesToWorkList(I);
2020 case Instruction::Cast: { // (setcc (cast X to larger), CI)
2021 const Type *SrcTy = LHSI->getOperand(0)->getType();
2022 if (SrcTy->isIntegral() && LHSI->getType()->isIntegral()) {
2023 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
2024 if (SrcTy == Type::BoolTy) SrcBits = 1;
2025 unsigned DestBits = LHSI->getType()->getPrimitiveSize()*8;
2026 if (LHSI->getType() == Type::BoolTy) DestBits = 1;
2027 if (SrcBits < DestBits &&
2028 // FIXME: Reenable the code below for < and >. However, we have
2029 // to handle the cases when the source of the cast and the dest of
2030 // the cast have different signs. e.g:
2031 // (cast sbyte %X to uint) >u 255U -> X <s (sbyte)0
2032 (I.getOpcode() == Instruction::SetEQ ||
2033 I.getOpcode() == Instruction::SetNE)) {
2034 // Check to see if the comparison is always true or false.
2035 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
2036 if (ConstantExpr::getCast(NewCst, LHSI->getType()) != CI) {
2037 switch (I.getOpcode()) {
2038 default: assert(0 && "unknown integer comparison");
2040 case Instruction::SetLT: {
2041 Constant *Max = ConstantIntegral::getMaxValue(SrcTy);
2042 Max = ConstantExpr::getCast(Max, LHSI->getType());
2043 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
2045 case Instruction::SetGT: {
2046 Constant *Min = ConstantIntegral::getMinValue(SrcTy);
2047 Min = ConstantExpr::getCast(Min, LHSI->getType());
2048 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
2051 case Instruction::SetEQ:
2052 return ReplaceInstUsesWith(I, ConstantBool::False);
2053 case Instruction::SetNE:
2054 return ReplaceInstUsesWith(I, ConstantBool::True);
2058 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0), NewCst);
2063 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2064 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2065 switch (I.getOpcode()) {
2067 case Instruction::SetEQ:
2068 case Instruction::SetNE: {
2069 // If we are comparing against bits always shifted out, the
2070 // comparison cannot succeed.
2072 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2073 if (Comp != CI) {// Comparing against a bit that we know is zero.
2074 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2075 Constant *Cst = ConstantBool::get(IsSetNE);
2076 return ReplaceInstUsesWith(I, Cst);
2079 if (LHSI->hasOneUse()) {
2080 // Otherwise strength reduce the shift into an and.
2081 unsigned ShAmtVal = ShAmt->getValue();
2082 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2083 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2086 if (CI->getType()->isUnsigned()) {
2087 Mask = ConstantUInt::get(CI->getType(), Val);
2088 } else if (ShAmtVal != 0) {
2089 Mask = ConstantSInt::get(CI->getType(), Val);
2091 Mask = ConstantInt::getAllOnesValue(CI->getType());
2095 BinaryOperator::createAnd(LHSI->getOperand(0),
2096 Mask, LHSI->getName()+".mask");
2097 Value *And = InsertNewInstBefore(AndI, I);
2098 return new SetCondInst(I.getOpcode(), And,
2099 ConstantExpr::getUShr(CI, ShAmt));
2106 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
2107 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2108 switch (I.getOpcode()) {
2110 case Instruction::SetEQ:
2111 case Instruction::SetNE: {
2112 // If we are comparing against bits always shifted out, the
2113 // comparison cannot succeed.
2115 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2117 if (Comp != CI) {// Comparing against a bit that we know is zero.
2118 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2119 Constant *Cst = ConstantBool::get(IsSetNE);
2120 return ReplaceInstUsesWith(I, Cst);
2123 if (LHSI->hasOneUse() || CI->isNullValue()) {
2124 unsigned ShAmtVal = ShAmt->getValue();
2126 // Otherwise strength reduce the shift into an and.
2127 uint64_t Val = ~0ULL; // All ones.
2128 Val <<= ShAmtVal; // Shift over to the right spot.
2131 if (CI->getType()->isUnsigned()) {
2132 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2133 Val &= (1ULL << TypeBits)-1;
2134 Mask = ConstantUInt::get(CI->getType(), Val);
2136 Mask = ConstantSInt::get(CI->getType(), Val);
2140 BinaryOperator::createAnd(LHSI->getOperand(0),
2141 Mask, LHSI->getName()+".mask");
2142 Value *And = InsertNewInstBefore(AndI, I);
2143 return new SetCondInst(I.getOpcode(), And,
2144 ConstantExpr::getShl(CI, ShAmt));
2152 case Instruction::Div:
2153 // Fold: (div X, C1) op C2 -> range check
2154 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2155 // Fold this div into the comparison, producing a range check.
2156 // Determine, based on the divide type, what the range is being
2157 // checked. If there is an overflow on the low or high side, remember
2158 // it, otherwise compute the range [low, hi) bounding the new value.
2159 bool LoOverflow = false, HiOverflow = 0;
2160 ConstantInt *LoBound = 0, *HiBound = 0;
2163 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2165 Instruction::BinaryOps Opcode = I.getOpcode();
2167 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2168 } else if (LHSI->getType()->isUnsigned()) { // udiv
2170 LoOverflow = ProdOV;
2171 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2172 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2173 if (CI->isNullValue()) { // (X / pos) op 0
2175 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2177 } else if (isPositive(CI)) { // (X / pos) op pos
2179 LoOverflow = ProdOV;
2180 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2181 } else { // (X / pos) op neg
2182 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2183 LoOverflow = AddWithOverflow(LoBound, Prod,
2184 cast<ConstantInt>(DivRHSH));
2186 HiOverflow = ProdOV;
2188 } else { // Divisor is < 0.
2189 if (CI->isNullValue()) { // (X / neg) op 0
2190 LoBound = AddOne(DivRHS);
2191 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2192 } else if (isPositive(CI)) { // (X / neg) op pos
2193 HiOverflow = LoOverflow = ProdOV;
2195 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2196 HiBound = AddOne(Prod);
2197 } else { // (X / neg) op neg
2199 LoOverflow = HiOverflow = ProdOV;
2200 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2203 // Dividing by a negate swaps the condition.
2204 Opcode = SetCondInst::getSwappedCondition(Opcode);
2208 Value *X = LHSI->getOperand(0);
2210 default: assert(0 && "Unhandled setcc opcode!");
2211 case Instruction::SetEQ:
2212 if (LoOverflow && HiOverflow)
2213 return ReplaceInstUsesWith(I, ConstantBool::False);
2214 else if (HiOverflow)
2215 return new SetCondInst(Instruction::SetGE, X, LoBound);
2216 else if (LoOverflow)
2217 return new SetCondInst(Instruction::SetLT, X, HiBound);
2219 return InsertRangeTest(X, LoBound, HiBound, true, I);
2220 case Instruction::SetNE:
2221 if (LoOverflow && HiOverflow)
2222 return ReplaceInstUsesWith(I, ConstantBool::True);
2223 else if (HiOverflow)
2224 return new SetCondInst(Instruction::SetLT, X, LoBound);
2225 else if (LoOverflow)
2226 return new SetCondInst(Instruction::SetGE, X, HiBound);
2228 return InsertRangeTest(X, LoBound, HiBound, false, I);
2229 case Instruction::SetLT:
2231 return ReplaceInstUsesWith(I, ConstantBool::False);
2232 return new SetCondInst(Instruction::SetLT, X, LoBound);
2233 case Instruction::SetGT:
2235 return ReplaceInstUsesWith(I, ConstantBool::False);
2236 return new SetCondInst(Instruction::SetGE, X, HiBound);
2241 case Instruction::Select:
2242 // If either operand of the select is a constant, we can fold the
2243 // comparison into the select arms, which will cause one to be
2244 // constant folded and the select turned into a bitwise or.
2245 Value *Op1 = 0, *Op2 = 0;
2246 if (LHSI->hasOneUse()) {
2247 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2248 // Fold the known value into the constant operand.
2249 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2250 // Insert a new SetCC of the other select operand.
2251 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
2252 LHSI->getOperand(2), CI,
2254 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2255 // Fold the known value into the constant operand.
2256 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2257 // Insert a new SetCC of the other select operand.
2258 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
2259 LHSI->getOperand(1), CI,
2265 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2269 // Simplify seteq and setne instructions...
2270 if (I.getOpcode() == Instruction::SetEQ ||
2271 I.getOpcode() == Instruction::SetNE) {
2272 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2274 // If the first operand is (and|or|xor) with a constant, and the second
2275 // operand is a constant, simplify a bit.
2276 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2277 switch (BO->getOpcode()) {
2278 case Instruction::Rem:
2279 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2280 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2282 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2284 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2285 const Type *UTy = BO->getType()->getUnsignedVersion();
2286 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2288 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2289 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2290 RHSCst, BO->getName()), I);
2291 return BinaryOperator::create(I.getOpcode(), NewRem,
2292 Constant::getNullValue(UTy));
2296 case Instruction::Add:
2297 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2298 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2299 if (BO->hasOneUse())
2300 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2301 ConstantExpr::getSub(CI, BOp1C));
2302 } else if (CI->isNullValue()) {
2303 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2304 // efficiently invertible, or if the add has just this one use.
2305 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
2307 if (Value *NegVal = dyn_castNegVal(BOp1))
2308 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2309 else if (Value *NegVal = dyn_castNegVal(BOp0))
2310 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
2311 else if (BO->hasOneUse()) {
2312 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2314 InsertNewInstBefore(Neg, I);
2315 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2319 case Instruction::Xor:
2320 // For the xor case, we can xor two constants together, eliminating
2321 // the explicit xor.
2322 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2323 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
2324 ConstantExpr::getXor(CI, BOC));
2327 case Instruction::Sub:
2328 // Replace (([sub|xor] A, B) != 0) with (A != B)
2329 if (CI->isNullValue())
2330 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2334 case Instruction::Or:
2335 // If bits are being or'd in that are not present in the constant we
2336 // are comparing against, then the comparison could never succeed!
2337 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
2338 Constant *NotCI = ConstantExpr::getNot(CI);
2339 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
2340 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
2344 case Instruction::And:
2345 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2346 // If bits are being compared against that are and'd out, then the
2347 // comparison can never succeed!
2348 if (!ConstantExpr::getAnd(CI,
2349 ConstantExpr::getNot(BOC))->isNullValue())
2350 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
2352 // If we have ((X & C) == C), turn it into ((X & C) != 0).
2353 if (CI == BOC && isOneBitSet(CI))
2354 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2355 Instruction::SetNE, Op0,
2356 Constant::getNullValue(CI->getType()));
2358 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2359 // to be a signed value as appropriate.
2360 if (isSignBit(BOC)) {
2361 Value *X = BO->getOperand(0);
2362 // If 'X' is not signed, insert a cast now...
2363 if (!BOC->getType()->isSigned()) {
2364 const Type *DestTy = BOC->getType()->getSignedVersion();
2365 X = InsertCastBefore(X, DestTy, I);
2367 return new SetCondInst(isSetNE ? Instruction::SetLT :
2368 Instruction::SetGE, X,
2369 Constant::getNullValue(X->getType()));
2372 // ((X & ~7) == 0) --> X < 8
2373 if (CI->isNullValue() && isHighOnes(BOC)) {
2374 Value *X = BO->getOperand(0);
2375 Constant *NegX = ConstantExpr::getNeg(BOC);
2377 // If 'X' is signed, insert a cast now.
2378 if (NegX->getType()->isSigned()) {
2379 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2380 X = InsertCastBefore(X, DestTy, I);
2381 NegX = ConstantExpr::getCast(NegX, DestTy);
2384 return new SetCondInst(isSetNE ? Instruction::SetGE :
2385 Instruction::SetLT, X, NegX);
2392 } else { // Not a SetEQ/SetNE
2393 // If the LHS is a cast from an integral value of the same size,
2394 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2395 Value *CastOp = Cast->getOperand(0);
2396 const Type *SrcTy = CastOp->getType();
2397 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2398 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2399 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2400 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2401 "Source and destination signednesses should differ!");
2402 if (Cast->getType()->isSigned()) {
2403 // If this is a signed comparison, check for comparisons in the
2404 // vicinity of zero.
2405 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2407 return BinaryOperator::createSetGT(CastOp,
2408 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2409 else if (I.getOpcode() == Instruction::SetGT &&
2410 cast<ConstantSInt>(CI)->getValue() == -1)
2411 // X > -1 => x < 128
2412 return BinaryOperator::createSetLT(CastOp,
2413 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2415 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2416 if (I.getOpcode() == Instruction::SetLT &&
2417 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2418 // X < 128 => X > -1
2419 return BinaryOperator::createSetGT(CastOp,
2420 ConstantSInt::get(SrcTy, -1));
2421 else if (I.getOpcode() == Instruction::SetGT &&
2422 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2424 return BinaryOperator::createSetLT(CastOp,
2425 Constant::getNullValue(SrcTy));
2432 // Test to see if the operands of the setcc are casted versions of other
2433 // values. If the cast can be stripped off both arguments, we do so now.
2434 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2435 Value *CastOp0 = CI->getOperand(0);
2436 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
2437 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
2438 (I.getOpcode() == Instruction::SetEQ ||
2439 I.getOpcode() == Instruction::SetNE)) {
2440 // We keep moving the cast from the left operand over to the right
2441 // operand, where it can often be eliminated completely.
2444 // If operand #1 is a cast instruction, see if we can eliminate it as
2446 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2447 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
2449 Op1 = CI2->getOperand(0);
2451 // If Op1 is a constant, we can fold the cast into the constant.
2452 if (Op1->getType() != Op0->getType())
2453 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2454 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2456 // Otherwise, cast the RHS right before the setcc
2457 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2458 InsertNewInstBefore(cast<Instruction>(Op1), I);
2460 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2463 // Handle the special case of: setcc (cast bool to X), <cst>
2464 // This comes up when you have code like
2467 // For generality, we handle any zero-extension of any operand comparison
2469 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2470 const Type *SrcTy = CastOp0->getType();
2471 const Type *DestTy = Op0->getType();
2472 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2473 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2474 // Ok, we have an expansion of operand 0 into a new type. Get the
2475 // constant value, masink off bits which are not set in the RHS. These
2476 // could be set if the destination value is signed.
2477 uint64_t ConstVal = ConstantRHS->getRawValue();
2478 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2480 // If the constant we are comparing it with has high bits set, which
2481 // don't exist in the original value, the values could never be equal,
2482 // because the source would be zero extended.
2484 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
2485 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2486 if (ConstVal & ~((1ULL << SrcBits)-1)) {
2487 switch (I.getOpcode()) {
2488 default: assert(0 && "Unknown comparison type!");
2489 case Instruction::SetEQ:
2490 return ReplaceInstUsesWith(I, ConstantBool::False);
2491 case Instruction::SetNE:
2492 return ReplaceInstUsesWith(I, ConstantBool::True);
2493 case Instruction::SetLT:
2494 case Instruction::SetLE:
2495 if (DestTy->isSigned() && HasSignBit)
2496 return ReplaceInstUsesWith(I, ConstantBool::False);
2497 return ReplaceInstUsesWith(I, ConstantBool::True);
2498 case Instruction::SetGT:
2499 case Instruction::SetGE:
2500 if (DestTy->isSigned() && HasSignBit)
2501 return ReplaceInstUsesWith(I, ConstantBool::True);
2502 return ReplaceInstUsesWith(I, ConstantBool::False);
2506 // Otherwise, we can replace the setcc with a setcc of the smaller
2508 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2509 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2513 return Changed ? &I : 0;
2518 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
2519 assert(I.getOperand(1)->getType() == Type::UByteTy);
2520 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2521 bool isLeftShift = I.getOpcode() == Instruction::Shl;
2523 // shl X, 0 == X and shr X, 0 == X
2524 // shl 0, X == 0 and shr 0, X == 0
2525 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
2526 Op0 == Constant::getNullValue(Op0->getType()))
2527 return ReplaceInstUsesWith(I, Op0);
2529 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
2530 if (!isLeftShift && I.getType()->isSigned())
2531 return ReplaceInstUsesWith(I, Op0);
2532 else // undef << X -> 0 AND undef >>u X -> 0
2533 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2535 if (isa<UndefValue>(Op1)) {
2536 if (isLeftShift || I.getType()->isUnsigned())
2537 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2539 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
2542 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
2544 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
2545 if (CSI->isAllOnesValue())
2546 return ReplaceInstUsesWith(I, CSI);
2548 // Try to fold constant and into select arguments.
2549 if (isa<Constant>(Op0))
2550 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2551 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2554 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
2555 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
2556 // of a signed value.
2558 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
2559 if (CUI->getValue() >= TypeBits) {
2560 if (!Op0->getType()->isSigned() || isLeftShift)
2561 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
2563 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
2568 // ((X*C1) << C2) == (X * (C1 << C2))
2569 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2570 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2571 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
2572 return BinaryOperator::createMul(BO->getOperand(0),
2573 ConstantExpr::getShl(BOOp, CUI));
2575 // Try to fold constant and into select arguments.
2576 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2577 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2579 if (isa<PHINode>(Op0))
2580 if (Instruction *NV = FoldOpIntoPhi(I))
2583 // If the operand is an bitwise operator with a constant RHS, and the
2584 // shift is the only use, we can pull it out of the shift.
2585 if (Op0->hasOneUse())
2586 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
2587 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2588 bool isValid = true; // Valid only for And, Or, Xor
2589 bool highBitSet = false; // Transform if high bit of constant set?
2591 switch (Op0BO->getOpcode()) {
2592 default: isValid = false; break; // Do not perform transform!
2593 case Instruction::Add:
2594 isValid = isLeftShift;
2596 case Instruction::Or:
2597 case Instruction::Xor:
2600 case Instruction::And:
2605 // If this is a signed shift right, and the high bit is modified
2606 // by the logical operation, do not perform the transformation.
2607 // The highBitSet boolean indicates the value of the high bit of
2608 // the constant which would cause it to be modified for this
2611 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
2612 uint64_t Val = Op0C->getRawValue();
2613 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
2617 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
2619 Instruction *NewShift =
2620 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2623 InsertNewInstBefore(NewShift, I);
2625 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2630 // If this is a shift of a shift, see if we can fold the two together...
2631 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
2632 if (ConstantUInt *ShiftAmt1C =
2633 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
2634 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2635 unsigned ShiftAmt2 = CUI->getValue();
2637 // Check for (A << c1) << c2 and (A >> c1) >> c2
2638 if (I.getOpcode() == Op0SI->getOpcode()) {
2639 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
2640 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2641 Amt = Op0->getType()->getPrimitiveSize()*8;
2642 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2643 ConstantUInt::get(Type::UByteTy, Amt));
2646 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
2647 // signed types, we can only support the (A >> c1) << c2 configuration,
2648 // because it can not turn an arbitrary bit of A into a sign bit.
2649 if (I.getType()->isUnsigned() || isLeftShift) {
2650 // Calculate bitmask for what gets shifted off the edge...
2651 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
2653 C = ConstantExpr::getShl(C, ShiftAmt1C);
2655 C = ConstantExpr::getShr(C, ShiftAmt1C);
2658 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2659 Op0SI->getOperand(0)->getName()+".mask");
2660 InsertNewInstBefore(Mask, I);
2662 // Figure out what flavor of shift we should use...
2663 if (ShiftAmt1 == ShiftAmt2)
2664 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
2665 else if (ShiftAmt1 < ShiftAmt2) {
2666 return new ShiftInst(I.getOpcode(), Mask,
2667 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2669 return new ShiftInst(Op0SI->getOpcode(), Mask,
2670 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2686 /// getCastType - In the future, we will split the cast instruction into these
2687 /// various types. Until then, we have to do the analysis here.
2688 static CastType getCastType(const Type *Src, const Type *Dest) {
2689 assert(Src->isIntegral() && Dest->isIntegral() &&
2690 "Only works on integral types!");
2691 unsigned SrcSize = Src->getPrimitiveSize()*8;
2692 if (Src == Type::BoolTy) SrcSize = 1;
2693 unsigned DestSize = Dest->getPrimitiveSize()*8;
2694 if (Dest == Type::BoolTy) DestSize = 1;
2696 if (SrcSize == DestSize) return Noop;
2697 if (SrcSize > DestSize) return Truncate;
2698 if (Src->isSigned()) return Signext;
2703 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2706 static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
2707 const Type *DstTy, TargetData *TD) {
2709 // It is legal to eliminate the instruction if casting A->B->A if the sizes
2710 // are identical and the bits don't get reinterpreted (for example
2711 // int->float->int would not be allowed).
2712 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
2715 // If we are casting between pointer and integer types, treat pointers as
2716 // integers of the appropriate size for the code below.
2717 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2718 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2719 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
2721 // Allow free casting and conversion of sizes as long as the sign doesn't
2723 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
2724 CastType FirstCast = getCastType(SrcTy, MidTy);
2725 CastType SecondCast = getCastType(MidTy, DstTy);
2727 // Capture the effect of these two casts. If the result is a legal cast,
2728 // the CastType is stored here, otherwise a special code is used.
2729 static const unsigned CastResult[] = {
2730 // First cast is noop
2732 // First cast is a truncate
2733 1, 1, 4, 4, // trunc->extend is not safe to eliminate
2734 // First cast is a sign ext
2735 2, 5, 2, 4, // signext->zeroext never ok
2736 // First cast is a zero ext
2740 unsigned Result = CastResult[FirstCast*4+SecondCast];
2742 default: assert(0 && "Illegal table value!");
2747 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2748 // truncates, we could eliminate more casts.
2749 return (unsigned)getCastType(SrcTy, DstTy) == Result;
2751 return false; // Not possible to eliminate this here.
2753 // Sign or zero extend followed by truncate is always ok if the result
2754 // is a truncate or noop.
2755 CastType ResultCast = getCastType(SrcTy, DstTy);
2756 if (ResultCast == Noop || ResultCast == Truncate)
2758 // Otherwise we are still growing the value, we are only safe if the
2759 // result will match the sign/zeroextendness of the result.
2760 return ResultCast == FirstCast;
2766 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
2767 if (V->getType() == Ty || isa<Constant>(V)) return false;
2768 if (const CastInst *CI = dyn_cast<CastInst>(V))
2769 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2775 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2776 /// InsertBefore instruction. This is specialized a bit to avoid inserting
2777 /// casts that are known to not do anything...
2779 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2780 Instruction *InsertBefore) {
2781 if (V->getType() == DestTy) return V;
2782 if (Constant *C = dyn_cast<Constant>(V))
2783 return ConstantExpr::getCast(C, DestTy);
2785 CastInst *CI = new CastInst(V, DestTy, V->getName());
2786 InsertNewInstBefore(CI, *InsertBefore);
2790 // CastInst simplification
2792 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
2793 Value *Src = CI.getOperand(0);
2795 // If the user is casting a value to the same type, eliminate this cast
2797 if (CI.getType() == Src->getType())
2798 return ReplaceInstUsesWith(CI, Src);
2800 if (isa<UndefValue>(Src)) // cast undef -> undef
2801 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
2803 // If casting the result of another cast instruction, try to eliminate this
2806 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
2807 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
2808 CSrc->getType(), CI.getType(), TD)) {
2809 // This instruction now refers directly to the cast's src operand. This
2810 // has a good chance of making CSrc dead.
2811 CI.setOperand(0, CSrc->getOperand(0));
2815 // If this is an A->B->A cast, and we are dealing with integral types, try
2816 // to convert this into a logical 'and' instruction.
2818 if (CSrc->getOperand(0)->getType() == CI.getType() &&
2819 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
2820 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2821 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2822 assert(CSrc->getType() != Type::ULongTy &&
2823 "Cannot have type bigger than ulong!");
2824 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
2825 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
2826 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
2830 // If this is a cast to bool, turn it into the appropriate setne instruction.
2831 if (CI.getType() == Type::BoolTy)
2832 return BinaryOperator::createSetNE(CI.getOperand(0),
2833 Constant::getNullValue(CI.getOperand(0)->getType()));
2835 // If casting the result of a getelementptr instruction with no offset, turn
2836 // this into a cast of the original pointer!
2838 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
2839 bool AllZeroOperands = true;
2840 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2841 if (!isa<Constant>(GEP->getOperand(i)) ||
2842 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2843 AllZeroOperands = false;
2846 if (AllZeroOperands) {
2847 CI.setOperand(0, GEP->getOperand(0));
2852 // If we are casting a malloc or alloca to a pointer to a type of the same
2853 // size, rewrite the allocation instruction to allocate the "right" type.
2855 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
2856 if (AI->hasOneUse() && !AI->isArrayAllocation())
2857 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2858 // Get the type really allocated and the type casted to...
2859 const Type *AllocElTy = AI->getAllocatedType();
2860 const Type *CastElTy = PTy->getElementType();
2861 if (AllocElTy->isSized() && CastElTy->isSized()) {
2862 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2863 unsigned CastElTySize = TD->getTypeSize(CastElTy);
2865 // If the allocation is for an even multiple of the cast type size
2866 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2867 Value *Amt = ConstantUInt::get(Type::UIntTy,
2868 AllocElTySize/CastElTySize);
2869 std::string Name = AI->getName(); AI->setName("");
2870 AllocationInst *New;
2871 if (isa<MallocInst>(AI))
2872 New = new MallocInst(CastElTy, Amt, Name);
2874 New = new AllocaInst(CastElTy, Amt, Name);
2875 InsertNewInstBefore(New, *AI);
2876 return ReplaceInstUsesWith(CI, New);
2881 if (isa<PHINode>(Src))
2882 if (Instruction *NV = FoldOpIntoPhi(CI))
2885 // If the source value is an instruction with only this use, we can attempt to
2886 // propagate the cast into the instruction. Also, only handle integral types
2888 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
2889 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
2890 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2891 const Type *DestTy = CI.getType();
2892 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2893 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2895 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2896 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2898 switch (SrcI->getOpcode()) {
2899 case Instruction::Add:
2900 case Instruction::Mul:
2901 case Instruction::And:
2902 case Instruction::Or:
2903 case Instruction::Xor:
2904 // If we are discarding information, or just changing the sign, rewrite.
2905 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2906 // Don't insert two casts if they cannot be eliminated. We allow two
2907 // casts to be inserted if the sizes are the same. This could only be
2908 // converting signedness, which is a noop.
2909 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2910 !ValueRequiresCast(Op0, DestTy, TD)) {
2911 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2912 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2913 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2914 ->getOpcode(), Op0c, Op1c);
2918 case Instruction::Shl:
2919 // Allow changing the sign of the source operand. Do not allow changing
2920 // the size of the shift, UNLESS the shift amount is a constant. We
2921 // mush not change variable sized shifts to a smaller size, because it
2922 // is undefined to shift more bits out than exist in the value.
2923 if (DestBitSize == SrcBitSize ||
2924 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2925 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2926 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2935 /// GetSelectFoldableOperands - We want to turn code that looks like this:
2937 /// %D = select %cond, %C, %A
2939 /// %C = select %cond, %B, 0
2942 /// Assuming that the specified instruction is an operand to the select, return
2943 /// a bitmask indicating which operands of this instruction are foldable if they
2944 /// equal the other incoming value of the select.
2946 static unsigned GetSelectFoldableOperands(Instruction *I) {
2947 switch (I->getOpcode()) {
2948 case Instruction::Add:
2949 case Instruction::Mul:
2950 case Instruction::And:
2951 case Instruction::Or:
2952 case Instruction::Xor:
2953 return 3; // Can fold through either operand.
2954 case Instruction::Sub: // Can only fold on the amount subtracted.
2955 case Instruction::Shl: // Can only fold on the shift amount.
2956 case Instruction::Shr:
2959 return 0; // Cannot fold
2963 /// GetSelectFoldableConstant - For the same transformation as the previous
2964 /// function, return the identity constant that goes into the select.
2965 static Constant *GetSelectFoldableConstant(Instruction *I) {
2966 switch (I->getOpcode()) {
2967 default: assert(0 && "This cannot happen!"); abort();
2968 case Instruction::Add:
2969 case Instruction::Sub:
2970 case Instruction::Or:
2971 case Instruction::Xor:
2972 return Constant::getNullValue(I->getType());
2973 case Instruction::Shl:
2974 case Instruction::Shr:
2975 return Constant::getNullValue(Type::UByteTy);
2976 case Instruction::And:
2977 return ConstantInt::getAllOnesValue(I->getType());
2978 case Instruction::Mul:
2979 return ConstantInt::get(I->getType(), 1);
2983 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
2984 Value *CondVal = SI.getCondition();
2985 Value *TrueVal = SI.getTrueValue();
2986 Value *FalseVal = SI.getFalseValue();
2988 // select true, X, Y -> X
2989 // select false, X, Y -> Y
2990 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
2991 if (C == ConstantBool::True)
2992 return ReplaceInstUsesWith(SI, TrueVal);
2994 assert(C == ConstantBool::False);
2995 return ReplaceInstUsesWith(SI, FalseVal);
2998 // select C, X, X -> X
2999 if (TrueVal == FalseVal)
3000 return ReplaceInstUsesWith(SI, TrueVal);
3002 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3003 return ReplaceInstUsesWith(SI, FalseVal);
3004 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3005 return ReplaceInstUsesWith(SI, TrueVal);
3006 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3007 if (isa<Constant>(TrueVal))
3008 return ReplaceInstUsesWith(SI, TrueVal);
3010 return ReplaceInstUsesWith(SI, FalseVal);
3013 if (SI.getType() == Type::BoolTy)
3014 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3015 if (C == ConstantBool::True) {
3016 // Change: A = select B, true, C --> A = or B, C
3017 return BinaryOperator::createOr(CondVal, FalseVal);
3019 // Change: A = select B, false, C --> A = and !B, C
3021 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3022 "not."+CondVal->getName()), SI);
3023 return BinaryOperator::createAnd(NotCond, FalseVal);
3025 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3026 if (C == ConstantBool::False) {
3027 // Change: A = select B, C, false --> A = and B, C
3028 return BinaryOperator::createAnd(CondVal, TrueVal);
3030 // Change: A = select B, C, true --> A = or !B, C
3032 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3033 "not."+CondVal->getName()), SI);
3034 return BinaryOperator::createOr(NotCond, TrueVal);
3038 // Selecting between two integer constants?
3039 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3040 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3041 // select C, 1, 0 -> cast C to int
3042 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3043 return new CastInst(CondVal, SI.getType());
3044 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3045 // select C, 0, 1 -> cast !C to int
3047 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3048 "not."+CondVal->getName()), SI);
3049 return new CastInst(NotCond, SI.getType());
3052 // If one of the constants is zero (we know they can't both be) and we
3053 // have a setcc instruction with zero, and we have an 'and' with the
3054 // non-constant value, eliminate this whole mess. This corresponds to
3055 // cases like this: ((X & 27) ? 27 : 0)
3056 if (TrueValC->isNullValue() || FalseValC->isNullValue())
3057 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3058 if ((IC->getOpcode() == Instruction::SetEQ ||
3059 IC->getOpcode() == Instruction::SetNE) &&
3060 isa<ConstantInt>(IC->getOperand(1)) &&
3061 cast<Constant>(IC->getOperand(1))->isNullValue())
3062 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3063 if (ICA->getOpcode() == Instruction::And &&
3064 isa<ConstantInt>(ICA->getOperand(1)) &&
3065 (ICA->getOperand(1) == TrueValC ||
3066 ICA->getOperand(1) == FalseValC) &&
3067 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3068 // Okay, now we know that everything is set up, we just don't
3069 // know whether we have a setne or seteq and whether the true or
3070 // false val is the zero.
3071 bool ShouldNotVal = !TrueValC->isNullValue();
3072 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3075 V = InsertNewInstBefore(BinaryOperator::create(
3076 Instruction::Xor, V, ICA->getOperand(1)), SI);
3077 return ReplaceInstUsesWith(SI, V);
3081 // See if we are selecting two values based on a comparison of the two values.
3082 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3083 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3084 // Transform (X == Y) ? X : Y -> Y
3085 if (SCI->getOpcode() == Instruction::SetEQ)
3086 return ReplaceInstUsesWith(SI, FalseVal);
3087 // Transform (X != Y) ? X : Y -> X
3088 if (SCI->getOpcode() == Instruction::SetNE)
3089 return ReplaceInstUsesWith(SI, TrueVal);
3090 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3092 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3093 // Transform (X == Y) ? Y : X -> X
3094 if (SCI->getOpcode() == Instruction::SetEQ)
3095 return ReplaceInstUsesWith(SI, FalseVal);
3096 // Transform (X != Y) ? Y : X -> Y
3097 if (SCI->getOpcode() == Instruction::SetNE)
3098 return ReplaceInstUsesWith(SI, TrueVal);
3099 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3103 // See if we can fold the select into one of our operands.
3104 if (SI.getType()->isInteger()) {
3105 // See the comment above GetSelectFoldableOperands for a description of the
3106 // transformation we are doing here.
3107 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3108 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3109 !isa<Constant>(FalseVal))
3110 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3111 unsigned OpToFold = 0;
3112 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3114 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3119 Constant *C = GetSelectFoldableConstant(TVI);
3120 std::string Name = TVI->getName(); TVI->setName("");
3121 Instruction *NewSel =
3122 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3124 InsertNewInstBefore(NewSel, SI);
3125 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3126 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3127 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3128 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3130 assert(0 && "Unknown instruction!!");
3135 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3136 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3137 !isa<Constant>(TrueVal))
3138 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3139 unsigned OpToFold = 0;
3140 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3142 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3147 Constant *C = GetSelectFoldableConstant(FVI);
3148 std::string Name = FVI->getName(); FVI->setName("");
3149 Instruction *NewSel =
3150 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3152 InsertNewInstBefore(NewSel, SI);
3153 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3154 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3155 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3156 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3158 assert(0 && "Unknown instruction!!");
3167 // CallInst simplification
3169 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
3170 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3172 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
3173 bool Changed = false;
3175 // memmove/cpy/set of zero bytes is a noop.
3176 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3177 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3179 // FIXME: Increase alignment here.
3181 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
3182 if (CI->getRawValue() == 1) {
3183 // Replace the instruction with just byte operations. We would
3184 // transform other cases to loads/stores, but we don't know if
3185 // alignment is sufficient.
3189 // If we have a memmove and the source operation is a constant global,
3190 // then the source and dest pointers can't alias, so we can change this
3191 // into a call to memcpy.
3192 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
3193 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3194 if (GVSrc->isConstant()) {
3195 Module *M = CI.getParent()->getParent()->getParent();
3196 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
3197 CI.getCalledFunction()->getFunctionType());
3198 CI.setOperand(0, MemCpy);
3202 if (Changed) return &CI;
3205 return visitCallSite(&CI);
3208 // InvokeInst simplification
3210 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
3211 return visitCallSite(&II);
3214 // visitCallSite - Improvements for call and invoke instructions.
3216 Instruction *InstCombiner::visitCallSite(CallSite CS) {
3217 bool Changed = false;
3219 // If the callee is a constexpr cast of a function, attempt to move the cast
3220 // to the arguments of the call/invoke.
3221 if (transformConstExprCastCall(CS)) return 0;
3223 Value *Callee = CS.getCalledValue();
3225 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
3226 // This instruction is not reachable, just remove it. We insert a store to
3227 // undef so that we know that this code is not reachable, despite the fact
3228 // that we can't modify the CFG here.
3229 new StoreInst(ConstantBool::True,
3230 UndefValue::get(PointerType::get(Type::BoolTy)),
3231 CS.getInstruction());
3233 if (!CS.getInstruction()->use_empty())
3234 CS.getInstruction()->
3235 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
3237 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
3238 // Don't break the CFG, insert a dummy cond branch.
3239 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
3240 ConstantBool::True, II);
3242 return EraseInstFromFunction(*CS.getInstruction());
3245 const PointerType *PTy = cast<PointerType>(Callee->getType());
3246 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3247 if (FTy->isVarArg()) {
3248 // See if we can optimize any arguments passed through the varargs area of
3250 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3251 E = CS.arg_end(); I != E; ++I)
3252 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3253 // If this cast does not effect the value passed through the varargs
3254 // area, we can eliminate the use of the cast.
3255 Value *Op = CI->getOperand(0);
3256 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3263 return Changed ? CS.getInstruction() : 0;
3266 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
3267 // attempt to move the cast to the arguments of the call/invoke.
3269 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3270 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3271 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
3272 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
3274 Function *Callee = cast<Function>(CE->getOperand(0));
3275 Instruction *Caller = CS.getInstruction();
3277 // Okay, this is a cast from a function to a different type. Unless doing so
3278 // would cause a type conversion of one of our arguments, change this call to
3279 // be a direct call with arguments casted to the appropriate types.
3281 const FunctionType *FT = Callee->getFunctionType();
3282 const Type *OldRetTy = Caller->getType();
3284 // Check to see if we are changing the return type...
3285 if (OldRetTy != FT->getReturnType()) {
3286 if (Callee->isExternal() &&
3287 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3288 !Caller->use_empty())
3289 return false; // Cannot transform this return value...
3291 // If the callsite is an invoke instruction, and the return value is used by
3292 // a PHI node in a successor, we cannot change the return type of the call
3293 // because there is no place to put the cast instruction (without breaking
3294 // the critical edge). Bail out in this case.
3295 if (!Caller->use_empty())
3296 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3297 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3299 if (PHINode *PN = dyn_cast<PHINode>(*UI))
3300 if (PN->getParent() == II->getNormalDest() ||
3301 PN->getParent() == II->getUnwindDest())
3305 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3306 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3308 CallSite::arg_iterator AI = CS.arg_begin();
3309 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3310 const Type *ParamTy = FT->getParamType(i);
3311 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
3312 if (Callee->isExternal() && !isConvertible) return false;
3315 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3316 Callee->isExternal())
3317 return false; // Do not delete arguments unless we have a function body...
3319 // Okay, we decided that this is a safe thing to do: go ahead and start
3320 // inserting cast instructions as necessary...
3321 std::vector<Value*> Args;
3322 Args.reserve(NumActualArgs);
3324 AI = CS.arg_begin();
3325 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3326 const Type *ParamTy = FT->getParamType(i);
3327 if ((*AI)->getType() == ParamTy) {
3328 Args.push_back(*AI);
3330 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
3335 // If the function takes more arguments than the call was taking, add them
3337 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3338 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3340 // If we are removing arguments to the function, emit an obnoxious warning...
3341 if (FT->getNumParams() < NumActualArgs)
3342 if (!FT->isVarArg()) {
3343 std::cerr << "WARNING: While resolving call to function '"
3344 << Callee->getName() << "' arguments were dropped!\n";
3346 // Add all of the arguments in their promoted form to the arg list...
3347 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3348 const Type *PTy = getPromotedType((*AI)->getType());
3349 if (PTy != (*AI)->getType()) {
3350 // Must promote to pass through va_arg area!
3351 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
3352 InsertNewInstBefore(Cast, *Caller);
3353 Args.push_back(Cast);
3355 Args.push_back(*AI);
3360 if (FT->getReturnType() == Type::VoidTy)
3361 Caller->setName(""); // Void type should not have a name...
3364 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3365 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
3366 Args, Caller->getName(), Caller);
3368 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
3371 // Insert a cast of the return type as necessary...
3373 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
3374 if (NV->getType() != Type::VoidTy) {
3375 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
3377 // If this is an invoke instruction, we should insert it after the first
3378 // non-phi, instruction in the normal successor block.
3379 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3380 BasicBlock::iterator I = II->getNormalDest()->begin();
3381 while (isa<PHINode>(I)) ++I;
3382 InsertNewInstBefore(NC, *I);
3384 // Otherwise, it's a call, just insert cast right after the call instr
3385 InsertNewInstBefore(NC, *Caller);
3387 AddUsersToWorkList(*Caller);
3389 NV = UndefValue::get(Caller->getType());
3393 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
3394 Caller->replaceAllUsesWith(NV);
3395 Caller->getParent()->getInstList().erase(Caller);
3396 removeFromWorkList(Caller);
3402 // PHINode simplification
3404 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
3405 if (Value *V = hasConstantValue(&PN)) {
3406 // If V is an instruction, we have to be certain that it dominates PN.
3407 // However, because we don't have dom info, we can't do a perfect job.
3408 if (Instruction *I = dyn_cast<Instruction>(V)) {
3409 // We know that the instruction dominates the PHI if there are no undef
3410 // values coming in.
3411 if (I->getParent() != &I->getParent()->getParent()->front() ||
3413 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3414 if (isa<UndefValue>(PN.getIncomingValue(i))) {
3421 return ReplaceInstUsesWith(PN, V);
3424 // If the only user of this instruction is a cast instruction, and all of the
3425 // incoming values are constants, change this PHI to merge together the casted
3428 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
3429 if (CI->getType() != PN.getType()) { // noop casts will be folded
3430 bool AllConstant = true;
3431 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3432 if (!isa<Constant>(PN.getIncomingValue(i))) {
3433 AllConstant = false;
3437 // Make a new PHI with all casted values.
3438 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
3439 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3440 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
3441 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
3442 PN.getIncomingBlock(i));
3445 // Update the cast instruction.
3446 CI->setOperand(0, New);
3447 WorkList.push_back(CI); // revisit the cast instruction to fold.
3448 WorkList.push_back(New); // Make sure to revisit the new Phi
3449 return &PN; // PN is now dead!
3455 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
3456 Instruction *InsertPoint,
3458 unsigned PS = IC->getTargetData().getPointerSize();
3459 const Type *VTy = V->getType();
3461 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
3462 // We must insert a cast to ensure we sign-extend.
3463 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
3464 V->getName()), *InsertPoint);
3465 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
3470 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
3471 Value *PtrOp = GEP.getOperand(0);
3472 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
3473 // If so, eliminate the noop.
3474 if (GEP.getNumOperands() == 1)
3475 return ReplaceInstUsesWith(GEP, PtrOp);
3477 if (isa<UndefValue>(GEP.getOperand(0)))
3478 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
3480 bool HasZeroPointerIndex = false;
3481 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
3482 HasZeroPointerIndex = C->isNullValue();
3484 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
3485 return ReplaceInstUsesWith(GEP, PtrOp);
3487 // Eliminate unneeded casts for indices.
3488 bool MadeChange = false;
3489 gep_type_iterator GTI = gep_type_begin(GEP);
3490 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
3491 if (isa<SequentialType>(*GTI)) {
3492 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
3493 Value *Src = CI->getOperand(0);
3494 const Type *SrcTy = Src->getType();
3495 const Type *DestTy = CI->getType();
3496 if (Src->getType()->isInteger()) {
3497 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
3498 // We can always eliminate a cast from ulong or long to the other.
3499 // We can always eliminate a cast from uint to int or the other on
3500 // 32-bit pointer platforms.
3501 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
3503 GEP.setOperand(i, Src);
3505 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
3506 SrcTy->getPrimitiveSize() == 4) {
3507 // We can always eliminate a cast from int to [u]long. We can
3508 // eliminate a cast from uint to [u]long iff the target is a 32-bit
3510 if (SrcTy->isSigned() ||
3511 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
3513 GEP.setOperand(i, Src);
3518 // If we are using a wider index than needed for this platform, shrink it
3519 // to what we need. If the incoming value needs a cast instruction,
3520 // insert it. This explicit cast can make subsequent optimizations more
3522 Value *Op = GEP.getOperand(i);
3523 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
3524 if (Constant *C = dyn_cast<Constant>(Op)) {
3525 GEP.setOperand(i, ConstantExpr::getCast(C,
3526 TD->getIntPtrType()->getSignedVersion()));
3529 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
3530 Op->getName()), GEP);
3531 GEP.setOperand(i, Op);
3535 // If this is a constant idx, make sure to canonicalize it to be a signed
3536 // operand, otherwise CSE and other optimizations are pessimized.
3537 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
3538 GEP.setOperand(i, ConstantExpr::getCast(CUI,
3539 CUI->getType()->getSignedVersion()));
3543 if (MadeChange) return &GEP;
3545 // Combine Indices - If the source pointer to this getelementptr instruction
3546 // is a getelementptr instruction, combine the indices of the two
3547 // getelementptr instructions into a single instruction.
3549 std::vector<Value*> SrcGEPOperands;
3550 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
3551 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
3552 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
3553 if (CE->getOpcode() == Instruction::GetElementPtr)
3554 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
3557 if (!SrcGEPOperands.empty()) {
3558 // Note that if our source is a gep chain itself that we wait for that
3559 // chain to be resolved before we perform this transformation. This
3560 // avoids us creating a TON of code in some cases.
3562 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
3563 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
3564 return 0; // Wait until our source is folded to completion.
3566 std::vector<Value *> Indices;
3568 // Find out whether the last index in the source GEP is a sequential idx.
3569 bool EndsWithSequential = false;
3570 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
3571 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
3572 EndsWithSequential = !isa<StructType>(*I);
3574 // Can we combine the two pointer arithmetics offsets?
3575 if (EndsWithSequential) {
3576 // Replace: gep (gep %P, long B), long A, ...
3577 // With: T = long A+B; gep %P, T, ...
3579 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
3580 if (SO1 == Constant::getNullValue(SO1->getType())) {
3582 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
3585 // If they aren't the same type, convert both to an integer of the
3586 // target's pointer size.
3587 if (SO1->getType() != GO1->getType()) {
3588 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
3589 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
3590 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
3591 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
3593 unsigned PS = TD->getPointerSize();
3595 if (SO1->getType()->getPrimitiveSize() == PS) {
3596 // Convert GO1 to SO1's type.
3597 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
3599 } else if (GO1->getType()->getPrimitiveSize() == PS) {
3600 // Convert SO1 to GO1's type.
3601 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
3603 const Type *PT = TD->getIntPtrType();
3604 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
3605 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
3609 if (isa<Constant>(SO1) && isa<Constant>(GO1))
3610 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
3612 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
3613 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
3617 // Recycle the GEP we already have if possible.
3618 if (SrcGEPOperands.size() == 2) {
3619 GEP.setOperand(0, SrcGEPOperands[0]);
3620 GEP.setOperand(1, Sum);
3623 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3624 SrcGEPOperands.end()-1);
3625 Indices.push_back(Sum);
3626 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
3628 } else if (isa<Constant>(*GEP.idx_begin()) &&
3629 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
3630 SrcGEPOperands.size() != 1) {
3631 // Otherwise we can do the fold if the first index of the GEP is a zero
3632 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3633 SrcGEPOperands.end());
3634 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
3637 if (!Indices.empty())
3638 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
3640 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
3641 // GEP of global variable. If all of the indices for this GEP are
3642 // constants, we can promote this to a constexpr instead of an instruction.
3644 // Scan for nonconstants...
3645 std::vector<Constant*> Indices;
3646 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
3647 for (; I != E && isa<Constant>(*I); ++I)
3648 Indices.push_back(cast<Constant>(*I));
3650 if (I == E) { // If they are all constants...
3651 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
3653 // Replace all uses of the GEP with the new constexpr...
3654 return ReplaceInstUsesWith(GEP, CE);
3656 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
3657 if (CE->getOpcode() == Instruction::Cast) {
3658 if (HasZeroPointerIndex) {
3659 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
3660 // into : GEP [10 x ubyte]* X, long 0, ...
3662 // This occurs when the program declares an array extern like "int X[];"
3664 Constant *X = CE->getOperand(0);
3665 const PointerType *CPTy = cast<PointerType>(CE->getType());
3666 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
3667 if (const ArrayType *XATy =
3668 dyn_cast<ArrayType>(XTy->getElementType()))
3669 if (const ArrayType *CATy =
3670 dyn_cast<ArrayType>(CPTy->getElementType()))
3671 if (CATy->getElementType() == XATy->getElementType()) {
3672 // At this point, we know that the cast source type is a pointer
3673 // to an array of the same type as the destination pointer
3674 // array. Because the array type is never stepped over (there
3675 // is a leading zero) we can fold the cast into this GEP.
3676 GEP.setOperand(0, X);
3686 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
3687 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
3688 if (AI.isArrayAllocation()) // Check C != 1
3689 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
3690 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
3691 AllocationInst *New = 0;
3693 // Create and insert the replacement instruction...
3694 if (isa<MallocInst>(AI))
3695 New = new MallocInst(NewTy, 0, AI.getName());
3697 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
3698 New = new AllocaInst(NewTy, 0, AI.getName());
3701 InsertNewInstBefore(New, AI);
3703 // Scan to the end of the allocation instructions, to skip over a block of
3704 // allocas if possible...
3706 BasicBlock::iterator It = New;
3707 while (isa<AllocationInst>(*It)) ++It;
3709 // Now that I is pointing to the first non-allocation-inst in the block,
3710 // insert our getelementptr instruction...
3712 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
3713 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
3715 // Now make everything use the getelementptr instead of the original
3717 return ReplaceInstUsesWith(AI, V);
3718 } else if (isa<UndefValue>(AI.getArraySize())) {
3719 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3722 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
3723 // Note that we only do this for alloca's, because malloc should allocate and
3724 // return a unique pointer, even for a zero byte allocation.
3725 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
3726 TD->getTypeSize(AI.getAllocatedType()) == 0)
3727 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3732 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
3733 Value *Op = FI.getOperand(0);
3735 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3736 if (CastInst *CI = dyn_cast<CastInst>(Op))
3737 if (isa<PointerType>(CI->getOperand(0)->getType())) {
3738 FI.setOperand(0, CI->getOperand(0));
3742 // free undef -> unreachable.
3743 if (isa<UndefValue>(Op)) {
3744 // Insert a new store to null because we cannot modify the CFG here.
3745 new StoreInst(ConstantBool::True,
3746 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
3747 return EraseInstFromFunction(FI);
3750 // If we have 'free null' delete the instruction. This can happen in stl code
3751 // when lots of inlining happens.
3752 if (isa<ConstantPointerNull>(Op))
3753 return EraseInstFromFunction(FI);
3759 /// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3760 /// constantexpr, return the constant value being addressed by the constant
3761 /// expression, or null if something is funny.
3763 static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
3764 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
3765 return 0; // Do not allow stepping over the value!
3767 // Loop over all of the operands, tracking down which value we are
3769 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3770 for (++I; I != E; ++I)
3771 if (const StructType *STy = dyn_cast<StructType>(*I)) {
3772 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
3773 assert(CU->getValue() < STy->getNumElements() &&
3774 "Struct index out of range!");
3775 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
3776 C = CS->getOperand(CU->getValue());
3777 } else if (isa<ConstantAggregateZero>(C)) {
3778 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
3779 } else if (isa<UndefValue>(C)) {
3780 C = UndefValue::get(STy->getElementType(CU->getValue()));
3784 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
3785 const ArrayType *ATy = cast<ArrayType>(*I);
3786 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
3787 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
3788 C = CA->getOperand(CI->getRawValue());
3789 else if (isa<ConstantAggregateZero>(C))
3790 C = Constant::getNullValue(ATy->getElementType());
3791 else if (isa<UndefValue>(C))
3792 C = UndefValue::get(ATy->getElementType());
3801 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
3802 User *CI = cast<User>(LI.getOperand(0));
3804 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
3805 if (const PointerType *SrcTy =
3806 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
3807 const Type *SrcPTy = SrcTy->getElementType();
3808 if (SrcPTy->isSized() && DestPTy->isSized() &&
3809 IC.getTargetData().getTypeSize(SrcPTy) ==
3810 IC.getTargetData().getTypeSize(DestPTy) &&
3811 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
3812 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
3813 // Okay, we are casting from one integer or pointer type to another of
3814 // the same size. Instead of casting the pointer before the load, cast
3815 // the result of the loaded value.
3816 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
3818 LI.isVolatile()),LI);
3819 // Now cast the result of the load.
3820 return new CastInst(NewLoad, LI.getType());
3826 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
3827 /// from this value cannot trap. If it is not obviously safe to load from the
3828 /// specified pointer, we do a quick local scan of the basic block containing
3829 /// ScanFrom, to determine if the address is already accessed.
3830 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3831 // If it is an alloca or global variable, it is always safe to load from.
3832 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3834 // Otherwise, be a little bit agressive by scanning the local block where we
3835 // want to check to see if the pointer is already being loaded or stored
3836 // from/to. If so, the previous load or store would have already trapped,
3837 // so there is no harm doing an extra load (also, CSE will later eliminate
3838 // the load entirely).
3839 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
3844 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3845 if (LI->getOperand(0) == V) return true;
3846 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
3847 if (SI->getOperand(1) == V) return true;
3853 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
3854 Value *Op = LI.getOperand(0);
3856 if (Constant *C = dyn_cast<Constant>(Op)) {
3857 if ((C->isNullValue() || isa<UndefValue>(C)) &&
3858 !LI.isVolatile()) { // load null/undef -> undef
3859 // Insert a new store to null instruction before the load to indicate that
3860 // this code is not reachable. We do this instead of inserting an
3861 // unreachable instruction directly because we cannot modify the CFG.
3862 new StoreInst(UndefValue::get(LI.getType()), C, &LI);
3863 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
3866 // Instcombine load (constant global) into the value loaded.
3867 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
3868 if (GV->isConstant() && !GV->isExternal())
3869 return ReplaceInstUsesWith(LI, GV->getInitializer());
3871 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
3872 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
3873 if (CE->getOpcode() == Instruction::GetElementPtr) {
3874 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
3875 if (GV->isConstant() && !GV->isExternal())
3876 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
3877 return ReplaceInstUsesWith(LI, V);
3878 } else if (CE->getOpcode() == Instruction::Cast) {
3879 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3884 // load (cast X) --> cast (load X) iff safe
3885 if (CastInst *CI = dyn_cast<CastInst>(Op))
3886 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3889 if (!LI.isVolatile() && Op->hasOneUse()) {
3890 // Change select and PHI nodes to select values instead of addresses: this
3891 // helps alias analysis out a lot, allows many others simplifications, and
3892 // exposes redundancy in the code.
3894 // Note that we cannot do the transformation unless we know that the
3895 // introduced loads cannot trap! Something like this is valid as long as
3896 // the condition is always false: load (select bool %C, int* null, int* %G),
3897 // but it would not be valid if we transformed it to load from null
3900 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
3901 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
3902 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
3903 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
3904 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
3905 SI->getOperand(1)->getName()+".val"), LI);
3906 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
3907 SI->getOperand(2)->getName()+".val"), LI);
3908 return new SelectInst(SI->getCondition(), V1, V2);
3911 // load (select (cond, null, P)) -> load P
3912 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
3913 if (C->isNullValue()) {
3914 LI.setOperand(0, SI->getOperand(2));
3918 // load (select (cond, P, null)) -> load P
3919 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
3920 if (C->isNullValue()) {
3921 LI.setOperand(0, SI->getOperand(1));
3925 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
3926 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
3927 bool Safe = PN->getParent() == LI.getParent();
3929 // Scan all of the instructions between the PHI and the load to make
3930 // sure there are no instructions that might possibly alter the value
3931 // loaded from the PHI.
3933 BasicBlock::iterator I = &LI;
3934 for (--I; !isa<PHINode>(I); --I)
3935 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
3941 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
3942 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
3943 PN->getIncomingBlock(i)->getTerminator()))
3948 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
3949 InsertNewInstBefore(NewPN, *PN);
3950 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
3952 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3953 BasicBlock *BB = PN->getIncomingBlock(i);
3954 Value *&TheLoad = LoadMap[BB];
3956 Value *InVal = PN->getIncomingValue(i);
3957 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
3958 InVal->getName()+".val"),
3959 *BB->getTerminator());
3961 NewPN->addIncoming(TheLoad, BB);
3963 return ReplaceInstUsesWith(LI, NewPN);
3970 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3971 // Change br (not X), label True, label False to: br X, label False, True
3973 BasicBlock *TrueDest;
3974 BasicBlock *FalseDest;
3975 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
3976 !isa<Constant>(X)) {
3977 // Swap Destinations and condition...
3979 BI.setSuccessor(0, FalseDest);
3980 BI.setSuccessor(1, TrueDest);
3984 // Cannonicalize setne -> seteq
3985 Instruction::BinaryOps Op; Value *Y;
3986 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
3987 TrueDest, FalseDest)))
3988 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
3989 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
3990 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
3991 std::string Name = I->getName(); I->setName("");
3992 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
3993 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
3994 // Swap Destinations and condition...
3995 BI.setCondition(NewSCC);
3996 BI.setSuccessor(0, FalseDest);
3997 BI.setSuccessor(1, TrueDest);
3998 removeFromWorkList(I);
3999 I->getParent()->getInstList().erase(I);
4000 WorkList.push_back(cast<Instruction>(NewSCC));
4007 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
4008 Value *Cond = SI.getCondition();
4009 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
4010 if (I->getOpcode() == Instruction::Add)
4011 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
4012 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
4013 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
4014 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
4016 SI.setOperand(0, I->getOperand(0));
4017 WorkList.push_back(I);
4025 void InstCombiner::removeFromWorkList(Instruction *I) {
4026 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
4030 bool InstCombiner::runOnFunction(Function &F) {
4031 bool Changed = false;
4032 TD = &getAnalysis<TargetData>();
4034 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
4035 WorkList.push_back(&*i);
4038 while (!WorkList.empty()) {
4039 Instruction *I = WorkList.back(); // Get an instruction from the worklist
4040 WorkList.pop_back();
4042 // Check to see if we can DCE or ConstantPropagate the instruction...
4043 // Check to see if we can DIE the instruction...
4044 if (isInstructionTriviallyDead(I)) {
4045 // Add operands to the worklist...
4046 if (I->getNumOperands() < 4)
4047 AddUsesToWorkList(*I);
4050 I->getParent()->getInstList().erase(I);
4051 removeFromWorkList(I);
4055 // Instruction isn't dead, see if we can constant propagate it...
4056 if (Constant *C = ConstantFoldInstruction(I)) {
4057 if (isa<GetElementPtrInst>(I) &&
4058 cast<Constant>(I->getOperand(0))->isNullValue() &&
4059 !isa<ConstantPointerNull>(C)) {
4060 // If this is a constant expr gep that is effectively computing an
4061 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
4062 bool isFoldableGEP = true;
4063 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
4064 if (!isa<ConstantInt>(I->getOperand(i)))
4065 isFoldableGEP = false;
4066 if (isFoldableGEP) {
4067 uint64_t Offset = TD->getIndexedOffset(I->getOperand(0)->getType(),
4068 std::vector<Value*>(I->op_begin()+1, I->op_end()));
4069 C = ConstantUInt::get(Type::ULongTy, Offset);
4070 C = ConstantExpr::getCast(C, TD->getIntPtrType());
4071 C = ConstantExpr::getCast(C, I->getType());
4075 // Add operands to the worklist...
4076 AddUsesToWorkList(*I);
4077 ReplaceInstUsesWith(*I, C);
4080 I->getParent()->getInstList().erase(I);
4081 removeFromWorkList(I);
4085 // Now that we have an instruction, try combining it to simplify it...
4086 if (Instruction *Result = visit(*I)) {
4088 // Should we replace the old instruction with a new one?
4090 DEBUG(std::cerr << "IC: Old = " << *I
4091 << " New = " << *Result);
4093 // Everything uses the new instruction now.
4094 I->replaceAllUsesWith(Result);
4096 // Push the new instruction and any users onto the worklist.
4097 WorkList.push_back(Result);
4098 AddUsersToWorkList(*Result);
4100 // Move the name to the new instruction first...
4101 std::string OldName = I->getName(); I->setName("");
4102 Result->setName(OldName);
4104 // Insert the new instruction into the basic block...
4105 BasicBlock *InstParent = I->getParent();
4106 InstParent->getInstList().insert(I, Result);
4108 // Make sure that we reprocess all operands now that we reduced their
4110 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4111 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4112 WorkList.push_back(OpI);
4114 // Instructions can end up on the worklist more than once. Make sure
4115 // we do not process an instruction that has been deleted.
4116 removeFromWorkList(I);
4118 // Erase the old instruction.
4119 InstParent->getInstList().erase(I);
4121 DEBUG(std::cerr << "IC: MOD = " << *I);
4123 // If the instruction was modified, it's possible that it is now dead.
4124 // if so, remove it.
4125 if (isInstructionTriviallyDead(I)) {
4126 // Make sure we process all operands now that we are reducing their
4128 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4129 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4130 WorkList.push_back(OpI);
4132 // Instructions may end up in the worklist more than once. Erase all
4133 // occurrances of this instruction.
4134 removeFromWorkList(I);
4135 I->getParent()->getInstList().erase(I);
4137 WorkList.push_back(Result);
4138 AddUsersToWorkList(*Result);
4148 FunctionPass *llvm::createInstructionCombiningPass() {
4149 return new InstCombiner();