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
34 //===----------------------------------------------------------------------===//
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include "llvm/Support/CallSite.h"
46 #include "llvm/Support/Debug.h"
47 #include "llvm/Support/GetElementPtrTypeIterator.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/PatternMatch.h"
51 #include "llvm/ADT/DepthFirstIterator.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/ADT/STLExtras.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");
62 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
64 class InstCombiner : public FunctionPass,
65 public InstVisitor<InstCombiner, Instruction*> {
66 // Worklist of all of the instructions that need to be simplified.
67 std::vector<Instruction*> WorkList;
70 /// AddUsersToWorkList - When an instruction is simplified, add all users of
71 /// the instruction to the work lists because they might get more simplified
74 void AddUsersToWorkList(Instruction &I) {
75 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
77 WorkList.push_back(cast<Instruction>(*UI));
80 /// AddUsesToWorkList - When an instruction is simplified, add operands to
81 /// the work lists because they might get more simplified now.
83 void AddUsesToWorkList(Instruction &I) {
84 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
85 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
86 WorkList.push_back(Op);
89 // removeFromWorkList - remove all instances of I from the worklist.
90 void removeFromWorkList(Instruction *I);
92 virtual bool runOnFunction(Function &F);
94 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
95 AU.addRequired<TargetData>();
99 TargetData &getTargetData() const { return *TD; }
101 // Visitation implementation - Implement instruction combining for different
102 // instruction types. The semantics are as follows:
104 // null - No change was made
105 // I - Change was made, I is still valid, I may be dead though
106 // otherwise - Change was made, replace I with returned instruction
108 Instruction *visitAdd(BinaryOperator &I);
109 Instruction *visitSub(BinaryOperator &I);
110 Instruction *visitMul(BinaryOperator &I);
111 Instruction *visitDiv(BinaryOperator &I);
112 Instruction *visitRem(BinaryOperator &I);
113 Instruction *visitAnd(BinaryOperator &I);
114 Instruction *visitOr (BinaryOperator &I);
115 Instruction *visitXor(BinaryOperator &I);
116 Instruction *visitSetCondInst(SetCondInst &I);
117 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
119 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
120 Instruction::BinaryOps Cond, Instruction &I);
121 Instruction *visitShiftInst(ShiftInst &I);
122 Instruction *visitCastInst(CastInst &CI);
123 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
125 Instruction *visitSelectInst(SelectInst &CI);
126 Instruction *visitCallInst(CallInst &CI);
127 Instruction *visitInvokeInst(InvokeInst &II);
128 Instruction *visitPHINode(PHINode &PN);
129 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
130 Instruction *visitAllocationInst(AllocationInst &AI);
131 Instruction *visitFreeInst(FreeInst &FI);
132 Instruction *visitLoadInst(LoadInst &LI);
133 Instruction *visitStoreInst(StoreInst &SI);
134 Instruction *visitBranchInst(BranchInst &BI);
135 Instruction *visitSwitchInst(SwitchInst &SI);
137 // visitInstruction - Specify what to return for unhandled instructions...
138 Instruction *visitInstruction(Instruction &I) { return 0; }
141 Instruction *visitCallSite(CallSite CS);
142 bool transformConstExprCastCall(CallSite CS);
145 // InsertNewInstBefore - insert an instruction New before instruction Old
146 // in the program. Add the new instruction to the worklist.
148 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
149 assert(New && New->getParent() == 0 &&
150 "New instruction already inserted into a basic block!");
151 BasicBlock *BB = Old.getParent();
152 BB->getInstList().insert(&Old, New); // Insert inst
153 WorkList.push_back(New); // Add to worklist
157 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
158 /// This also adds the cast to the worklist. Finally, this returns the
160 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
161 if (V->getType() == Ty) return V;
163 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
164 WorkList.push_back(C);
168 // ReplaceInstUsesWith - This method is to be used when an instruction is
169 // found to be dead, replacable with another preexisting expression. Here
170 // we add all uses of I to the worklist, replace all uses of I with the new
171 // value, then return I, so that the inst combiner will know that I was
174 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
175 AddUsersToWorkList(I); // Add all modified instrs to worklist
177 I.replaceAllUsesWith(V);
180 // If we are replacing the instruction with itself, this must be in a
181 // segment of unreachable code, so just clobber the instruction.
182 I.replaceAllUsesWith(UndefValue::get(I.getType()));
187 // EraseInstFromFunction - When dealing with an instruction that has side
188 // effects or produces a void value, we can't rely on DCE to delete the
189 // instruction. Instead, visit methods should return the value returned by
191 Instruction *EraseInstFromFunction(Instruction &I) {
192 assert(I.use_empty() && "Cannot erase instruction that is used!");
193 AddUsesToWorkList(I);
194 removeFromWorkList(&I);
196 return 0; // Don't do anything with FI
201 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
202 /// InsertBefore instruction. This is specialized a bit to avoid inserting
203 /// casts that are known to not do anything...
205 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
206 Instruction *InsertBefore);
208 // SimplifyCommutative - This performs a few simplifications for commutative
210 bool SimplifyCommutative(BinaryOperator &I);
213 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
214 // PHI node as operand #0, see if we can fold the instruction into the PHI
215 // (which is only possible if all operands to the PHI are constants).
216 Instruction *FoldOpIntoPhi(Instruction &I);
218 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
219 // operator and they all are only used by the PHI, PHI together their
220 // inputs, and do the operation once, to the result of the PHI.
221 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
223 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
224 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
226 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
227 bool isSub, Instruction &I);
228 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
229 bool Inside, Instruction &IB);
230 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
233 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
236 // getComplexity: Assign a complexity or rank value to LLVM Values...
237 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
238 static unsigned getComplexity(Value *V) {
239 if (isa<Instruction>(V)) {
240 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
244 if (isa<Argument>(V)) return 3;
245 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
248 // isOnlyUse - Return true if this instruction will be deleted if we stop using
250 static bool isOnlyUse(Value *V) {
251 return V->hasOneUse() || isa<Constant>(V);
254 // getPromotedType - Return the specified type promoted as it would be to pass
255 // though a va_arg area...
256 static const Type *getPromotedType(const Type *Ty) {
257 switch (Ty->getTypeID()) {
258 case Type::SByteTyID:
259 case Type::ShortTyID: return Type::IntTy;
260 case Type::UByteTyID:
261 case Type::UShortTyID: return Type::UIntTy;
262 case Type::FloatTyID: return Type::DoubleTy;
267 /// isCast - If the specified operand is a CastInst or a constant expr cast,
268 /// return the operand value, otherwise return null.
269 static Value *isCast(Value *V) {
270 if (CastInst *I = dyn_cast<CastInst>(V))
271 return I->getOperand(0);
272 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
273 if (CE->getOpcode() == Instruction::Cast)
274 return CE->getOperand(0);
278 // SimplifyCommutative - This performs a few simplifications for commutative
281 // 1. Order operands such that they are listed from right (least complex) to
282 // left (most complex). This puts constants before unary operators before
285 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
286 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
288 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
289 bool Changed = false;
290 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
291 Changed = !I.swapOperands();
293 if (!I.isAssociative()) return Changed;
294 Instruction::BinaryOps Opcode = I.getOpcode();
295 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
296 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
297 if (isa<Constant>(I.getOperand(1))) {
298 Constant *Folded = ConstantExpr::get(I.getOpcode(),
299 cast<Constant>(I.getOperand(1)),
300 cast<Constant>(Op->getOperand(1)));
301 I.setOperand(0, Op->getOperand(0));
302 I.setOperand(1, Folded);
304 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
305 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
306 isOnlyUse(Op) && isOnlyUse(Op1)) {
307 Constant *C1 = cast<Constant>(Op->getOperand(1));
308 Constant *C2 = cast<Constant>(Op1->getOperand(1));
310 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
311 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
312 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
315 WorkList.push_back(New);
316 I.setOperand(0, New);
317 I.setOperand(1, Folded);
324 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
325 // if the LHS is a constant zero (which is the 'negate' form).
327 static inline Value *dyn_castNegVal(Value *V) {
328 if (BinaryOperator::isNeg(V))
329 return BinaryOperator::getNegArgument(V);
331 // Constants can be considered to be negated values if they can be folded.
332 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
333 return ConstantExpr::getNeg(C);
337 static inline Value *dyn_castNotVal(Value *V) {
338 if (BinaryOperator::isNot(V))
339 return BinaryOperator::getNotArgument(V);
341 // Constants can be considered to be not'ed values...
342 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
343 return ConstantExpr::getNot(C);
347 // dyn_castFoldableMul - If this value is a multiply that can be folded into
348 // other computations (because it has a constant operand), return the
349 // non-constant operand of the multiply, and set CST to point to the multiplier.
350 // Otherwise, return null.
352 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
353 if (V->hasOneUse() && V->getType()->isInteger())
354 if (Instruction *I = dyn_cast<Instruction>(V)) {
355 if (I->getOpcode() == Instruction::Mul)
356 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
357 return I->getOperand(0);
358 if (I->getOpcode() == Instruction::Shl)
359 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
360 // The multiplier is really 1 << CST.
361 Constant *One = ConstantInt::get(V->getType(), 1);
362 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
363 return I->getOperand(0);
369 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
370 /// expression, return it.
371 static User *dyn_castGetElementPtr(Value *V) {
372 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
373 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
374 if (CE->getOpcode() == Instruction::GetElementPtr)
375 return cast<User>(V);
379 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
380 static ConstantInt *AddOne(ConstantInt *C) {
381 return cast<ConstantInt>(ConstantExpr::getAdd(C,
382 ConstantInt::get(C->getType(), 1)));
384 static ConstantInt *SubOne(ConstantInt *C) {
385 return cast<ConstantInt>(ConstantExpr::getSub(C,
386 ConstantInt::get(C->getType(), 1)));
389 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
390 /// this predicate to simplify operations downstream. V and Mask are known to
391 /// be the same type.
392 static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask,
393 unsigned Depth = 0) {
394 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
395 // we cannot optimize based on the assumption that it is zero without changing
396 // to to an explicit zero. If we don't change it to zero, other code could
397 // optimized based on the contradictory assumption that it is non-zero.
398 // Because instcombine aggressively folds operations with undef args anyway,
399 // this won't lose us code quality.
400 if (Mask->isNullValue())
402 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
403 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
405 if (Depth == 6) return false; // Limit search depth.
407 if (Instruction *I = dyn_cast<Instruction>(V)) {
408 switch (I->getOpcode()) {
409 case Instruction::And:
410 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
411 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1))) {
412 ConstantIntegral *C1C2 =
413 cast<ConstantIntegral>(ConstantExpr::getAnd(CI, Mask));
414 if (MaskedValueIsZero(I->getOperand(0), C1C2, Depth+1))
417 // If either the LHS or the RHS are MaskedValueIsZero, the result is zero.
418 return MaskedValueIsZero(I->getOperand(1), Mask, Depth+1) ||
419 MaskedValueIsZero(I->getOperand(0), Mask, Depth+1);
420 case Instruction::Or:
421 case Instruction::Xor:
422 // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
423 return MaskedValueIsZero(I->getOperand(1), Mask, Depth+1) &&
424 MaskedValueIsZero(I->getOperand(0), Mask, Depth+1);
425 case Instruction::Select:
426 // If the T and F values are MaskedValueIsZero, the result is also zero.
427 return MaskedValueIsZero(I->getOperand(2), Mask, Depth+1) &&
428 MaskedValueIsZero(I->getOperand(1), Mask, Depth+1);
429 case Instruction::Cast: {
430 const Type *SrcTy = I->getOperand(0)->getType();
431 if (SrcTy == Type::BoolTy)
432 return (Mask->getRawValue() & 1) == 0;
434 if (SrcTy->isInteger()) {
435 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
436 if (SrcTy->isUnsigned() && // Only handle zero ext.
437 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
440 // If this is a noop cast, recurse.
441 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() == I->getType())||
442 SrcTy->getSignedVersion() == I->getType()) {
444 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
445 return MaskedValueIsZero(I->getOperand(0),
446 cast<ConstantIntegral>(NewMask), Depth+1);
451 case Instruction::Shl:
452 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
453 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
454 return MaskedValueIsZero(I->getOperand(0),
455 cast<ConstantIntegral>(ConstantExpr::getUShr(Mask, SA)),
458 case Instruction::Shr:
459 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
460 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
461 if (I->getType()->isUnsigned()) {
462 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
463 C1 = ConstantExpr::getShr(C1, SA);
464 C1 = ConstantExpr::getAnd(C1, Mask);
465 if (C1->isNullValue())
475 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
476 // true when both operands are equal...
478 static bool isTrueWhenEqual(Instruction &I) {
479 return I.getOpcode() == Instruction::SetEQ ||
480 I.getOpcode() == Instruction::SetGE ||
481 I.getOpcode() == Instruction::SetLE;
484 /// AssociativeOpt - Perform an optimization on an associative operator. This
485 /// function is designed to check a chain of associative operators for a
486 /// potential to apply a certain optimization. Since the optimization may be
487 /// applicable if the expression was reassociated, this checks the chain, then
488 /// reassociates the expression as necessary to expose the optimization
489 /// opportunity. This makes use of a special Functor, which must define
490 /// 'shouldApply' and 'apply' methods.
492 template<typename Functor>
493 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
494 unsigned Opcode = Root.getOpcode();
495 Value *LHS = Root.getOperand(0);
497 // Quick check, see if the immediate LHS matches...
498 if (F.shouldApply(LHS))
499 return F.apply(Root);
501 // Otherwise, if the LHS is not of the same opcode as the root, return.
502 Instruction *LHSI = dyn_cast<Instruction>(LHS);
503 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
504 // Should we apply this transform to the RHS?
505 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
507 // If not to the RHS, check to see if we should apply to the LHS...
508 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
509 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
513 // If the functor wants to apply the optimization to the RHS of LHSI,
514 // reassociate the expression from ((? op A) op B) to (? op (A op B))
516 BasicBlock *BB = Root.getParent();
518 // Now all of the instructions are in the current basic block, go ahead
519 // and perform the reassociation.
520 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
522 // First move the selected RHS to the LHS of the root...
523 Root.setOperand(0, LHSI->getOperand(1));
525 // Make what used to be the LHS of the root be the user of the root...
526 Value *ExtraOperand = TmpLHSI->getOperand(1);
527 if (&Root == TmpLHSI) {
528 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
531 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
532 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
533 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
534 BasicBlock::iterator ARI = &Root; ++ARI;
535 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
538 // Now propagate the ExtraOperand down the chain of instructions until we
540 while (TmpLHSI != LHSI) {
541 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
542 // Move the instruction to immediately before the chain we are
543 // constructing to avoid breaking dominance properties.
544 NextLHSI->getParent()->getInstList().remove(NextLHSI);
545 BB->getInstList().insert(ARI, NextLHSI);
548 Value *NextOp = NextLHSI->getOperand(1);
549 NextLHSI->setOperand(1, ExtraOperand);
551 ExtraOperand = NextOp;
554 // Now that the instructions are reassociated, have the functor perform
555 // the transformation...
556 return F.apply(Root);
559 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
565 // AddRHS - Implements: X + X --> X << 1
568 AddRHS(Value *rhs) : RHS(rhs) {}
569 bool shouldApply(Value *LHS) const { return LHS == RHS; }
570 Instruction *apply(BinaryOperator &Add) const {
571 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
572 ConstantInt::get(Type::UByteTy, 1));
576 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
578 struct AddMaskingAnd {
580 AddMaskingAnd(Constant *c) : C2(c) {}
581 bool shouldApply(Value *LHS) const {
583 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
584 ConstantExpr::getAnd(C1, C2)->isNullValue();
586 Instruction *apply(BinaryOperator &Add) const {
587 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
591 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
593 if (isa<CastInst>(I)) {
594 if (Constant *SOC = dyn_cast<Constant>(SO))
595 return ConstantExpr::getCast(SOC, I.getType());
597 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
598 SO->getName() + ".cast"), I);
601 // Figure out if the constant is the left or the right argument.
602 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
603 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
605 if (Constant *SOC = dyn_cast<Constant>(SO)) {
607 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
608 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
611 Value *Op0 = SO, *Op1 = ConstOperand;
615 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
616 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
617 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
618 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
620 assert(0 && "Unknown binary instruction type!");
623 return IC->InsertNewInstBefore(New, I);
626 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
627 // constant as the other operand, try to fold the binary operator into the
628 // select arguments. This also works for Cast instructions, which obviously do
629 // not have a second operand.
630 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
632 // Don't modify shared select instructions
633 if (!SI->hasOneUse()) return 0;
634 Value *TV = SI->getOperand(1);
635 Value *FV = SI->getOperand(2);
637 if (isa<Constant>(TV) || isa<Constant>(FV)) {
638 // Bool selects with constant operands can be folded to logical ops.
639 if (SI->getType() == Type::BoolTy) return 0;
641 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
642 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
644 return new SelectInst(SI->getCondition(), SelectTrueVal,
651 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
652 /// node as operand #0, see if we can fold the instruction into the PHI (which
653 /// is only possible if all operands to the PHI are constants).
654 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
655 PHINode *PN = cast<PHINode>(I.getOperand(0));
656 unsigned NumPHIValues = PN->getNumIncomingValues();
657 if (!PN->hasOneUse() || NumPHIValues == 0 ||
658 !isa<Constant>(PN->getIncomingValue(0))) return 0;
660 // Check to see if all of the operands of the PHI are constants. If not, we
661 // cannot do the transformation.
662 for (unsigned i = 1; i != NumPHIValues; ++i)
663 if (!isa<Constant>(PN->getIncomingValue(i)))
666 // Okay, we can do the transformation: create the new PHI node.
667 PHINode *NewPN = new PHINode(I.getType(), I.getName());
669 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
670 InsertNewInstBefore(NewPN, *PN);
672 // Next, add all of the operands to the PHI.
673 if (I.getNumOperands() == 2) {
674 Constant *C = cast<Constant>(I.getOperand(1));
675 for (unsigned i = 0; i != NumPHIValues; ++i) {
676 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
677 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
678 PN->getIncomingBlock(i));
681 assert(isa<CastInst>(I) && "Unary op should be a cast!");
682 const Type *RetTy = I.getType();
683 for (unsigned i = 0; i != NumPHIValues; ++i) {
684 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
685 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
686 PN->getIncomingBlock(i));
689 return ReplaceInstUsesWith(I, NewPN);
692 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
693 bool Changed = SimplifyCommutative(I);
694 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
696 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
697 // X + undef -> undef
698 if (isa<UndefValue>(RHS))
699 return ReplaceInstUsesWith(I, RHS);
702 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
703 if (RHSC->isNullValue())
704 return ReplaceInstUsesWith(I, LHS);
705 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
706 if (CFP->isExactlyValue(-0.0))
707 return ReplaceInstUsesWith(I, LHS);
710 // X + (signbit) --> X ^ signbit
711 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
712 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
713 uint64_t Val = CI->getRawValue() & (~0ULL >> (64- NumBits));
714 if (Val == (1ULL << (NumBits-1)))
715 return BinaryOperator::createXor(LHS, RHS);
718 if (isa<PHINode>(LHS))
719 if (Instruction *NV = FoldOpIntoPhi(I))
724 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
725 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
726 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
727 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
729 uint64_t C0080Val = 1ULL << 31;
730 int64_t CFF80Val = -C0080Val;
733 if (TySizeBits > Size) {
735 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
736 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
737 if (RHSSExt == CFF80Val) {
738 if (XorRHS->getZExtValue() == C0080Val)
740 } else if (RHSZExt == C0080Val) {
741 if (XorRHS->getSExtValue() == CFF80Val)
745 // This is a sign extend if the top bits are known zero.
746 Constant *Mask = ConstantInt::getAllOnesValue(XorLHS->getType());
747 Mask = ConstantExpr::getShl(Mask,
748 ConstantInt::get(Type::UByteTy, 64-TySizeBits-Size));
749 if (!MaskedValueIsZero(XorLHS, cast<ConstantInt>(Mask)))
750 Size = 0; // Not a sign ext, but can't be any others either.
760 const Type *MiddleType = 0;
763 case 32: MiddleType = Type::IntTy; break;
764 case 16: MiddleType = Type::ShortTy; break;
765 case 8: MiddleType = Type::SByteTy; break;
768 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
769 InsertNewInstBefore(NewTrunc, I);
770 return new CastInst(NewTrunc, I.getType());
776 if (I.getType()->isInteger()) {
777 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
779 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
780 if (RHSI->getOpcode() == Instruction::Sub)
781 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
782 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
784 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
785 if (LHSI->getOpcode() == Instruction::Sub)
786 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
787 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
792 if (Value *V = dyn_castNegVal(LHS))
793 return BinaryOperator::createSub(RHS, V);
796 if (!isa<Constant>(RHS))
797 if (Value *V = dyn_castNegVal(RHS))
798 return BinaryOperator::createSub(LHS, V);
802 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
803 if (X == RHS) // X*C + X --> X * (C+1)
804 return BinaryOperator::createMul(RHS, AddOne(C2));
806 // X*C1 + X*C2 --> X * (C1+C2)
808 if (X == dyn_castFoldableMul(RHS, C1))
809 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
812 // X + X*C --> X * (C+1)
813 if (dyn_castFoldableMul(RHS, C2) == LHS)
814 return BinaryOperator::createMul(LHS, AddOne(C2));
817 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
818 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
819 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
821 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
823 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
824 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
825 return BinaryOperator::createSub(C, X);
828 // (X & FF00) + xx00 -> (X+xx00) & FF00
829 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
830 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
832 // See if all bits from the first bit set in the Add RHS up are included
833 // in the mask. First, get the rightmost bit.
834 uint64_t AddRHSV = CRHS->getRawValue();
836 // Form a mask of all bits from the lowest bit added through the top.
837 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
838 AddRHSHighBits &= ~0ULL >> (64-C2->getType()->getPrimitiveSizeInBits());
840 // See if the and mask includes all of these bits.
841 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
843 if (AddRHSHighBits == AddRHSHighBitsAnd) {
844 // Okay, the xform is safe. Insert the new add pronto.
845 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
847 return BinaryOperator::createAnd(NewAdd, C2);
852 // Try to fold constant add into select arguments.
853 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
854 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
858 return Changed ? &I : 0;
861 // isSignBit - Return true if the value represented by the constant only has the
862 // highest order bit set.
863 static bool isSignBit(ConstantInt *CI) {
864 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
865 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
868 /// RemoveNoopCast - Strip off nonconverting casts from the value.
870 static Value *RemoveNoopCast(Value *V) {
871 if (CastInst *CI = dyn_cast<CastInst>(V)) {
872 const Type *CTy = CI->getType();
873 const Type *OpTy = CI->getOperand(0)->getType();
874 if (CTy->isInteger() && OpTy->isInteger()) {
875 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
876 return RemoveNoopCast(CI->getOperand(0));
877 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
878 return RemoveNoopCast(CI->getOperand(0));
883 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
884 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
886 if (Op0 == Op1) // sub X, X -> 0
887 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
889 // If this is a 'B = x-(-A)', change to B = x+A...
890 if (Value *V = dyn_castNegVal(Op1))
891 return BinaryOperator::createAdd(Op0, V);
893 if (isa<UndefValue>(Op0))
894 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
895 if (isa<UndefValue>(Op1))
896 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
898 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
899 // Replace (-1 - A) with (~A)...
900 if (C->isAllOnesValue())
901 return BinaryOperator::createNot(Op1);
903 // C - ~X == X + (1+C)
905 if (match(Op1, m_Not(m_Value(X))))
906 return BinaryOperator::createAdd(X,
907 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
908 // -((uint)X >> 31) -> ((int)X >> 31)
909 // -((int)X >> 31) -> ((uint)X >> 31)
910 if (C->isNullValue()) {
911 Value *NoopCastedRHS = RemoveNoopCast(Op1);
912 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
913 if (SI->getOpcode() == Instruction::Shr)
914 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
916 if (SI->getType()->isSigned())
917 NewTy = SI->getType()->getUnsignedVersion();
919 NewTy = SI->getType()->getSignedVersion();
920 // Check to see if we are shifting out everything but the sign bit.
921 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
922 // Ok, the transformation is safe. Insert a cast of the incoming
923 // value, then the new shift, then the new cast.
924 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
925 SI->getOperand(0)->getName());
926 Value *InV = InsertNewInstBefore(FirstCast, I);
927 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
929 if (NewShift->getType() == I.getType())
932 InV = InsertNewInstBefore(NewShift, I);
933 return new CastInst(NewShift, I.getType());
939 // Try to fold constant sub into select arguments.
940 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
941 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
944 if (isa<PHINode>(Op0))
945 if (Instruction *NV = FoldOpIntoPhi(I))
949 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
950 if (Op1I->getOpcode() == Instruction::Add &&
951 !Op0->getType()->isFloatingPoint()) {
952 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
953 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
954 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
955 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
956 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
957 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
958 // C1-(X+C2) --> (C1-C2)-X
959 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
960 Op1I->getOperand(0));
964 if (Op1I->hasOneUse()) {
965 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
966 // is not used by anyone else...
968 if (Op1I->getOpcode() == Instruction::Sub &&
969 !Op1I->getType()->isFloatingPoint()) {
970 // Swap the two operands of the subexpr...
971 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
972 Op1I->setOperand(0, IIOp1);
973 Op1I->setOperand(1, IIOp0);
975 // Create the new top level add instruction...
976 return BinaryOperator::createAdd(Op0, Op1);
979 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
981 if (Op1I->getOpcode() == Instruction::And &&
982 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
983 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
986 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
987 return BinaryOperator::createAnd(Op0, NewNot);
990 // -(X sdiv C) -> (X sdiv -C)
991 if (Op1I->getOpcode() == Instruction::Div)
992 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
993 if (CSI->isNullValue())
994 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
995 return BinaryOperator::createDiv(Op1I->getOperand(0),
996 ConstantExpr::getNeg(DivRHS));
998 // X - X*C --> X * (1-C)
1000 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
1002 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
1003 return BinaryOperator::createMul(Op0, CP1);
1008 if (!Op0->getType()->isFloatingPoint())
1009 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1010 if (Op0I->getOpcode() == Instruction::Add) {
1011 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1012 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1013 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1014 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1015 } else if (Op0I->getOpcode() == Instruction::Sub) {
1016 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1017 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
1021 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1022 if (X == Op1) { // X*C - X --> X * (C-1)
1023 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1024 return BinaryOperator::createMul(Op1, CP1);
1027 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1028 if (X == dyn_castFoldableMul(Op1, C2))
1029 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1034 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1035 /// really just returns true if the most significant (sign) bit is set.
1036 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1037 if (RHS->getType()->isSigned()) {
1038 // True if source is LHS < 0 or LHS <= -1
1039 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1040 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1042 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1043 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1044 // the size of the integer type.
1045 if (Opcode == Instruction::SetGE)
1046 return RHSC->getValue() ==
1047 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
1048 if (Opcode == Instruction::SetGT)
1049 return RHSC->getValue() ==
1050 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
1055 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
1056 bool Changed = SimplifyCommutative(I);
1057 Value *Op0 = I.getOperand(0);
1059 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1060 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1062 // Simplify mul instructions with a constant RHS...
1063 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1064 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1066 // ((X << C1)*C2) == (X * (C2 << C1))
1067 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1068 if (SI->getOpcode() == Instruction::Shl)
1069 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
1070 return BinaryOperator::createMul(SI->getOperand(0),
1071 ConstantExpr::getShl(CI, ShOp));
1073 if (CI->isNullValue())
1074 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1075 if (CI->equalsInt(1)) // X * 1 == X
1076 return ReplaceInstUsesWith(I, Op0);
1077 if (CI->isAllOnesValue()) // X * -1 == 0 - X
1078 return BinaryOperator::createNeg(Op0, I.getName());
1080 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
1081 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1082 uint64_t C = Log2_64(Val);
1083 return new ShiftInst(Instruction::Shl, Op0,
1084 ConstantUInt::get(Type::UByteTy, C));
1086 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
1087 if (Op1F->isNullValue())
1088 return ReplaceInstUsesWith(I, Op1);
1090 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1091 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1092 if (Op1F->getValue() == 1.0)
1093 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1096 // Try to fold constant mul into select arguments.
1097 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1098 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1101 if (isa<PHINode>(Op0))
1102 if (Instruction *NV = FoldOpIntoPhi(I))
1106 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1107 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
1108 return BinaryOperator::createMul(Op0v, Op1v);
1110 // If one of the operands of the multiply is a cast from a boolean value, then
1111 // we know the bool is either zero or one, so this is a 'masking' multiply.
1112 // See if we can simplify things based on how the boolean was originally
1114 CastInst *BoolCast = 0;
1115 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1116 if (CI->getOperand(0)->getType() == Type::BoolTy)
1119 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1120 if (CI->getOperand(0)->getType() == Type::BoolTy)
1123 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1124 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1125 const Type *SCOpTy = SCIOp0->getType();
1127 // If the setcc is true iff the sign bit of X is set, then convert this
1128 // multiply into a shift/and combination.
1129 if (isa<ConstantInt>(SCIOp1) &&
1130 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
1131 // Shift the X value right to turn it into "all signbits".
1132 Constant *Amt = ConstantUInt::get(Type::UByteTy,
1133 SCOpTy->getPrimitiveSizeInBits()-1);
1134 if (SCIOp0->getType()->isUnsigned()) {
1135 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
1136 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1137 SCIOp0->getName()), I);
1141 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1142 BoolCast->getOperand(0)->getName()+
1145 // If the multiply type is not the same as the source type, sign extend
1146 // or truncate to the multiply type.
1147 if (I.getType() != V->getType())
1148 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
1150 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
1151 return BinaryOperator::createAnd(V, OtherOp);
1156 return Changed ? &I : 0;
1159 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
1160 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1162 if (isa<UndefValue>(Op0)) // undef / X -> 0
1163 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1164 if (isa<UndefValue>(Op1))
1165 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1167 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1169 if (RHS->equalsInt(1))
1170 return ReplaceInstUsesWith(I, Op0);
1173 if (RHS->isAllOnesValue())
1174 return BinaryOperator::createNeg(Op0);
1176 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
1177 if (LHS->getOpcode() == Instruction::Div)
1178 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
1179 // (X / C1) / C2 -> X / (C1*C2)
1180 return BinaryOperator::createDiv(LHS->getOperand(0),
1181 ConstantExpr::getMul(RHS, LHSRHS));
1184 // Check to see if this is an unsigned division with an exact power of 2,
1185 // if so, convert to a right shift.
1186 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1187 if (uint64_t Val = C->getValue()) // Don't break X / 0
1188 if (isPowerOf2_64(Val)) {
1189 uint64_t C = Log2_64(Val);
1190 return new ShiftInst(Instruction::Shr, Op0,
1191 ConstantUInt::get(Type::UByteTy, C));
1195 if (RHS->getType()->isSigned())
1196 if (Value *LHSNeg = dyn_castNegVal(Op0))
1197 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1199 if (!RHS->isNullValue()) {
1200 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1201 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1203 if (isa<PHINode>(Op0))
1204 if (Instruction *NV = FoldOpIntoPhi(I))
1209 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1210 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1211 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1212 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1213 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1214 if (STO->getValue() == 0) { // Couldn't be this argument.
1215 I.setOperand(1, SFO);
1217 } else if (SFO->getValue() == 0) {
1218 I.setOperand(1, STO);
1222 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
1223 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1224 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
1225 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1226 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1227 TC, SI->getName()+".t");
1228 TSI = InsertNewInstBefore(TSI, I);
1230 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1231 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1232 FC, SI->getName()+".f");
1233 FSI = InsertNewInstBefore(FSI, I);
1234 return new SelectInst(SI->getOperand(0), TSI, FSI);
1238 // 0 / X == 0, we don't need to preserve faults!
1239 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
1240 if (LHS->equalsInt(0))
1241 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1247 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
1248 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1249 if (I.getType()->isSigned())
1250 if (Value *RHSNeg = dyn_castNegVal(Op1))
1251 if (!isa<ConstantSInt>(RHSNeg) ||
1252 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
1254 AddUsesToWorkList(I);
1255 I.setOperand(1, RHSNeg);
1259 if (isa<UndefValue>(Op0)) // undef % X -> 0
1260 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1261 if (isa<UndefValue>(Op1))
1262 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
1264 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1265 if (RHS->equalsInt(1)) // X % 1 == 0
1266 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1268 // Check to see if this is an unsigned remainder with an exact power of 2,
1269 // if so, convert to a bitwise and.
1270 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1271 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
1272 if (!(Val & (Val-1))) // Power of 2
1273 return BinaryOperator::createAnd(Op0,
1274 ConstantUInt::get(I.getType(), Val-1));
1276 if (!RHS->isNullValue()) {
1277 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1278 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1280 if (isa<PHINode>(Op0))
1281 if (Instruction *NV = FoldOpIntoPhi(I))
1286 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1287 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1288 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1289 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1290 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1291 if (STO->getValue() == 0) { // Couldn't be this argument.
1292 I.setOperand(1, SFO);
1294 } else if (SFO->getValue() == 0) {
1295 I.setOperand(1, STO);
1299 if (!(STO->getValue() & (STO->getValue()-1)) &&
1300 !(SFO->getValue() & (SFO->getValue()-1))) {
1301 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1302 SubOne(STO), SI->getName()+".t"), I);
1303 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1304 SubOne(SFO), SI->getName()+".f"), I);
1305 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1309 // 0 % X == 0, we don't need to preserve faults!
1310 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
1311 if (LHS->equalsInt(0))
1312 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1317 // isMaxValueMinusOne - return true if this is Max-1
1318 static bool isMaxValueMinusOne(const ConstantInt *C) {
1319 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1320 // Calculate -1 casted to the right type...
1321 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
1322 uint64_t Val = ~0ULL; // All ones
1323 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1324 return CU->getValue() == Val-1;
1327 const ConstantSInt *CS = cast<ConstantSInt>(C);
1329 // Calculate 0111111111..11111
1330 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
1331 int64_t Val = INT64_MAX; // All ones
1332 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1333 return CS->getValue() == Val-1;
1336 // isMinValuePlusOne - return true if this is Min+1
1337 static bool isMinValuePlusOne(const ConstantInt *C) {
1338 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1339 return CU->getValue() == 1;
1341 const ConstantSInt *CS = cast<ConstantSInt>(C);
1343 // Calculate 1111111111000000000000
1344 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
1345 int64_t Val = -1; // All ones
1346 Val <<= TypeBits-1; // Shift over to the right spot
1347 return CS->getValue() == Val+1;
1350 // isOneBitSet - Return true if there is exactly one bit set in the specified
1352 static bool isOneBitSet(const ConstantInt *CI) {
1353 uint64_t V = CI->getRawValue();
1354 return V && (V & (V-1)) == 0;
1357 #if 0 // Currently unused
1358 // isLowOnes - Return true if the constant is of the form 0+1+.
1359 static bool isLowOnes(const ConstantInt *CI) {
1360 uint64_t V = CI->getRawValue();
1362 // There won't be bits set in parts that the type doesn't contain.
1363 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1365 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1366 return U && V && (U & V) == 0;
1370 // isHighOnes - Return true if the constant is of the form 1+0+.
1371 // This is the same as lowones(~X).
1372 static bool isHighOnes(const ConstantInt *CI) {
1373 uint64_t V = ~CI->getRawValue();
1374 if (~V == 0) return false; // 0's does not match "1+"
1376 // There won't be bits set in parts that the type doesn't contain.
1377 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1379 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1380 return U && V && (U & V) == 0;
1384 /// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1385 /// are carefully arranged to allow folding of expressions such as:
1387 /// (A < B) | (A > B) --> (A != B)
1389 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1390 /// represents that the comparison is true if A == B, and bit value '1' is true
1393 static unsigned getSetCondCode(const SetCondInst *SCI) {
1394 switch (SCI->getOpcode()) {
1396 case Instruction::SetGT: return 1;
1397 case Instruction::SetEQ: return 2;
1398 case Instruction::SetGE: return 3;
1399 case Instruction::SetLT: return 4;
1400 case Instruction::SetNE: return 5;
1401 case Instruction::SetLE: return 6;
1404 assert(0 && "Invalid SetCC opcode!");
1409 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
1410 /// opcode and two operands into either a constant true or false, or a brand new
1411 /// SetCC instruction.
1412 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1414 case 0: return ConstantBool::False;
1415 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1416 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1417 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1418 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1419 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1420 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1421 case 7: return ConstantBool::True;
1422 default: assert(0 && "Illegal SetCCCode!"); return 0;
1426 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1427 struct FoldSetCCLogical {
1430 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1431 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1432 bool shouldApply(Value *V) const {
1433 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1434 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1435 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1438 Instruction *apply(BinaryOperator &Log) const {
1439 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1440 if (SCI->getOperand(0) != LHS) {
1441 assert(SCI->getOperand(1) == LHS);
1442 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1445 unsigned LHSCode = getSetCondCode(SCI);
1446 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1448 switch (Log.getOpcode()) {
1449 case Instruction::And: Code = LHSCode & RHSCode; break;
1450 case Instruction::Or: Code = LHSCode | RHSCode; break;
1451 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
1452 default: assert(0 && "Illegal logical opcode!"); return 0;
1455 Value *RV = getSetCCValue(Code, LHS, RHS);
1456 if (Instruction *I = dyn_cast<Instruction>(RV))
1458 // Otherwise, it's a constant boolean value...
1459 return IC.ReplaceInstUsesWith(Log, RV);
1463 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1464 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1465 // guaranteed to be either a shift instruction or a binary operator.
1466 Instruction *InstCombiner::OptAndOp(Instruction *Op,
1467 ConstantIntegral *OpRHS,
1468 ConstantIntegral *AndRHS,
1469 BinaryOperator &TheAnd) {
1470 Value *X = Op->getOperand(0);
1471 Constant *Together = 0;
1472 if (!isa<ShiftInst>(Op))
1473 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
1475 switch (Op->getOpcode()) {
1476 case Instruction::Xor:
1477 if (Op->hasOneUse()) {
1478 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1479 std::string OpName = Op->getName(); Op->setName("");
1480 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
1481 InsertNewInstBefore(And, TheAnd);
1482 return BinaryOperator::createXor(And, Together);
1485 case Instruction::Or:
1486 if (Together == AndRHS) // (X | C) & C --> C
1487 return ReplaceInstUsesWith(TheAnd, AndRHS);
1489 if (Op->hasOneUse() && Together != OpRHS) {
1490 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1491 std::string Op0Name = Op->getName(); Op->setName("");
1492 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1493 InsertNewInstBefore(Or, TheAnd);
1494 return BinaryOperator::createAnd(Or, AndRHS);
1497 case Instruction::Add:
1498 if (Op->hasOneUse()) {
1499 // Adding a one to a single bit bit-field should be turned into an XOR
1500 // of the bit. First thing to check is to see if this AND is with a
1501 // single bit constant.
1502 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
1504 // Clear bits that are not part of the constant.
1505 AndRHSV &= ~0ULL >> (64-AndRHS->getType()->getPrimitiveSizeInBits());
1507 // If there is only one bit set...
1508 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
1509 // Ok, at this point, we know that we are masking the result of the
1510 // ADD down to exactly one bit. If the constant we are adding has
1511 // no bits set below this bit, then we can eliminate the ADD.
1512 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
1514 // Check to see if any bits below the one bit set in AndRHSV are set.
1515 if ((AddRHS & (AndRHSV-1)) == 0) {
1516 // If not, the only thing that can effect the output of the AND is
1517 // the bit specified by AndRHSV. If that bit is set, the effect of
1518 // the XOR is to toggle the bit. If it is clear, then the ADD has
1520 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1521 TheAnd.setOperand(0, X);
1524 std::string Name = Op->getName(); Op->setName("");
1525 // Pull the XOR out of the AND.
1526 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
1527 InsertNewInstBefore(NewAnd, TheAnd);
1528 return BinaryOperator::createXor(NewAnd, AndRHS);
1535 case Instruction::Shl: {
1536 // We know that the AND will not produce any of the bits shifted in, so if
1537 // the anded constant includes them, clear them now!
1539 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1540 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1541 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1543 if (CI == ShlMask) { // Masking out bits that the shift already masks
1544 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1545 } else if (CI != AndRHS) { // Reducing bits set in and.
1546 TheAnd.setOperand(1, CI);
1551 case Instruction::Shr:
1552 // We know that the AND will not produce any of the bits shifted in, so if
1553 // the anded constant includes them, clear them now! This only applies to
1554 // unsigned shifts, because a signed shr may bring in set bits!
1556 if (AndRHS->getType()->isUnsigned()) {
1557 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1558 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1559 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1561 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1562 return ReplaceInstUsesWith(TheAnd, Op);
1563 } else if (CI != AndRHS) {
1564 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
1567 } else { // Signed shr.
1568 // See if this is shifting in some sign extension, then masking it out
1570 if (Op->hasOneUse()) {
1571 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1572 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1573 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1574 if (CI == AndRHS) { // Masking out bits shifted in.
1575 // Make the argument unsigned.
1576 Value *ShVal = Op->getOperand(0);
1577 ShVal = InsertCastBefore(ShVal,
1578 ShVal->getType()->getUnsignedVersion(),
1580 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1581 OpRHS, Op->getName()),
1583 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1584 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1587 return new CastInst(ShVal, Op->getType());
1597 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1598 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1599 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1600 /// insert new instructions.
1601 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1602 bool Inside, Instruction &IB) {
1603 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1604 "Lo is not <= Hi in range emission code!");
1606 if (Lo == Hi) // Trivially false.
1607 return new SetCondInst(Instruction::SetNE, V, V);
1608 if (cast<ConstantIntegral>(Lo)->isMinValue())
1609 return new SetCondInst(Instruction::SetLT, V, Hi);
1611 Constant *AddCST = ConstantExpr::getNeg(Lo);
1612 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1613 InsertNewInstBefore(Add, IB);
1614 // Convert to unsigned for the comparison.
1615 const Type *UnsType = Add->getType()->getUnsignedVersion();
1616 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1617 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1618 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1619 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1622 if (Lo == Hi) // Trivially true.
1623 return new SetCondInst(Instruction::SetEQ, V, V);
1625 Hi = SubOne(cast<ConstantInt>(Hi));
1626 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1627 return new SetCondInst(Instruction::SetGT, V, Hi);
1629 // Emit X-Lo > Hi-Lo-1
1630 Constant *AddCST = ConstantExpr::getNeg(Lo);
1631 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1632 InsertNewInstBefore(Add, IB);
1633 // Convert to unsigned for the comparison.
1634 const Type *UnsType = Add->getType()->getUnsignedVersion();
1635 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1636 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1637 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1638 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1641 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
1642 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
1643 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
1644 // not, since all 1s are not contiguous.
1645 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
1646 uint64_t V = Val->getRawValue();
1647 if (!isShiftedMask_64(V)) return false;
1649 // look for the first zero bit after the run of ones
1650 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
1651 // look for the first non-zero bit
1652 ME = 64-CountLeadingZeros_64(V);
1658 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
1659 /// where isSub determines whether the operator is a sub. If we can fold one of
1660 /// the following xforms:
1662 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
1663 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1664 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1666 /// return (A +/- B).
1668 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
1669 ConstantIntegral *Mask, bool isSub,
1671 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1672 if (!LHSI || LHSI->getNumOperands() != 2 ||
1673 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
1675 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
1677 switch (LHSI->getOpcode()) {
1679 case Instruction::And:
1680 if (ConstantExpr::getAnd(N, Mask) == Mask) {
1681 // If the AndRHS is a power of two minus one (0+1+), this is simple.
1682 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
1685 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
1686 // part, we don't need any explicit masks to take them out of A. If that
1687 // is all N is, ignore it.
1689 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
1690 Constant *Mask = ConstantInt::getAllOnesValue(RHS->getType());
1691 Mask = ConstantExpr::getUShr(Mask,
1692 ConstantInt::get(Type::UByteTy,
1694 if (MaskedValueIsZero(RHS, cast<ConstantIntegral>(Mask)))
1699 case Instruction::Or:
1700 case Instruction::Xor:
1701 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
1702 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
1703 ConstantExpr::getAnd(N, Mask)->isNullValue())
1710 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
1712 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
1713 return InsertNewInstBefore(New, I);
1716 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1717 bool Changed = SimplifyCommutative(I);
1718 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1720 if (isa<UndefValue>(Op1)) // X & undef -> 0
1721 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1725 return ReplaceInstUsesWith(I, Op1);
1727 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
1729 if (AndRHS->isAllOnesValue())
1730 return ReplaceInstUsesWith(I, Op0);
1732 // and (and X, c1), c2 -> and (x, c1&c2). Handle this case here, before
1733 // calling MaskedValueIsZero, to avoid inefficient cases where we traipse
1734 // through many levels of ands.
1736 Value *X; ConstantInt *C1;
1737 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))))
1738 return BinaryOperator::createAnd(X, ConstantExpr::getAnd(C1, AndRHS));
1741 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1742 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1744 // If the mask is not masking out any bits, there is no reason to do the
1745 // and in the first place.
1746 ConstantIntegral *NotAndRHS =
1747 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS));
1748 if (MaskedValueIsZero(Op0, NotAndRHS))
1749 return ReplaceInstUsesWith(I, Op0);
1751 // Optimize a variety of ((val OP C1) & C2) combinations...
1752 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1753 Instruction *Op0I = cast<Instruction>(Op0);
1754 Value *Op0LHS = Op0I->getOperand(0);
1755 Value *Op0RHS = Op0I->getOperand(1);
1756 switch (Op0I->getOpcode()) {
1757 case Instruction::Xor:
1758 case Instruction::Or:
1759 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1760 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1761 if (MaskedValueIsZero(Op0LHS, AndRHS))
1762 return BinaryOperator::createAnd(Op0RHS, AndRHS);
1763 if (MaskedValueIsZero(Op0RHS, AndRHS))
1764 return BinaryOperator::createAnd(Op0LHS, AndRHS);
1766 // If the mask is only needed on one incoming arm, push it up.
1767 if (Op0I->hasOneUse()) {
1768 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1769 // Not masking anything out for the LHS, move to RHS.
1770 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1771 Op0RHS->getName()+".masked");
1772 InsertNewInstBefore(NewRHS, I);
1773 return BinaryOperator::create(
1774 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
1776 if (!isa<Constant>(NotAndRHS) &&
1777 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1778 // Not masking anything out for the RHS, move to LHS.
1779 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1780 Op0LHS->getName()+".masked");
1781 InsertNewInstBefore(NewLHS, I);
1782 return BinaryOperator::create(
1783 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
1788 case Instruction::And:
1789 // (X & V) & C2 --> 0 iff (V & C2) == 0
1790 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
1791 MaskedValueIsZero(Op0RHS, AndRHS))
1792 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1794 case Instruction::Add:
1795 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
1796 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1797 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
1798 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
1799 return BinaryOperator::createAnd(V, AndRHS);
1800 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
1801 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
1804 case Instruction::Sub:
1805 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
1806 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1807 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
1808 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
1809 return BinaryOperator::createAnd(V, AndRHS);
1813 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1814 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
1816 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
1817 const Type *SrcTy = CI->getOperand(0)->getType();
1819 // If this is an integer truncation or change from signed-to-unsigned, and
1820 // if the source is an and/or with immediate, transform it. This
1821 // frequently occurs for bitfield accesses.
1822 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
1823 if (SrcTy->getPrimitiveSizeInBits() >=
1824 I.getType()->getPrimitiveSizeInBits() &&
1825 CastOp->getNumOperands() == 2)
1826 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1)))
1827 if (CastOp->getOpcode() == Instruction::And) {
1828 // Change: and (cast (and X, C1) to T), C2
1829 // into : and (cast X to T), trunc(C1)&C2
1830 // This will folds the two ands together, which may allow other
1832 Instruction *NewCast =
1833 new CastInst(CastOp->getOperand(0), I.getType(),
1834 CastOp->getName()+".shrunk");
1835 NewCast = InsertNewInstBefore(NewCast, I);
1837 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1838 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
1839 return BinaryOperator::createAnd(NewCast, C3);
1840 } else if (CastOp->getOpcode() == Instruction::Or) {
1841 // Change: and (cast (or X, C1) to T), C2
1842 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
1843 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
1844 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
1845 return ReplaceInstUsesWith(I, AndRHS);
1850 // If this is an integer sign or zero extension instruction.
1851 if (SrcTy->isIntegral() &&
1852 SrcTy->getPrimitiveSizeInBits() <
1853 CI->getType()->getPrimitiveSizeInBits()) {
1855 if (SrcTy->isUnsigned()) {
1856 // See if this and is clearing out bits that are known to be zero
1857 // anyway (due to the zero extension).
1858 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1859 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1860 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
1861 if (Result == Mask) // The "and" isn't doing anything, remove it.
1862 return ReplaceInstUsesWith(I, CI);
1863 if (Result != AndRHS) { // Reduce the and RHS constant.
1864 I.setOperand(1, Result);
1869 if (CI->hasOneUse() && SrcTy->isInteger()) {
1870 // We can only do this if all of the sign bits brought in are masked
1871 // out. Compute this by first getting 0000011111, then inverting
1873 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
1874 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
1875 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
1876 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
1877 // If the and is clearing all of the sign bits, change this to a
1878 // zero extension cast. To do this, cast the cast input to
1879 // unsigned, then to the requested size.
1880 Value *CastOp = CI->getOperand(0);
1882 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
1883 CI->getName()+".uns");
1884 NC = InsertNewInstBefore(NC, I);
1885 // Finally, insert a replacement for CI.
1886 NC = new CastInst(NC, CI->getType(), CI->getName());
1888 NC = InsertNewInstBefore(NC, I);
1889 WorkList.push_back(CI); // Delete CI later.
1890 I.setOperand(0, NC);
1891 return &I; // The AND operand was modified.
1898 // Try to fold constant and into select arguments.
1899 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1900 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1902 if (isa<PHINode>(Op0))
1903 if (Instruction *NV = FoldOpIntoPhi(I))
1907 Value *Op0NotVal = dyn_castNotVal(Op0);
1908 Value *Op1NotVal = dyn_castNotVal(Op1);
1910 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1911 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1913 // (~A & ~B) == (~(A | B)) - De Morgan's Law
1914 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1915 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1916 I.getName()+".demorgan");
1917 InsertNewInstBefore(Or, I);
1918 return BinaryOperator::createNot(Or);
1921 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1922 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1923 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1926 Value *LHSVal, *RHSVal;
1927 ConstantInt *LHSCst, *RHSCst;
1928 Instruction::BinaryOps LHSCC, RHSCC;
1929 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1930 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1931 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1932 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1933 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1934 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1935 // Ensure that the larger constant is on the RHS.
1936 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1937 SetCondInst *LHS = cast<SetCondInst>(Op0);
1938 if (cast<ConstantBool>(Cmp)->getValue()) {
1939 std::swap(LHS, RHS);
1940 std::swap(LHSCst, RHSCst);
1941 std::swap(LHSCC, RHSCC);
1944 // At this point, we know we have have two setcc instructions
1945 // comparing a value against two constants and and'ing the result
1946 // together. Because of the above check, we know that we only have
1947 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1948 // FoldSetCCLogical check above), that the two constants are not
1950 assert(LHSCst != RHSCst && "Compares not folded above?");
1953 default: assert(0 && "Unknown integer condition code!");
1954 case Instruction::SetEQ:
1956 default: assert(0 && "Unknown integer condition code!");
1957 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1958 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1959 return ReplaceInstUsesWith(I, ConstantBool::False);
1960 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1961 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1962 return ReplaceInstUsesWith(I, LHS);
1964 case Instruction::SetNE:
1966 default: assert(0 && "Unknown integer condition code!");
1967 case Instruction::SetLT:
1968 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1969 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1970 break; // (X != 13 & X < 15) -> no change
1971 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1972 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1973 return ReplaceInstUsesWith(I, RHS);
1974 case Instruction::SetNE:
1975 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1976 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1977 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1978 LHSVal->getName()+".off");
1979 InsertNewInstBefore(Add, I);
1980 const Type *UnsType = Add->getType()->getUnsignedVersion();
1981 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1982 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1983 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1984 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1986 break; // (X != 13 & X != 15) -> no change
1989 case Instruction::SetLT:
1991 default: assert(0 && "Unknown integer condition code!");
1992 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1993 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1994 return ReplaceInstUsesWith(I, ConstantBool::False);
1995 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1996 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1997 return ReplaceInstUsesWith(I, LHS);
1999 case Instruction::SetGT:
2001 default: assert(0 && "Unknown integer condition code!");
2002 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2003 return ReplaceInstUsesWith(I, LHS);
2004 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2005 return ReplaceInstUsesWith(I, RHS);
2006 case Instruction::SetNE:
2007 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2008 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2009 break; // (X > 13 & X != 15) -> no change
2010 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2011 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
2017 return Changed ? &I : 0;
2020 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
2021 bool Changed = SimplifyCommutative(I);
2022 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2024 if (isa<UndefValue>(Op1))
2025 return ReplaceInstUsesWith(I, // X | undef -> -1
2026 ConstantIntegral::getAllOnesValue(I.getType()));
2028 // or X, X = X or X, 0 == X
2029 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
2030 return ReplaceInstUsesWith(I, Op0);
2033 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
2034 // If X is known to only contain bits that already exist in RHS, just
2035 // replace this instruction with RHS directly.
2036 if (MaskedValueIsZero(Op0,
2037 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
2038 return ReplaceInstUsesWith(I, RHS);
2040 ConstantInt *C1; Value *X;
2041 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2042 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2043 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2045 InsertNewInstBefore(Or, I);
2046 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2049 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2050 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2051 std::string Op0Name = Op0->getName(); Op0->setName("");
2052 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2053 InsertNewInstBefore(Or, I);
2054 return BinaryOperator::createXor(Or,
2055 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
2058 // Try to fold constant and into select arguments.
2059 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2060 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2062 if (isa<PHINode>(Op0))
2063 if (Instruction *NV = FoldOpIntoPhi(I))
2067 Value *A, *B; ConstantInt *C1, *C2;
2069 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2070 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2071 return ReplaceInstUsesWith(I, Op1);
2072 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2073 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2074 return ReplaceInstUsesWith(I, Op0);
2076 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2077 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2078 MaskedValueIsZero(Op1, C1)) {
2079 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2081 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2084 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2085 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2086 MaskedValueIsZero(Op0, C1)) {
2087 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2089 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2092 // (A & C1)|(B & C2)
2093 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2094 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2096 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2097 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2100 // If we have: ((V + N) & C1) | (V & C2)
2101 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2102 // replace with V+N.
2103 if (C1 == ConstantExpr::getNot(C2)) {
2105 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2106 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2107 // Add commutes, try both ways.
2108 if (V1 == B && MaskedValueIsZero(V2, C2))
2109 return ReplaceInstUsesWith(I, A);
2110 if (V2 == B && MaskedValueIsZero(V1, C2))
2111 return ReplaceInstUsesWith(I, A);
2113 // Or commutes, try both ways.
2114 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2115 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2116 // Add commutes, try both ways.
2117 if (V1 == A && MaskedValueIsZero(V2, C1))
2118 return ReplaceInstUsesWith(I, B);
2119 if (V2 == A && MaskedValueIsZero(V1, C1))
2120 return ReplaceInstUsesWith(I, B);
2125 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2126 if (A == Op1) // ~A | A == -1
2127 return ReplaceInstUsesWith(I,
2128 ConstantIntegral::getAllOnesValue(I.getType()));
2132 // Note, A is still live here!
2133 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2135 return ReplaceInstUsesWith(I,
2136 ConstantIntegral::getAllOnesValue(I.getType()));
2138 // (~A | ~B) == (~(A & B)) - De Morgan's Law
2139 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2140 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2141 I.getName()+".demorgan"), I);
2142 return BinaryOperator::createNot(And);
2146 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
2147 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
2148 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2151 Value *LHSVal, *RHSVal;
2152 ConstantInt *LHSCst, *RHSCst;
2153 Instruction::BinaryOps LHSCC, RHSCC;
2154 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2155 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2156 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2157 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
2158 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
2159 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2160 // Ensure that the larger constant is on the RHS.
2161 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2162 SetCondInst *LHS = cast<SetCondInst>(Op0);
2163 if (cast<ConstantBool>(Cmp)->getValue()) {
2164 std::swap(LHS, RHS);
2165 std::swap(LHSCst, RHSCst);
2166 std::swap(LHSCC, RHSCC);
2169 // At this point, we know we have have two setcc instructions
2170 // comparing a value against two constants and or'ing the result
2171 // together. Because of the above check, we know that we only have
2172 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2173 // FoldSetCCLogical check above), that the two constants are not
2175 assert(LHSCst != RHSCst && "Compares not folded above?");
2178 default: assert(0 && "Unknown integer condition code!");
2179 case Instruction::SetEQ:
2181 default: assert(0 && "Unknown integer condition code!");
2182 case Instruction::SetEQ:
2183 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2184 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2185 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2186 LHSVal->getName()+".off");
2187 InsertNewInstBefore(Add, I);
2188 const Type *UnsType = Add->getType()->getUnsignedVersion();
2189 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2190 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2191 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2192 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2194 break; // (X == 13 | X == 15) -> no change
2196 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2198 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2199 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2200 return ReplaceInstUsesWith(I, RHS);
2203 case Instruction::SetNE:
2205 default: assert(0 && "Unknown integer condition code!");
2206 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2207 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2208 return ReplaceInstUsesWith(I, LHS);
2209 case Instruction::SetNE: // (X != 13 | X != 15) -> true
2210 case Instruction::SetLT: // (X != 13 | X < 15) -> true
2211 return ReplaceInstUsesWith(I, ConstantBool::True);
2214 case Instruction::SetLT:
2216 default: assert(0 && "Unknown integer condition code!");
2217 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2219 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2220 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
2221 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2222 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2223 return ReplaceInstUsesWith(I, RHS);
2226 case Instruction::SetGT:
2228 default: assert(0 && "Unknown integer condition code!");
2229 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2230 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2231 return ReplaceInstUsesWith(I, LHS);
2232 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2233 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2234 return ReplaceInstUsesWith(I, ConstantBool::True);
2240 return Changed ? &I : 0;
2243 // XorSelf - Implements: X ^ X --> 0
2246 XorSelf(Value *rhs) : RHS(rhs) {}
2247 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2248 Instruction *apply(BinaryOperator &Xor) const {
2254 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2255 bool Changed = SimplifyCommutative(I);
2256 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2258 if (isa<UndefValue>(Op1))
2259 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2261 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2262 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2263 assert(Result == &I && "AssociativeOpt didn't work?");
2264 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2267 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
2269 if (RHS->isNullValue())
2270 return ReplaceInstUsesWith(I, Op0);
2272 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2273 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
2274 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
2275 if (RHS == ConstantBool::True && SCI->hasOneUse())
2276 return new SetCondInst(SCI->getInverseCondition(),
2277 SCI->getOperand(0), SCI->getOperand(1));
2279 // ~(c-X) == X-c-1 == X+(-c-1)
2280 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2281 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2282 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2283 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2284 ConstantInt::get(I.getType(), 1));
2285 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
2288 // ~(~X & Y) --> (X | ~Y)
2289 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2290 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2291 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2293 BinaryOperator::createNot(Op0I->getOperand(1),
2294 Op0I->getOperand(1)->getName()+".not");
2295 InsertNewInstBefore(NotY, I);
2296 return BinaryOperator::createOr(Op0NotVal, NotY);
2300 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2301 switch (Op0I->getOpcode()) {
2302 case Instruction::Add:
2303 // ~(X-c) --> (-c-1)-X
2304 if (RHS->isAllOnesValue()) {
2305 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2306 return BinaryOperator::createSub(
2307 ConstantExpr::getSub(NegOp0CI,
2308 ConstantInt::get(I.getType(), 1)),
2309 Op0I->getOperand(0));
2312 case Instruction::And:
2313 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
2314 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2315 return BinaryOperator::createOr(Op0, RHS);
2317 case Instruction::Or:
2318 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
2319 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
2320 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
2326 // Try to fold constant and into select arguments.
2327 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2328 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2330 if (isa<PHINode>(Op0))
2331 if (Instruction *NV = FoldOpIntoPhi(I))
2335 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
2337 return ReplaceInstUsesWith(I,
2338 ConstantIntegral::getAllOnesValue(I.getType()));
2340 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
2342 return ReplaceInstUsesWith(I,
2343 ConstantIntegral::getAllOnesValue(I.getType()));
2345 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
2346 if (Op1I->getOpcode() == Instruction::Or) {
2347 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2348 cast<BinaryOperator>(Op1I)->swapOperands();
2350 std::swap(Op0, Op1);
2351 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2353 std::swap(Op0, Op1);
2355 } else if (Op1I->getOpcode() == Instruction::Xor) {
2356 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2357 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2358 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2359 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2362 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
2363 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
2364 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2365 cast<BinaryOperator>(Op0I)->swapOperands();
2366 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
2367 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2368 Op1->getName()+".not"), I);
2369 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
2371 } else if (Op0I->getOpcode() == Instruction::Xor) {
2372 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2373 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2374 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2375 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2378 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
2379 Value *A, *B; ConstantInt *C1, *C2;
2380 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2381 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
2382 ConstantExpr::getAnd(C1, C2)->isNullValue())
2383 return BinaryOperator::createOr(Op0, Op1);
2385 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2386 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2387 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2390 return Changed ? &I : 0;
2393 /// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2394 /// overflowed for this type.
2395 static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2397 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2398 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2401 static bool isPositive(ConstantInt *C) {
2402 return cast<ConstantSInt>(C)->getValue() >= 0;
2405 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2406 /// overflowed for this type.
2407 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2409 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2411 if (In1->getType()->isUnsigned())
2412 return cast<ConstantUInt>(Result)->getValue() <
2413 cast<ConstantUInt>(In1)->getValue();
2414 if (isPositive(In1) != isPositive(In2))
2416 if (isPositive(In1))
2417 return cast<ConstantSInt>(Result)->getValue() <
2418 cast<ConstantSInt>(In1)->getValue();
2419 return cast<ConstantSInt>(Result)->getValue() >
2420 cast<ConstantSInt>(In1)->getValue();
2423 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2424 /// code necessary to compute the offset from the base pointer (without adding
2425 /// in the base pointer). Return the result as a signed integer of intptr size.
2426 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2427 TargetData &TD = IC.getTargetData();
2428 gep_type_iterator GTI = gep_type_begin(GEP);
2429 const Type *UIntPtrTy = TD.getIntPtrType();
2430 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2431 Value *Result = Constant::getNullValue(SIntPtrTy);
2433 // Build a mask for high order bits.
2434 uint64_t PtrSizeMask = ~0ULL;
2435 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2437 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2438 Value *Op = GEP->getOperand(i);
2439 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
2440 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2442 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2443 if (!OpC->isNullValue()) {
2444 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
2445 Scale = ConstantExpr::getMul(OpC, Scale);
2446 if (Constant *RC = dyn_cast<Constant>(Result))
2447 Result = ConstantExpr::getAdd(RC, Scale);
2449 // Emit an add instruction.
2450 Result = IC.InsertNewInstBefore(
2451 BinaryOperator::createAdd(Result, Scale,
2452 GEP->getName()+".offs"), I);
2456 // Convert to correct type.
2457 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2458 Op->getName()+".c"), I);
2460 // We'll let instcombine(mul) convert this to a shl if possible.
2461 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2462 GEP->getName()+".idx"), I);
2464 // Emit an add instruction.
2465 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
2466 GEP->getName()+".offs"), I);
2472 /// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2473 /// else. At this point we know that the GEP is on the LHS of the comparison.
2474 Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2475 Instruction::BinaryOps Cond,
2477 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
2479 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2480 if (isa<PointerType>(CI->getOperand(0)->getType()))
2481 RHS = CI->getOperand(0);
2483 Value *PtrBase = GEPLHS->getOperand(0);
2484 if (PtrBase == RHS) {
2485 // As an optimization, we don't actually have to compute the actual value of
2486 // OFFSET if this is a seteq or setne comparison, just return whether each
2487 // index is zero or not.
2488 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2489 Instruction *InVal = 0;
2490 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2491 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
2493 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2494 if (isa<UndefValue>(C)) // undef index -> undef.
2495 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2496 if (C->isNullValue())
2498 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2499 EmitIt = false; // This is indexing into a zero sized array?
2500 } else if (isa<ConstantInt>(C))
2501 return ReplaceInstUsesWith(I, // No comparison is needed here.
2502 ConstantBool::get(Cond == Instruction::SetNE));
2507 new SetCondInst(Cond, GEPLHS->getOperand(i),
2508 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2512 InVal = InsertNewInstBefore(InVal, I);
2513 InsertNewInstBefore(Comp, I);
2514 if (Cond == Instruction::SetNE) // True if any are unequal
2515 InVal = BinaryOperator::createOr(InVal, Comp);
2516 else // True if all are equal
2517 InVal = BinaryOperator::createAnd(InVal, Comp);
2525 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2526 ConstantBool::get(Cond == Instruction::SetEQ));
2529 // Only lower this if the setcc is the only user of the GEP or if we expect
2530 // the result to fold to a constant!
2531 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2532 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2533 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2534 return new SetCondInst(Cond, Offset,
2535 Constant::getNullValue(Offset->getType()));
2537 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
2538 // If the base pointers are different, but the indices are the same, just
2539 // compare the base pointer.
2540 if (PtrBase != GEPRHS->getOperand(0)) {
2541 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
2542 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
2543 GEPRHS->getOperand(0)->getType();
2545 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2546 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2547 IndicesTheSame = false;
2551 // If all indices are the same, just compare the base pointers.
2553 return new SetCondInst(Cond, GEPLHS->getOperand(0),
2554 GEPRHS->getOperand(0));
2556 // Otherwise, the base pointers are different and the indices are
2557 // different, bail out.
2561 // If one of the GEPs has all zero indices, recurse.
2562 bool AllZeros = true;
2563 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2564 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2565 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2570 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2571 SetCondInst::getSwappedCondition(Cond), I);
2573 // If the other GEP has all zero indices, recurse.
2575 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2576 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2577 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2582 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2584 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2585 // If the GEPs only differ by one index, compare it.
2586 unsigned NumDifferences = 0; // Keep track of # differences.
2587 unsigned DiffOperand = 0; // The operand that differs.
2588 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2589 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2590 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
2591 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
2592 // Irreconcilable differences.
2596 if (NumDifferences++) break;
2601 if (NumDifferences == 0) // SAME GEP?
2602 return ReplaceInstUsesWith(I, // No comparison is needed here.
2603 ConstantBool::get(Cond == Instruction::SetEQ));
2604 else if (NumDifferences == 1) {
2605 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2606 Value *RHSV = GEPRHS->getOperand(DiffOperand);
2608 // Convert the operands to signed values to make sure to perform a
2609 // signed comparison.
2610 const Type *NewTy = LHSV->getType()->getSignedVersion();
2611 if (LHSV->getType() != NewTy)
2612 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
2613 LHSV->getName()), I);
2614 if (RHSV->getType() != NewTy)
2615 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
2616 RHSV->getName()), I);
2617 return new SetCondInst(Cond, LHSV, RHSV);
2621 // Only lower this if the setcc is the only user of the GEP or if we expect
2622 // the result to fold to a constant!
2623 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2624 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2625 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2626 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2627 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2628 return new SetCondInst(Cond, L, R);
2635 Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
2636 bool Changed = SimplifyCommutative(I);
2637 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2638 const Type *Ty = Op0->getType();
2642 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
2644 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2645 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2647 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2648 // addresses never equal each other! We already know that Op0 != Op1.
2649 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2650 isa<ConstantPointerNull>(Op0)) &&
2651 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
2652 isa<ConstantPointerNull>(Op1)))
2653 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2655 // setcc's with boolean values can always be turned into bitwise operations
2656 if (Ty == Type::BoolTy) {
2657 switch (I.getOpcode()) {
2658 default: assert(0 && "Invalid setcc instruction!");
2659 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
2660 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
2661 InsertNewInstBefore(Xor, I);
2662 return BinaryOperator::createNot(Xor);
2664 case Instruction::SetNE:
2665 return BinaryOperator::createXor(Op0, Op1);
2667 case Instruction::SetGT:
2668 std::swap(Op0, Op1); // Change setgt -> setlt
2670 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2671 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2672 InsertNewInstBefore(Not, I);
2673 return BinaryOperator::createAnd(Not, Op1);
2675 case Instruction::SetGE:
2676 std::swap(Op0, Op1); // Change setge -> setle
2678 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2679 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2680 InsertNewInstBefore(Not, I);
2681 return BinaryOperator::createOr(Not, Op1);
2686 // See if we are doing a comparison between a constant and an instruction that
2687 // can be folded into the comparison.
2688 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2689 // Check to see if we are comparing against the minimum or maximum value...
2690 if (CI->isMinValue()) {
2691 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2692 return ReplaceInstUsesWith(I, ConstantBool::False);
2693 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2694 return ReplaceInstUsesWith(I, ConstantBool::True);
2695 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2696 return BinaryOperator::createSetEQ(Op0, Op1);
2697 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2698 return BinaryOperator::createSetNE(Op0, Op1);
2700 } else if (CI->isMaxValue()) {
2701 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2702 return ReplaceInstUsesWith(I, ConstantBool::False);
2703 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2704 return ReplaceInstUsesWith(I, ConstantBool::True);
2705 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2706 return BinaryOperator::createSetEQ(Op0, Op1);
2707 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2708 return BinaryOperator::createSetNE(Op0, Op1);
2710 // Comparing against a value really close to min or max?
2711 } else if (isMinValuePlusOne(CI)) {
2712 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2713 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2714 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2715 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2717 } else if (isMaxValueMinusOne(CI)) {
2718 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2719 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2720 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2721 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2724 // If we still have a setle or setge instruction, turn it into the
2725 // appropriate setlt or setgt instruction. Since the border cases have
2726 // already been handled above, this requires little checking.
2728 if (I.getOpcode() == Instruction::SetLE)
2729 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2730 if (I.getOpcode() == Instruction::SetGE)
2731 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2733 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2734 switch (LHSI->getOpcode()) {
2735 case Instruction::And:
2736 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2737 LHSI->getOperand(0)->hasOneUse()) {
2738 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2739 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2740 // happens a LOT in code produced by the C front-end, for bitfield
2742 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2743 ConstantUInt *ShAmt;
2744 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2745 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2746 const Type *Ty = LHSI->getType();
2748 // We can fold this as long as we can't shift unknown bits
2749 // into the mask. This can only happen with signed shift
2750 // rights, as they sign-extend.
2752 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
2753 Shift->getType()->isUnsigned();
2755 // To test for the bad case of the signed shr, see if any
2756 // of the bits shifted in could be tested after the mask.
2757 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
2758 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
2760 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
2762 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2763 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2769 if (Shift->getOpcode() == Instruction::Shl)
2770 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2772 NewCst = ConstantExpr::getShl(CI, ShAmt);
2774 // Check to see if we are shifting out any of the bits being
2776 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2777 // If we shifted bits out, the fold is not going to work out.
2778 // As a special case, check to see if this means that the
2779 // result is always true or false now.
2780 if (I.getOpcode() == Instruction::SetEQ)
2781 return ReplaceInstUsesWith(I, ConstantBool::False);
2782 if (I.getOpcode() == Instruction::SetNE)
2783 return ReplaceInstUsesWith(I, ConstantBool::True);
2785 I.setOperand(1, NewCst);
2786 Constant *NewAndCST;
2787 if (Shift->getOpcode() == Instruction::Shl)
2788 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2790 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2791 LHSI->setOperand(1, NewAndCST);
2792 LHSI->setOperand(0, Shift->getOperand(0));
2793 WorkList.push_back(Shift); // Shift is dead.
2794 AddUsesToWorkList(I);
2802 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2803 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2804 switch (I.getOpcode()) {
2806 case Instruction::SetEQ:
2807 case Instruction::SetNE: {
2808 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
2810 // Check that the shift amount is in range. If not, don't perform
2811 // undefined shifts. When the shift is visited it will be
2813 if (ShAmt->getValue() >= TypeBits)
2816 // If we are comparing against bits always shifted out, the
2817 // comparison cannot succeed.
2819 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2820 if (Comp != CI) {// Comparing against a bit that we know is zero.
2821 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2822 Constant *Cst = ConstantBool::get(IsSetNE);
2823 return ReplaceInstUsesWith(I, Cst);
2826 if (LHSI->hasOneUse()) {
2827 // Otherwise strength reduce the shift into an and.
2828 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
2829 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2832 if (CI->getType()->isUnsigned()) {
2833 Mask = ConstantUInt::get(CI->getType(), Val);
2834 } else if (ShAmtVal != 0) {
2835 Mask = ConstantSInt::get(CI->getType(), Val);
2837 Mask = ConstantInt::getAllOnesValue(CI->getType());
2841 BinaryOperator::createAnd(LHSI->getOperand(0),
2842 Mask, LHSI->getName()+".mask");
2843 Value *And = InsertNewInstBefore(AndI, I);
2844 return new SetCondInst(I.getOpcode(), And,
2845 ConstantExpr::getUShr(CI, ShAmt));
2852 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
2853 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2854 switch (I.getOpcode()) {
2856 case Instruction::SetEQ:
2857 case Instruction::SetNE: {
2859 // Check that the shift amount is in range. If not, don't perform
2860 // undefined shifts. When the shift is visited it will be
2862 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
2863 if (ShAmt->getValue() >= TypeBits)
2866 // If we are comparing against bits always shifted out, the
2867 // comparison cannot succeed.
2869 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2871 if (Comp != CI) {// Comparing against a bit that we know is zero.
2872 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2873 Constant *Cst = ConstantBool::get(IsSetNE);
2874 return ReplaceInstUsesWith(I, Cst);
2877 if (LHSI->hasOneUse() || CI->isNullValue()) {
2878 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
2880 // Otherwise strength reduce the shift into an and.
2881 uint64_t Val = ~0ULL; // All ones.
2882 Val <<= ShAmtVal; // Shift over to the right spot.
2885 if (CI->getType()->isUnsigned()) {
2886 Val &= ~0ULL >> (64-TypeBits);
2887 Mask = ConstantUInt::get(CI->getType(), Val);
2889 Mask = ConstantSInt::get(CI->getType(), Val);
2893 BinaryOperator::createAnd(LHSI->getOperand(0),
2894 Mask, LHSI->getName()+".mask");
2895 Value *And = InsertNewInstBefore(AndI, I);
2896 return new SetCondInst(I.getOpcode(), And,
2897 ConstantExpr::getShl(CI, ShAmt));
2905 case Instruction::Div:
2906 // Fold: (div X, C1) op C2 -> range check
2907 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2908 // Fold this div into the comparison, producing a range check.
2909 // Determine, based on the divide type, what the range is being
2910 // checked. If there is an overflow on the low or high side, remember
2911 // it, otherwise compute the range [low, hi) bounding the new value.
2912 bool LoOverflow = false, HiOverflow = 0;
2913 ConstantInt *LoBound = 0, *HiBound = 0;
2916 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2918 Instruction::BinaryOps Opcode = I.getOpcode();
2920 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2921 } else if (LHSI->getType()->isUnsigned()) { // udiv
2923 LoOverflow = ProdOV;
2924 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2925 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2926 if (CI->isNullValue()) { // (X / pos) op 0
2928 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2930 } else if (isPositive(CI)) { // (X / pos) op pos
2932 LoOverflow = ProdOV;
2933 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2934 } else { // (X / pos) op neg
2935 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2936 LoOverflow = AddWithOverflow(LoBound, Prod,
2937 cast<ConstantInt>(DivRHSH));
2939 HiOverflow = ProdOV;
2941 } else { // Divisor is < 0.
2942 if (CI->isNullValue()) { // (X / neg) op 0
2943 LoBound = AddOne(DivRHS);
2944 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2945 if (HiBound == DivRHS)
2946 LoBound = 0; // - INTMIN = INTMIN
2947 } else if (isPositive(CI)) { // (X / neg) op pos
2948 HiOverflow = LoOverflow = ProdOV;
2950 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2951 HiBound = AddOne(Prod);
2952 } else { // (X / neg) op neg
2954 LoOverflow = HiOverflow = ProdOV;
2955 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2958 // Dividing by a negate swaps the condition.
2959 Opcode = SetCondInst::getSwappedCondition(Opcode);
2963 Value *X = LHSI->getOperand(0);
2965 default: assert(0 && "Unhandled setcc opcode!");
2966 case Instruction::SetEQ:
2967 if (LoOverflow && HiOverflow)
2968 return ReplaceInstUsesWith(I, ConstantBool::False);
2969 else if (HiOverflow)
2970 return new SetCondInst(Instruction::SetGE, X, LoBound);
2971 else if (LoOverflow)
2972 return new SetCondInst(Instruction::SetLT, X, HiBound);
2974 return InsertRangeTest(X, LoBound, HiBound, true, I);
2975 case Instruction::SetNE:
2976 if (LoOverflow && HiOverflow)
2977 return ReplaceInstUsesWith(I, ConstantBool::True);
2978 else if (HiOverflow)
2979 return new SetCondInst(Instruction::SetLT, X, LoBound);
2980 else if (LoOverflow)
2981 return new SetCondInst(Instruction::SetGE, X, HiBound);
2983 return InsertRangeTest(X, LoBound, HiBound, false, I);
2984 case Instruction::SetLT:
2986 return ReplaceInstUsesWith(I, ConstantBool::False);
2987 return new SetCondInst(Instruction::SetLT, X, LoBound);
2988 case Instruction::SetGT:
2990 return ReplaceInstUsesWith(I, ConstantBool::False);
2991 return new SetCondInst(Instruction::SetGE, X, HiBound);
2998 // Simplify seteq and setne instructions...
2999 if (I.getOpcode() == Instruction::SetEQ ||
3000 I.getOpcode() == Instruction::SetNE) {
3001 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3003 // If the first operand is (and|or|xor) with a constant, and the second
3004 // operand is a constant, simplify a bit.
3005 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3006 switch (BO->getOpcode()) {
3007 case Instruction::Rem:
3008 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3009 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3011 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3012 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3013 if (isPowerOf2_64(V)) {
3014 unsigned L2 = Log2_64(V);
3015 const Type *UTy = BO->getType()->getUnsignedVersion();
3016 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3018 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3019 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3020 RHSCst, BO->getName()), I);
3021 return BinaryOperator::create(I.getOpcode(), NewRem,
3022 Constant::getNullValue(UTy));
3027 case Instruction::Add:
3028 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3029 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3030 if (BO->hasOneUse())
3031 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3032 ConstantExpr::getSub(CI, BOp1C));
3033 } else if (CI->isNullValue()) {
3034 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3035 // efficiently invertible, or if the add has just this one use.
3036 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3038 if (Value *NegVal = dyn_castNegVal(BOp1))
3039 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3040 else if (Value *NegVal = dyn_castNegVal(BOp0))
3041 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
3042 else if (BO->hasOneUse()) {
3043 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3045 InsertNewInstBefore(Neg, I);
3046 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3050 case Instruction::Xor:
3051 // For the xor case, we can xor two constants together, eliminating
3052 // the explicit xor.
3053 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3054 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
3055 ConstantExpr::getXor(CI, BOC));
3058 case Instruction::Sub:
3059 // Replace (([sub|xor] A, B) != 0) with (A != B)
3060 if (CI->isNullValue())
3061 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3065 case Instruction::Or:
3066 // If bits are being or'd in that are not present in the constant we
3067 // are comparing against, then the comparison could never succeed!
3068 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
3069 Constant *NotCI = ConstantExpr::getNot(CI);
3070 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
3071 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
3075 case Instruction::And:
3076 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3077 // If bits are being compared against that are and'd out, then the
3078 // comparison can never succeed!
3079 if (!ConstantExpr::getAnd(CI,
3080 ConstantExpr::getNot(BOC))->isNullValue())
3081 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
3083 // If we have ((X & C) == C), turn it into ((X & C) != 0).
3084 if (CI == BOC && isOneBitSet(CI))
3085 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3086 Instruction::SetNE, Op0,
3087 Constant::getNullValue(CI->getType()));
3089 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3090 // to be a signed value as appropriate.
3091 if (isSignBit(BOC)) {
3092 Value *X = BO->getOperand(0);
3093 // If 'X' is not signed, insert a cast now...
3094 if (!BOC->getType()->isSigned()) {
3095 const Type *DestTy = BOC->getType()->getSignedVersion();
3096 X = InsertCastBefore(X, DestTy, I);
3098 return new SetCondInst(isSetNE ? Instruction::SetLT :
3099 Instruction::SetGE, X,
3100 Constant::getNullValue(X->getType()));
3103 // ((X & ~7) == 0) --> X < 8
3104 if (CI->isNullValue() && isHighOnes(BOC)) {
3105 Value *X = BO->getOperand(0);
3106 Constant *NegX = ConstantExpr::getNeg(BOC);
3108 // If 'X' is signed, insert a cast now.
3109 if (NegX->getType()->isSigned()) {
3110 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3111 X = InsertCastBefore(X, DestTy, I);
3112 NegX = ConstantExpr::getCast(NegX, DestTy);
3115 return new SetCondInst(isSetNE ? Instruction::SetGE :
3116 Instruction::SetLT, X, NegX);
3123 } else { // Not a SetEQ/SetNE
3124 // If the LHS is a cast from an integral value of the same size,
3125 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3126 Value *CastOp = Cast->getOperand(0);
3127 const Type *SrcTy = CastOp->getType();
3128 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
3129 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
3130 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
3131 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
3132 "Source and destination signednesses should differ!");
3133 if (Cast->getType()->isSigned()) {
3134 // If this is a signed comparison, check for comparisons in the
3135 // vicinity of zero.
3136 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3138 return BinaryOperator::createSetGT(CastOp,
3139 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
3140 else if (I.getOpcode() == Instruction::SetGT &&
3141 cast<ConstantSInt>(CI)->getValue() == -1)
3142 // X > -1 => x < 128
3143 return BinaryOperator::createSetLT(CastOp,
3144 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
3146 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3147 if (I.getOpcode() == Instruction::SetLT &&
3148 CUI->getValue() == 1ULL << (SrcTySize-1))
3149 // X < 128 => X > -1
3150 return BinaryOperator::createSetGT(CastOp,
3151 ConstantSInt::get(SrcTy, -1));
3152 else if (I.getOpcode() == Instruction::SetGT &&
3153 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
3155 return BinaryOperator::createSetLT(CastOp,
3156 Constant::getNullValue(SrcTy));
3163 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3164 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3165 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3166 switch (LHSI->getOpcode()) {
3167 case Instruction::GetElementPtr:
3168 if (RHSC->isNullValue()) {
3169 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3170 bool isAllZeros = true;
3171 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3172 if (!isa<Constant>(LHSI->getOperand(i)) ||
3173 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3178 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3179 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3183 case Instruction::PHI:
3184 if (Instruction *NV = FoldOpIntoPhi(I))
3187 case Instruction::Select:
3188 // If either operand of the select is a constant, we can fold the
3189 // comparison into the select arms, which will cause one to be
3190 // constant folded and the select turned into a bitwise or.
3191 Value *Op1 = 0, *Op2 = 0;
3192 if (LHSI->hasOneUse()) {
3193 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3194 // Fold the known value into the constant operand.
3195 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3196 // Insert a new SetCC of the other select operand.
3197 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3198 LHSI->getOperand(2), RHSC,
3200 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3201 // Fold the known value into the constant operand.
3202 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3203 // Insert a new SetCC of the other select operand.
3204 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3205 LHSI->getOperand(1), RHSC,
3211 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3216 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3217 if (User *GEP = dyn_castGetElementPtr(Op0))
3218 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3220 if (User *GEP = dyn_castGetElementPtr(Op1))
3221 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3222 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3225 // Test to see if the operands of the setcc are casted versions of other
3226 // values. If the cast can be stripped off both arguments, we do so now.
3227 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3228 Value *CastOp0 = CI->getOperand(0);
3229 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
3230 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
3231 (I.getOpcode() == Instruction::SetEQ ||
3232 I.getOpcode() == Instruction::SetNE)) {
3233 // We keep moving the cast from the left operand over to the right
3234 // operand, where it can often be eliminated completely.
3237 // If operand #1 is a cast instruction, see if we can eliminate it as
3239 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3240 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
3242 Op1 = CI2->getOperand(0);
3244 // If Op1 is a constant, we can fold the cast into the constant.
3245 if (Op1->getType() != Op0->getType())
3246 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3247 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3249 // Otherwise, cast the RHS right before the setcc
3250 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3251 InsertNewInstBefore(cast<Instruction>(Op1), I);
3253 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3256 // Handle the special case of: setcc (cast bool to X), <cst>
3257 // This comes up when you have code like
3260 // For generality, we handle any zero-extension of any operand comparison
3261 // with a constant or another cast from the same type.
3262 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3263 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3266 return Changed ? &I : 0;
3269 // visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3270 // We only handle extending casts so far.
3272 Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3273 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3274 const Type *SrcTy = LHSCIOp->getType();
3275 const Type *DestTy = SCI.getOperand(0)->getType();
3278 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
3281 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3282 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3283 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3285 // Is this a sign or zero extension?
3286 bool isSignSrc = SrcTy->isSigned();
3287 bool isSignDest = DestTy->isSigned();
3289 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3290 // Not an extension from the same type?
3291 RHSCIOp = CI->getOperand(0);
3292 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3293 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3294 // Compute the constant that would happen if we truncated to SrcTy then
3295 // reextended to DestTy.
3296 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3298 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3301 // If the value cannot be represented in the shorter type, we cannot emit
3302 // a simple comparison.
3303 if (SCI.getOpcode() == Instruction::SetEQ)
3304 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3305 if (SCI.getOpcode() == Instruction::SetNE)
3306 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3308 // Evaluate the comparison for LT.
3310 if (DestTy->isSigned()) {
3311 // We're performing a signed comparison.
3313 // Signed extend and signed comparison.
3314 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3315 Result = ConstantBool::False;
3317 Result = ConstantBool::True; // X < (large) --> true
3319 // Unsigned extend and signed comparison.
3320 if (cast<ConstantSInt>(CI)->getValue() < 0)
3321 Result = ConstantBool::False;
3323 Result = ConstantBool::True;
3326 // We're performing an unsigned comparison.
3328 // Unsigned extend & compare -> always true.
3329 Result = ConstantBool::True;
3331 // We're performing an unsigned comp with a sign extended value.
3332 // This is true if the input is >= 0. [aka >s -1]
3333 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3334 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3335 NegOne, SCI.getName()), SCI);
3339 // Finally, return the value computed.
3340 if (SCI.getOpcode() == Instruction::SetLT) {
3341 return ReplaceInstUsesWith(SCI, Result);
3343 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3344 if (Constant *CI = dyn_cast<Constant>(Result))
3345 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3347 return BinaryOperator::createNot(Result);
3354 // Okay, just insert a compare of the reduced operands now!
3355 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3358 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
3359 assert(I.getOperand(1)->getType() == Type::UByteTy);
3360 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3361 bool isLeftShift = I.getOpcode() == Instruction::Shl;
3363 // shl X, 0 == X and shr X, 0 == X
3364 // shl 0, X == 0 and shr 0, X == 0
3365 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
3366 Op0 == Constant::getNullValue(Op0->getType()))
3367 return ReplaceInstUsesWith(I, Op0);
3369 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3370 if (!isLeftShift && I.getType()->isSigned())
3371 return ReplaceInstUsesWith(I, Op0);
3372 else // undef << X -> 0 AND undef >>u X -> 0
3373 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3375 if (isa<UndefValue>(Op1)) {
3376 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
3377 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3379 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3382 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3384 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3385 if (CSI->isAllOnesValue())
3386 return ReplaceInstUsesWith(I, CSI);
3388 // Try to fold constant and into select arguments.
3389 if (isa<Constant>(Op0))
3390 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3391 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3394 // See if we can turn a signed shr into an unsigned shr.
3395 if (!isLeftShift && I.getType()->isSigned()) {
3396 if (MaskedValueIsZero(Op0, ConstantInt::getMinValue(I.getType()))) {
3397 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3398 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3400 return new CastInst(V, I.getType());
3404 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
3405 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3406 // of a signed value.
3408 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
3409 if (CUI->getValue() >= TypeBits) {
3410 if (!Op0->getType()->isSigned() || isLeftShift)
3411 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3413 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3418 // ((X*C1) << C2) == (X * (C1 << C2))
3419 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3420 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3421 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
3422 return BinaryOperator::createMul(BO->getOperand(0),
3423 ConstantExpr::getShl(BOOp, CUI));
3425 // Try to fold constant and into select arguments.
3426 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3427 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3429 if (isa<PHINode>(Op0))
3430 if (Instruction *NV = FoldOpIntoPhi(I))
3433 if (Op0->hasOneUse()) {
3434 // If this is a SHL of a sign-extending cast, see if we can turn the input
3435 // into a zero extending cast (a simple strength reduction).
3436 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3437 const Type *SrcTy = CI->getOperand(0)->getType();
3438 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
3439 SrcTy->getPrimitiveSizeInBits() <
3440 CI->getType()->getPrimitiveSizeInBits()) {
3441 // We can change it to a zero extension if we are shifting out all of
3442 // the sign extended bits. To check this, form a mask of all of the
3443 // sign extend bits, then shift them left and see if we have anything
3445 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3446 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3447 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3448 if (ConstantExpr::getShl(Mask, CUI)->isNullValue()) {
3449 // If the shift is nuking all of the sign bits, change this to a
3450 // zero extension cast. To do this, cast the cast input to
3451 // unsigned, then to the requested size.
3452 Value *CastOp = CI->getOperand(0);
3454 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3455 CI->getName()+".uns");
3456 NC = InsertNewInstBefore(NC, I);
3457 // Finally, insert a replacement for CI.
3458 NC = new CastInst(NC, CI->getType(), CI->getName());
3460 NC = InsertNewInstBefore(NC, I);
3461 WorkList.push_back(CI); // Delete CI later.
3462 I.setOperand(0, NC);
3463 return &I; // The SHL operand was modified.
3468 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
3469 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
3472 switch (Op0BO->getOpcode()) {
3474 case Instruction::Add:
3475 case Instruction::And:
3476 case Instruction::Or:
3477 case Instruction::Xor:
3478 // These operators commute.
3479 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
3480 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3481 match(Op0BO->getOperand(1),
3482 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == CUI) {
3483 Instruction *YS = new ShiftInst(Instruction::Shl,
3484 Op0BO->getOperand(0), CUI,
3486 InsertNewInstBefore(YS, I); // (Y << C)
3487 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3489 Op0BO->getOperand(1)->getName());
3490 InsertNewInstBefore(X, I); // (X + (Y << C))
3491 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3492 C2 = ConstantExpr::getShl(C2, CUI);
3493 return BinaryOperator::createAnd(X, C2);
3496 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
3497 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3498 match(Op0BO->getOperand(1),
3499 m_And(m_Shr(m_Value(V1), m_Value(V2)),
3500 m_ConstantInt(CC))) && V2 == CUI &&
3501 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
3502 Instruction *YS = new ShiftInst(Instruction::Shl,
3503 Op0BO->getOperand(0), CUI,
3505 InsertNewInstBefore(YS, I); // (Y << C)
3507 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, CUI),
3508 V1->getName()+".mask");
3509 InsertNewInstBefore(XM, I); // X & (CC << C)
3511 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3515 case Instruction::Sub:
3516 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
3517 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3518 match(Op0BO->getOperand(0),
3519 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == CUI) {
3520 Instruction *YS = new ShiftInst(Instruction::Shl,
3521 Op0BO->getOperand(1), CUI,
3523 InsertNewInstBefore(YS, I); // (Y << C)
3524 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3526 Op0BO->getOperand(0)->getName());
3527 InsertNewInstBefore(X, I); // (X + (Y << C))
3528 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3529 C2 = ConstantExpr::getShl(C2, CUI);
3530 return BinaryOperator::createAnd(X, C2);
3533 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3534 match(Op0BO->getOperand(0),
3535 m_And(m_Shr(m_Value(V1), m_Value(V2)),
3536 m_ConstantInt(CC))) && V2 == CUI &&
3537 cast<BinaryOperator>(Op0BO->getOperand(0))->getOperand(0)->hasOneUse()) {
3538 Instruction *YS = new ShiftInst(Instruction::Shl,
3539 Op0BO->getOperand(1), CUI,
3541 InsertNewInstBefore(YS, I); // (Y << C)
3543 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, CUI),
3544 V1->getName()+".mask");
3545 InsertNewInstBefore(XM, I); // X & (CC << C)
3547 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3554 // If the operand is an bitwise operator with a constant RHS, and the
3555 // shift is the only use, we can pull it out of the shift.
3556 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3557 bool isValid = true; // Valid only for And, Or, Xor
3558 bool highBitSet = false; // Transform if high bit of constant set?
3560 switch (Op0BO->getOpcode()) {
3561 default: isValid = false; break; // Do not perform transform!
3562 case Instruction::Add:
3563 isValid = isLeftShift;
3565 case Instruction::Or:
3566 case Instruction::Xor:
3569 case Instruction::And:
3574 // If this is a signed shift right, and the high bit is modified
3575 // by the logical operation, do not perform the transformation.
3576 // The highBitSet boolean indicates the value of the high bit of
3577 // the constant which would cause it to be modified for this
3580 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
3581 uint64_t Val = Op0C->getRawValue();
3582 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3586 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
3588 Instruction *NewShift =
3589 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
3592 InsertNewInstBefore(NewShift, I);
3594 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3601 // If this is a shift of a shift, see if we can fold the two together...
3602 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
3603 if (ConstantUInt *ShiftAmt1C =
3604 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
3605 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3606 unsigned ShiftAmt2 = (unsigned)CUI->getValue();
3608 // Check for (A << c1) << c2 and (A >> c1) >> c2
3609 if (I.getOpcode() == Op0SI->getOpcode()) {
3610 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
3611 if (Op0->getType()->getPrimitiveSizeInBits() < Amt)
3612 Amt = Op0->getType()->getPrimitiveSizeInBits();
3613 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
3614 ConstantUInt::get(Type::UByteTy, Amt));
3617 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
3618 // signed types, we can only support the (A >> c1) << c2 configuration,
3619 // because it can not turn an arbitrary bit of A into a sign bit.
3620 if (I.getType()->isUnsigned() || isLeftShift) {
3621 // Calculate bitmask for what gets shifted off the edge...
3622 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
3624 C = ConstantExpr::getShl(C, ShiftAmt1C);
3626 C = ConstantExpr::getShr(C, ShiftAmt1C);
3629 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
3630 Op0SI->getOperand(0)->getName()+".mask");
3631 InsertNewInstBefore(Mask, I);
3633 // Figure out what flavor of shift we should use...
3634 if (ShiftAmt1 == ShiftAmt2)
3635 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
3636 else if (ShiftAmt1 < ShiftAmt2) {
3637 return new ShiftInst(I.getOpcode(), Mask,
3638 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3640 return new ShiftInst(Op0SI->getOpcode(), Mask,
3641 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3644 // We can handle signed (X << C1) >> C2 if it's a sign extend. In
3645 // this case, C1 == C2 and C1 is 8, 16, or 32.
3646 if (ShiftAmt1 == ShiftAmt2) {
3647 const Type *SExtType = 0;
3648 switch (ShiftAmt1) {
3649 case 8 : SExtType = Type::SByteTy; break;
3650 case 16: SExtType = Type::ShortTy; break;
3651 case 32: SExtType = Type::IntTy; break;
3655 Instruction *NewTrunc = new CastInst(Op0SI->getOperand(0),
3657 InsertNewInstBefore(NewTrunc, I);
3658 return new CastInst(NewTrunc, I.getType());
3675 /// getCastType - In the future, we will split the cast instruction into these
3676 /// various types. Until then, we have to do the analysis here.
3677 static CastType getCastType(const Type *Src, const Type *Dest) {
3678 assert(Src->isIntegral() && Dest->isIntegral() &&
3679 "Only works on integral types!");
3680 unsigned SrcSize = Src->getPrimitiveSizeInBits();
3681 unsigned DestSize = Dest->getPrimitiveSizeInBits();
3683 if (SrcSize == DestSize) return Noop;
3684 if (SrcSize > DestSize) return Truncate;
3685 if (Src->isSigned()) return Signext;
3690 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3693 static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
3694 const Type *DstTy, TargetData *TD) {
3696 // It is legal to eliminate the instruction if casting A->B->A if the sizes
3697 // are identical and the bits don't get reinterpreted (for example
3698 // int->float->int would not be allowed).
3699 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
3702 // If we are casting between pointer and integer types, treat pointers as
3703 // integers of the appropriate size for the code below.
3704 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3705 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3706 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
3708 // Allow free casting and conversion of sizes as long as the sign doesn't
3710 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
3711 CastType FirstCast = getCastType(SrcTy, MidTy);
3712 CastType SecondCast = getCastType(MidTy, DstTy);
3714 // Capture the effect of these two casts. If the result is a legal cast,
3715 // the CastType is stored here, otherwise a special code is used.
3716 static const unsigned CastResult[] = {
3717 // First cast is noop
3719 // First cast is a truncate
3720 1, 1, 4, 4, // trunc->extend is not safe to eliminate
3721 // First cast is a sign ext
3722 2, 5, 2, 4, // signext->zeroext never ok
3723 // First cast is a zero ext
3727 unsigned Result = CastResult[FirstCast*4+SecondCast];
3729 default: assert(0 && "Illegal table value!");
3734 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
3735 // truncates, we could eliminate more casts.
3736 return (unsigned)getCastType(SrcTy, DstTy) == Result;
3738 return false; // Not possible to eliminate this here.
3740 // Sign or zero extend followed by truncate is always ok if the result
3741 // is a truncate or noop.
3742 CastType ResultCast = getCastType(SrcTy, DstTy);
3743 if (ResultCast == Noop || ResultCast == Truncate)
3745 // Otherwise we are still growing the value, we are only safe if the
3746 // result will match the sign/zeroextendness of the result.
3747 return ResultCast == FirstCast;
3753 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
3754 if (V->getType() == Ty || isa<Constant>(V)) return false;
3755 if (const CastInst *CI = dyn_cast<CastInst>(V))
3756 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
3762 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
3763 /// InsertBefore instruction. This is specialized a bit to avoid inserting
3764 /// casts that are known to not do anything...
3766 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
3767 Instruction *InsertBefore) {
3768 if (V->getType() == DestTy) return V;
3769 if (Constant *C = dyn_cast<Constant>(V))
3770 return ConstantExpr::getCast(C, DestTy);
3772 CastInst *CI = new CastInst(V, DestTy, V->getName());
3773 InsertNewInstBefore(CI, *InsertBefore);
3777 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
3778 /// expression. If so, decompose it, returning some value X, such that Val is
3781 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
3783 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
3784 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
3785 Offset = CI->getValue();
3787 return ConstantUInt::get(Type::UIntTy, 0);
3788 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
3789 if (I->getNumOperands() == 2) {
3790 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
3791 if (I->getOpcode() == Instruction::Shl) {
3792 // This is a value scaled by '1 << the shift amt'.
3793 Scale = 1U << CUI->getValue();
3795 return I->getOperand(0);
3796 } else if (I->getOpcode() == Instruction::Mul) {
3797 // This value is scaled by 'CUI'.
3798 Scale = CUI->getValue();
3800 return I->getOperand(0);
3801 } else if (I->getOpcode() == Instruction::Add) {
3802 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
3805 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
3807 Offset += CUI->getValue();
3808 if (SubScale > 1 && (Offset % SubScale == 0)) {
3817 // Otherwise, we can't look past this.
3824 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
3825 /// try to eliminate the cast by moving the type information into the alloc.
3826 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
3827 AllocationInst &AI) {
3828 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
3829 if (!PTy) return 0; // Not casting the allocation to a pointer type.
3831 // Remove any uses of AI that are dead.
3832 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
3833 std::vector<Instruction*> DeadUsers;
3834 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
3835 Instruction *User = cast<Instruction>(*UI++);
3836 if (isInstructionTriviallyDead(User)) {
3837 while (UI != E && *UI == User)
3838 ++UI; // If this instruction uses AI more than once, don't break UI.
3840 // Add operands to the worklist.
3841 AddUsesToWorkList(*User);
3843 DEBUG(std::cerr << "IC: DCE: " << *User);
3845 User->eraseFromParent();
3846 removeFromWorkList(User);
3850 // Get the type really allocated and the type casted to.
3851 const Type *AllocElTy = AI.getAllocatedType();
3852 const Type *CastElTy = PTy->getElementType();
3853 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
3855 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
3856 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
3857 if (CastElTyAlign < AllocElTyAlign) return 0;
3859 // If the allocation has multiple uses, only promote it if we are strictly
3860 // increasing the alignment of the resultant allocation. If we keep it the
3861 // same, we open the door to infinite loops of various kinds.
3862 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
3864 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
3865 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
3866 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
3868 // See if we can satisfy the modulus by pulling a scale out of the array
3870 unsigned ArraySizeScale, ArrayOffset;
3871 Value *NumElements = // See if the array size is a decomposable linear expr.
3872 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
3874 // If we can now satisfy the modulus, by using a non-1 scale, we really can
3876 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
3877 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
3879 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
3884 Amt = ConstantUInt::get(Type::UIntTy, Scale);
3885 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
3886 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
3887 else if (Scale != 1) {
3888 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
3889 Amt = InsertNewInstBefore(Tmp, AI);
3893 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
3894 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
3895 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
3896 Amt = InsertNewInstBefore(Tmp, AI);
3899 std::string Name = AI.getName(); AI.setName("");
3900 AllocationInst *New;
3901 if (isa<MallocInst>(AI))
3902 New = new MallocInst(CastElTy, Amt, Name);
3904 New = new AllocaInst(CastElTy, Amt, Name);
3905 InsertNewInstBefore(New, AI);
3907 // If the allocation has multiple uses, insert a cast and change all things
3908 // that used it to use the new cast. This will also hack on CI, but it will
3910 if (!AI.hasOneUse()) {
3911 AddUsesToWorkList(AI);
3912 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
3913 InsertNewInstBefore(NewCast, AI);
3914 AI.replaceAllUsesWith(NewCast);
3916 return ReplaceInstUsesWith(CI, New);
3920 // CastInst simplification
3922 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
3923 Value *Src = CI.getOperand(0);
3925 // If the user is casting a value to the same type, eliminate this cast
3927 if (CI.getType() == Src->getType())
3928 return ReplaceInstUsesWith(CI, Src);
3930 if (isa<UndefValue>(Src)) // cast undef -> undef
3931 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
3933 // If casting the result of another cast instruction, try to eliminate this
3936 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
3937 Value *A = CSrc->getOperand(0);
3938 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
3939 CI.getType(), TD)) {
3940 // This instruction now refers directly to the cast's src operand. This
3941 // has a good chance of making CSrc dead.
3942 CI.setOperand(0, CSrc->getOperand(0));
3946 // If this is an A->B->A cast, and we are dealing with integral types, try
3947 // to convert this into a logical 'and' instruction.
3949 if (A->getType()->isInteger() &&
3950 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
3951 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
3952 CSrc->getType()->getPrimitiveSizeInBits() <
3953 CI.getType()->getPrimitiveSizeInBits()&&
3954 A->getType()->getPrimitiveSizeInBits() ==
3955 CI.getType()->getPrimitiveSizeInBits()) {
3956 assert(CSrc->getType() != Type::ULongTy &&
3957 "Cannot have type bigger than ulong!");
3958 uint64_t AndValue = ~0ULL>>(64-CSrc->getType()->getPrimitiveSizeInBits());
3959 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
3961 AndOp = ConstantExpr::getCast(AndOp, A->getType());
3962 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
3963 if (And->getType() != CI.getType()) {
3964 And->setName(CSrc->getName()+".mask");
3965 InsertNewInstBefore(And, CI);
3966 And = new CastInst(And, CI.getType());
3972 // If this is a cast to bool, turn it into the appropriate setne instruction.
3973 if (CI.getType() == Type::BoolTy)
3974 return BinaryOperator::createSetNE(CI.getOperand(0),
3975 Constant::getNullValue(CI.getOperand(0)->getType()));
3977 // If casting the result of a getelementptr instruction with no offset, turn
3978 // this into a cast of the original pointer!
3980 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
3981 bool AllZeroOperands = true;
3982 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
3983 if (!isa<Constant>(GEP->getOperand(i)) ||
3984 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
3985 AllZeroOperands = false;
3988 if (AllZeroOperands) {
3989 CI.setOperand(0, GEP->getOperand(0));
3994 // If we are casting a malloc or alloca to a pointer to a type of the same
3995 // size, rewrite the allocation instruction to allocate the "right" type.
3997 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
3998 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4001 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4002 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4004 if (isa<PHINode>(Src))
4005 if (Instruction *NV = FoldOpIntoPhi(CI))
4008 // If the source value is an instruction with only this use, we can attempt to
4009 // propagate the cast into the instruction. Also, only handle integral types
4011 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
4012 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
4013 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4014 const Type *DestTy = CI.getType();
4015 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4016 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
4018 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4019 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4021 switch (SrcI->getOpcode()) {
4022 case Instruction::Add:
4023 case Instruction::Mul:
4024 case Instruction::And:
4025 case Instruction::Or:
4026 case Instruction::Xor:
4027 // If we are discarding information, or just changing the sign, rewrite.
4028 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4029 // Don't insert two casts if they cannot be eliminated. We allow two
4030 // casts to be inserted if the sizes are the same. This could only be
4031 // converting signedness, which is a noop.
4032 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4033 !ValueRequiresCast(Op0, DestTy, TD)) {
4034 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4035 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4036 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4037 ->getOpcode(), Op0c, Op1c);
4041 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4042 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4043 Op1 == ConstantBool::True &&
4044 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4045 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4046 return BinaryOperator::createXor(New,
4047 ConstantInt::get(CI.getType(), 1));
4050 case Instruction::Shl:
4051 // Allow changing the sign of the source operand. Do not allow changing
4052 // the size of the shift, UNLESS the shift amount is a constant. We
4053 // mush not change variable sized shifts to a smaller size, because it
4054 // is undefined to shift more bits out than exist in the value.
4055 if (DestBitSize == SrcBitSize ||
4056 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4057 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4058 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4061 case Instruction::Shr:
4062 // If this is a signed shr, and if all bits shifted in are about to be
4063 // truncated off, turn it into an unsigned shr to allow greater
4065 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4066 isa<ConstantInt>(Op1)) {
4067 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4068 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4069 // Convert to unsigned.
4070 Value *N1 = InsertOperandCastBefore(Op0,
4071 Op0->getType()->getUnsignedVersion(), &CI);
4072 // Insert the new shift, which is now unsigned.
4073 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4074 Op1, Src->getName()), CI);
4075 return new CastInst(N1, CI.getType());
4080 case Instruction::SetNE:
4081 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4082 if (Op1C->getRawValue() == 0) {
4083 // If the input only has the low bit set, simplify directly.
4085 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
4086 // cast (X != 0) to int --> X if X&~1 == 0
4087 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
4088 if (CI.getType() == Op0->getType())
4089 return ReplaceInstUsesWith(CI, Op0);
4091 return new CastInst(Op0, CI.getType());
4094 // If the input is an and with a single bit, shift then simplify.
4095 ConstantInt *AndRHS;
4096 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
4097 if (AndRHS->getRawValue() &&
4098 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
4099 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
4100 // Perform an unsigned shr by shiftamt. Convert input to
4101 // unsigned if it is signed.
4103 if (In->getType()->isSigned())
4104 In = InsertNewInstBefore(new CastInst(In,
4105 In->getType()->getUnsignedVersion(), In->getName()),CI);
4106 // Insert the shift to put the result in the low bit.
4107 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
4108 ConstantInt::get(Type::UByteTy, ShiftAmt),
4109 In->getName()+".lobit"), CI);
4110 if (CI.getType() == In->getType())
4111 return ReplaceInstUsesWith(CI, In);
4113 return new CastInst(In, CI.getType());
4118 case Instruction::SetEQ:
4119 // We if we are just checking for a seteq of a single bit and casting it
4120 // to an integer. If so, shift the bit to the appropriate place then
4121 // cast to integer to avoid the comparison.
4122 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4123 // Is Op1C a power of two or zero?
4124 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
4125 // cast (X == 1) to int -> X iff X has only the low bit set.
4126 if (Op1C->getRawValue() == 1) {
4128 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
4129 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
4130 if (CI.getType() == Op0->getType())
4131 return ReplaceInstUsesWith(CI, Op0);
4133 return new CastInst(Op0, CI.getType());
4145 /// GetSelectFoldableOperands - We want to turn code that looks like this:
4147 /// %D = select %cond, %C, %A
4149 /// %C = select %cond, %B, 0
4152 /// Assuming that the specified instruction is an operand to the select, return
4153 /// a bitmask indicating which operands of this instruction are foldable if they
4154 /// equal the other incoming value of the select.
4156 static unsigned GetSelectFoldableOperands(Instruction *I) {
4157 switch (I->getOpcode()) {
4158 case Instruction::Add:
4159 case Instruction::Mul:
4160 case Instruction::And:
4161 case Instruction::Or:
4162 case Instruction::Xor:
4163 return 3; // Can fold through either operand.
4164 case Instruction::Sub: // Can only fold on the amount subtracted.
4165 case Instruction::Shl: // Can only fold on the shift amount.
4166 case Instruction::Shr:
4169 return 0; // Cannot fold
4173 /// GetSelectFoldableConstant - For the same transformation as the previous
4174 /// function, return the identity constant that goes into the select.
4175 static Constant *GetSelectFoldableConstant(Instruction *I) {
4176 switch (I->getOpcode()) {
4177 default: assert(0 && "This cannot happen!"); abort();
4178 case Instruction::Add:
4179 case Instruction::Sub:
4180 case Instruction::Or:
4181 case Instruction::Xor:
4182 return Constant::getNullValue(I->getType());
4183 case Instruction::Shl:
4184 case Instruction::Shr:
4185 return Constant::getNullValue(Type::UByteTy);
4186 case Instruction::And:
4187 return ConstantInt::getAllOnesValue(I->getType());
4188 case Instruction::Mul:
4189 return ConstantInt::get(I->getType(), 1);
4193 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4194 /// have the same opcode and only one use each. Try to simplify this.
4195 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4197 if (TI->getNumOperands() == 1) {
4198 // If this is a non-volatile load or a cast from the same type,
4200 if (TI->getOpcode() == Instruction::Cast) {
4201 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4204 return 0; // unknown unary op.
4207 // Fold this by inserting a select from the input values.
4208 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4209 FI->getOperand(0), SI.getName()+".v");
4210 InsertNewInstBefore(NewSI, SI);
4211 return new CastInst(NewSI, TI->getType());
4214 // Only handle binary operators here.
4215 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4218 // Figure out if the operations have any operands in common.
4219 Value *MatchOp, *OtherOpT, *OtherOpF;
4221 if (TI->getOperand(0) == FI->getOperand(0)) {
4222 MatchOp = TI->getOperand(0);
4223 OtherOpT = TI->getOperand(1);
4224 OtherOpF = FI->getOperand(1);
4225 MatchIsOpZero = true;
4226 } else if (TI->getOperand(1) == FI->getOperand(1)) {
4227 MatchOp = TI->getOperand(1);
4228 OtherOpT = TI->getOperand(0);
4229 OtherOpF = FI->getOperand(0);
4230 MatchIsOpZero = false;
4231 } else if (!TI->isCommutative()) {
4233 } else if (TI->getOperand(0) == FI->getOperand(1)) {
4234 MatchOp = TI->getOperand(0);
4235 OtherOpT = TI->getOperand(1);
4236 OtherOpF = FI->getOperand(0);
4237 MatchIsOpZero = true;
4238 } else if (TI->getOperand(1) == FI->getOperand(0)) {
4239 MatchOp = TI->getOperand(1);
4240 OtherOpT = TI->getOperand(0);
4241 OtherOpF = FI->getOperand(1);
4242 MatchIsOpZero = true;
4247 // If we reach here, they do have operations in common.
4248 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4249 OtherOpF, SI.getName()+".v");
4250 InsertNewInstBefore(NewSI, SI);
4252 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4254 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
4256 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
4259 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
4261 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
4265 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
4266 Value *CondVal = SI.getCondition();
4267 Value *TrueVal = SI.getTrueValue();
4268 Value *FalseVal = SI.getFalseValue();
4270 // select true, X, Y -> X
4271 // select false, X, Y -> Y
4272 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
4273 if (C == ConstantBool::True)
4274 return ReplaceInstUsesWith(SI, TrueVal);
4276 assert(C == ConstantBool::False);
4277 return ReplaceInstUsesWith(SI, FalseVal);
4280 // select C, X, X -> X
4281 if (TrueVal == FalseVal)
4282 return ReplaceInstUsesWith(SI, TrueVal);
4284 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
4285 return ReplaceInstUsesWith(SI, FalseVal);
4286 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
4287 return ReplaceInstUsesWith(SI, TrueVal);
4288 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
4289 if (isa<Constant>(TrueVal))
4290 return ReplaceInstUsesWith(SI, TrueVal);
4292 return ReplaceInstUsesWith(SI, FalseVal);
4295 if (SI.getType() == Type::BoolTy)
4296 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
4297 if (C == ConstantBool::True) {
4298 // Change: A = select B, true, C --> A = or B, C
4299 return BinaryOperator::createOr(CondVal, FalseVal);
4301 // Change: A = select B, false, C --> A = and !B, C
4303 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4304 "not."+CondVal->getName()), SI);
4305 return BinaryOperator::createAnd(NotCond, FalseVal);
4307 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
4308 if (C == ConstantBool::False) {
4309 // Change: A = select B, C, false --> A = and B, C
4310 return BinaryOperator::createAnd(CondVal, TrueVal);
4312 // Change: A = select B, C, true --> A = or !B, C
4314 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4315 "not."+CondVal->getName()), SI);
4316 return BinaryOperator::createOr(NotCond, TrueVal);
4320 // Selecting between two integer constants?
4321 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
4322 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
4323 // select C, 1, 0 -> cast C to int
4324 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
4325 return new CastInst(CondVal, SI.getType());
4326 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
4327 // select C, 0, 1 -> cast !C to int
4329 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4330 "not."+CondVal->getName()), SI);
4331 return new CastInst(NotCond, SI.getType());
4334 // If one of the constants is zero (we know they can't both be) and we
4335 // have a setcc instruction with zero, and we have an 'and' with the
4336 // non-constant value, eliminate this whole mess. This corresponds to
4337 // cases like this: ((X & 27) ? 27 : 0)
4338 if (TrueValC->isNullValue() || FalseValC->isNullValue())
4339 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
4340 if ((IC->getOpcode() == Instruction::SetEQ ||
4341 IC->getOpcode() == Instruction::SetNE) &&
4342 isa<ConstantInt>(IC->getOperand(1)) &&
4343 cast<Constant>(IC->getOperand(1))->isNullValue())
4344 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
4345 if (ICA->getOpcode() == Instruction::And &&
4346 isa<ConstantInt>(ICA->getOperand(1)) &&
4347 (ICA->getOperand(1) == TrueValC ||
4348 ICA->getOperand(1) == FalseValC) &&
4349 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
4350 // Okay, now we know that everything is set up, we just don't
4351 // know whether we have a setne or seteq and whether the true or
4352 // false val is the zero.
4353 bool ShouldNotVal = !TrueValC->isNullValue();
4354 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
4357 V = InsertNewInstBefore(BinaryOperator::create(
4358 Instruction::Xor, V, ICA->getOperand(1)), SI);
4359 return ReplaceInstUsesWith(SI, V);
4363 // See if we are selecting two values based on a comparison of the two values.
4364 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
4365 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
4366 // Transform (X == Y) ? X : Y -> Y
4367 if (SCI->getOpcode() == Instruction::SetEQ)
4368 return ReplaceInstUsesWith(SI, FalseVal);
4369 // Transform (X != Y) ? X : Y -> X
4370 if (SCI->getOpcode() == Instruction::SetNE)
4371 return ReplaceInstUsesWith(SI, TrueVal);
4372 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4374 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
4375 // Transform (X == Y) ? Y : X -> X
4376 if (SCI->getOpcode() == Instruction::SetEQ)
4377 return ReplaceInstUsesWith(SI, FalseVal);
4378 // Transform (X != Y) ? Y : X -> Y
4379 if (SCI->getOpcode() == Instruction::SetNE)
4380 return ReplaceInstUsesWith(SI, TrueVal);
4381 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4385 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
4386 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
4387 if (TI->hasOneUse() && FI->hasOneUse()) {
4388 bool isInverse = false;
4389 Instruction *AddOp = 0, *SubOp = 0;
4391 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
4392 if (TI->getOpcode() == FI->getOpcode())
4393 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
4396 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
4397 // even legal for FP.
4398 if (TI->getOpcode() == Instruction::Sub &&
4399 FI->getOpcode() == Instruction::Add) {
4400 AddOp = FI; SubOp = TI;
4401 } else if (FI->getOpcode() == Instruction::Sub &&
4402 TI->getOpcode() == Instruction::Add) {
4403 AddOp = TI; SubOp = FI;
4407 Value *OtherAddOp = 0;
4408 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
4409 OtherAddOp = AddOp->getOperand(1);
4410 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
4411 OtherAddOp = AddOp->getOperand(0);
4415 // So at this point we know we have:
4416 // select C, (add X, Y), (sub X, ?)
4417 // We can do the transform profitably if either 'Y' = '?' or '?' is
4419 if (SubOp->getOperand(1) == AddOp ||
4420 isa<Constant>(SubOp->getOperand(1))) {
4422 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
4423 NegVal = ConstantExpr::getNeg(C);
4425 NegVal = InsertNewInstBefore(
4426 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
4429 Value *NewTrueOp = OtherAddOp;
4430 Value *NewFalseOp = NegVal;
4432 std::swap(NewTrueOp, NewFalseOp);
4433 Instruction *NewSel =
4434 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
4436 NewSel = InsertNewInstBefore(NewSel, SI);
4437 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
4443 // See if we can fold the select into one of our operands.
4444 if (SI.getType()->isInteger()) {
4445 // See the comment above GetSelectFoldableOperands for a description of the
4446 // transformation we are doing here.
4447 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
4448 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
4449 !isa<Constant>(FalseVal))
4450 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
4451 unsigned OpToFold = 0;
4452 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
4454 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
4459 Constant *C = GetSelectFoldableConstant(TVI);
4460 std::string Name = TVI->getName(); TVI->setName("");
4461 Instruction *NewSel =
4462 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
4464 InsertNewInstBefore(NewSel, SI);
4465 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
4466 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
4467 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
4468 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
4470 assert(0 && "Unknown instruction!!");
4475 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
4476 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4477 !isa<Constant>(TrueVal))
4478 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4479 unsigned OpToFold = 0;
4480 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4482 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4487 Constant *C = GetSelectFoldableConstant(FVI);
4488 std::string Name = FVI->getName(); FVI->setName("");
4489 Instruction *NewSel =
4490 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
4492 InsertNewInstBefore(NewSel, SI);
4493 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4494 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
4495 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
4496 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
4498 assert(0 && "Unknown instruction!!");
4504 if (BinaryOperator::isNot(CondVal)) {
4505 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
4506 SI.setOperand(1, FalseVal);
4507 SI.setOperand(2, TrueVal);
4515 // CallInst simplification
4517 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
4518 // Intrinsics cannot occur in an invoke, so handle them here instead of in
4520 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
4521 bool Changed = false;
4523 // memmove/cpy/set of zero bytes is a noop.
4524 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4525 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4527 // FIXME: Increase alignment here.
4529 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4530 if (CI->getRawValue() == 1) {
4531 // Replace the instruction with just byte operations. We would
4532 // transform other cases to loads/stores, but we don't know if
4533 // alignment is sufficient.
4537 // If we have a memmove and the source operation is a constant global,
4538 // then the source and dest pointers can't alias, so we can change this
4539 // into a call to memcpy.
4540 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
4541 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4542 if (GVSrc->isConstant()) {
4543 Module *M = CI.getParent()->getParent()->getParent();
4544 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
4545 CI.getCalledFunction()->getFunctionType());
4546 CI.setOperand(0, MemCpy);
4550 if (Changed) return &CI;
4551 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
4552 // If this stoppoint is at the same source location as the previous
4553 // stoppoint in the chain, it is not needed.
4554 if (DbgStopPointInst *PrevSPI =
4555 dyn_cast<DbgStopPointInst>(SPI->getChain()))
4556 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
4557 SPI->getColNo() == PrevSPI->getColNo()) {
4558 SPI->replaceAllUsesWith(PrevSPI);
4559 return EraseInstFromFunction(CI);
4563 return visitCallSite(&CI);
4566 // InvokeInst simplification
4568 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
4569 return visitCallSite(&II);
4572 // visitCallSite - Improvements for call and invoke instructions.
4574 Instruction *InstCombiner::visitCallSite(CallSite CS) {
4575 bool Changed = false;
4577 // If the callee is a constexpr cast of a function, attempt to move the cast
4578 // to the arguments of the call/invoke.
4579 if (transformConstExprCastCall(CS)) return 0;
4581 Value *Callee = CS.getCalledValue();
4583 if (Function *CalleeF = dyn_cast<Function>(Callee))
4584 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4585 Instruction *OldCall = CS.getInstruction();
4586 // If the call and callee calling conventions don't match, this call must
4587 // be unreachable, as the call is undefined.
4588 new StoreInst(ConstantBool::True,
4589 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
4590 if (!OldCall->use_empty())
4591 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
4592 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4593 return EraseInstFromFunction(*OldCall);
4597 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4598 // This instruction is not reachable, just remove it. We insert a store to
4599 // undef so that we know that this code is not reachable, despite the fact
4600 // that we can't modify the CFG here.
4601 new StoreInst(ConstantBool::True,
4602 UndefValue::get(PointerType::get(Type::BoolTy)),
4603 CS.getInstruction());
4605 if (!CS.getInstruction()->use_empty())
4606 CS.getInstruction()->
4607 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
4609 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4610 // Don't break the CFG, insert a dummy cond branch.
4611 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
4612 ConstantBool::True, II);
4614 return EraseInstFromFunction(*CS.getInstruction());
4617 const PointerType *PTy = cast<PointerType>(Callee->getType());
4618 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4619 if (FTy->isVarArg()) {
4620 // See if we can optimize any arguments passed through the varargs area of
4622 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
4623 E = CS.arg_end(); I != E; ++I)
4624 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
4625 // If this cast does not effect the value passed through the varargs
4626 // area, we can eliminate the use of the cast.
4627 Value *Op = CI->getOperand(0);
4628 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
4635 return Changed ? CS.getInstruction() : 0;
4638 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
4639 // attempt to move the cast to the arguments of the call/invoke.
4641 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4642 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4643 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
4644 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
4646 Function *Callee = cast<Function>(CE->getOperand(0));
4647 Instruction *Caller = CS.getInstruction();
4649 // Okay, this is a cast from a function to a different type. Unless doing so
4650 // would cause a type conversion of one of our arguments, change this call to
4651 // be a direct call with arguments casted to the appropriate types.
4653 const FunctionType *FT = Callee->getFunctionType();
4654 const Type *OldRetTy = Caller->getType();
4656 // Check to see if we are changing the return type...
4657 if (OldRetTy != FT->getReturnType()) {
4658 if (Callee->isExternal() &&
4659 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4660 !Caller->use_empty())
4661 return false; // Cannot transform this return value...
4663 // If the callsite is an invoke instruction, and the return value is used by
4664 // a PHI node in a successor, we cannot change the return type of the call
4665 // because there is no place to put the cast instruction (without breaking
4666 // the critical edge). Bail out in this case.
4667 if (!Caller->use_empty())
4668 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
4669 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
4671 if (PHINode *PN = dyn_cast<PHINode>(*UI))
4672 if (PN->getParent() == II->getNormalDest() ||
4673 PN->getParent() == II->getUnwindDest())
4677 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
4678 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
4680 CallSite::arg_iterator AI = CS.arg_begin();
4681 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
4682 const Type *ParamTy = FT->getParamType(i);
4683 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
4684 if (Callee->isExternal() && !isConvertible) return false;
4687 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
4688 Callee->isExternal())
4689 return false; // Do not delete arguments unless we have a function body...
4691 // Okay, we decided that this is a safe thing to do: go ahead and start
4692 // inserting cast instructions as necessary...
4693 std::vector<Value*> Args;
4694 Args.reserve(NumActualArgs);
4696 AI = CS.arg_begin();
4697 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
4698 const Type *ParamTy = FT->getParamType(i);
4699 if ((*AI)->getType() == ParamTy) {
4700 Args.push_back(*AI);
4702 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
4707 // If the function takes more arguments than the call was taking, add them
4709 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
4710 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
4712 // If we are removing arguments to the function, emit an obnoxious warning...
4713 if (FT->getNumParams() < NumActualArgs)
4714 if (!FT->isVarArg()) {
4715 std::cerr << "WARNING: While resolving call to function '"
4716 << Callee->getName() << "' arguments were dropped!\n";
4718 // Add all of the arguments in their promoted form to the arg list...
4719 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
4720 const Type *PTy = getPromotedType((*AI)->getType());
4721 if (PTy != (*AI)->getType()) {
4722 // Must promote to pass through va_arg area!
4723 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
4724 InsertNewInstBefore(Cast, *Caller);
4725 Args.push_back(Cast);
4727 Args.push_back(*AI);
4732 if (FT->getReturnType() == Type::VoidTy)
4733 Caller->setName(""); // Void type should not have a name...
4736 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4737 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
4738 Args, Caller->getName(), Caller);
4739 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
4741 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
4742 if (cast<CallInst>(Caller)->isTailCall())
4743 cast<CallInst>(NC)->setTailCall();
4744 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
4747 // Insert a cast of the return type as necessary...
4749 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
4750 if (NV->getType() != Type::VoidTy) {
4751 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
4753 // If this is an invoke instruction, we should insert it after the first
4754 // non-phi, instruction in the normal successor block.
4755 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
4756 BasicBlock::iterator I = II->getNormalDest()->begin();
4757 while (isa<PHINode>(I)) ++I;
4758 InsertNewInstBefore(NC, *I);
4760 // Otherwise, it's a call, just insert cast right after the call instr
4761 InsertNewInstBefore(NC, *Caller);
4763 AddUsersToWorkList(*Caller);
4765 NV = UndefValue::get(Caller->getType());
4769 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
4770 Caller->replaceAllUsesWith(NV);
4771 Caller->getParent()->getInstList().erase(Caller);
4772 removeFromWorkList(Caller);
4777 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
4778 // operator and they all are only used by the PHI, PHI together their
4779 // inputs, and do the operation once, to the result of the PHI.
4780 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
4781 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
4783 // Scan the instruction, looking for input operations that can be folded away.
4784 // If all input operands to the phi are the same instruction (e.g. a cast from
4785 // the same type or "+42") we can pull the operation through the PHI, reducing
4786 // code size and simplifying code.
4787 Constant *ConstantOp = 0;
4788 const Type *CastSrcTy = 0;
4789 if (isa<CastInst>(FirstInst)) {
4790 CastSrcTy = FirstInst->getOperand(0)->getType();
4791 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
4792 // Can fold binop or shift if the RHS is a constant.
4793 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
4794 if (ConstantOp == 0) return 0;
4796 return 0; // Cannot fold this operation.
4799 // Check to see if all arguments are the same operation.
4800 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4801 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
4802 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
4803 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
4806 if (I->getOperand(0)->getType() != CastSrcTy)
4807 return 0; // Cast operation must match.
4808 } else if (I->getOperand(1) != ConstantOp) {
4813 // Okay, they are all the same operation. Create a new PHI node of the
4814 // correct type, and PHI together all of the LHS's of the instructions.
4815 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
4816 PN.getName()+".in");
4817 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
4819 Value *InVal = FirstInst->getOperand(0);
4820 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
4822 // Add all operands to the new PHI.
4823 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
4824 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
4825 if (NewInVal != InVal)
4827 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
4832 // The new PHI unions all of the same values together. This is really
4833 // common, so we handle it intelligently here for compile-time speed.
4837 InsertNewInstBefore(NewPN, PN);
4841 // Insert and return the new operation.
4842 if (isa<CastInst>(FirstInst))
4843 return new CastInst(PhiVal, PN.getType());
4844 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
4845 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
4847 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
4848 PhiVal, ConstantOp);
4851 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
4853 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
4854 if (PN->use_empty()) return true;
4855 if (!PN->hasOneUse()) return false;
4857 // Remember this node, and if we find the cycle, return.
4858 if (!PotentiallyDeadPHIs.insert(PN).second)
4861 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
4862 return DeadPHICycle(PU, PotentiallyDeadPHIs);
4867 // PHINode simplification
4869 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
4870 if (Value *V = PN.hasConstantValue())
4871 return ReplaceInstUsesWith(PN, V);
4873 // If the only user of this instruction is a cast instruction, and all of the
4874 // incoming values are constants, change this PHI to merge together the casted
4877 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
4878 if (CI->getType() != PN.getType()) { // noop casts will be folded
4879 bool AllConstant = true;
4880 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
4881 if (!isa<Constant>(PN.getIncomingValue(i))) {
4882 AllConstant = false;
4886 // Make a new PHI with all casted values.
4887 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
4888 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
4889 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
4890 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
4891 PN.getIncomingBlock(i));
4894 // Update the cast instruction.
4895 CI->setOperand(0, New);
4896 WorkList.push_back(CI); // revisit the cast instruction to fold.
4897 WorkList.push_back(New); // Make sure to revisit the new Phi
4898 return &PN; // PN is now dead!
4902 // If all PHI operands are the same operation, pull them through the PHI,
4903 // reducing code size.
4904 if (isa<Instruction>(PN.getIncomingValue(0)) &&
4905 PN.getIncomingValue(0)->hasOneUse())
4906 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
4909 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
4910 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
4911 // PHI)... break the cycle.
4913 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
4914 std::set<PHINode*> PotentiallyDeadPHIs;
4915 PotentiallyDeadPHIs.insert(&PN);
4916 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
4917 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
4923 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
4924 Instruction *InsertPoint,
4926 unsigned PS = IC->getTargetData().getPointerSize();
4927 const Type *VTy = V->getType();
4928 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
4929 // We must insert a cast to ensure we sign-extend.
4930 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
4931 V->getName()), *InsertPoint);
4932 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
4937 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
4938 Value *PtrOp = GEP.getOperand(0);
4939 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
4940 // If so, eliminate the noop.
4941 if (GEP.getNumOperands() == 1)
4942 return ReplaceInstUsesWith(GEP, PtrOp);
4944 if (isa<UndefValue>(GEP.getOperand(0)))
4945 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
4947 bool HasZeroPointerIndex = false;
4948 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
4949 HasZeroPointerIndex = C->isNullValue();
4951 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
4952 return ReplaceInstUsesWith(GEP, PtrOp);
4954 // Eliminate unneeded casts for indices.
4955 bool MadeChange = false;
4956 gep_type_iterator GTI = gep_type_begin(GEP);
4957 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
4958 if (isa<SequentialType>(*GTI)) {
4959 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
4960 Value *Src = CI->getOperand(0);
4961 const Type *SrcTy = Src->getType();
4962 const Type *DestTy = CI->getType();
4963 if (Src->getType()->isInteger()) {
4964 if (SrcTy->getPrimitiveSizeInBits() ==
4965 DestTy->getPrimitiveSizeInBits()) {
4966 // We can always eliminate a cast from ulong or long to the other.
4967 // We can always eliminate a cast from uint to int or the other on
4968 // 32-bit pointer platforms.
4969 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
4971 GEP.setOperand(i, Src);
4973 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
4974 SrcTy->getPrimitiveSize() == 4) {
4975 // We can always eliminate a cast from int to [u]long. We can
4976 // eliminate a cast from uint to [u]long iff the target is a 32-bit
4978 if (SrcTy->isSigned() ||
4979 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
4981 GEP.setOperand(i, Src);
4986 // If we are using a wider index than needed for this platform, shrink it
4987 // to what we need. If the incoming value needs a cast instruction,
4988 // insert it. This explicit cast can make subsequent optimizations more
4990 Value *Op = GEP.getOperand(i);
4991 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
4992 if (Constant *C = dyn_cast<Constant>(Op)) {
4993 GEP.setOperand(i, ConstantExpr::getCast(C,
4994 TD->getIntPtrType()->getSignedVersion()));
4997 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
4998 Op->getName()), GEP);
4999 GEP.setOperand(i, Op);
5003 // If this is a constant idx, make sure to canonicalize it to be a signed
5004 // operand, otherwise CSE and other optimizations are pessimized.
5005 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5006 GEP.setOperand(i, ConstantExpr::getCast(CUI,
5007 CUI->getType()->getSignedVersion()));
5011 if (MadeChange) return &GEP;
5013 // Combine Indices - If the source pointer to this getelementptr instruction
5014 // is a getelementptr instruction, combine the indices of the two
5015 // getelementptr instructions into a single instruction.
5017 std::vector<Value*> SrcGEPOperands;
5018 if (User *Src = dyn_castGetElementPtr(PtrOp))
5019 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
5021 if (!SrcGEPOperands.empty()) {
5022 // Note that if our source is a gep chain itself that we wait for that
5023 // chain to be resolved before we perform this transformation. This
5024 // avoids us creating a TON of code in some cases.
5026 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
5027 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
5028 return 0; // Wait until our source is folded to completion.
5030 std::vector<Value *> Indices;
5032 // Find out whether the last index in the source GEP is a sequential idx.
5033 bool EndsWithSequential = false;
5034 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
5035 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
5036 EndsWithSequential = !isa<StructType>(*I);
5038 // Can we combine the two pointer arithmetics offsets?
5039 if (EndsWithSequential) {
5040 // Replace: gep (gep %P, long B), long A, ...
5041 // With: T = long A+B; gep %P, T, ...
5043 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
5044 if (SO1 == Constant::getNullValue(SO1->getType())) {
5046 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
5049 // If they aren't the same type, convert both to an integer of the
5050 // target's pointer size.
5051 if (SO1->getType() != GO1->getType()) {
5052 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
5053 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
5054 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
5055 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
5057 unsigned PS = TD->getPointerSize();
5058 if (SO1->getType()->getPrimitiveSize() == PS) {
5059 // Convert GO1 to SO1's type.
5060 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
5062 } else if (GO1->getType()->getPrimitiveSize() == PS) {
5063 // Convert SO1 to GO1's type.
5064 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
5066 const Type *PT = TD->getIntPtrType();
5067 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
5068 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
5072 if (isa<Constant>(SO1) && isa<Constant>(GO1))
5073 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
5075 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
5076 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
5080 // Recycle the GEP we already have if possible.
5081 if (SrcGEPOperands.size() == 2) {
5082 GEP.setOperand(0, SrcGEPOperands[0]);
5083 GEP.setOperand(1, Sum);
5086 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5087 SrcGEPOperands.end()-1);
5088 Indices.push_back(Sum);
5089 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
5091 } else if (isa<Constant>(*GEP.idx_begin()) &&
5092 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
5093 SrcGEPOperands.size() != 1) {
5094 // Otherwise we can do the fold if the first index of the GEP is a zero
5095 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5096 SrcGEPOperands.end());
5097 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
5100 if (!Indices.empty())
5101 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
5103 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
5104 // GEP of global variable. If all of the indices for this GEP are
5105 // constants, we can promote this to a constexpr instead of an instruction.
5107 // Scan for nonconstants...
5108 std::vector<Constant*> Indices;
5109 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
5110 for (; I != E && isa<Constant>(*I); ++I)
5111 Indices.push_back(cast<Constant>(*I));
5113 if (I == E) { // If they are all constants...
5114 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
5116 // Replace all uses of the GEP with the new constexpr...
5117 return ReplaceInstUsesWith(GEP, CE);
5119 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
5120 if (!isa<PointerType>(X->getType())) {
5121 // Not interesting. Source pointer must be a cast from pointer.
5122 } else if (HasZeroPointerIndex) {
5123 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
5124 // into : GEP [10 x ubyte]* X, long 0, ...
5126 // This occurs when the program declares an array extern like "int X[];"
5128 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
5129 const PointerType *XTy = cast<PointerType>(X->getType());
5130 if (const ArrayType *XATy =
5131 dyn_cast<ArrayType>(XTy->getElementType()))
5132 if (const ArrayType *CATy =
5133 dyn_cast<ArrayType>(CPTy->getElementType()))
5134 if (CATy->getElementType() == XATy->getElementType()) {
5135 // At this point, we know that the cast source type is a pointer
5136 // to an array of the same type as the destination pointer
5137 // array. Because the array type is never stepped over (there
5138 // is a leading zero) we can fold the cast into this GEP.
5139 GEP.setOperand(0, X);
5142 } else if (GEP.getNumOperands() == 2) {
5143 // Transform things like:
5144 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5145 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
5146 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5147 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5148 if (isa<ArrayType>(SrcElTy) &&
5149 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5150 TD->getTypeSize(ResElTy)) {
5151 Value *V = InsertNewInstBefore(
5152 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5153 GEP.getOperand(1), GEP.getName()), GEP);
5154 return new CastInst(V, GEP.getType());
5157 // Transform things like:
5158 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5159 // (where tmp = 8*tmp2) into:
5160 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5162 if (isa<ArrayType>(SrcElTy) &&
5163 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5164 uint64_t ArrayEltSize =
5165 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5167 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
5168 // allow either a mul, shift, or constant here.
5170 ConstantInt *Scale = 0;
5171 if (ArrayEltSize == 1) {
5172 NewIdx = GEP.getOperand(1);
5173 Scale = ConstantInt::get(NewIdx->getType(), 1);
5174 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
5175 NewIdx = ConstantInt::get(CI->getType(), 1);
5177 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5178 if (Inst->getOpcode() == Instruction::Shl &&
5179 isa<ConstantInt>(Inst->getOperand(1))) {
5180 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5181 if (Inst->getType()->isSigned())
5182 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5184 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5185 NewIdx = Inst->getOperand(0);
5186 } else if (Inst->getOpcode() == Instruction::Mul &&
5187 isa<ConstantInt>(Inst->getOperand(1))) {
5188 Scale = cast<ConstantInt>(Inst->getOperand(1));
5189 NewIdx = Inst->getOperand(0);
5193 // If the index will be to exactly the right offset with the scale taken
5194 // out, perform the transformation.
5195 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5196 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5197 Scale = ConstantSInt::get(C->getType(),
5198 (int64_t)C->getRawValue() /
5199 (int64_t)ArrayEltSize);
5201 Scale = ConstantUInt::get(Scale->getType(),
5202 Scale->getRawValue() / ArrayEltSize);
5203 if (Scale->getRawValue() != 1) {
5204 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5205 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5206 NewIdx = InsertNewInstBefore(Sc, GEP);
5209 // Insert the new GEP instruction.
5211 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5212 NewIdx, GEP.getName());
5213 Idx = InsertNewInstBefore(Idx, GEP);
5214 return new CastInst(Idx, GEP.getType());
5223 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
5224 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
5225 if (AI.isArrayAllocation()) // Check C != 1
5226 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
5227 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
5228 AllocationInst *New = 0;
5230 // Create and insert the replacement instruction...
5231 if (isa<MallocInst>(AI))
5232 New = new MallocInst(NewTy, 0, AI.getName());
5234 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
5235 New = new AllocaInst(NewTy, 0, AI.getName());
5238 InsertNewInstBefore(New, AI);
5240 // Scan to the end of the allocation instructions, to skip over a block of
5241 // allocas if possible...
5243 BasicBlock::iterator It = New;
5244 while (isa<AllocationInst>(*It)) ++It;
5246 // Now that I is pointing to the first non-allocation-inst in the block,
5247 // insert our getelementptr instruction...
5249 Value *NullIdx = Constant::getNullValue(Type::IntTy);
5250 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
5251 New->getName()+".sub", It);
5253 // Now make everything use the getelementptr instead of the original
5255 return ReplaceInstUsesWith(AI, V);
5256 } else if (isa<UndefValue>(AI.getArraySize())) {
5257 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5260 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
5261 // Note that we only do this for alloca's, because malloc should allocate and
5262 // return a unique pointer, even for a zero byte allocation.
5263 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
5264 TD->getTypeSize(AI.getAllocatedType()) == 0)
5265 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5270 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
5271 Value *Op = FI.getOperand(0);
5273 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
5274 if (CastInst *CI = dyn_cast<CastInst>(Op))
5275 if (isa<PointerType>(CI->getOperand(0)->getType())) {
5276 FI.setOperand(0, CI->getOperand(0));
5280 // free undef -> unreachable.
5281 if (isa<UndefValue>(Op)) {
5282 // Insert a new store to null because we cannot modify the CFG here.
5283 new StoreInst(ConstantBool::True,
5284 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
5285 return EraseInstFromFunction(FI);
5288 // If we have 'free null' delete the instruction. This can happen in stl code
5289 // when lots of inlining happens.
5290 if (isa<ConstantPointerNull>(Op))
5291 return EraseInstFromFunction(FI);
5297 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
5298 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
5299 User *CI = cast<User>(LI.getOperand(0));
5300 Value *CastOp = CI->getOperand(0);
5302 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5303 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5304 const Type *SrcPTy = SrcTy->getElementType();
5306 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5307 // If the source is an array, the code below will not succeed. Check to
5308 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5310 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5311 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5312 if (ASrcTy->getNumElements() != 0) {
5313 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5314 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5315 SrcTy = cast<PointerType>(CastOp->getType());
5316 SrcPTy = SrcTy->getElementType();
5319 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
5320 // Do not allow turning this into a load of an integer, which is then
5321 // casted to a pointer, this pessimizes pointer analysis a lot.
5322 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
5323 IC.getTargetData().getTypeSize(SrcPTy) ==
5324 IC.getTargetData().getTypeSize(DestPTy)) {
5326 // Okay, we are casting from one integer or pointer type to another of
5327 // the same size. Instead of casting the pointer before the load, cast
5328 // the result of the loaded value.
5329 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
5331 LI.isVolatile()),LI);
5332 // Now cast the result of the load.
5333 return new CastInst(NewLoad, LI.getType());
5340 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
5341 /// from this value cannot trap. If it is not obviously safe to load from the
5342 /// specified pointer, we do a quick local scan of the basic block containing
5343 /// ScanFrom, to determine if the address is already accessed.
5344 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
5345 // If it is an alloca or global variable, it is always safe to load from.
5346 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
5348 // Otherwise, be a little bit agressive by scanning the local block where we
5349 // want to check to see if the pointer is already being loaded or stored
5350 // from/to. If so, the previous load or store would have already trapped,
5351 // so there is no harm doing an extra load (also, CSE will later eliminate
5352 // the load entirely).
5353 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
5358 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
5359 if (LI->getOperand(0) == V) return true;
5360 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5361 if (SI->getOperand(1) == V) return true;
5367 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
5368 Value *Op = LI.getOperand(0);
5370 // load (cast X) --> cast (load X) iff safe
5371 if (CastInst *CI = dyn_cast<CastInst>(Op))
5372 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5375 // None of the following transforms are legal for volatile loads.
5376 if (LI.isVolatile()) return 0;
5378 if (&LI.getParent()->front() != &LI) {
5379 BasicBlock::iterator BBI = &LI; --BBI;
5380 // If the instruction immediately before this is a store to the same
5381 // address, do a simple form of store->load forwarding.
5382 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5383 if (SI->getOperand(1) == LI.getOperand(0))
5384 return ReplaceInstUsesWith(LI, SI->getOperand(0));
5385 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
5386 if (LIB->getOperand(0) == LI.getOperand(0))
5387 return ReplaceInstUsesWith(LI, LIB);
5390 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
5391 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
5392 isa<UndefValue>(GEPI->getOperand(0))) {
5393 // Insert a new store to null instruction before the load to indicate
5394 // that this code is not reachable. We do this instead of inserting
5395 // an unreachable instruction directly because we cannot modify the
5397 new StoreInst(UndefValue::get(LI.getType()),
5398 Constant::getNullValue(Op->getType()), &LI);
5399 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5402 if (Constant *C = dyn_cast<Constant>(Op)) {
5403 // load null/undef -> undef
5404 if ((C->isNullValue() || isa<UndefValue>(C))) {
5405 // Insert a new store to null instruction before the load to indicate that
5406 // this code is not reachable. We do this instead of inserting an
5407 // unreachable instruction directly because we cannot modify the CFG.
5408 new StoreInst(UndefValue::get(LI.getType()),
5409 Constant::getNullValue(Op->getType()), &LI);
5410 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5413 // Instcombine load (constant global) into the value loaded.
5414 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
5415 if (GV->isConstant() && !GV->isExternal())
5416 return ReplaceInstUsesWith(LI, GV->getInitializer());
5418 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
5419 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
5420 if (CE->getOpcode() == Instruction::GetElementPtr) {
5421 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
5422 if (GV->isConstant() && !GV->isExternal())
5424 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
5425 return ReplaceInstUsesWith(LI, V);
5426 if (CE->getOperand(0)->isNullValue()) {
5427 // Insert a new store to null instruction before the load to indicate
5428 // that this code is not reachable. We do this instead of inserting
5429 // an unreachable instruction directly because we cannot modify the
5431 new StoreInst(UndefValue::get(LI.getType()),
5432 Constant::getNullValue(Op->getType()), &LI);
5433 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5436 } else if (CE->getOpcode() == Instruction::Cast) {
5437 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5442 if (Op->hasOneUse()) {
5443 // Change select and PHI nodes to select values instead of addresses: this
5444 // helps alias analysis out a lot, allows many others simplifications, and
5445 // exposes redundancy in the code.
5447 // Note that we cannot do the transformation unless we know that the
5448 // introduced loads cannot trap! Something like this is valid as long as
5449 // the condition is always false: load (select bool %C, int* null, int* %G),
5450 // but it would not be valid if we transformed it to load from null
5453 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
5454 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
5455 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
5456 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
5457 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
5458 SI->getOperand(1)->getName()+".val"), LI);
5459 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
5460 SI->getOperand(2)->getName()+".val"), LI);
5461 return new SelectInst(SI->getCondition(), V1, V2);
5464 // load (select (cond, null, P)) -> load P
5465 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
5466 if (C->isNullValue()) {
5467 LI.setOperand(0, SI->getOperand(2));
5471 // load (select (cond, P, null)) -> load P
5472 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
5473 if (C->isNullValue()) {
5474 LI.setOperand(0, SI->getOperand(1));
5478 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
5479 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
5480 bool Safe = PN->getParent() == LI.getParent();
5482 // Scan all of the instructions between the PHI and the load to make
5483 // sure there are no instructions that might possibly alter the value
5484 // loaded from the PHI.
5486 BasicBlock::iterator I = &LI;
5487 for (--I; !isa<PHINode>(I); --I)
5488 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
5494 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
5495 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
5496 PN->getIncomingBlock(i)->getTerminator()))
5501 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
5502 InsertNewInstBefore(NewPN, *PN);
5503 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
5505 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5506 BasicBlock *BB = PN->getIncomingBlock(i);
5507 Value *&TheLoad = LoadMap[BB];
5509 Value *InVal = PN->getIncomingValue(i);
5510 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
5511 InVal->getName()+".val"),
5512 *BB->getTerminator());
5514 NewPN->addIncoming(TheLoad, BB);
5516 return ReplaceInstUsesWith(LI, NewPN);
5523 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
5525 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
5526 User *CI = cast<User>(SI.getOperand(1));
5527 Value *CastOp = CI->getOperand(0);
5529 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5530 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5531 const Type *SrcPTy = SrcTy->getElementType();
5533 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5534 // If the source is an array, the code below will not succeed. Check to
5535 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5537 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5538 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5539 if (ASrcTy->getNumElements() != 0) {
5540 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5541 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5542 SrcTy = cast<PointerType>(CastOp->getType());
5543 SrcPTy = SrcTy->getElementType();
5546 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
5547 IC.getTargetData().getTypeSize(SrcPTy) ==
5548 IC.getTargetData().getTypeSize(DestPTy)) {
5550 // Okay, we are casting from one integer or pointer type to another of
5551 // the same size. Instead of casting the pointer before the store, cast
5552 // the value to be stored.
5554 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
5555 NewCast = ConstantExpr::getCast(C, SrcPTy);
5557 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
5559 SI.getOperand(0)->getName()+".c"), SI);
5561 return new StoreInst(NewCast, CastOp);
5568 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
5569 Value *Val = SI.getOperand(0);
5570 Value *Ptr = SI.getOperand(1);
5572 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
5573 removeFromWorkList(&SI);
5574 SI.eraseFromParent();
5579 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
5581 // store X, null -> turns into 'unreachable' in SimplifyCFG
5582 if (isa<ConstantPointerNull>(Ptr)) {
5583 if (!isa<UndefValue>(Val)) {
5584 SI.setOperand(0, UndefValue::get(Val->getType()));
5585 if (Instruction *U = dyn_cast<Instruction>(Val))
5586 WorkList.push_back(U); // Dropped a use.
5589 return 0; // Do not modify these!
5592 // store undef, Ptr -> noop
5593 if (isa<UndefValue>(Val)) {
5594 removeFromWorkList(&SI);
5595 SI.eraseFromParent();
5600 // If the pointer destination is a cast, see if we can fold the cast into the
5602 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
5603 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5605 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
5606 if (CE->getOpcode() == Instruction::Cast)
5607 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5611 // If this store is the last instruction in the basic block, and if the block
5612 // ends with an unconditional branch, try to move it to the successor block.
5613 BasicBlock::iterator BBI = &SI; ++BBI;
5614 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
5615 if (BI->isUnconditional()) {
5616 // Check to see if the successor block has exactly two incoming edges. If
5617 // so, see if the other predecessor contains a store to the same location.
5618 // if so, insert a PHI node (if needed) and move the stores down.
5619 BasicBlock *Dest = BI->getSuccessor(0);
5621 pred_iterator PI = pred_begin(Dest);
5622 BasicBlock *Other = 0;
5623 if (*PI != BI->getParent())
5626 if (PI != pred_end(Dest)) {
5627 if (*PI != BI->getParent())
5632 if (++PI != pred_end(Dest))
5635 if (Other) { // If only one other pred...
5636 BBI = Other->getTerminator();
5637 // Make sure this other block ends in an unconditional branch and that
5638 // there is an instruction before the branch.
5639 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
5640 BBI != Other->begin()) {
5642 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
5644 // If this instruction is a store to the same location.
5645 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
5646 // Okay, we know we can perform this transformation. Insert a PHI
5647 // node now if we need it.
5648 Value *MergedVal = OtherStore->getOperand(0);
5649 if (MergedVal != SI.getOperand(0)) {
5650 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
5651 PN->reserveOperandSpace(2);
5652 PN->addIncoming(SI.getOperand(0), SI.getParent());
5653 PN->addIncoming(OtherStore->getOperand(0), Other);
5654 MergedVal = InsertNewInstBefore(PN, Dest->front());
5657 // Advance to a place where it is safe to insert the new store and
5659 BBI = Dest->begin();
5660 while (isa<PHINode>(BBI)) ++BBI;
5661 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
5662 OtherStore->isVolatile()), *BBI);
5664 // Nuke the old stores.
5665 removeFromWorkList(&SI);
5666 removeFromWorkList(OtherStore);
5667 SI.eraseFromParent();
5668 OtherStore->eraseFromParent();
5680 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
5681 // Change br (not X), label True, label False to: br X, label False, True
5683 BasicBlock *TrueDest;
5684 BasicBlock *FalseDest;
5685 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
5686 !isa<Constant>(X)) {
5687 // Swap Destinations and condition...
5689 BI.setSuccessor(0, FalseDest);
5690 BI.setSuccessor(1, TrueDest);
5694 // Cannonicalize setne -> seteq
5695 Instruction::BinaryOps Op; Value *Y;
5696 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
5697 TrueDest, FalseDest)))
5698 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
5699 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
5700 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
5701 std::string Name = I->getName(); I->setName("");
5702 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
5703 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
5704 // Swap Destinations and condition...
5705 BI.setCondition(NewSCC);
5706 BI.setSuccessor(0, FalseDest);
5707 BI.setSuccessor(1, TrueDest);
5708 removeFromWorkList(I);
5709 I->getParent()->getInstList().erase(I);
5710 WorkList.push_back(cast<Instruction>(NewSCC));
5717 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
5718 Value *Cond = SI.getCondition();
5719 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
5720 if (I->getOpcode() == Instruction::Add)
5721 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
5722 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
5723 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
5724 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
5726 SI.setOperand(0, I->getOperand(0));
5727 WorkList.push_back(I);
5734 void InstCombiner::removeFromWorkList(Instruction *I) {
5735 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
5740 /// TryToSinkInstruction - Try to move the specified instruction from its
5741 /// current block into the beginning of DestBlock, which can only happen if it's
5742 /// safe to move the instruction past all of the instructions between it and the
5743 /// end of its block.
5744 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
5745 assert(I->hasOneUse() && "Invariants didn't hold!");
5747 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
5748 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
5750 // Do not sink alloca instructions out of the entry block.
5751 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
5754 // We can only sink load instructions if there is nothing between the load and
5755 // the end of block that could change the value.
5756 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
5757 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
5759 if (Scan->mayWriteToMemory())
5763 BasicBlock::iterator InsertPos = DestBlock->begin();
5764 while (isa<PHINode>(InsertPos)) ++InsertPos;
5766 I->moveBefore(InsertPos);
5771 bool InstCombiner::runOnFunction(Function &F) {
5772 bool Changed = false;
5773 TD = &getAnalysis<TargetData>();
5776 // Populate the worklist with the reachable instructions.
5777 std::set<BasicBlock*> Visited;
5778 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
5779 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
5780 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
5781 WorkList.push_back(I);
5783 // Do a quick scan over the function. If we find any blocks that are
5784 // unreachable, remove any instructions inside of them. This prevents
5785 // the instcombine code from having to deal with some bad special cases.
5786 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
5787 if (!Visited.count(BB)) {
5788 Instruction *Term = BB->getTerminator();
5789 while (Term != BB->begin()) { // Remove instrs bottom-up
5790 BasicBlock::iterator I = Term; --I;
5792 DEBUG(std::cerr << "IC: DCE: " << *I);
5795 if (!I->use_empty())
5796 I->replaceAllUsesWith(UndefValue::get(I->getType()));
5797 I->eraseFromParent();
5802 while (!WorkList.empty()) {
5803 Instruction *I = WorkList.back(); // Get an instruction from the worklist
5804 WorkList.pop_back();
5806 // Check to see if we can DCE or ConstantPropagate the instruction...
5807 // Check to see if we can DIE the instruction...
5808 if (isInstructionTriviallyDead(I)) {
5809 // Add operands to the worklist...
5810 if (I->getNumOperands() < 4)
5811 AddUsesToWorkList(*I);
5814 DEBUG(std::cerr << "IC: DCE: " << *I);
5816 I->eraseFromParent();
5817 removeFromWorkList(I);
5821 // Instruction isn't dead, see if we can constant propagate it...
5822 if (Constant *C = ConstantFoldInstruction(I)) {
5823 Value* Ptr = I->getOperand(0);
5824 if (isa<GetElementPtrInst>(I) &&
5825 cast<Constant>(Ptr)->isNullValue() &&
5826 !isa<ConstantPointerNull>(C) &&
5827 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
5828 // If this is a constant expr gep that is effectively computing an
5829 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
5830 bool isFoldableGEP = true;
5831 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
5832 if (!isa<ConstantInt>(I->getOperand(i)))
5833 isFoldableGEP = false;
5834 if (isFoldableGEP) {
5835 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
5836 std::vector<Value*>(I->op_begin()+1, I->op_end()));
5837 C = ConstantUInt::get(Type::ULongTy, Offset);
5838 C = ConstantExpr::getCast(C, TD->getIntPtrType());
5839 C = ConstantExpr::getCast(C, I->getType());
5843 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
5845 // Add operands to the worklist...
5846 AddUsesToWorkList(*I);
5847 ReplaceInstUsesWith(*I, C);
5850 I->getParent()->getInstList().erase(I);
5851 removeFromWorkList(I);
5855 // See if we can trivially sink this instruction to a successor basic block.
5856 if (I->hasOneUse()) {
5857 BasicBlock *BB = I->getParent();
5858 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
5859 if (UserParent != BB) {
5860 bool UserIsSuccessor = false;
5861 // See if the user is one of our successors.
5862 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
5863 if (*SI == UserParent) {
5864 UserIsSuccessor = true;
5868 // If the user is one of our immediate successors, and if that successor
5869 // only has us as a predecessors (we'd have to split the critical edge
5870 // otherwise), we can keep going.
5871 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
5872 next(pred_begin(UserParent)) == pred_end(UserParent))
5873 // Okay, the CFG is simple enough, try to sink this instruction.
5874 Changed |= TryToSinkInstruction(I, UserParent);
5878 // Now that we have an instruction, try combining it to simplify it...
5879 if (Instruction *Result = visit(*I)) {
5881 // Should we replace the old instruction with a new one?
5883 DEBUG(std::cerr << "IC: Old = " << *I
5884 << " New = " << *Result);
5886 // Everything uses the new instruction now.
5887 I->replaceAllUsesWith(Result);
5889 // Push the new instruction and any users onto the worklist.
5890 WorkList.push_back(Result);
5891 AddUsersToWorkList(*Result);
5893 // Move the name to the new instruction first...
5894 std::string OldName = I->getName(); I->setName("");
5895 Result->setName(OldName);
5897 // Insert the new instruction into the basic block...
5898 BasicBlock *InstParent = I->getParent();
5899 BasicBlock::iterator InsertPos = I;
5901 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
5902 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
5905 InstParent->getInstList().insert(InsertPos, Result);
5907 // Make sure that we reprocess all operands now that we reduced their
5909 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5910 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5911 WorkList.push_back(OpI);
5913 // Instructions can end up on the worklist more than once. Make sure
5914 // we do not process an instruction that has been deleted.
5915 removeFromWorkList(I);
5917 // Erase the old instruction.
5918 InstParent->getInstList().erase(I);
5920 DEBUG(std::cerr << "IC: MOD = " << *I);
5922 // If the instruction was modified, it's possible that it is now dead.
5923 // if so, remove it.
5924 if (isInstructionTriviallyDead(I)) {
5925 // Make sure we process all operands now that we are reducing their
5927 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
5928 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
5929 WorkList.push_back(OpI);
5931 // Instructions may end up in the worklist more than once. Erase all
5932 // occurrances of this instruction.
5933 removeFromWorkList(I);
5934 I->eraseFromParent();
5936 WorkList.push_back(Result);
5937 AddUsersToWorkList(*Result);
5947 FunctionPass *llvm::createInstructionCombiningPass() {
5948 return new InstCombiner();