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/Instructions.h"
39 #include "llvm/Intrinsics.h"
40 #include "llvm/Pass.h"
41 #include "llvm/Constants.h"
42 #include "llvm/DerivedTypes.h"
43 #include "llvm/GlobalVariable.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/GetElementPtrTypeIterator.h"
49 #include "llvm/Support/InstIterator.h"
50 #include "llvm/Support/InstVisitor.h"
51 #include "llvm/Support/PatternMatch.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/ADT/Statistic.h"
56 using namespace llvm::PatternMatch;
59 Statistic<> NumCombined ("instcombine", "Number of insts combined");
60 Statistic<> NumConstProp("instcombine", "Number of constant folds");
61 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
63 class InstCombiner : public FunctionPass,
64 public InstVisitor<InstCombiner, Instruction*> {
65 // Worklist of all of the instructions that need to be simplified.
66 std::vector<Instruction*> WorkList;
69 /// AddUsersToWorkList - When an instruction is simplified, add all users of
70 /// the instruction to the work lists because they might get more simplified
73 void AddUsersToWorkList(Instruction &I) {
74 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
76 WorkList.push_back(cast<Instruction>(*UI));
79 /// AddUsesToWorkList - When an instruction is simplified, add operands to
80 /// the work lists because they might get more simplified now.
82 void AddUsesToWorkList(Instruction &I) {
83 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
84 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
85 WorkList.push_back(Op);
88 // removeFromWorkList - remove all instances of I from the worklist.
89 void removeFromWorkList(Instruction *I);
91 virtual bool runOnFunction(Function &F);
93 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
94 AU.addRequired<TargetData>();
98 TargetData &getTargetData() const { return *TD; }
100 // Visitation implementation - Implement instruction combining for different
101 // instruction types. The semantics are as follows:
103 // null - No change was made
104 // I - Change was made, I is still valid, I may be dead though
105 // otherwise - Change was made, replace I with returned instruction
107 Instruction *visitAdd(BinaryOperator &I);
108 Instruction *visitSub(BinaryOperator &I);
109 Instruction *visitMul(BinaryOperator &I);
110 Instruction *visitDiv(BinaryOperator &I);
111 Instruction *visitRem(BinaryOperator &I);
112 Instruction *visitAnd(BinaryOperator &I);
113 Instruction *visitOr (BinaryOperator &I);
114 Instruction *visitXor(BinaryOperator &I);
115 Instruction *visitSetCondInst(BinaryOperator &I);
116 Instruction *visitShiftInst(ShiftInst &I);
117 Instruction *visitCastInst(CastInst &CI);
118 Instruction *visitSelectInst(SelectInst &CI);
119 Instruction *visitCallInst(CallInst &CI);
120 Instruction *visitInvokeInst(InvokeInst &II);
121 Instruction *visitPHINode(PHINode &PN);
122 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
123 Instruction *visitAllocationInst(AllocationInst &AI);
124 Instruction *visitFreeInst(FreeInst &FI);
125 Instruction *visitLoadInst(LoadInst &LI);
126 Instruction *visitBranchInst(BranchInst &BI);
127 Instruction *visitSwitchInst(SwitchInst &SI);
129 // visitInstruction - Specify what to return for unhandled instructions...
130 Instruction *visitInstruction(Instruction &I) { return 0; }
133 Instruction *visitCallSite(CallSite CS);
134 bool transformConstExprCastCall(CallSite CS);
137 // InsertNewInstBefore - insert an instruction New before instruction Old
138 // in the program. Add the new instruction to the worklist.
140 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
141 assert(New && New->getParent() == 0 &&
142 "New instruction already inserted into a basic block!");
143 BasicBlock *BB = Old.getParent();
144 BB->getInstList().insert(&Old, New); // Insert inst
145 WorkList.push_back(New); // Add to worklist
149 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
150 /// This also adds the cast to the worklist. Finally, this returns the
152 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
153 if (V->getType() == Ty) return V;
155 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
156 WorkList.push_back(C);
160 // ReplaceInstUsesWith - This method is to be used when an instruction is
161 // found to be dead, replacable with another preexisting expression. Here
162 // we add all uses of I to the worklist, replace all uses of I with the new
163 // value, then return I, so that the inst combiner will know that I was
166 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
167 AddUsersToWorkList(I); // Add all modified instrs to worklist
169 I.replaceAllUsesWith(V);
172 // If we are replacing the instruction with itself, this must be in a
173 // segment of unreachable code, so just clobber the instruction.
174 I.replaceAllUsesWith(Constant::getNullValue(I.getType()));
179 // EraseInstFromFunction - When dealing with an instruction that has side
180 // effects or produces a void value, we can't rely on DCE to delete the
181 // instruction. Instead, visit methods should return the value returned by
183 Instruction *EraseInstFromFunction(Instruction &I) {
184 assert(I.use_empty() && "Cannot erase instruction that is used!");
185 AddUsesToWorkList(I);
186 removeFromWorkList(&I);
187 I.getParent()->getInstList().erase(&I);
188 return 0; // Don't do anything with FI
193 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
194 /// InsertBefore instruction. This is specialized a bit to avoid inserting
195 /// casts that are known to not do anything...
197 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
198 Instruction *InsertBefore);
200 // SimplifyCommutative - This performs a few simplifications for commutative
202 bool SimplifyCommutative(BinaryOperator &I);
205 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
206 // PHI node as operand #0, see if we can fold the instruction into the PHI
207 // (which is only possible if all operands to the PHI are constants).
208 Instruction *FoldOpIntoPhi(Instruction &I);
210 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
211 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
213 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
214 bool Inside, Instruction &IB);
217 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
220 // getComplexity: Assign a complexity or rank value to LLVM Values...
221 // 0 -> Constant, 1 -> Other, 2 -> Argument, 2 -> Unary, 3 -> OtherInst
222 static unsigned getComplexity(Value *V) {
223 if (isa<Instruction>(V)) {
224 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
228 if (isa<Argument>(V)) return 2;
229 return isa<Constant>(V) ? 0 : 1;
232 // isOnlyUse - Return true if this instruction will be deleted if we stop using
234 static bool isOnlyUse(Value *V) {
235 return V->hasOneUse() || isa<Constant>(V);
238 // getPromotedType - Return the specified type promoted as it would be to pass
239 // though a va_arg area...
240 static const Type *getPromotedType(const Type *Ty) {
241 switch (Ty->getTypeID()) {
242 case Type::SByteTyID:
243 case Type::ShortTyID: return Type::IntTy;
244 case Type::UByteTyID:
245 case Type::UShortTyID: return Type::UIntTy;
246 case Type::FloatTyID: return Type::DoubleTy;
251 // SimplifyCommutative - This performs a few simplifications for commutative
254 // 1. Order operands such that they are listed from right (least complex) to
255 // left (most complex). This puts constants before unary operators before
258 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
259 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
261 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
262 bool Changed = false;
263 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
264 Changed = !I.swapOperands();
266 if (!I.isAssociative()) return Changed;
267 Instruction::BinaryOps Opcode = I.getOpcode();
268 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
269 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
270 if (isa<Constant>(I.getOperand(1))) {
271 Constant *Folded = ConstantExpr::get(I.getOpcode(),
272 cast<Constant>(I.getOperand(1)),
273 cast<Constant>(Op->getOperand(1)));
274 I.setOperand(0, Op->getOperand(0));
275 I.setOperand(1, Folded);
277 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
278 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
279 isOnlyUse(Op) && isOnlyUse(Op1)) {
280 Constant *C1 = cast<Constant>(Op->getOperand(1));
281 Constant *C2 = cast<Constant>(Op1->getOperand(1));
283 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
284 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
285 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
288 WorkList.push_back(New);
289 I.setOperand(0, New);
290 I.setOperand(1, Folded);
297 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
298 // if the LHS is a constant zero (which is the 'negate' form).
300 static inline Value *dyn_castNegVal(Value *V) {
301 if (BinaryOperator::isNeg(V))
302 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
304 // Constants can be considered to be negated values if they can be folded...
305 if (Constant *C = dyn_cast<Constant>(V))
306 return ConstantExpr::getNeg(C);
310 static inline Value *dyn_castNotVal(Value *V) {
311 if (BinaryOperator::isNot(V))
312 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
314 // Constants can be considered to be not'ed values...
315 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
316 return ConstantExpr::getNot(C);
320 // dyn_castFoldableMul - If this value is a multiply that can be folded into
321 // other computations (because it has a constant operand), return the
322 // non-constant operand of the multiply.
324 static inline Value *dyn_castFoldableMul(Value *V) {
325 if (V->hasOneUse() && V->getType()->isInteger())
326 if (Instruction *I = dyn_cast<Instruction>(V))
327 if (I->getOpcode() == Instruction::Mul)
328 if (isa<Constant>(I->getOperand(1)))
329 return I->getOperand(0);
333 // Log2 - Calculate the log base 2 for the specified value if it is exactly a
335 static unsigned Log2(uint64_t Val) {
336 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
339 if (Val & 1) return 0; // Multiple bits set?
346 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
347 static ConstantInt *AddOne(ConstantInt *C) {
348 return cast<ConstantInt>(ConstantExpr::getAdd(C,
349 ConstantInt::get(C->getType(), 1)));
351 static ConstantInt *SubOne(ConstantInt *C) {
352 return cast<ConstantInt>(ConstantExpr::getSub(C,
353 ConstantInt::get(C->getType(), 1)));
356 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
357 // true when both operands are equal...
359 static bool isTrueWhenEqual(Instruction &I) {
360 return I.getOpcode() == Instruction::SetEQ ||
361 I.getOpcode() == Instruction::SetGE ||
362 I.getOpcode() == Instruction::SetLE;
365 /// AssociativeOpt - Perform an optimization on an associative operator. This
366 /// function is designed to check a chain of associative operators for a
367 /// potential to apply a certain optimization. Since the optimization may be
368 /// applicable if the expression was reassociated, this checks the chain, then
369 /// reassociates the expression as necessary to expose the optimization
370 /// opportunity. This makes use of a special Functor, which must define
371 /// 'shouldApply' and 'apply' methods.
373 template<typename Functor>
374 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
375 unsigned Opcode = Root.getOpcode();
376 Value *LHS = Root.getOperand(0);
378 // Quick check, see if the immediate LHS matches...
379 if (F.shouldApply(LHS))
380 return F.apply(Root);
382 // Otherwise, if the LHS is not of the same opcode as the root, return.
383 Instruction *LHSI = dyn_cast<Instruction>(LHS);
384 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
385 // Should we apply this transform to the RHS?
386 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
388 // If not to the RHS, check to see if we should apply to the LHS...
389 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
390 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
394 // If the functor wants to apply the optimization to the RHS of LHSI,
395 // reassociate the expression from ((? op A) op B) to (? op (A op B))
397 BasicBlock *BB = Root.getParent();
399 // Now all of the instructions are in the current basic block, go ahead
400 // and perform the reassociation.
401 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
403 // First move the selected RHS to the LHS of the root...
404 Root.setOperand(0, LHSI->getOperand(1));
406 // Make what used to be the LHS of the root be the user of the root...
407 Value *ExtraOperand = TmpLHSI->getOperand(1);
408 if (&Root == TmpLHSI) {
409 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
412 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
413 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
414 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
415 BasicBlock::iterator ARI = &Root; ++ARI;
416 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
419 // Now propagate the ExtraOperand down the chain of instructions until we
421 while (TmpLHSI != LHSI) {
422 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
423 // Move the instruction to immediately before the chain we are
424 // constructing to avoid breaking dominance properties.
425 NextLHSI->getParent()->getInstList().remove(NextLHSI);
426 BB->getInstList().insert(ARI, NextLHSI);
429 Value *NextOp = NextLHSI->getOperand(1);
430 NextLHSI->setOperand(1, ExtraOperand);
432 ExtraOperand = NextOp;
435 // Now that the instructions are reassociated, have the functor perform
436 // the transformation...
437 return F.apply(Root);
440 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
446 // AddRHS - Implements: X + X --> X << 1
449 AddRHS(Value *rhs) : RHS(rhs) {}
450 bool shouldApply(Value *LHS) const { return LHS == RHS; }
451 Instruction *apply(BinaryOperator &Add) const {
452 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
453 ConstantInt::get(Type::UByteTy, 1));
457 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
459 struct AddMaskingAnd {
461 AddMaskingAnd(Constant *c) : C2(c) {}
462 bool shouldApply(Value *LHS) const {
464 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
465 ConstantExpr::getAnd(C1, C2)->isNullValue();
467 Instruction *apply(BinaryOperator &Add) const {
468 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
472 static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
474 // Figure out if the constant is the left or the right argument.
475 bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
476 Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
478 if (Constant *SOC = dyn_cast<Constant>(SO)) {
480 return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
481 return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
484 Value *Op0 = SO, *Op1 = ConstOperand;
488 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
489 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
490 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
491 New = new ShiftInst(SI->getOpcode(), Op0, Op1);
493 assert(0 && "Unknown binary instruction type!");
496 return IC->InsertNewInstBefore(New, BI);
500 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
501 /// node as operand #0, see if we can fold the instruction into the PHI (which
502 /// is only possible if all operands to the PHI are constants).
503 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
504 PHINode *PN = cast<PHINode>(I.getOperand(0));
505 if (!PN->hasOneUse()) return 0;
507 // Check to see if all of the operands of the PHI are constants. If not, we
508 // cannot do the transformation.
509 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
510 if (!isa<Constant>(PN->getIncomingValue(i)))
513 // Okay, we can do the transformation: create the new PHI node.
514 PHINode *NewPN = new PHINode(I.getType(), I.getName());
516 NewPN->op_reserve(PN->getNumOperands());
517 InsertNewInstBefore(NewPN, *PN);
519 // Next, add all of the operands to the PHI.
520 if (I.getNumOperands() == 2) {
521 Constant *C = cast<Constant>(I.getOperand(1));
522 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
523 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
524 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
525 PN->getIncomingBlock(i));
528 assert(isa<CastInst>(I) && "Unary op should be a cast!");
529 const Type *RetTy = I.getType();
530 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
531 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
532 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
533 PN->getIncomingBlock(i));
536 return ReplaceInstUsesWith(I, NewPN);
539 // FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
540 // constant as the other operand, try to fold the binary operator into the
542 static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
544 // Don't modify shared select instructions
545 if (!SI->hasOneUse()) return 0;
546 Value *TV = SI->getOperand(1);
547 Value *FV = SI->getOperand(2);
549 if (isa<Constant>(TV) || isa<Constant>(FV)) {
550 Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
551 Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
553 return new SelectInst(SI->getCondition(), SelectTrueVal,
559 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
560 bool Changed = SimplifyCommutative(I);
561 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
563 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
565 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
567 return ReplaceInstUsesWith(I, LHS);
569 // X + (signbit) --> X ^ signbit
570 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
571 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
572 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
573 if (Val == (1ULL << NumBits-1))
574 return BinaryOperator::createXor(LHS, RHS);
577 if (isa<PHINode>(LHS))
578 if (Instruction *NV = FoldOpIntoPhi(I))
583 if (I.getType()->isInteger()) {
584 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
588 if (Value *V = dyn_castNegVal(LHS))
589 return BinaryOperator::createSub(RHS, V);
592 if (!isa<Constant>(RHS))
593 if (Value *V = dyn_castNegVal(RHS))
594 return BinaryOperator::createSub(LHS, V);
596 // X*C + X --> X * (C+1)
597 if (dyn_castFoldableMul(LHS) == RHS) {
599 ConstantExpr::getAdd(
600 cast<Constant>(cast<Instruction>(LHS)->getOperand(1)),
601 ConstantInt::get(I.getType(), 1));
602 return BinaryOperator::createMul(RHS, CP1);
605 // X + X*C --> X * (C+1)
606 if (dyn_castFoldableMul(RHS) == LHS) {
608 ConstantExpr::getAdd(
609 cast<Constant>(cast<Instruction>(RHS)->getOperand(1)),
610 ConstantInt::get(I.getType(), 1));
611 return BinaryOperator::createMul(LHS, CP1);
614 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
616 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
617 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
619 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
621 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
622 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
623 return BinaryOperator::createSub(C, X);
626 // Try to fold constant add into select arguments.
627 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
628 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
632 return Changed ? &I : 0;
635 // isSignBit - Return true if the value represented by the constant only has the
636 // highest order bit set.
637 static bool isSignBit(ConstantInt *CI) {
638 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
639 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
642 static unsigned getTypeSizeInBits(const Type *Ty) {
643 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
646 /// RemoveNoopCast - Strip off nonconverting casts from the value.
648 static Value *RemoveNoopCast(Value *V) {
649 if (CastInst *CI = dyn_cast<CastInst>(V)) {
650 const Type *CTy = CI->getType();
651 const Type *OpTy = CI->getOperand(0)->getType();
652 if (CTy->isInteger() && OpTy->isInteger()) {
653 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
654 return RemoveNoopCast(CI->getOperand(0));
655 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
656 return RemoveNoopCast(CI->getOperand(0));
661 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
662 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
664 if (Op0 == Op1) // sub X, X -> 0
665 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
667 // If this is a 'B = x-(-A)', change to B = x+A...
668 if (Value *V = dyn_castNegVal(Op1))
669 return BinaryOperator::createAdd(Op0, V);
671 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
672 // Replace (-1 - A) with (~A)...
673 if (C->isAllOnesValue())
674 return BinaryOperator::createNot(Op1);
676 // C - ~X == X + (1+C)
678 if (match(Op1, m_Not(m_Value(X))))
679 return BinaryOperator::createAdd(X,
680 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
681 // -((uint)X >> 31) -> ((int)X >> 31)
682 // -((int)X >> 31) -> ((uint)X >> 31)
683 if (C->isNullValue()) {
684 Value *NoopCastedRHS = RemoveNoopCast(Op1);
685 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
686 if (SI->getOpcode() == Instruction::Shr)
687 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
689 if (SI->getType()->isSigned())
690 NewTy = SI->getType()->getUnsignedVersion();
692 NewTy = SI->getType()->getSignedVersion();
693 // Check to see if we are shifting out everything but the sign bit.
694 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
695 // Ok, the transformation is safe. Insert a cast of the incoming
696 // value, then the new shift, then the new cast.
697 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
698 SI->getOperand(0)->getName());
699 Value *InV = InsertNewInstBefore(FirstCast, I);
700 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
702 if (NewShift->getType() == I.getType())
705 InV = InsertNewInstBefore(NewShift, I);
706 return new CastInst(NewShift, I.getType());
712 // Try to fold constant sub into select arguments.
713 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
714 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
717 if (isa<PHINode>(Op0))
718 if (Instruction *NV = FoldOpIntoPhi(I))
722 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
723 if (Op1I->hasOneUse()) {
724 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
725 // is not used by anyone else...
727 if (Op1I->getOpcode() == Instruction::Sub &&
728 !Op1I->getType()->isFloatingPoint()) {
729 // Swap the two operands of the subexpr...
730 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
731 Op1I->setOperand(0, IIOp1);
732 Op1I->setOperand(1, IIOp0);
734 // Create the new top level add instruction...
735 return BinaryOperator::createAdd(Op0, Op1);
738 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
740 if (Op1I->getOpcode() == Instruction::And &&
741 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
742 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
745 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
746 return BinaryOperator::createAnd(Op0, NewNot);
749 // -(X sdiv C) -> (X sdiv -C)
750 if (Op1I->getOpcode() == Instruction::Div)
751 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
752 if (CSI->getValue() == 0)
753 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
754 return BinaryOperator::createDiv(Op1I->getOperand(0),
755 ConstantExpr::getNeg(DivRHS));
757 // X - X*C --> X * (1-C)
758 if (dyn_castFoldableMul(Op1I) == Op0) {
760 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
761 cast<Constant>(cast<Instruction>(Op1)->getOperand(1)));
762 assert(CP1 && "Couldn't constant fold 1-C?");
763 return BinaryOperator::createMul(Op0, CP1);
767 // X*C - X --> X * (C-1)
768 if (dyn_castFoldableMul(Op0) == Op1) {
770 ConstantExpr::getSub(cast<Constant>(cast<Instruction>(Op0)->getOperand(1)),
771 ConstantInt::get(I.getType(), 1));
772 assert(CP1 && "Couldn't constant fold C - 1?");
773 return BinaryOperator::createMul(Op1, CP1);
779 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
780 /// really just returns true if the most significant (sign) bit is set.
781 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
782 if (RHS->getType()->isSigned()) {
783 // True if source is LHS < 0 or LHS <= -1
784 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
785 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
787 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
788 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
789 // the size of the integer type.
790 if (Opcode == Instruction::SetGE)
791 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
792 if (Opcode == Instruction::SetGT)
793 return RHSC->getValue() ==
794 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
799 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
800 bool Changed = SimplifyCommutative(I);
801 Value *Op0 = I.getOperand(0);
803 // Simplify mul instructions with a constant RHS...
804 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
805 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
807 // ((X << C1)*C2) == (X * (C2 << C1))
808 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
809 if (SI->getOpcode() == Instruction::Shl)
810 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
811 return BinaryOperator::createMul(SI->getOperand(0),
812 ConstantExpr::getShl(CI, ShOp));
814 if (CI->isNullValue())
815 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
816 if (CI->equalsInt(1)) // X * 1 == X
817 return ReplaceInstUsesWith(I, Op0);
818 if (CI->isAllOnesValue()) // X * -1 == 0 - X
819 return BinaryOperator::createNeg(Op0, I.getName());
821 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
822 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
823 return new ShiftInst(Instruction::Shl, Op0,
824 ConstantUInt::get(Type::UByteTy, C));
825 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
826 if (Op1F->isNullValue())
827 return ReplaceInstUsesWith(I, Op1);
829 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
830 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
831 if (Op1F->getValue() == 1.0)
832 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
835 // Try to fold constant mul into select arguments.
836 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
837 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
840 if (isa<PHINode>(Op0))
841 if (Instruction *NV = FoldOpIntoPhi(I))
845 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
846 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
847 return BinaryOperator::createMul(Op0v, Op1v);
849 // If one of the operands of the multiply is a cast from a boolean value, then
850 // we know the bool is either zero or one, so this is a 'masking' multiply.
851 // See if we can simplify things based on how the boolean was originally
853 CastInst *BoolCast = 0;
854 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
855 if (CI->getOperand(0)->getType() == Type::BoolTy)
858 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
859 if (CI->getOperand(0)->getType() == Type::BoolTy)
862 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
863 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
864 const Type *SCOpTy = SCIOp0->getType();
866 // If the setcc is true iff the sign bit of X is set, then convert this
867 // multiply into a shift/and combination.
868 if (isa<ConstantInt>(SCIOp1) &&
869 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
870 // Shift the X value right to turn it into "all signbits".
871 Constant *Amt = ConstantUInt::get(Type::UByteTy,
872 SCOpTy->getPrimitiveSize()*8-1);
873 if (SCIOp0->getType()->isUnsigned()) {
874 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
875 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
876 SCIOp0->getName()), I);
880 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
881 BoolCast->getOperand(0)->getName()+
884 // If the multiply type is not the same as the source type, sign extend
885 // or truncate to the multiply type.
886 if (I.getType() != V->getType())
887 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
889 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
890 return BinaryOperator::createAnd(V, OtherOp);
895 return Changed ? &I : 0;
898 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
899 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
901 if (RHS->equalsInt(1))
902 return ReplaceInstUsesWith(I, I.getOperand(0));
905 if (RHS->isAllOnesValue())
906 return BinaryOperator::createNeg(I.getOperand(0));
908 if (Instruction *LHS = dyn_cast<Instruction>(I.getOperand(0)))
909 if (LHS->getOpcode() == Instruction::Div)
910 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
911 // (X / C1) / C2 -> X / (C1*C2)
912 return BinaryOperator::createDiv(LHS->getOperand(0),
913 ConstantExpr::getMul(RHS, LHSRHS));
916 // Check to see if this is an unsigned division with an exact power of 2,
917 // if so, convert to a right shift.
918 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
919 if (uint64_t Val = C->getValue()) // Don't break X / 0
920 if (uint64_t C = Log2(Val))
921 return new ShiftInst(Instruction::Shr, I.getOperand(0),
922 ConstantUInt::get(Type::UByteTy, C));
924 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
925 if (Instruction *NV = FoldOpIntoPhi(I))
929 // 0 / X == 0, we don't need to preserve faults!
930 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
931 if (LHS->equalsInt(0))
932 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
938 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
939 if (I.getType()->isSigned())
940 if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
941 if (!isa<ConstantSInt>(RHSNeg) ||
942 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
944 AddUsesToWorkList(I);
945 I.setOperand(1, RHSNeg);
949 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
950 if (RHS->equalsInt(1)) // X % 1 == 0
951 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
953 // Check to see if this is an unsigned remainder with an exact power of 2,
954 // if so, convert to a bitwise and.
955 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
956 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
957 if (!(Val & (Val-1))) // Power of 2
958 return BinaryOperator::createAnd(I.getOperand(0),
959 ConstantUInt::get(I.getType(), Val-1));
960 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
961 if (Instruction *NV = FoldOpIntoPhi(I))
965 // 0 % X == 0, we don't need to preserve faults!
966 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
967 if (LHS->equalsInt(0))
968 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
973 // isMaxValueMinusOne - return true if this is Max-1
974 static bool isMaxValueMinusOne(const ConstantInt *C) {
975 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
976 // Calculate -1 casted to the right type...
977 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
978 uint64_t Val = ~0ULL; // All ones
979 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
980 return CU->getValue() == Val-1;
983 const ConstantSInt *CS = cast<ConstantSInt>(C);
985 // Calculate 0111111111..11111
986 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
987 int64_t Val = INT64_MAX; // All ones
988 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
989 return CS->getValue() == Val-1;
992 // isMinValuePlusOne - return true if this is Min+1
993 static bool isMinValuePlusOne(const ConstantInt *C) {
994 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
995 return CU->getValue() == 1;
997 const ConstantSInt *CS = cast<ConstantSInt>(C);
999 // Calculate 1111111111000000000000
1000 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1001 int64_t Val = -1; // All ones
1002 Val <<= TypeBits-1; // Shift over to the right spot
1003 return CS->getValue() == Val+1;
1006 // isOneBitSet - Return true if there is exactly one bit set in the specified
1008 static bool isOneBitSet(const ConstantInt *CI) {
1009 uint64_t V = CI->getRawValue();
1010 return V && (V & (V-1)) == 0;
1013 #if 0 // Currently unused
1014 // isLowOnes - Return true if the constant is of the form 0+1+.
1015 static bool isLowOnes(const ConstantInt *CI) {
1016 uint64_t V = CI->getRawValue();
1018 // There won't be bits set in parts that the type doesn't contain.
1019 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1021 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1022 return U && V && (U & V) == 0;
1026 // isHighOnes - Return true if the constant is of the form 1+0+.
1027 // This is the same as lowones(~X).
1028 static bool isHighOnes(const ConstantInt *CI) {
1029 uint64_t V = ~CI->getRawValue();
1031 // There won't be bits set in parts that the type doesn't contain.
1032 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1034 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1035 return U && V && (U & V) == 0;
1039 /// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1040 /// are carefully arranged to allow folding of expressions such as:
1042 /// (A < B) | (A > B) --> (A != B)
1044 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1045 /// represents that the comparison is true if A == B, and bit value '1' is true
1048 static unsigned getSetCondCode(const SetCondInst *SCI) {
1049 switch (SCI->getOpcode()) {
1051 case Instruction::SetGT: return 1;
1052 case Instruction::SetEQ: return 2;
1053 case Instruction::SetGE: return 3;
1054 case Instruction::SetLT: return 4;
1055 case Instruction::SetNE: return 5;
1056 case Instruction::SetLE: return 6;
1059 assert(0 && "Invalid SetCC opcode!");
1064 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
1065 /// opcode and two operands into either a constant true or false, or a brand new
1066 /// SetCC instruction.
1067 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1069 case 0: return ConstantBool::False;
1070 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1071 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1072 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1073 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1074 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1075 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1076 case 7: return ConstantBool::True;
1077 default: assert(0 && "Illegal SetCCCode!"); return 0;
1081 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1082 struct FoldSetCCLogical {
1085 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1086 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1087 bool shouldApply(Value *V) const {
1088 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1089 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1090 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1093 Instruction *apply(BinaryOperator &Log) const {
1094 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1095 if (SCI->getOperand(0) != LHS) {
1096 assert(SCI->getOperand(1) == LHS);
1097 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1100 unsigned LHSCode = getSetCondCode(SCI);
1101 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1103 switch (Log.getOpcode()) {
1104 case Instruction::And: Code = LHSCode & RHSCode; break;
1105 case Instruction::Or: Code = LHSCode | RHSCode; break;
1106 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
1107 default: assert(0 && "Illegal logical opcode!"); return 0;
1110 Value *RV = getSetCCValue(Code, LHS, RHS);
1111 if (Instruction *I = dyn_cast<Instruction>(RV))
1113 // Otherwise, it's a constant boolean value...
1114 return IC.ReplaceInstUsesWith(Log, RV);
1119 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1120 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1121 // guaranteed to be either a shift instruction or a binary operator.
1122 Instruction *InstCombiner::OptAndOp(Instruction *Op,
1123 ConstantIntegral *OpRHS,
1124 ConstantIntegral *AndRHS,
1125 BinaryOperator &TheAnd) {
1126 Value *X = Op->getOperand(0);
1127 Constant *Together = 0;
1128 if (!isa<ShiftInst>(Op))
1129 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
1131 switch (Op->getOpcode()) {
1132 case Instruction::Xor:
1133 if (Together->isNullValue()) {
1134 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
1135 return BinaryOperator::createAnd(X, AndRHS);
1136 } else if (Op->hasOneUse()) {
1137 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1138 std::string OpName = Op->getName(); Op->setName("");
1139 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
1140 InsertNewInstBefore(And, TheAnd);
1141 return BinaryOperator::createXor(And, Together);
1144 case Instruction::Or:
1145 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
1146 if (Together->isNullValue())
1147 return BinaryOperator::createAnd(X, AndRHS);
1149 if (Together == AndRHS) // (X | C) & C --> C
1150 return ReplaceInstUsesWith(TheAnd, AndRHS);
1152 if (Op->hasOneUse() && Together != OpRHS) {
1153 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1154 std::string Op0Name = Op->getName(); Op->setName("");
1155 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1156 InsertNewInstBefore(Or, TheAnd);
1157 return BinaryOperator::createAnd(Or, AndRHS);
1161 case Instruction::Add:
1162 if (Op->hasOneUse()) {
1163 // Adding a one to a single bit bit-field should be turned into an XOR
1164 // of the bit. First thing to check is to see if this AND is with a
1165 // single bit constant.
1166 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
1168 // Clear bits that are not part of the constant.
1169 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1171 // If there is only one bit set...
1172 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
1173 // Ok, at this point, we know that we are masking the result of the
1174 // ADD down to exactly one bit. If the constant we are adding has
1175 // no bits set below this bit, then we can eliminate the ADD.
1176 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
1178 // Check to see if any bits below the one bit set in AndRHSV are set.
1179 if ((AddRHS & (AndRHSV-1)) == 0) {
1180 // If not, the only thing that can effect the output of the AND is
1181 // the bit specified by AndRHSV. If that bit is set, the effect of
1182 // the XOR is to toggle the bit. If it is clear, then the ADD has
1184 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1185 TheAnd.setOperand(0, X);
1188 std::string Name = Op->getName(); Op->setName("");
1189 // Pull the XOR out of the AND.
1190 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
1191 InsertNewInstBefore(NewAnd, TheAnd);
1192 return BinaryOperator::createXor(NewAnd, AndRHS);
1199 case Instruction::Shl: {
1200 // We know that the AND will not produce any of the bits shifted in, so if
1201 // the anded constant includes them, clear them now!
1203 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1204 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1205 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1207 if (CI == ShlMask) { // Masking out bits that the shift already masks
1208 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1209 } else if (CI != AndRHS) { // Reducing bits set in and.
1210 TheAnd.setOperand(1, CI);
1215 case Instruction::Shr:
1216 // We know that the AND will not produce any of the bits shifted in, so if
1217 // the anded constant includes them, clear them now! This only applies to
1218 // unsigned shifts, because a signed shr may bring in set bits!
1220 if (AndRHS->getType()->isUnsigned()) {
1221 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1222 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1223 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1225 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1226 return ReplaceInstUsesWith(TheAnd, Op);
1227 } else if (CI != AndRHS) {
1228 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
1231 } else { // Signed shr.
1232 // See if this is shifting in some sign extension, then masking it out
1234 if (Op->hasOneUse()) {
1235 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1236 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1237 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1238 if (CI == ShrMask) { // Masking out bits shifted in.
1239 // Make the argument unsigned.
1240 Value *ShVal = Op->getOperand(0);
1241 ShVal = InsertCastBefore(ShVal,
1242 ShVal->getType()->getUnsignedVersion(),
1244 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1245 OpRHS, Op->getName()),
1247 return new CastInst(ShVal, Op->getType());
1257 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1258 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1259 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1260 /// insert new instructions.
1261 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1262 bool Inside, Instruction &IB) {
1263 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1264 "Lo is not <= Hi in range emission code!");
1266 if (Lo == Hi) // Trivially false.
1267 return new SetCondInst(Instruction::SetNE, V, V);
1268 if (cast<ConstantIntegral>(Lo)->isMinValue())
1269 return new SetCondInst(Instruction::SetLT, V, Hi);
1271 Constant *AddCST = ConstantExpr::getNeg(Lo);
1272 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1273 InsertNewInstBefore(Add, IB);
1274 // Convert to unsigned for the comparison.
1275 const Type *UnsType = Add->getType()->getUnsignedVersion();
1276 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1277 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1278 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1279 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1282 if (Lo == Hi) // Trivially true.
1283 return new SetCondInst(Instruction::SetEQ, V, V);
1285 Hi = SubOne(cast<ConstantInt>(Hi));
1286 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1287 return new SetCondInst(Instruction::SetGT, V, Hi);
1289 // Emit X-Lo > Hi-Lo-1
1290 Constant *AddCST = ConstantExpr::getNeg(Lo);
1291 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1292 InsertNewInstBefore(Add, IB);
1293 // Convert to unsigned for the comparison.
1294 const Type *UnsType = Add->getType()->getUnsignedVersion();
1295 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1296 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1297 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1298 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1302 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1303 bool Changed = SimplifyCommutative(I);
1304 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1306 // and X, X = X and X, 0 == 0
1307 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1308 return ReplaceInstUsesWith(I, Op1);
1311 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
1312 if (RHS->isAllOnesValue())
1313 return ReplaceInstUsesWith(I, Op0);
1315 // Optimize a variety of ((val OP C1) & C2) combinations...
1316 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1317 Instruction *Op0I = cast<Instruction>(Op0);
1318 Value *X = Op0I->getOperand(0);
1319 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1320 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1324 // Try to fold constant and into select arguments.
1325 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1326 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1328 if (isa<PHINode>(Op0))
1329 if (Instruction *NV = FoldOpIntoPhi(I))
1333 Value *Op0NotVal = dyn_castNotVal(Op0);
1334 Value *Op1NotVal = dyn_castNotVal(Op1);
1336 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1337 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1339 // (~A & ~B) == (~(A | B)) - De Morgan's Law
1340 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1341 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1342 I.getName()+".demorgan");
1343 InsertNewInstBefore(Or, I);
1344 return BinaryOperator::createNot(Or);
1347 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1348 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1349 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1352 Value *LHSVal, *RHSVal;
1353 ConstantInt *LHSCst, *RHSCst;
1354 Instruction::BinaryOps LHSCC, RHSCC;
1355 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1356 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1357 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1358 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1359 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1360 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1361 // Ensure that the larger constant is on the RHS.
1362 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1363 SetCondInst *LHS = cast<SetCondInst>(Op0);
1364 if (cast<ConstantBool>(Cmp)->getValue()) {
1365 std::swap(LHS, RHS);
1366 std::swap(LHSCst, RHSCst);
1367 std::swap(LHSCC, RHSCC);
1370 // At this point, we know we have have two setcc instructions
1371 // comparing a value against two constants and and'ing the result
1372 // together. Because of the above check, we know that we only have
1373 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1374 // FoldSetCCLogical check above), that the two constants are not
1376 assert(LHSCst != RHSCst && "Compares not folded above?");
1379 default: assert(0 && "Unknown integer condition code!");
1380 case Instruction::SetEQ:
1382 default: assert(0 && "Unknown integer condition code!");
1383 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1384 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1385 return ReplaceInstUsesWith(I, ConstantBool::False);
1386 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1387 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1388 return ReplaceInstUsesWith(I, LHS);
1390 case Instruction::SetNE:
1392 default: assert(0 && "Unknown integer condition code!");
1393 case Instruction::SetLT:
1394 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1395 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1396 break; // (X != 13 & X < 15) -> no change
1397 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1398 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1399 return ReplaceInstUsesWith(I, RHS);
1400 case Instruction::SetNE:
1401 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1402 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1403 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1404 LHSVal->getName()+".off");
1405 InsertNewInstBefore(Add, I);
1406 const Type *UnsType = Add->getType()->getUnsignedVersion();
1407 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1408 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1409 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1410 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1412 break; // (X != 13 & X != 15) -> no change
1415 case Instruction::SetLT:
1417 default: assert(0 && "Unknown integer condition code!");
1418 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1419 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1420 return ReplaceInstUsesWith(I, ConstantBool::False);
1421 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1422 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1423 return ReplaceInstUsesWith(I, LHS);
1425 case Instruction::SetGT:
1427 default: assert(0 && "Unknown integer condition code!");
1428 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1429 return ReplaceInstUsesWith(I, LHS);
1430 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1431 return ReplaceInstUsesWith(I, RHS);
1432 case Instruction::SetNE:
1433 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1434 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1435 break; // (X > 13 & X != 15) -> no change
1436 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1437 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
1443 return Changed ? &I : 0;
1446 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1447 bool Changed = SimplifyCommutative(I);
1448 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1450 // or X, X = X or X, 0 == X
1451 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1452 return ReplaceInstUsesWith(I, Op0);
1455 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
1456 if (RHS->isAllOnesValue())
1457 return ReplaceInstUsesWith(I, Op1);
1459 ConstantInt *C1; Value *X;
1460 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1461 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1462 std::string Op0Name = Op0->getName(); Op0->setName("");
1463 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1464 InsertNewInstBefore(Or, I);
1465 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1468 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1469 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1470 std::string Op0Name = Op0->getName(); Op0->setName("");
1471 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1472 InsertNewInstBefore(Or, I);
1473 return BinaryOperator::createXor(Or,
1474 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
1477 // Try to fold constant and into select arguments.
1478 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1479 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1481 if (isa<PHINode>(Op0))
1482 if (Instruction *NV = FoldOpIntoPhi(I))
1486 // (A & C1)|(A & C2) == A & (C1|C2)
1487 Value *A, *B; ConstantInt *C1, *C2;
1488 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1489 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1490 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
1492 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1493 if (A == Op1) // ~A | A == -1
1494 return ReplaceInstUsesWith(I,
1495 ConstantIntegral::getAllOnesValue(I.getType()));
1500 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1502 return ReplaceInstUsesWith(I,
1503 ConstantIntegral::getAllOnesValue(I.getType()));
1505 // (~A | ~B) == (~(A & B)) - De Morgan's Law
1506 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1507 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1508 I.getName()+".demorgan"), I);
1509 return BinaryOperator::createNot(And);
1513 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
1514 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
1515 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1518 Value *LHSVal, *RHSVal;
1519 ConstantInt *LHSCst, *RHSCst;
1520 Instruction::BinaryOps LHSCC, RHSCC;
1521 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1522 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1523 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1524 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1525 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1526 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1527 // Ensure that the larger constant is on the RHS.
1528 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1529 SetCondInst *LHS = cast<SetCondInst>(Op0);
1530 if (cast<ConstantBool>(Cmp)->getValue()) {
1531 std::swap(LHS, RHS);
1532 std::swap(LHSCst, RHSCst);
1533 std::swap(LHSCC, RHSCC);
1536 // At this point, we know we have have two setcc instructions
1537 // comparing a value against two constants and or'ing the result
1538 // together. Because of the above check, we know that we only have
1539 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1540 // FoldSetCCLogical check above), that the two constants are not
1542 assert(LHSCst != RHSCst && "Compares not folded above?");
1545 default: assert(0 && "Unknown integer condition code!");
1546 case Instruction::SetEQ:
1548 default: assert(0 && "Unknown integer condition code!");
1549 case Instruction::SetEQ:
1550 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1551 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1552 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1553 LHSVal->getName()+".off");
1554 InsertNewInstBefore(Add, I);
1555 const Type *UnsType = Add->getType()->getUnsignedVersion();
1556 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1557 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1558 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1559 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1561 break; // (X == 13 | X == 15) -> no change
1563 case Instruction::SetGT:
1564 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1565 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1566 break; // (X == 13 | X > 15) -> no change
1567 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1568 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1569 return ReplaceInstUsesWith(I, RHS);
1572 case Instruction::SetNE:
1574 default: assert(0 && "Unknown integer condition code!");
1575 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1576 return ReplaceInstUsesWith(I, RHS);
1577 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1578 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1579 return ReplaceInstUsesWith(I, LHS);
1580 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1581 return ReplaceInstUsesWith(I, ConstantBool::True);
1584 case Instruction::SetLT:
1586 default: assert(0 && "Unknown integer condition code!");
1587 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1589 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1590 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
1591 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1592 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1593 return ReplaceInstUsesWith(I, RHS);
1596 case Instruction::SetGT:
1598 default: assert(0 && "Unknown integer condition code!");
1599 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1600 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1601 return ReplaceInstUsesWith(I, LHS);
1602 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1603 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1604 return ReplaceInstUsesWith(I, ConstantBool::True);
1609 return Changed ? &I : 0;
1612 // XorSelf - Implements: X ^ X --> 0
1615 XorSelf(Value *rhs) : RHS(rhs) {}
1616 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1617 Instruction *apply(BinaryOperator &Xor) const {
1623 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
1624 bool Changed = SimplifyCommutative(I);
1625 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1627 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1628 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1629 assert(Result == &I && "AssociativeOpt didn't work?");
1630 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1633 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
1635 if (RHS->isNullValue())
1636 return ReplaceInstUsesWith(I, Op0);
1638 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1639 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
1640 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
1641 if (RHS == ConstantBool::True && SCI->hasOneUse())
1642 return new SetCondInst(SCI->getInverseCondition(),
1643 SCI->getOperand(0), SCI->getOperand(1));
1645 // ~(c-X) == X-c-1 == X+(-c-1)
1646 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1647 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
1648 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1649 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
1650 ConstantInt::get(I.getType(), 1));
1651 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
1654 // ~(~X & Y) --> (X | ~Y)
1655 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1656 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1657 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1659 BinaryOperator::createNot(Op0I->getOperand(1),
1660 Op0I->getOperand(1)->getName()+".not");
1661 InsertNewInstBefore(NotY, I);
1662 return BinaryOperator::createOr(Op0NotVal, NotY);
1666 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1667 switch (Op0I->getOpcode()) {
1668 case Instruction::Add:
1669 // ~(X-c) --> (-c-1)-X
1670 if (RHS->isAllOnesValue()) {
1671 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1672 return BinaryOperator::createSub(
1673 ConstantExpr::getSub(NegOp0CI,
1674 ConstantInt::get(I.getType(), 1)),
1675 Op0I->getOperand(0));
1678 case Instruction::And:
1679 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
1680 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1681 return BinaryOperator::createOr(Op0, RHS);
1683 case Instruction::Or:
1684 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1685 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
1686 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
1692 // Try to fold constant and into select arguments.
1693 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1694 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1696 if (isa<PHINode>(Op0))
1697 if (Instruction *NV = FoldOpIntoPhi(I))
1701 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
1703 return ReplaceInstUsesWith(I,
1704 ConstantIntegral::getAllOnesValue(I.getType()));
1706 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
1708 return ReplaceInstUsesWith(I,
1709 ConstantIntegral::getAllOnesValue(I.getType()));
1711 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
1712 if (Op1I->getOpcode() == Instruction::Or) {
1713 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1714 cast<BinaryOperator>(Op1I)->swapOperands();
1716 std::swap(Op0, Op1);
1717 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1719 std::swap(Op0, Op1);
1721 } else if (Op1I->getOpcode() == Instruction::Xor) {
1722 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1723 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1724 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1725 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1728 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
1729 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
1730 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1731 cast<BinaryOperator>(Op0I)->swapOperands();
1732 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
1733 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1734 Op1->getName()+".not"), I);
1735 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
1737 } else if (Op0I->getOpcode() == Instruction::Xor) {
1738 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1739 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1740 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1741 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1744 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1745 Value *A, *B; ConstantInt *C1, *C2;
1746 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1747 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
1748 ConstantExpr::getAnd(C1, C2)->isNullValue())
1749 return BinaryOperator::createOr(Op0, Op1);
1751 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1752 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1753 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1756 return Changed ? &I : 0;
1759 /// MulWithOverflow - Compute Result = In1*In2, returning true if the result
1760 /// overflowed for this type.
1761 static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1763 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
1764 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
1767 static bool isPositive(ConstantInt *C) {
1768 return cast<ConstantSInt>(C)->getValue() >= 0;
1771 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
1772 /// overflowed for this type.
1773 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1775 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
1777 if (In1->getType()->isUnsigned())
1778 return cast<ConstantUInt>(Result)->getValue() <
1779 cast<ConstantUInt>(In1)->getValue();
1780 if (isPositive(In1) != isPositive(In2))
1782 if (isPositive(In1))
1783 return cast<ConstantSInt>(Result)->getValue() <
1784 cast<ConstantSInt>(In1)->getValue();
1785 return cast<ConstantSInt>(Result)->getValue() >
1786 cast<ConstantSInt>(In1)->getValue();
1789 Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
1790 bool Changed = SimplifyCommutative(I);
1791 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1792 const Type *Ty = Op0->getType();
1796 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
1798 // setcc <global/alloca*>, 0 - Global/Stack value addresses are never null!
1799 if (isa<ConstantPointerNull>(Op1) &&
1800 (isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0)))
1801 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1804 // setcc's with boolean values can always be turned into bitwise operations
1805 if (Ty == Type::BoolTy) {
1806 switch (I.getOpcode()) {
1807 default: assert(0 && "Invalid setcc instruction!");
1808 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
1809 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
1810 InsertNewInstBefore(Xor, I);
1811 return BinaryOperator::createNot(Xor);
1813 case Instruction::SetNE:
1814 return BinaryOperator::createXor(Op0, Op1);
1816 case Instruction::SetGT:
1817 std::swap(Op0, Op1); // Change setgt -> setlt
1819 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
1820 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1821 InsertNewInstBefore(Not, I);
1822 return BinaryOperator::createAnd(Not, Op1);
1824 case Instruction::SetGE:
1825 std::swap(Op0, Op1); // Change setge -> setle
1827 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
1828 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1829 InsertNewInstBefore(Not, I);
1830 return BinaryOperator::createOr(Not, Op1);
1835 // See if we are doing a comparison between a constant and an instruction that
1836 // can be folded into the comparison.
1837 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1838 // Check to see if we are comparing against the minimum or maximum value...
1839 if (CI->isMinValue()) {
1840 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1841 return ReplaceInstUsesWith(I, ConstantBool::False);
1842 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1843 return ReplaceInstUsesWith(I, ConstantBool::True);
1844 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
1845 return BinaryOperator::createSetEQ(Op0, Op1);
1846 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
1847 return BinaryOperator::createSetNE(Op0, Op1);
1849 } else if (CI->isMaxValue()) {
1850 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1851 return ReplaceInstUsesWith(I, ConstantBool::False);
1852 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1853 return ReplaceInstUsesWith(I, ConstantBool::True);
1854 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
1855 return BinaryOperator::createSetEQ(Op0, Op1);
1856 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
1857 return BinaryOperator::createSetNE(Op0, Op1);
1859 // Comparing against a value really close to min or max?
1860 } else if (isMinValuePlusOne(CI)) {
1861 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
1862 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
1863 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
1864 return BinaryOperator::createSetNE(Op0, SubOne(CI));
1866 } else if (isMaxValueMinusOne(CI)) {
1867 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
1868 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
1869 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
1870 return BinaryOperator::createSetNE(Op0, AddOne(CI));
1873 // If we still have a setle or setge instruction, turn it into the
1874 // appropriate setlt or setgt instruction. Since the border cases have
1875 // already been handled above, this requires little checking.
1877 if (I.getOpcode() == Instruction::SetLE)
1878 return BinaryOperator::createSetLT(Op0, AddOne(CI));
1879 if (I.getOpcode() == Instruction::SetGE)
1880 return BinaryOperator::createSetGT(Op0, SubOne(CI));
1882 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
1883 switch (LHSI->getOpcode()) {
1884 case Instruction::PHI:
1885 if (Instruction *NV = FoldOpIntoPhi(I))
1888 case Instruction::And:
1889 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1890 LHSI->getOperand(0)->hasOneUse()) {
1891 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1892 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1893 // happens a LOT in code produced by the C front-end, for bitfield
1895 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
1896 ConstantUInt *ShAmt;
1897 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
1898 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1899 const Type *Ty = LHSI->getType();
1901 // We can fold this as long as we can't shift unknown bits
1902 // into the mask. This can only happen with signed shift
1903 // rights, as they sign-extend.
1905 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
1906 Shift->getType()->isUnsigned();
1908 // To test for the bad case of the signed shr, see if any
1909 // of the bits shifted in could be tested after the mask.
1910 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
1911 Ty->getPrimitiveSize()*8-ShAmt->getValue());
1913 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
1914 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
1920 if (Shift->getOpcode() == Instruction::Shl)
1921 NewCst = ConstantExpr::getUShr(CI, ShAmt);
1923 NewCst = ConstantExpr::getShl(CI, ShAmt);
1925 // Check to see if we are shifting out any of the bits being
1927 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
1928 // If we shifted bits out, the fold is not going to work out.
1929 // As a special case, check to see if this means that the
1930 // result is always true or false now.
1931 if (I.getOpcode() == Instruction::SetEQ)
1932 return ReplaceInstUsesWith(I, ConstantBool::False);
1933 if (I.getOpcode() == Instruction::SetNE)
1934 return ReplaceInstUsesWith(I, ConstantBool::True);
1936 I.setOperand(1, NewCst);
1937 Constant *NewAndCST;
1938 if (Shift->getOpcode() == Instruction::Shl)
1939 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
1941 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
1942 LHSI->setOperand(1, NewAndCST);
1943 LHSI->setOperand(0, Shift->getOperand(0));
1944 WorkList.push_back(Shift); // Shift is dead.
1945 AddUsesToWorkList(I);
1953 case Instruction::Cast: { // (setcc (cast X to larger), CI)
1954 const Type *SrcTy = LHSI->getOperand(0)->getType();
1955 if (SrcTy->isIntegral() && LHSI->getType()->isIntegral()) {
1956 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
1957 if (SrcTy == Type::BoolTy) SrcBits = 1;
1958 unsigned DestBits = LHSI->getType()->getPrimitiveSize()*8;
1959 if (LHSI->getType() == Type::BoolTy) DestBits = 1;
1960 if (SrcBits < DestBits) {
1961 // Check to see if the comparison is always true or false.
1962 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
1963 if (ConstantExpr::getCast(NewCst, LHSI->getType()) != CI) {
1964 Constant *Min = ConstantIntegral::getMinValue(SrcTy);
1965 Constant *Max = ConstantIntegral::getMaxValue(SrcTy);
1966 Min = ConstantExpr::getCast(Min, LHSI->getType());
1967 Max = ConstantExpr::getCast(Max, LHSI->getType());
1968 switch (I.getOpcode()) {
1969 default: assert(0 && "unknown integer comparison");
1970 case Instruction::SetEQ:
1971 return ReplaceInstUsesWith(I, ConstantBool::False);
1972 case Instruction::SetNE:
1973 return ReplaceInstUsesWith(I, ConstantBool::True);
1974 case Instruction::SetLT:
1975 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
1976 case Instruction::SetGT:
1977 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
1981 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
1982 ConstantExpr::getCast(CI, SrcTy));
1987 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
1988 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
1989 switch (I.getOpcode()) {
1991 case Instruction::SetEQ:
1992 case Instruction::SetNE: {
1993 // If we are comparing against bits always shifted out, the
1994 // comparison cannot succeed.
1996 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
1997 if (Comp != CI) {// Comparing against a bit that we know is zero.
1998 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
1999 Constant *Cst = ConstantBool::get(IsSetNE);
2000 return ReplaceInstUsesWith(I, Cst);
2003 if (LHSI->hasOneUse()) {
2004 // Otherwise strength reduce the shift into an and.
2005 unsigned ShAmtVal = ShAmt->getValue();
2006 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2007 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2010 if (CI->getType()->isUnsigned()) {
2011 Mask = ConstantUInt::get(CI->getType(), Val);
2012 } else if (ShAmtVal != 0) {
2013 Mask = ConstantSInt::get(CI->getType(), Val);
2015 Mask = ConstantInt::getAllOnesValue(CI->getType());
2019 BinaryOperator::createAnd(LHSI->getOperand(0),
2020 Mask, LHSI->getName()+".mask");
2021 Value *And = InsertNewInstBefore(AndI, I);
2022 return new SetCondInst(I.getOpcode(), And,
2023 ConstantExpr::getUShr(CI, ShAmt));
2030 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
2031 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2032 switch (I.getOpcode()) {
2034 case Instruction::SetEQ:
2035 case Instruction::SetNE: {
2036 // If we are comparing against bits always shifted out, the
2037 // comparison cannot succeed.
2039 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2041 if (Comp != CI) {// Comparing against a bit that we know is zero.
2042 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2043 Constant *Cst = ConstantBool::get(IsSetNE);
2044 return ReplaceInstUsesWith(I, Cst);
2047 if (LHSI->hasOneUse() || CI->isNullValue()) {
2048 unsigned ShAmtVal = ShAmt->getValue();
2050 // Otherwise strength reduce the shift into an and.
2051 uint64_t Val = ~0ULL; // All ones.
2052 Val <<= ShAmtVal; // Shift over to the right spot.
2055 if (CI->getType()->isUnsigned()) {
2056 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2057 Val &= (1ULL << TypeBits)-1;
2058 Mask = ConstantUInt::get(CI->getType(), Val);
2060 Mask = ConstantSInt::get(CI->getType(), Val);
2064 BinaryOperator::createAnd(LHSI->getOperand(0),
2065 Mask, LHSI->getName()+".mask");
2066 Value *And = InsertNewInstBefore(AndI, I);
2067 return new SetCondInst(I.getOpcode(), And,
2068 ConstantExpr::getShl(CI, ShAmt));
2076 case Instruction::Div:
2077 // Fold: (div X, C1) op C2 -> range check
2078 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2079 // Fold this div into the comparison, producing a range check.
2080 // Determine, based on the divide type, what the range is being
2081 // checked. If there is an overflow on the low or high side, remember
2082 // it, otherwise compute the range [low, hi) bounding the new value.
2083 bool LoOverflow = false, HiOverflow = 0;
2084 ConstantInt *LoBound = 0, *HiBound = 0;
2087 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2089 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2090 } else if (LHSI->getType()->isUnsigned()) { // udiv
2092 LoOverflow = ProdOV;
2093 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2094 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2095 if (CI->isNullValue()) { // (X / pos) op 0
2097 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2099 } else if (isPositive(CI)) { // (X / pos) op pos
2101 LoOverflow = ProdOV;
2102 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2103 } else { // (X / pos) op neg
2104 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2105 LoOverflow = AddWithOverflow(LoBound, Prod,
2106 cast<ConstantInt>(DivRHSH));
2108 HiOverflow = ProdOV;
2110 } else { // Divisor is < 0.
2111 if (CI->isNullValue()) { // (X / neg) op 0
2112 LoBound = AddOne(DivRHS);
2113 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2114 } else if (isPositive(CI)) { // (X / neg) op pos
2115 HiOverflow = LoOverflow = ProdOV;
2117 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2118 HiBound = AddOne(Prod);
2119 } else { // (X / neg) op neg
2121 LoOverflow = HiOverflow = ProdOV;
2122 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2127 Value *X = LHSI->getOperand(0);
2128 switch (I.getOpcode()) {
2129 default: assert(0 && "Unhandled setcc opcode!");
2130 case Instruction::SetEQ:
2131 if (LoOverflow && HiOverflow)
2132 return ReplaceInstUsesWith(I, ConstantBool::False);
2133 else if (HiOverflow)
2134 return new SetCondInst(Instruction::SetGE, X, LoBound);
2135 else if (LoOverflow)
2136 return new SetCondInst(Instruction::SetLT, X, HiBound);
2138 return InsertRangeTest(X, LoBound, HiBound, true, I);
2139 case Instruction::SetNE:
2140 if (LoOverflow && HiOverflow)
2141 return ReplaceInstUsesWith(I, ConstantBool::True);
2142 else if (HiOverflow)
2143 return new SetCondInst(Instruction::SetLT, X, LoBound);
2144 else if (LoOverflow)
2145 return new SetCondInst(Instruction::SetGE, X, HiBound);
2147 return InsertRangeTest(X, LoBound, HiBound, false, I);
2148 case Instruction::SetLT:
2150 return ReplaceInstUsesWith(I, ConstantBool::False);
2151 return new SetCondInst(Instruction::SetLT, X, LoBound);
2152 case Instruction::SetGT:
2154 return ReplaceInstUsesWith(I, ConstantBool::False);
2155 return new SetCondInst(Instruction::SetGE, X, HiBound);
2160 case Instruction::Select:
2161 // If either operand of the select is a constant, we can fold the
2162 // comparison into the select arms, which will cause one to be
2163 // constant folded and the select turned into a bitwise or.
2164 Value *Op1 = 0, *Op2 = 0;
2165 if (LHSI->hasOneUse()) {
2166 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2167 // Fold the known value into the constant operand.
2168 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2169 // Insert a new SetCC of the other select operand.
2170 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
2171 LHSI->getOperand(2), CI,
2173 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2174 // Fold the known value into the constant operand.
2175 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2176 // Insert a new SetCC of the other select operand.
2177 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
2178 LHSI->getOperand(1), CI,
2184 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2188 // Simplify seteq and setne instructions...
2189 if (I.getOpcode() == Instruction::SetEQ ||
2190 I.getOpcode() == Instruction::SetNE) {
2191 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2193 // If the first operand is (and|or|xor) with a constant, and the second
2194 // operand is a constant, simplify a bit.
2195 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2196 switch (BO->getOpcode()) {
2197 case Instruction::Rem:
2198 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2199 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2201 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2203 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2204 const Type *UTy = BO->getType()->getUnsignedVersion();
2205 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2207 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2208 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2209 RHSCst, BO->getName()), I);
2210 return BinaryOperator::create(I.getOpcode(), NewRem,
2211 Constant::getNullValue(UTy));
2215 case Instruction::Add:
2216 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2217 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2218 if (BO->hasOneUse())
2219 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2220 ConstantExpr::getSub(CI, BOp1C));
2221 } else if (CI->isNullValue()) {
2222 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2223 // efficiently invertible, or if the add has just this one use.
2224 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
2226 if (Value *NegVal = dyn_castNegVal(BOp1))
2227 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2228 else if (Value *NegVal = dyn_castNegVal(BOp0))
2229 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
2230 else if (BO->hasOneUse()) {
2231 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2233 InsertNewInstBefore(Neg, I);
2234 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2238 case Instruction::Xor:
2239 // For the xor case, we can xor two constants together, eliminating
2240 // the explicit xor.
2241 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2242 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
2243 ConstantExpr::getXor(CI, BOC));
2246 case Instruction::Sub:
2247 // Replace (([sub|xor] A, B) != 0) with (A != B)
2248 if (CI->isNullValue())
2249 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2253 case Instruction::Or:
2254 // If bits are being or'd in that are not present in the constant we
2255 // are comparing against, then the comparison could never succeed!
2256 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
2257 Constant *NotCI = ConstantExpr::getNot(CI);
2258 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
2259 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
2263 case Instruction::And:
2264 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2265 // If bits are being compared against that are and'd out, then the
2266 // comparison can never succeed!
2267 if (!ConstantExpr::getAnd(CI,
2268 ConstantExpr::getNot(BOC))->isNullValue())
2269 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
2271 // If we have ((X & C) == C), turn it into ((X & C) != 0).
2272 if (CI == BOC && isOneBitSet(CI))
2273 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2274 Instruction::SetNE, Op0,
2275 Constant::getNullValue(CI->getType()));
2277 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2278 // to be a signed value as appropriate.
2279 if (isSignBit(BOC)) {
2280 Value *X = BO->getOperand(0);
2281 // If 'X' is not signed, insert a cast now...
2282 if (!BOC->getType()->isSigned()) {
2283 const Type *DestTy = BOC->getType()->getSignedVersion();
2284 X = InsertCastBefore(X, DestTy, I);
2286 return new SetCondInst(isSetNE ? Instruction::SetLT :
2287 Instruction::SetGE, X,
2288 Constant::getNullValue(X->getType()));
2291 // ((X & ~7) == 0) --> X < 8
2292 if (CI->isNullValue() && isHighOnes(BOC)) {
2293 Value *X = BO->getOperand(0);
2294 Constant *NegX = ConstantExpr::getNeg(BOC);
2296 // If 'X' is signed, insert a cast now.
2297 if (NegX->getType()->isSigned()) {
2298 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2299 X = InsertCastBefore(X, DestTy, I);
2300 NegX = ConstantExpr::getCast(NegX, DestTy);
2303 return new SetCondInst(isSetNE ? Instruction::SetGE :
2304 Instruction::SetLT, X, NegX);
2311 } else { // Not a SetEQ/SetNE
2312 // If the LHS is a cast from an integral value of the same size,
2313 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2314 Value *CastOp = Cast->getOperand(0);
2315 const Type *SrcTy = CastOp->getType();
2316 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2317 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2318 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2319 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2320 "Source and destination signednesses should differ!");
2321 if (Cast->getType()->isSigned()) {
2322 // If this is a signed comparison, check for comparisons in the
2323 // vicinity of zero.
2324 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2326 return BinaryOperator::createSetGT(CastOp,
2327 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2328 else if (I.getOpcode() == Instruction::SetGT &&
2329 cast<ConstantSInt>(CI)->getValue() == -1)
2330 // X > -1 => x < 128
2331 return BinaryOperator::createSetLT(CastOp,
2332 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2334 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2335 if (I.getOpcode() == Instruction::SetLT &&
2336 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2337 // X < 128 => X > -1
2338 return BinaryOperator::createSetGT(CastOp,
2339 ConstantSInt::get(SrcTy, -1));
2340 else if (I.getOpcode() == Instruction::SetGT &&
2341 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2343 return BinaryOperator::createSetLT(CastOp,
2344 Constant::getNullValue(SrcTy));
2351 // Test to see if the operands of the setcc are casted versions of other
2352 // values. If the cast can be stripped off both arguments, we do so now.
2353 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2354 Value *CastOp0 = CI->getOperand(0);
2355 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
2356 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
2357 (I.getOpcode() == Instruction::SetEQ ||
2358 I.getOpcode() == Instruction::SetNE)) {
2359 // We keep moving the cast from the left operand over to the right
2360 // operand, where it can often be eliminated completely.
2363 // If operand #1 is a cast instruction, see if we can eliminate it as
2365 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2366 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
2368 Op1 = CI2->getOperand(0);
2370 // If Op1 is a constant, we can fold the cast into the constant.
2371 if (Op1->getType() != Op0->getType())
2372 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2373 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2375 // Otherwise, cast the RHS right before the setcc
2376 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2377 InsertNewInstBefore(cast<Instruction>(Op1), I);
2379 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2382 // Handle the special case of: setcc (cast bool to X), <cst>
2383 // This comes up when you have code like
2386 // For generality, we handle any zero-extension of any operand comparison
2388 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2389 const Type *SrcTy = CastOp0->getType();
2390 const Type *DestTy = Op0->getType();
2391 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2392 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2393 // Ok, we have an expansion of operand 0 into a new type. Get the
2394 // constant value, masink off bits which are not set in the RHS. These
2395 // could be set if the destination value is signed.
2396 uint64_t ConstVal = ConstantRHS->getRawValue();
2397 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2399 // If the constant we are comparing it with has high bits set, which
2400 // don't exist in the original value, the values could never be equal,
2401 // because the source would be zero extended.
2403 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
2404 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2405 if (ConstVal & ~((1ULL << SrcBits)-1)) {
2406 switch (I.getOpcode()) {
2407 default: assert(0 && "Unknown comparison type!");
2408 case Instruction::SetEQ:
2409 return ReplaceInstUsesWith(I, ConstantBool::False);
2410 case Instruction::SetNE:
2411 return ReplaceInstUsesWith(I, ConstantBool::True);
2412 case Instruction::SetLT:
2413 case Instruction::SetLE:
2414 if (DestTy->isSigned() && HasSignBit)
2415 return ReplaceInstUsesWith(I, ConstantBool::False);
2416 return ReplaceInstUsesWith(I, ConstantBool::True);
2417 case Instruction::SetGT:
2418 case Instruction::SetGE:
2419 if (DestTy->isSigned() && HasSignBit)
2420 return ReplaceInstUsesWith(I, ConstantBool::True);
2421 return ReplaceInstUsesWith(I, ConstantBool::False);
2425 // Otherwise, we can replace the setcc with a setcc of the smaller
2427 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2428 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2432 return Changed ? &I : 0;
2437 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
2438 assert(I.getOperand(1)->getType() == Type::UByteTy);
2439 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2440 bool isLeftShift = I.getOpcode() == Instruction::Shl;
2442 // shl X, 0 == X and shr X, 0 == X
2443 // shl 0, X == 0 and shr 0, X == 0
2444 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
2445 Op0 == Constant::getNullValue(Op0->getType()))
2446 return ReplaceInstUsesWith(I, Op0);
2448 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
2450 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
2451 if (CSI->isAllOnesValue())
2452 return ReplaceInstUsesWith(I, CSI);
2454 // Try to fold constant and into select arguments.
2455 if (isa<Constant>(Op0))
2456 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2457 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2460 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
2461 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
2462 // of a signed value.
2464 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
2465 if (CUI->getValue() >= TypeBits) {
2466 if (!Op0->getType()->isSigned() || isLeftShift)
2467 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
2469 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
2474 // ((X*C1) << C2) == (X * (C1 << C2))
2475 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2476 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2477 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
2478 return BinaryOperator::createMul(BO->getOperand(0),
2479 ConstantExpr::getShl(BOOp, CUI));
2481 // Try to fold constant and into select arguments.
2482 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2483 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2485 if (isa<PHINode>(Op0))
2486 if (Instruction *NV = FoldOpIntoPhi(I))
2489 // If the operand is an bitwise operator with a constant RHS, and the
2490 // shift is the only use, we can pull it out of the shift.
2491 if (Op0->hasOneUse())
2492 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
2493 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2494 bool isValid = true; // Valid only for And, Or, Xor
2495 bool highBitSet = false; // Transform if high bit of constant set?
2497 switch (Op0BO->getOpcode()) {
2498 default: isValid = false; break; // Do not perform transform!
2499 case Instruction::Add:
2500 isValid = isLeftShift;
2502 case Instruction::Or:
2503 case Instruction::Xor:
2506 case Instruction::And:
2511 // If this is a signed shift right, and the high bit is modified
2512 // by the logical operation, do not perform the transformation.
2513 // The highBitSet boolean indicates the value of the high bit of
2514 // the constant which would cause it to be modified for this
2517 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
2518 uint64_t Val = Op0C->getRawValue();
2519 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
2523 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
2525 Instruction *NewShift =
2526 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2529 InsertNewInstBefore(NewShift, I);
2531 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2536 // If this is a shift of a shift, see if we can fold the two together...
2537 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
2538 if (ConstantUInt *ShiftAmt1C =
2539 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
2540 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2541 unsigned ShiftAmt2 = CUI->getValue();
2543 // Check for (A << c1) << c2 and (A >> c1) >> c2
2544 if (I.getOpcode() == Op0SI->getOpcode()) {
2545 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
2546 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2547 Amt = Op0->getType()->getPrimitiveSize()*8;
2548 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2549 ConstantUInt::get(Type::UByteTy, Amt));
2552 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
2553 // signed types, we can only support the (A >> c1) << c2 configuration,
2554 // because it can not turn an arbitrary bit of A into a sign bit.
2555 if (I.getType()->isUnsigned() || isLeftShift) {
2556 // Calculate bitmask for what gets shifted off the edge...
2557 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
2559 C = ConstantExpr::getShl(C, ShiftAmt1C);
2561 C = ConstantExpr::getShr(C, ShiftAmt1C);
2564 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2565 Op0SI->getOperand(0)->getName()+".mask");
2566 InsertNewInstBefore(Mask, I);
2568 // Figure out what flavor of shift we should use...
2569 if (ShiftAmt1 == ShiftAmt2)
2570 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
2571 else if (ShiftAmt1 < ShiftAmt2) {
2572 return new ShiftInst(I.getOpcode(), Mask,
2573 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2575 return new ShiftInst(Op0SI->getOpcode(), Mask,
2576 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2592 /// getCastType - In the future, we will split the cast instruction into these
2593 /// various types. Until then, we have to do the analysis here.
2594 static CastType getCastType(const Type *Src, const Type *Dest) {
2595 assert(Src->isIntegral() && Dest->isIntegral() &&
2596 "Only works on integral types!");
2597 unsigned SrcSize = Src->getPrimitiveSize()*8;
2598 if (Src == Type::BoolTy) SrcSize = 1;
2599 unsigned DestSize = Dest->getPrimitiveSize()*8;
2600 if (Dest == Type::BoolTy) DestSize = 1;
2602 if (SrcSize == DestSize) return Noop;
2603 if (SrcSize > DestSize) return Truncate;
2604 if (Src->isSigned()) return Signext;
2609 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2612 static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
2613 const Type *DstTy, TargetData *TD) {
2615 // It is legal to eliminate the instruction if casting A->B->A if the sizes
2616 // are identical and the bits don't get reinterpreted (for example
2617 // int->float->int would not be allowed).
2618 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
2621 // If we are casting between pointer and integer types, treat pointers as
2622 // integers of the appropriate size for the code below.
2623 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2624 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2625 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
2627 // Allow free casting and conversion of sizes as long as the sign doesn't
2629 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
2630 CastType FirstCast = getCastType(SrcTy, MidTy);
2631 CastType SecondCast = getCastType(MidTy, DstTy);
2633 // Capture the effect of these two casts. If the result is a legal cast,
2634 // the CastType is stored here, otherwise a special code is used.
2635 static const unsigned CastResult[] = {
2636 // First cast is noop
2638 // First cast is a truncate
2639 1, 1, 4, 4, // trunc->extend is not safe to eliminate
2640 // First cast is a sign ext
2641 2, 5, 2, 4, // signext->zeroext never ok
2642 // First cast is a zero ext
2646 unsigned Result = CastResult[FirstCast*4+SecondCast];
2648 default: assert(0 && "Illegal table value!");
2653 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2654 // truncates, we could eliminate more casts.
2655 return (unsigned)getCastType(SrcTy, DstTy) == Result;
2657 return false; // Not possible to eliminate this here.
2659 // Sign or zero extend followed by truncate is always ok if the result
2660 // is a truncate or noop.
2661 CastType ResultCast = getCastType(SrcTy, DstTy);
2662 if (ResultCast == Noop || ResultCast == Truncate)
2664 // Otherwise we are still growing the value, we are only safe if the
2665 // result will match the sign/zeroextendness of the result.
2666 return ResultCast == FirstCast;
2672 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
2673 if (V->getType() == Ty || isa<Constant>(V)) return false;
2674 if (const CastInst *CI = dyn_cast<CastInst>(V))
2675 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2681 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2682 /// InsertBefore instruction. This is specialized a bit to avoid inserting
2683 /// casts that are known to not do anything...
2685 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2686 Instruction *InsertBefore) {
2687 if (V->getType() == DestTy) return V;
2688 if (Constant *C = dyn_cast<Constant>(V))
2689 return ConstantExpr::getCast(C, DestTy);
2691 CastInst *CI = new CastInst(V, DestTy, V->getName());
2692 InsertNewInstBefore(CI, *InsertBefore);
2696 // CastInst simplification
2698 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
2699 Value *Src = CI.getOperand(0);
2701 // If the user is casting a value to the same type, eliminate this cast
2703 if (CI.getType() == Src->getType())
2704 return ReplaceInstUsesWith(CI, Src);
2706 // If casting the result of another cast instruction, try to eliminate this
2709 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
2710 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
2711 CSrc->getType(), CI.getType(), TD)) {
2712 // This instruction now refers directly to the cast's src operand. This
2713 // has a good chance of making CSrc dead.
2714 CI.setOperand(0, CSrc->getOperand(0));
2718 // If this is an A->B->A cast, and we are dealing with integral types, try
2719 // to convert this into a logical 'and' instruction.
2721 if (CSrc->getOperand(0)->getType() == CI.getType() &&
2722 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
2723 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2724 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2725 assert(CSrc->getType() != Type::ULongTy &&
2726 "Cannot have type bigger than ulong!");
2727 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
2728 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
2729 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
2733 // If this is a cast to bool, turn it into the appropriate setne instruction.
2734 if (CI.getType() == Type::BoolTy)
2735 return BinaryOperator::createSetNE(CI.getOperand(0),
2736 Constant::getNullValue(CI.getOperand(0)->getType()));
2738 // If casting the result of a getelementptr instruction with no offset, turn
2739 // this into a cast of the original pointer!
2741 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
2742 bool AllZeroOperands = true;
2743 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2744 if (!isa<Constant>(GEP->getOperand(i)) ||
2745 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2746 AllZeroOperands = false;
2749 if (AllZeroOperands) {
2750 CI.setOperand(0, GEP->getOperand(0));
2755 // If we are casting a malloc or alloca to a pointer to a type of the same
2756 // size, rewrite the allocation instruction to allocate the "right" type.
2758 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
2759 if (AI->hasOneUse() && !AI->isArrayAllocation())
2760 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2761 // Get the type really allocated and the type casted to...
2762 const Type *AllocElTy = AI->getAllocatedType();
2763 const Type *CastElTy = PTy->getElementType();
2764 if (AllocElTy->isSized() && CastElTy->isSized()) {
2765 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2766 unsigned CastElTySize = TD->getTypeSize(CastElTy);
2768 // If the allocation is for an even multiple of the cast type size
2769 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2770 Value *Amt = ConstantUInt::get(Type::UIntTy,
2771 AllocElTySize/CastElTySize);
2772 std::string Name = AI->getName(); AI->setName("");
2773 AllocationInst *New;
2774 if (isa<MallocInst>(AI))
2775 New = new MallocInst(CastElTy, Amt, Name);
2777 New = new AllocaInst(CastElTy, Amt, Name);
2778 InsertNewInstBefore(New, *AI);
2779 return ReplaceInstUsesWith(CI, New);
2784 if (isa<PHINode>(Src))
2785 if (Instruction *NV = FoldOpIntoPhi(CI))
2788 // If the source value is an instruction with only this use, we can attempt to
2789 // propagate the cast into the instruction. Also, only handle integral types
2791 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
2792 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
2793 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2794 const Type *DestTy = CI.getType();
2795 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2796 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2798 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2799 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2801 switch (SrcI->getOpcode()) {
2802 case Instruction::Add:
2803 case Instruction::Mul:
2804 case Instruction::And:
2805 case Instruction::Or:
2806 case Instruction::Xor:
2807 // If we are discarding information, or just changing the sign, rewrite.
2808 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2809 // Don't insert two casts if they cannot be eliminated. We allow two
2810 // casts to be inserted if the sizes are the same. This could only be
2811 // converting signedness, which is a noop.
2812 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2813 !ValueRequiresCast(Op0, DestTy, TD)) {
2814 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2815 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2816 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2817 ->getOpcode(), Op0c, Op1c);
2821 case Instruction::Shl:
2822 // Allow changing the sign of the source operand. Do not allow changing
2823 // the size of the shift, UNLESS the shift amount is a constant. We
2824 // mush not change variable sized shifts to a smaller size, because it
2825 // is undefined to shift more bits out than exist in the value.
2826 if (DestBitSize == SrcBitSize ||
2827 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2828 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2829 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2838 /// GetSelectFoldableOperands - We want to turn code that looks like this:
2840 /// %D = select %cond, %C, %A
2842 /// %C = select %cond, %B, 0
2845 /// Assuming that the specified instruction is an operand to the select, return
2846 /// a bitmask indicating which operands of this instruction are foldable if they
2847 /// equal the other incoming value of the select.
2849 static unsigned GetSelectFoldableOperands(Instruction *I) {
2850 switch (I->getOpcode()) {
2851 case Instruction::Add:
2852 case Instruction::Mul:
2853 case Instruction::And:
2854 case Instruction::Or:
2855 case Instruction::Xor:
2856 return 3; // Can fold through either operand.
2857 case Instruction::Sub: // Can only fold on the amount subtracted.
2858 case Instruction::Shl: // Can only fold on the shift amount.
2859 case Instruction::Shr:
2862 return 0; // Cannot fold
2866 /// GetSelectFoldableConstant - For the same transformation as the previous
2867 /// function, return the identity constant that goes into the select.
2868 static Constant *GetSelectFoldableConstant(Instruction *I) {
2869 switch (I->getOpcode()) {
2870 default: assert(0 && "This cannot happen!"); abort();
2871 case Instruction::Add:
2872 case Instruction::Sub:
2873 case Instruction::Or:
2874 case Instruction::Xor:
2875 return Constant::getNullValue(I->getType());
2876 case Instruction::Shl:
2877 case Instruction::Shr:
2878 return Constant::getNullValue(Type::UByteTy);
2879 case Instruction::And:
2880 return ConstantInt::getAllOnesValue(I->getType());
2881 case Instruction::Mul:
2882 return ConstantInt::get(I->getType(), 1);
2886 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
2887 Value *CondVal = SI.getCondition();
2888 Value *TrueVal = SI.getTrueValue();
2889 Value *FalseVal = SI.getFalseValue();
2891 // select true, X, Y -> X
2892 // select false, X, Y -> Y
2893 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
2894 if (C == ConstantBool::True)
2895 return ReplaceInstUsesWith(SI, TrueVal);
2897 assert(C == ConstantBool::False);
2898 return ReplaceInstUsesWith(SI, FalseVal);
2901 // select C, X, X -> X
2902 if (TrueVal == FalseVal)
2903 return ReplaceInstUsesWith(SI, TrueVal);
2905 if (SI.getType() == Type::BoolTy)
2906 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
2907 if (C == ConstantBool::True) {
2908 // Change: A = select B, true, C --> A = or B, C
2909 return BinaryOperator::createOr(CondVal, FalseVal);
2911 // Change: A = select B, false, C --> A = and !B, C
2913 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2914 "not."+CondVal->getName()), SI);
2915 return BinaryOperator::createAnd(NotCond, FalseVal);
2917 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
2918 if (C == ConstantBool::False) {
2919 // Change: A = select B, C, false --> A = and B, C
2920 return BinaryOperator::createAnd(CondVal, TrueVal);
2922 // Change: A = select B, C, true --> A = or !B, C
2924 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2925 "not."+CondVal->getName()), SI);
2926 return BinaryOperator::createOr(NotCond, TrueVal);
2930 // Selecting between two integer constants?
2931 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
2932 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
2933 // select C, 1, 0 -> cast C to int
2934 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
2935 return new CastInst(CondVal, SI.getType());
2936 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
2937 // select C, 0, 1 -> cast !C to int
2939 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
2940 "not."+CondVal->getName()), SI);
2941 return new CastInst(NotCond, SI.getType());
2944 // If one of the constants is zero (we know they can't both be) and we
2945 // have a setcc instruction with zero, and we have an 'and' with the
2946 // non-constant value, eliminate this whole mess. This corresponds to
2947 // cases like this: ((X & 27) ? 27 : 0)
2948 if (TrueValC->isNullValue() || FalseValC->isNullValue())
2949 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
2950 if ((IC->getOpcode() == Instruction::SetEQ ||
2951 IC->getOpcode() == Instruction::SetNE) &&
2952 isa<ConstantInt>(IC->getOperand(1)) &&
2953 cast<Constant>(IC->getOperand(1))->isNullValue())
2954 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
2955 if (ICA->getOpcode() == Instruction::And &&
2956 isa<ConstantInt>(ICA->getOperand(1)) &&
2957 (ICA->getOperand(1) == TrueValC ||
2958 ICA->getOperand(1) == FalseValC) &&
2959 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
2960 // Okay, now we know that everything is set up, we just don't
2961 // know whether we have a setne or seteq and whether the true or
2962 // false val is the zero.
2963 bool ShouldNotVal = !TrueValC->isNullValue();
2964 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
2967 V = InsertNewInstBefore(BinaryOperator::create(
2968 Instruction::Xor, V, ICA->getOperand(1)), SI);
2969 return ReplaceInstUsesWith(SI, V);
2973 // See if we are selecting two values based on a comparison of the two values.
2974 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
2975 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
2976 // Transform (X == Y) ? X : Y -> Y
2977 if (SCI->getOpcode() == Instruction::SetEQ)
2978 return ReplaceInstUsesWith(SI, FalseVal);
2979 // Transform (X != Y) ? X : Y -> X
2980 if (SCI->getOpcode() == Instruction::SetNE)
2981 return ReplaceInstUsesWith(SI, TrueVal);
2982 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2984 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
2985 // Transform (X == Y) ? Y : X -> X
2986 if (SCI->getOpcode() == Instruction::SetEQ)
2987 return ReplaceInstUsesWith(SI, FalseVal);
2988 // Transform (X != Y) ? Y : X -> Y
2989 if (SCI->getOpcode() == Instruction::SetNE)
2990 return ReplaceInstUsesWith(SI, TrueVal);
2991 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
2995 // See if we can fold the select into one of our operands.
2996 if (SI.getType()->isInteger()) {
2997 // See the comment above GetSelectFoldableOperands for a description of the
2998 // transformation we are doing here.
2999 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3000 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3001 !isa<Constant>(FalseVal))
3002 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3003 unsigned OpToFold = 0;
3004 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3006 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3011 Constant *C = GetSelectFoldableConstant(TVI);
3012 std::string Name = TVI->getName(); TVI->setName("");
3013 Instruction *NewSel =
3014 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3016 InsertNewInstBefore(NewSel, SI);
3017 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3018 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3019 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3020 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3022 assert(0 && "Unknown instruction!!");
3027 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3028 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3029 !isa<Constant>(TrueVal))
3030 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3031 unsigned OpToFold = 0;
3032 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3034 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3039 Constant *C = GetSelectFoldableConstant(FVI);
3040 std::string Name = FVI->getName(); FVI->setName("");
3041 Instruction *NewSel =
3042 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3044 InsertNewInstBefore(NewSel, SI);
3045 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3046 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3047 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3048 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3050 assert(0 && "Unknown instruction!!");
3059 // CallInst simplification
3061 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
3062 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3064 if (Function *F = CI.getCalledFunction())
3065 switch (F->getIntrinsicID()) {
3066 case Intrinsic::memmove:
3067 case Intrinsic::memcpy:
3068 case Intrinsic::memset:
3069 // memmove/cpy/set of zero bytes is a noop.
3070 if (Constant *NumBytes = dyn_cast<Constant>(CI.getOperand(3))) {
3071 if (NumBytes->isNullValue())
3072 return EraseInstFromFunction(CI);
3079 return visitCallSite(&CI);
3082 // InvokeInst simplification
3084 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
3085 return visitCallSite(&II);
3088 // visitCallSite - Improvements for call and invoke instructions.
3090 Instruction *InstCombiner::visitCallSite(CallSite CS) {
3091 bool Changed = false;
3093 // If the callee is a constexpr cast of a function, attempt to move the cast
3094 // to the arguments of the call/invoke.
3095 if (transformConstExprCastCall(CS)) return 0;
3097 Value *Callee = CS.getCalledValue();
3098 const PointerType *PTy = cast<PointerType>(Callee->getType());
3099 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3100 if (FTy->isVarArg()) {
3101 // See if we can optimize any arguments passed through the varargs area of
3103 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3104 E = CS.arg_end(); I != E; ++I)
3105 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3106 // If this cast does not effect the value passed through the varargs
3107 // area, we can eliminate the use of the cast.
3108 Value *Op = CI->getOperand(0);
3109 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3116 return Changed ? CS.getInstruction() : 0;
3119 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
3120 // attempt to move the cast to the arguments of the call/invoke.
3122 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3123 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3124 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
3125 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
3127 Function *Callee = cast<Function>(CE->getOperand(0));
3128 Instruction *Caller = CS.getInstruction();
3130 // Okay, this is a cast from a function to a different type. Unless doing so
3131 // would cause a type conversion of one of our arguments, change this call to
3132 // be a direct call with arguments casted to the appropriate types.
3134 const FunctionType *FT = Callee->getFunctionType();
3135 const Type *OldRetTy = Caller->getType();
3137 // Check to see if we are changing the return type...
3138 if (OldRetTy != FT->getReturnType()) {
3139 if (Callee->isExternal() &&
3140 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3141 !Caller->use_empty())
3142 return false; // Cannot transform this return value...
3144 // If the callsite is an invoke instruction, and the return value is used by
3145 // a PHI node in a successor, we cannot change the return type of the call
3146 // because there is no place to put the cast instruction (without breaking
3147 // the critical edge). Bail out in this case.
3148 if (!Caller->use_empty())
3149 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3150 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3152 if (PHINode *PN = dyn_cast<PHINode>(*UI))
3153 if (PN->getParent() == II->getNormalDest() ||
3154 PN->getParent() == II->getUnwindDest())
3158 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3159 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3161 CallSite::arg_iterator AI = CS.arg_begin();
3162 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3163 const Type *ParamTy = FT->getParamType(i);
3164 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
3165 if (Callee->isExternal() && !isConvertible) return false;
3168 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3169 Callee->isExternal())
3170 return false; // Do not delete arguments unless we have a function body...
3172 // Okay, we decided that this is a safe thing to do: go ahead and start
3173 // inserting cast instructions as necessary...
3174 std::vector<Value*> Args;
3175 Args.reserve(NumActualArgs);
3177 AI = CS.arg_begin();
3178 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3179 const Type *ParamTy = FT->getParamType(i);
3180 if ((*AI)->getType() == ParamTy) {
3181 Args.push_back(*AI);
3183 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
3188 // If the function takes more arguments than the call was taking, add them
3190 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3191 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3193 // If we are removing arguments to the function, emit an obnoxious warning...
3194 if (FT->getNumParams() < NumActualArgs)
3195 if (!FT->isVarArg()) {
3196 std::cerr << "WARNING: While resolving call to function '"
3197 << Callee->getName() << "' arguments were dropped!\n";
3199 // Add all of the arguments in their promoted form to the arg list...
3200 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3201 const Type *PTy = getPromotedType((*AI)->getType());
3202 if (PTy != (*AI)->getType()) {
3203 // Must promote to pass through va_arg area!
3204 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
3205 InsertNewInstBefore(Cast, *Caller);
3206 Args.push_back(Cast);
3208 Args.push_back(*AI);
3213 if (FT->getReturnType() == Type::VoidTy)
3214 Caller->setName(""); // Void type should not have a name...
3217 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3218 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
3219 Args, Caller->getName(), Caller);
3221 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
3224 // Insert a cast of the return type as necessary...
3226 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
3227 if (NV->getType() != Type::VoidTy) {
3228 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
3230 // If this is an invoke instruction, we should insert it after the first
3231 // non-phi, instruction in the normal successor block.
3232 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3233 BasicBlock::iterator I = II->getNormalDest()->begin();
3234 while (isa<PHINode>(I)) ++I;
3235 InsertNewInstBefore(NC, *I);
3237 // Otherwise, it's a call, just insert cast right after the call instr
3238 InsertNewInstBefore(NC, *Caller);
3240 AddUsersToWorkList(*Caller);
3242 NV = Constant::getNullValue(Caller->getType());
3246 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
3247 Caller->replaceAllUsesWith(NV);
3248 Caller->getParent()->getInstList().erase(Caller);
3249 removeFromWorkList(Caller);
3255 // PHINode simplification
3257 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
3258 if (Value *V = hasConstantValue(&PN))
3259 return ReplaceInstUsesWith(PN, V);
3261 // If the only user of this instruction is a cast instruction, and all of the
3262 // incoming values are constants, change this PHI to merge together the casted
3265 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
3266 if (CI->getType() != PN.getType()) { // noop casts will be folded
3267 bool AllConstant = true;
3268 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3269 if (!isa<Constant>(PN.getIncomingValue(i))) {
3270 AllConstant = false;
3274 // Make a new PHI with all casted values.
3275 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
3276 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3277 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
3278 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
3279 PN.getIncomingBlock(i));
3282 // Update the cast instruction.
3283 CI->setOperand(0, New);
3284 WorkList.push_back(CI); // revisit the cast instruction to fold.
3285 WorkList.push_back(New); // Make sure to revisit the new Phi
3286 return &PN; // PN is now dead!
3292 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
3293 Instruction *InsertPoint,
3295 unsigned PS = IC->getTargetData().getPointerSize();
3296 const Type *VTy = V->getType();
3298 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
3299 // We must insert a cast to ensure we sign-extend.
3300 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
3301 V->getName()), *InsertPoint);
3302 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
3307 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
3308 Value *PtrOp = GEP.getOperand(0);
3309 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
3310 // If so, eliminate the noop.
3311 if (GEP.getNumOperands() == 1)
3312 return ReplaceInstUsesWith(GEP, PtrOp);
3314 bool HasZeroPointerIndex = false;
3315 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
3316 HasZeroPointerIndex = C->isNullValue();
3318 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
3319 return ReplaceInstUsesWith(GEP, PtrOp);
3321 // Eliminate unneeded casts for indices.
3322 bool MadeChange = false;
3323 gep_type_iterator GTI = gep_type_begin(GEP);
3324 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
3325 if (isa<SequentialType>(*GTI)) {
3326 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
3327 Value *Src = CI->getOperand(0);
3328 const Type *SrcTy = Src->getType();
3329 const Type *DestTy = CI->getType();
3330 if (Src->getType()->isInteger()) {
3331 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
3332 // We can always eliminate a cast from ulong or long to the other.
3333 // We can always eliminate a cast from uint to int or the other on
3334 // 32-bit pointer platforms.
3335 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
3337 GEP.setOperand(i, Src);
3339 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
3340 SrcTy->getPrimitiveSize() == 4) {
3341 // We can always eliminate a cast from int to [u]long. We can
3342 // eliminate a cast from uint to [u]long iff the target is a 32-bit
3344 if (SrcTy->isSigned() ||
3345 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
3347 GEP.setOperand(i, Src);
3352 // If we are using a wider index than needed for this platform, shrink it
3353 // to what we need. If the incoming value needs a cast instruction,
3354 // insert it. This explicit cast can make subsequent optimizations more
3356 Value *Op = GEP.getOperand(i);
3357 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
3358 if (Constant *C = dyn_cast<Constant>(Op)) {
3359 GEP.setOperand(i, ConstantExpr::getCast(C,
3360 TD->getIntPtrType()->getSignedVersion()));
3363 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
3364 Op->getName()), GEP);
3365 GEP.setOperand(i, Op);
3369 // If this is a constant idx, make sure to canonicalize it to be a signed
3370 // operand, otherwise CSE and other optimizations are pessimized.
3371 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
3372 GEP.setOperand(i, ConstantExpr::getCast(CUI,
3373 CUI->getType()->getSignedVersion()));
3377 if (MadeChange) return &GEP;
3379 // Combine Indices - If the source pointer to this getelementptr instruction
3380 // is a getelementptr instruction, combine the indices of the two
3381 // getelementptr instructions into a single instruction.
3383 std::vector<Value*> SrcGEPOperands;
3384 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
3385 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
3386 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
3387 if (CE->getOpcode() == Instruction::GetElementPtr)
3388 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
3391 if (!SrcGEPOperands.empty()) {
3392 // Note that if our source is a gep chain itself that we wait for that
3393 // chain to be resolved before we perform this transformation. This
3394 // avoids us creating a TON of code in some cases.
3396 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
3397 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
3398 return 0; // Wait until our source is folded to completion.
3400 std::vector<Value *> Indices;
3402 // Find out whether the last index in the source GEP is a sequential idx.
3403 bool EndsWithSequential = false;
3404 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
3405 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
3406 EndsWithSequential = !isa<StructType>(*I);
3408 // Can we combine the two pointer arithmetics offsets?
3409 if (EndsWithSequential) {
3410 // Replace: gep (gep %P, long B), long A, ...
3411 // With: T = long A+B; gep %P, T, ...
3413 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
3414 if (SO1 == Constant::getNullValue(SO1->getType())) {
3416 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
3419 // If they aren't the same type, convert both to an integer of the
3420 // target's pointer size.
3421 if (SO1->getType() != GO1->getType()) {
3422 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
3423 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
3424 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
3425 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
3427 unsigned PS = TD->getPointerSize();
3429 if (SO1->getType()->getPrimitiveSize() == PS) {
3430 // Convert GO1 to SO1's type.
3431 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
3433 } else if (GO1->getType()->getPrimitiveSize() == PS) {
3434 // Convert SO1 to GO1's type.
3435 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
3437 const Type *PT = TD->getIntPtrType();
3438 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
3439 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
3443 if (isa<Constant>(SO1) && isa<Constant>(GO1))
3444 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
3446 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
3447 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
3451 // Recycle the GEP we already have if possible.
3452 if (SrcGEPOperands.size() == 2) {
3453 GEP.setOperand(0, SrcGEPOperands[0]);
3454 GEP.setOperand(1, Sum);
3457 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3458 SrcGEPOperands.end()-1);
3459 Indices.push_back(Sum);
3460 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
3462 } else if (isa<Constant>(*GEP.idx_begin()) &&
3463 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
3464 SrcGEPOperands.size() != 1) {
3465 // Otherwise we can do the fold if the first index of the GEP is a zero
3466 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3467 SrcGEPOperands.end());
3468 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
3471 if (!Indices.empty())
3472 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
3474 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
3475 // GEP of global variable. If all of the indices for this GEP are
3476 // constants, we can promote this to a constexpr instead of an instruction.
3478 // Scan for nonconstants...
3479 std::vector<Constant*> Indices;
3480 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
3481 for (; I != E && isa<Constant>(*I); ++I)
3482 Indices.push_back(cast<Constant>(*I));
3484 if (I == E) { // If they are all constants...
3485 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
3487 // Replace all uses of the GEP with the new constexpr...
3488 return ReplaceInstUsesWith(GEP, CE);
3490 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
3491 if (CE->getOpcode() == Instruction::Cast) {
3492 if (HasZeroPointerIndex) {
3493 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
3494 // into : GEP [10 x ubyte]* X, long 0, ...
3496 // This occurs when the program declares an array extern like "int X[];"
3498 Constant *X = CE->getOperand(0);
3499 const PointerType *CPTy = cast<PointerType>(CE->getType());
3500 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
3501 if (const ArrayType *XATy =
3502 dyn_cast<ArrayType>(XTy->getElementType()))
3503 if (const ArrayType *CATy =
3504 dyn_cast<ArrayType>(CPTy->getElementType()))
3505 if (CATy->getElementType() == XATy->getElementType()) {
3506 // At this point, we know that the cast source type is a pointer
3507 // to an array of the same type as the destination pointer
3508 // array. Because the array type is never stepped over (there
3509 // is a leading zero) we can fold the cast into this GEP.
3510 GEP.setOperand(0, X);
3520 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
3521 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
3522 if (AI.isArrayAllocation()) // Check C != 1
3523 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
3524 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
3525 AllocationInst *New = 0;
3527 // Create and insert the replacement instruction...
3528 if (isa<MallocInst>(AI))
3529 New = new MallocInst(NewTy, 0, AI.getName());
3531 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
3532 New = new AllocaInst(NewTy, 0, AI.getName());
3535 InsertNewInstBefore(New, AI);
3537 // Scan to the end of the allocation instructions, to skip over a block of
3538 // allocas if possible...
3540 BasicBlock::iterator It = New;
3541 while (isa<AllocationInst>(*It)) ++It;
3543 // Now that I is pointing to the first non-allocation-inst in the block,
3544 // insert our getelementptr instruction...
3546 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
3547 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
3549 // Now make everything use the getelementptr instead of the original
3551 return ReplaceInstUsesWith(AI, V);
3554 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
3555 // Note that we only do this for alloca's, because malloc should allocate and
3556 // return a unique pointer, even for a zero byte allocation.
3557 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
3558 TD->getTypeSize(AI.getAllocatedType()) == 0)
3559 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3564 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
3565 Value *Op = FI.getOperand(0);
3567 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3568 if (CastInst *CI = dyn_cast<CastInst>(Op))
3569 if (isa<PointerType>(CI->getOperand(0)->getType())) {
3570 FI.setOperand(0, CI->getOperand(0));
3574 // If we have 'free null' delete the instruction. This can happen in stl code
3575 // when lots of inlining happens.
3576 if (isa<ConstantPointerNull>(Op))
3577 return EraseInstFromFunction(FI);
3583 /// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3584 /// constantexpr, return the constant value being addressed by the constant
3585 /// expression, or null if something is funny.
3587 static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
3588 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
3589 return 0; // Do not allow stepping over the value!
3591 // Loop over all of the operands, tracking down which value we are
3593 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3594 for (++I; I != E; ++I)
3595 if (const StructType *STy = dyn_cast<StructType>(*I)) {
3596 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
3597 assert(CU->getValue() < STy->getNumElements() &&
3598 "Struct index out of range!");
3599 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
3600 C = CS->getOperand(CU->getValue());
3601 } else if (isa<ConstantAggregateZero>(C)) {
3602 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
3606 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
3607 const ArrayType *ATy = cast<ArrayType>(*I);
3608 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
3609 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
3610 C = CA->getOperand(CI->getRawValue());
3611 else if (isa<ConstantAggregateZero>(C))
3612 C = Constant::getNullValue(ATy->getElementType());
3621 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
3622 User *CI = cast<User>(LI.getOperand(0));
3624 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
3625 if (const PointerType *SrcTy =
3626 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
3627 const Type *SrcPTy = SrcTy->getElementType();
3628 if (SrcPTy->isSized() && DestPTy->isSized() &&
3629 IC.getTargetData().getTypeSize(SrcPTy) ==
3630 IC.getTargetData().getTypeSize(DestPTy) &&
3631 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
3632 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
3633 // Okay, we are casting from one integer or pointer type to another of
3634 // the same size. Instead of casting the pointer before the load, cast
3635 // the result of the loaded value.
3636 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
3638 LI.isVolatile()),LI);
3639 // Now cast the result of the load.
3640 return new CastInst(NewLoad, LI.getType());
3646 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
3647 /// from this value cannot trap. If it is not obviously safe to load from the
3648 /// specified pointer, we do a quick local scan of the basic block containing
3649 /// ScanFrom, to determine if the address is already accessed.
3650 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3651 // If it is an alloca or global variable, it is always safe to load from.
3652 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3654 // Otherwise, be a little bit agressive by scanning the local block where we
3655 // want to check to see if the pointer is already being loaded or stored
3656 // from/to. If so, the previous load or store would have already trapped,
3657 // so there is no harm doing an extra load (also, CSE will later eliminate
3658 // the load entirely).
3659 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
3664 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3665 if (LI->getOperand(0) == V) return true;
3666 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
3667 if (SI->getOperand(1) == V) return true;
3673 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
3674 Value *Op = LI.getOperand(0);
3676 if (Constant *C = dyn_cast<Constant>(Op))
3677 if (C->isNullValue() && !LI.isVolatile()) // load null -> 0
3678 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
3680 // Instcombine load (constant global) into the value loaded...
3681 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
3682 if (GV->isConstant() && !GV->isExternal())
3683 return ReplaceInstUsesWith(LI, GV->getInitializer());
3685 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded...
3686 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
3687 if (CE->getOpcode() == Instruction::GetElementPtr) {
3688 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
3689 if (GV->isConstant() && !GV->isExternal())
3690 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
3691 return ReplaceInstUsesWith(LI, V);
3692 } else if (CE->getOpcode() == Instruction::Cast) {
3693 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3697 // load (cast X) --> cast (load X) iff safe
3698 if (CastInst *CI = dyn_cast<CastInst>(Op))
3699 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3702 if (!LI.isVolatile() && Op->hasOneUse()) {
3703 // Change select and PHI nodes to select values instead of addresses: this
3704 // helps alias analysis out a lot, allows many others simplifications, and
3705 // exposes redundancy in the code.
3707 // Note that we cannot do the transformation unless we know that the
3708 // introduced loads cannot trap! Something like this is valid as long as
3709 // the condition is always false: load (select bool %C, int* null, int* %G),
3710 // but it would not be valid if we transformed it to load from null
3713 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
3714 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
3715 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
3716 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
3717 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
3718 SI->getOperand(1)->getName()+".val"), LI);
3719 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
3720 SI->getOperand(2)->getName()+".val"), LI);
3721 return new SelectInst(SI->getCondition(), V1, V2);
3724 // load (select (cond, null, P)) -> load P
3725 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
3726 if (C->isNullValue()) {
3727 LI.setOperand(0, SI->getOperand(2));
3731 // load (select (cond, P, null)) -> load P
3732 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
3733 if (C->isNullValue()) {
3734 LI.setOperand(0, SI->getOperand(1));
3738 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
3739 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
3740 bool Safe = PN->getParent() == LI.getParent();
3742 // Scan all of the instructions between the PHI and the load to make
3743 // sure there are no instructions that might possibly alter the value
3744 // loaded from the PHI.
3746 BasicBlock::iterator I = &LI;
3747 for (--I; !isa<PHINode>(I); --I)
3748 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
3754 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
3755 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
3756 PN->getIncomingBlock(i)->getTerminator()))
3761 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
3762 InsertNewInstBefore(NewPN, *PN);
3763 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
3765 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
3766 BasicBlock *BB = PN->getIncomingBlock(i);
3767 Value *&TheLoad = LoadMap[BB];
3769 Value *InVal = PN->getIncomingValue(i);
3770 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
3771 InVal->getName()+".val"),
3772 *BB->getTerminator());
3774 NewPN->addIncoming(TheLoad, BB);
3776 return ReplaceInstUsesWith(LI, NewPN);
3784 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
3785 // Change br (not X), label True, label False to: br X, label False, True
3787 BasicBlock *TrueDest;
3788 BasicBlock *FalseDest;
3789 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
3790 !isa<Constant>(X)) {
3791 // Swap Destinations and condition...
3793 BI.setSuccessor(0, FalseDest);
3794 BI.setSuccessor(1, TrueDest);
3798 // Cannonicalize setne -> seteq
3799 Instruction::BinaryOps Op; Value *Y;
3800 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
3801 TrueDest, FalseDest)))
3802 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
3803 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
3804 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
3805 std::string Name = I->getName(); I->setName("");
3806 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
3807 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
3808 // Swap Destinations and condition...
3809 BI.setCondition(NewSCC);
3810 BI.setSuccessor(0, FalseDest);
3811 BI.setSuccessor(1, TrueDest);
3812 removeFromWorkList(I);
3813 I->getParent()->getInstList().erase(I);
3814 WorkList.push_back(cast<Instruction>(NewSCC));
3821 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
3822 Value *Cond = SI.getCondition();
3823 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
3824 if (I->getOpcode() == Instruction::Add)
3825 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
3826 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
3827 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
3828 SI.setOperand(i, ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
3830 SI.setOperand(0, I->getOperand(0));
3831 WorkList.push_back(I);
3839 void InstCombiner::removeFromWorkList(Instruction *I) {
3840 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
3844 bool InstCombiner::runOnFunction(Function &F) {
3845 bool Changed = false;
3846 TD = &getAnalysis<TargetData>();
3848 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
3849 WorkList.push_back(&*i);
3852 while (!WorkList.empty()) {
3853 Instruction *I = WorkList.back(); // Get an instruction from the worklist
3854 WorkList.pop_back();
3856 // Check to see if we can DCE or ConstantPropagate the instruction...
3857 // Check to see if we can DIE the instruction...
3858 if (isInstructionTriviallyDead(I)) {
3859 // Add operands to the worklist...
3860 if (I->getNumOperands() < 4)
3861 AddUsesToWorkList(*I);
3864 I->getParent()->getInstList().erase(I);
3865 removeFromWorkList(I);
3869 // Instruction isn't dead, see if we can constant propagate it...
3870 if (Constant *C = ConstantFoldInstruction(I)) {
3871 // Add operands to the worklist...
3872 AddUsesToWorkList(*I);
3873 ReplaceInstUsesWith(*I, C);
3876 I->getParent()->getInstList().erase(I);
3877 removeFromWorkList(I);
3881 // Now that we have an instruction, try combining it to simplify it...
3882 if (Instruction *Result = visit(*I)) {
3884 // Should we replace the old instruction with a new one?
3886 DEBUG(std::cerr << "IC: Old = " << *I
3887 << " New = " << *Result);
3889 // Everything uses the new instruction now.
3890 I->replaceAllUsesWith(Result);
3892 // Push the new instruction and any users onto the worklist.
3893 WorkList.push_back(Result);
3894 AddUsersToWorkList(*Result);
3896 // Move the name to the new instruction first...
3897 std::string OldName = I->getName(); I->setName("");
3898 Result->setName(OldName);
3900 // Insert the new instruction into the basic block...
3901 BasicBlock *InstParent = I->getParent();
3902 InstParent->getInstList().insert(I, Result);
3904 // Make sure that we reprocess all operands now that we reduced their
3906 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3907 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3908 WorkList.push_back(OpI);
3910 // Instructions can end up on the worklist more than once. Make sure
3911 // we do not process an instruction that has been deleted.
3912 removeFromWorkList(I);
3914 // Erase the old instruction.
3915 InstParent->getInstList().erase(I);
3917 DEBUG(std::cerr << "IC: MOD = " << *I);
3919 // If the instruction was modified, it's possible that it is now dead.
3920 // if so, remove it.
3921 if (isInstructionTriviallyDead(I)) {
3922 // Make sure we process all operands now that we are reducing their
3924 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
3925 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
3926 WorkList.push_back(OpI);
3928 // Instructions may end up in the worklist more than once. Erase all
3929 // occurrances of this instruction.
3930 removeFromWorkList(I);
3931 I->getParent()->getInstList().erase(I);
3933 WorkList.push_back(Result);
3934 AddUsersToWorkList(*Result);
3944 FunctionPass *llvm::createInstructionCombiningPass() {
3945 return new InstCombiner();