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"
57 using namespace llvm::PatternMatch;
60 Statistic<> NumCombined ("instcombine", "Number of insts combined");
61 Statistic<> NumConstProp("instcombine", "Number of constant folds");
62 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
63 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
65 class InstCombiner : public FunctionPass,
66 public InstVisitor<InstCombiner, Instruction*> {
67 // Worklist of all of the instructions that need to be simplified.
68 std::vector<Instruction*> WorkList;
71 /// AddUsersToWorkList - When an instruction is simplified, add all users of
72 /// the instruction to the work lists because they might get more simplified
75 void AddUsersToWorkList(Value &I) {
76 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
78 WorkList.push_back(cast<Instruction>(*UI));
81 /// AddUsesToWorkList - When an instruction is simplified, add operands to
82 /// the work lists because they might get more simplified now.
84 void AddUsesToWorkList(Instruction &I) {
85 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
86 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
87 WorkList.push_back(Op);
90 // removeFromWorkList - remove all instances of I from the worklist.
91 void removeFromWorkList(Instruction *I);
93 virtual bool runOnFunction(Function &F);
95 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
96 AU.addRequired<TargetData>();
100 TargetData &getTargetData() const { return *TD; }
102 // Visitation implementation - Implement instruction combining for different
103 // instruction types. The semantics are as follows:
105 // null - No change was made
106 // I - Change was made, I is still valid, I may be dead though
107 // otherwise - Change was made, replace I with returned instruction
109 Instruction *visitAdd(BinaryOperator &I);
110 Instruction *visitSub(BinaryOperator &I);
111 Instruction *visitMul(BinaryOperator &I);
112 Instruction *visitDiv(BinaryOperator &I);
113 Instruction *visitRem(BinaryOperator &I);
114 Instruction *visitAnd(BinaryOperator &I);
115 Instruction *visitOr (BinaryOperator &I);
116 Instruction *visitXor(BinaryOperator &I);
117 Instruction *visitSetCondInst(SetCondInst &I);
118 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
120 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
121 Instruction::BinaryOps Cond, Instruction &I);
122 Instruction *visitShiftInst(ShiftInst &I);
123 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
125 Instruction *visitCastInst(CastInst &CI);
126 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
128 Instruction *visitSelectInst(SelectInst &CI);
129 Instruction *visitCallInst(CallInst &CI);
130 Instruction *visitInvokeInst(InvokeInst &II);
131 Instruction *visitPHINode(PHINode &PN);
132 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
133 Instruction *visitAllocationInst(AllocationInst &AI);
134 Instruction *visitFreeInst(FreeInst &FI);
135 Instruction *visitLoadInst(LoadInst &LI);
136 Instruction *visitStoreInst(StoreInst &SI);
137 Instruction *visitBranchInst(BranchInst &BI);
138 Instruction *visitSwitchInst(SwitchInst &SI);
139 Instruction *visitExtractElementInst(ExtractElementInst &EI);
141 // visitInstruction - Specify what to return for unhandled instructions...
142 Instruction *visitInstruction(Instruction &I) { return 0; }
145 Instruction *visitCallSite(CallSite CS);
146 bool transformConstExprCastCall(CallSite CS);
149 // InsertNewInstBefore - insert an instruction New before instruction Old
150 // in the program. Add the new instruction to the worklist.
152 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
153 assert(New && New->getParent() == 0 &&
154 "New instruction already inserted into a basic block!");
155 BasicBlock *BB = Old.getParent();
156 BB->getInstList().insert(&Old, New); // Insert inst
157 WorkList.push_back(New); // Add to worklist
161 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
162 /// This also adds the cast to the worklist. Finally, this returns the
164 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
165 if (V->getType() == Ty) return V;
167 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
168 WorkList.push_back(C);
172 // ReplaceInstUsesWith - This method is to be used when an instruction is
173 // found to be dead, replacable with another preexisting expression. Here
174 // we add all uses of I to the worklist, replace all uses of I with the new
175 // value, then return I, so that the inst combiner will know that I was
178 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
179 AddUsersToWorkList(I); // Add all modified instrs to worklist
181 I.replaceAllUsesWith(V);
184 // If we are replacing the instruction with itself, this must be in a
185 // segment of unreachable code, so just clobber the instruction.
186 I.replaceAllUsesWith(UndefValue::get(I.getType()));
191 // UpdateValueUsesWith - This method is to be used when an value is
192 // found to be replacable with another preexisting expression or was
193 // updated. Here we add all uses of I to the worklist, replace all uses of
194 // I with the new value (unless the instruction was just updated), then
195 // return true, so that the inst combiner will know that I was modified.
197 bool UpdateValueUsesWith(Value *Old, Value *New) {
198 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
200 Old->replaceAllUsesWith(New);
201 if (Instruction *I = dyn_cast<Instruction>(Old))
202 WorkList.push_back(I);
206 // EraseInstFromFunction - When dealing with an instruction that has side
207 // effects or produces a void value, we can't rely on DCE to delete the
208 // instruction. Instead, visit methods should return the value returned by
210 Instruction *EraseInstFromFunction(Instruction &I) {
211 assert(I.use_empty() && "Cannot erase instruction that is used!");
212 AddUsesToWorkList(I);
213 removeFromWorkList(&I);
215 return 0; // Don't do anything with FI
219 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
220 /// InsertBefore instruction. This is specialized a bit to avoid inserting
221 /// casts that are known to not do anything...
223 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
224 Instruction *InsertBefore);
226 // SimplifyCommutative - This performs a few simplifications for commutative
228 bool SimplifyCommutative(BinaryOperator &I);
230 bool SimplifyDemandedBits(Value *V, uint64_t Mask, unsigned Depth = 0);
232 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
233 // PHI node as operand #0, see if we can fold the instruction into the PHI
234 // (which is only possible if all operands to the PHI are constants).
235 Instruction *FoldOpIntoPhi(Instruction &I);
237 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
238 // operator and they all are only used by the PHI, PHI together their
239 // inputs, and do the operation once, to the result of the PHI.
240 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
242 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
243 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
245 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
246 bool isSub, Instruction &I);
247 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
248 bool Inside, Instruction &IB);
249 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
252 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
255 // getComplexity: Assign a complexity or rank value to LLVM Values...
256 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
257 static unsigned getComplexity(Value *V) {
258 if (isa<Instruction>(V)) {
259 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
263 if (isa<Argument>(V)) return 3;
264 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
267 // isOnlyUse - Return true if this instruction will be deleted if we stop using
269 static bool isOnlyUse(Value *V) {
270 return V->hasOneUse() || isa<Constant>(V);
273 // getPromotedType - Return the specified type promoted as it would be to pass
274 // though a va_arg area...
275 static const Type *getPromotedType(const Type *Ty) {
276 switch (Ty->getTypeID()) {
277 case Type::SByteTyID:
278 case Type::ShortTyID: return Type::IntTy;
279 case Type::UByteTyID:
280 case Type::UShortTyID: return Type::UIntTy;
281 case Type::FloatTyID: return Type::DoubleTy;
286 /// isCast - If the specified operand is a CastInst or a constant expr cast,
287 /// return the operand value, otherwise return null.
288 static Value *isCast(Value *V) {
289 if (CastInst *I = dyn_cast<CastInst>(V))
290 return I->getOperand(0);
291 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
292 if (CE->getOpcode() == Instruction::Cast)
293 return CE->getOperand(0);
297 // SimplifyCommutative - This performs a few simplifications for commutative
300 // 1. Order operands such that they are listed from right (least complex) to
301 // left (most complex). This puts constants before unary operators before
304 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
305 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
307 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
308 bool Changed = false;
309 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
310 Changed = !I.swapOperands();
312 if (!I.isAssociative()) return Changed;
313 Instruction::BinaryOps Opcode = I.getOpcode();
314 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
315 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
316 if (isa<Constant>(I.getOperand(1))) {
317 Constant *Folded = ConstantExpr::get(I.getOpcode(),
318 cast<Constant>(I.getOperand(1)),
319 cast<Constant>(Op->getOperand(1)));
320 I.setOperand(0, Op->getOperand(0));
321 I.setOperand(1, Folded);
323 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
324 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
325 isOnlyUse(Op) && isOnlyUse(Op1)) {
326 Constant *C1 = cast<Constant>(Op->getOperand(1));
327 Constant *C2 = cast<Constant>(Op1->getOperand(1));
329 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
330 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
331 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
334 WorkList.push_back(New);
335 I.setOperand(0, New);
336 I.setOperand(1, Folded);
343 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
344 // if the LHS is a constant zero (which is the 'negate' form).
346 static inline Value *dyn_castNegVal(Value *V) {
347 if (BinaryOperator::isNeg(V))
348 return BinaryOperator::getNegArgument(V);
350 // Constants can be considered to be negated values if they can be folded.
351 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
352 return ConstantExpr::getNeg(C);
356 static inline Value *dyn_castNotVal(Value *V) {
357 if (BinaryOperator::isNot(V))
358 return BinaryOperator::getNotArgument(V);
360 // Constants can be considered to be not'ed values...
361 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
362 return ConstantExpr::getNot(C);
366 // dyn_castFoldableMul - If this value is a multiply that can be folded into
367 // other computations (because it has a constant operand), return the
368 // non-constant operand of the multiply, and set CST to point to the multiplier.
369 // Otherwise, return null.
371 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
372 if (V->hasOneUse() && V->getType()->isInteger())
373 if (Instruction *I = dyn_cast<Instruction>(V)) {
374 if (I->getOpcode() == Instruction::Mul)
375 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
376 return I->getOperand(0);
377 if (I->getOpcode() == Instruction::Shl)
378 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
379 // The multiplier is really 1 << CST.
380 Constant *One = ConstantInt::get(V->getType(), 1);
381 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
382 return I->getOperand(0);
388 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
389 /// expression, return it.
390 static User *dyn_castGetElementPtr(Value *V) {
391 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
392 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
393 if (CE->getOpcode() == Instruction::GetElementPtr)
394 return cast<User>(V);
398 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
399 static ConstantInt *AddOne(ConstantInt *C) {
400 return cast<ConstantInt>(ConstantExpr::getAdd(C,
401 ConstantInt::get(C->getType(), 1)));
403 static ConstantInt *SubOne(ConstantInt *C) {
404 return cast<ConstantInt>(ConstantExpr::getSub(C,
405 ConstantInt::get(C->getType(), 1)));
408 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
409 /// this predicate to simplify operations downstream. V and Mask are known to
410 /// be the same type.
411 static bool MaskedValueIsZero(Value *V, ConstantIntegral *Mask,
412 unsigned Depth = 0) {
413 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
414 // we cannot optimize based on the assumption that it is zero without changing
415 // to to an explicit zero. If we don't change it to zero, other code could
416 // optimized based on the contradictory assumption that it is non-zero.
417 // Because instcombine aggressively folds operations with undef args anyway,
418 // this won't lose us code quality.
419 if (Mask->isNullValue())
421 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V))
422 return ConstantExpr::getAnd(CI, Mask)->isNullValue();
424 if (Depth == 6) return false; // Limit search depth.
426 if (Instruction *I = dyn_cast<Instruction>(V)) {
427 switch (I->getOpcode()) {
428 case Instruction::And:
429 // (X & C1) & C2 == 0 iff C1 & C2 == 0.
430 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(I->getOperand(1))) {
431 ConstantIntegral *C1C2 =
432 cast<ConstantIntegral>(ConstantExpr::getAnd(CI, Mask));
433 if (MaskedValueIsZero(I->getOperand(0), C1C2, Depth+1))
436 // If either the LHS or the RHS are MaskedValueIsZero, the result is zero.
437 return MaskedValueIsZero(I->getOperand(1), Mask, Depth+1) ||
438 MaskedValueIsZero(I->getOperand(0), Mask, Depth+1);
439 case Instruction::Or:
440 case Instruction::Xor:
441 // If the LHS and the RHS are MaskedValueIsZero, the result is also zero.
442 return MaskedValueIsZero(I->getOperand(1), Mask, Depth+1) &&
443 MaskedValueIsZero(I->getOperand(0), Mask, Depth+1);
444 case Instruction::Select:
445 // If the T and F values are MaskedValueIsZero, the result is also zero.
446 return MaskedValueIsZero(I->getOperand(2), Mask, Depth+1) &&
447 MaskedValueIsZero(I->getOperand(1), Mask, Depth+1);
448 case Instruction::Cast: {
449 const Type *SrcTy = I->getOperand(0)->getType();
450 if (SrcTy == Type::BoolTy)
451 return (Mask->getRawValue() & 1) == 0;
453 if (SrcTy->isInteger()) {
454 // (cast <ty> X to int) & C2 == 0 iff <ty> could not have contained C2.
455 if (SrcTy->isUnsigned() && // Only handle zero ext.
456 ConstantExpr::getCast(Mask, SrcTy)->isNullValue())
459 // If this is a noop cast, recurse.
460 if ((SrcTy->isSigned() && SrcTy->getUnsignedVersion() == I->getType())||
461 SrcTy->getSignedVersion() == I->getType()) {
463 ConstantExpr::getCast(Mask, I->getOperand(0)->getType());
464 return MaskedValueIsZero(I->getOperand(0),
465 cast<ConstantIntegral>(NewMask), Depth+1);
470 case Instruction::Shl:
471 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
472 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
473 return MaskedValueIsZero(I->getOperand(0),
474 cast<ConstantIntegral>(ConstantExpr::getUShr(Mask, SA)),
477 case Instruction::Shr:
478 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
479 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
480 if (I->getType()->isUnsigned()) {
481 Constant *C1 = ConstantIntegral::getAllOnesValue(I->getType());
482 C1 = ConstantExpr::getShr(C1, SA);
483 C1 = ConstantExpr::getAnd(C1, Mask);
484 if (C1->isNullValue())
494 /// SimplifyDemandedBits - Look at V. At this point, we know that only the Mask
495 /// bits of the result of V are ever used downstream. If we can use this
496 /// information to simplify V, return V and set NewVal to the new value we
497 /// should use in V's place.
498 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t Mask,
500 if (!V->hasOneUse()) { // Other users may use these bits.
501 if (Depth != 0) // Not at the root.
503 // If this is the root being simplified, allow it to have multiple uses,
504 // just set the Mask to all bits.
505 Mask = V->getType()->getIntegralTypeMask();
506 } else if (Mask == 0) { // Not demanding any bits from V.
507 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
508 } else if (Depth == 6) { // Limit search depth.
512 Instruction *I = dyn_cast<Instruction>(V);
513 if (!I) return false; // Only analyze instructions.
515 switch (I->getOpcode()) {
517 case Instruction::And:
518 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
519 // Only demanding an intersection of the bits.
520 if (SimplifyDemandedBits(I->getOperand(0), RHS->getRawValue() & Mask,
523 if (~Mask & RHS->getRawValue()) {
524 // If this is producing any bits that are not needed, simplify the RHS.
525 if (I->getType()->isSigned()) {
526 int64_t Val = Mask & cast<ConstantSInt>(RHS)->getValue();
527 I->setOperand(1, ConstantSInt::get(I->getType(), Val));
529 uint64_t Val = Mask & cast<ConstantUInt>(RHS)->getValue();
530 I->setOperand(1, ConstantUInt::get(I->getType(), Val));
532 return UpdateValueUsesWith(I, I);
535 // Walk the LHS and the RHS.
536 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1) ||
537 SimplifyDemandedBits(I->getOperand(1), Mask, Depth+1);
538 case Instruction::Or:
539 case Instruction::Xor:
540 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
541 // If none of the [x]or'd in bits are demanded, don't both with the [x]or.
542 if ((Mask & RHS->getRawValue()) == 0)
543 return UpdateValueUsesWith(I, I->getOperand(0));
545 // Otherwise, for an OR, we only demand those bits not set by the OR.
546 if (I->getOpcode() == Instruction::Or)
547 Mask &= ~RHS->getRawValue();
548 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1);
550 // Walk the LHS and the RHS.
551 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1) ||
552 SimplifyDemandedBits(I->getOperand(1), Mask, Depth+1);
553 case Instruction::Cast: {
554 const Type *SrcTy = I->getOperand(0)->getType();
555 if (SrcTy == Type::BoolTy)
556 return SimplifyDemandedBits(I->getOperand(0), Mask&1, Depth+1);
558 if (!SrcTy->isInteger()) return false;
560 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
561 // If this is a sign-extend, treat specially.
562 if (SrcTy->isSigned() &&
563 SrcBits < I->getType()->getPrimitiveSizeInBits()) {
564 // If none of the top bits are demanded, convert this into an unsigned
565 // extend instead of a sign extend.
566 if ((Mask & ((1ULL << SrcBits)-1)) == 0) {
567 // Convert to unsigned first.
569 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
570 I->getOperand(0)->getName(), I);
571 NewVal = new CastInst(I->getOperand(0), I->getType(), I->getName());
572 return UpdateValueUsesWith(I, NewVal);
575 // Otherwise, the high-bits *are* demanded. This means that the code
576 // implicitly demands computation of the sign bit of the input, make sure
577 // we explicitly include it in Mask.
578 Mask |= 1ULL << (SrcBits-1);
581 // If this is an extension, the top bits are ignored.
582 Mask &= SrcTy->getIntegralTypeMask();
583 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1);
585 case Instruction::Select:
586 // Simplify the T and F values if they are not demanded.
587 return SimplifyDemandedBits(I->getOperand(2), Mask, Depth+1) ||
588 SimplifyDemandedBits(I->getOperand(1), Mask, Depth+1);
589 case Instruction::Shl:
590 // We only demand the low bits of the input.
591 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1)))
592 return SimplifyDemandedBits(I->getOperand(0), Mask >> SA->getValue(),
595 case Instruction::Shr:
596 // We only demand the high bits of the input.
597 if (I->getType()->isUnsigned())
598 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
599 Mask <<= SA->getValue();
600 Mask &= I->getType()->getIntegralTypeMask();
601 return SimplifyDemandedBits(I->getOperand(0), Mask, Depth+1);
603 // FIXME: handle signed shr, demanding the appropriate bits. If the top
604 // bits aren't demanded, strength reduce to a logical SHR instead.
610 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
611 // true when both operands are equal...
613 static bool isTrueWhenEqual(Instruction &I) {
614 return I.getOpcode() == Instruction::SetEQ ||
615 I.getOpcode() == Instruction::SetGE ||
616 I.getOpcode() == Instruction::SetLE;
619 /// AssociativeOpt - Perform an optimization on an associative operator. This
620 /// function is designed to check a chain of associative operators for a
621 /// potential to apply a certain optimization. Since the optimization may be
622 /// applicable if the expression was reassociated, this checks the chain, then
623 /// reassociates the expression as necessary to expose the optimization
624 /// opportunity. This makes use of a special Functor, which must define
625 /// 'shouldApply' and 'apply' methods.
627 template<typename Functor>
628 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
629 unsigned Opcode = Root.getOpcode();
630 Value *LHS = Root.getOperand(0);
632 // Quick check, see if the immediate LHS matches...
633 if (F.shouldApply(LHS))
634 return F.apply(Root);
636 // Otherwise, if the LHS is not of the same opcode as the root, return.
637 Instruction *LHSI = dyn_cast<Instruction>(LHS);
638 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
639 // Should we apply this transform to the RHS?
640 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
642 // If not to the RHS, check to see if we should apply to the LHS...
643 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
644 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
648 // If the functor wants to apply the optimization to the RHS of LHSI,
649 // reassociate the expression from ((? op A) op B) to (? op (A op B))
651 BasicBlock *BB = Root.getParent();
653 // Now all of the instructions are in the current basic block, go ahead
654 // and perform the reassociation.
655 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
657 // First move the selected RHS to the LHS of the root...
658 Root.setOperand(0, LHSI->getOperand(1));
660 // Make what used to be the LHS of the root be the user of the root...
661 Value *ExtraOperand = TmpLHSI->getOperand(1);
662 if (&Root == TmpLHSI) {
663 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
666 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
667 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
668 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
669 BasicBlock::iterator ARI = &Root; ++ARI;
670 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
673 // Now propagate the ExtraOperand down the chain of instructions until we
675 while (TmpLHSI != LHSI) {
676 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
677 // Move the instruction to immediately before the chain we are
678 // constructing to avoid breaking dominance properties.
679 NextLHSI->getParent()->getInstList().remove(NextLHSI);
680 BB->getInstList().insert(ARI, NextLHSI);
683 Value *NextOp = NextLHSI->getOperand(1);
684 NextLHSI->setOperand(1, ExtraOperand);
686 ExtraOperand = NextOp;
689 // Now that the instructions are reassociated, have the functor perform
690 // the transformation...
691 return F.apply(Root);
694 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
700 // AddRHS - Implements: X + X --> X << 1
703 AddRHS(Value *rhs) : RHS(rhs) {}
704 bool shouldApply(Value *LHS) const { return LHS == RHS; }
705 Instruction *apply(BinaryOperator &Add) const {
706 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
707 ConstantInt::get(Type::UByteTy, 1));
711 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
713 struct AddMaskingAnd {
715 AddMaskingAnd(Constant *c) : C2(c) {}
716 bool shouldApply(Value *LHS) const {
718 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
719 ConstantExpr::getAnd(C1, C2)->isNullValue();
721 Instruction *apply(BinaryOperator &Add) const {
722 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
726 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
728 if (isa<CastInst>(I)) {
729 if (Constant *SOC = dyn_cast<Constant>(SO))
730 return ConstantExpr::getCast(SOC, I.getType());
732 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
733 SO->getName() + ".cast"), I);
736 // Figure out if the constant is the left or the right argument.
737 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
738 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
740 if (Constant *SOC = dyn_cast<Constant>(SO)) {
742 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
743 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
746 Value *Op0 = SO, *Op1 = ConstOperand;
750 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
751 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
752 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
753 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
755 assert(0 && "Unknown binary instruction type!");
758 return IC->InsertNewInstBefore(New, I);
761 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
762 // constant as the other operand, try to fold the binary operator into the
763 // select arguments. This also works for Cast instructions, which obviously do
764 // not have a second operand.
765 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
767 // Don't modify shared select instructions
768 if (!SI->hasOneUse()) return 0;
769 Value *TV = SI->getOperand(1);
770 Value *FV = SI->getOperand(2);
772 if (isa<Constant>(TV) || isa<Constant>(FV)) {
773 // Bool selects with constant operands can be folded to logical ops.
774 if (SI->getType() == Type::BoolTy) return 0;
776 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
777 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
779 return new SelectInst(SI->getCondition(), SelectTrueVal,
786 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
787 /// node as operand #0, see if we can fold the instruction into the PHI (which
788 /// is only possible if all operands to the PHI are constants).
789 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
790 PHINode *PN = cast<PHINode>(I.getOperand(0));
791 unsigned NumPHIValues = PN->getNumIncomingValues();
792 if (!PN->hasOneUse() || NumPHIValues == 0 ||
793 !isa<Constant>(PN->getIncomingValue(0))) return 0;
795 // Check to see if all of the operands of the PHI are constants. If not, we
796 // cannot do the transformation.
797 for (unsigned i = 1; i != NumPHIValues; ++i)
798 if (!isa<Constant>(PN->getIncomingValue(i)))
801 // Okay, we can do the transformation: create the new PHI node.
802 PHINode *NewPN = new PHINode(I.getType(), I.getName());
804 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
805 InsertNewInstBefore(NewPN, *PN);
807 // Next, add all of the operands to the PHI.
808 if (I.getNumOperands() == 2) {
809 Constant *C = cast<Constant>(I.getOperand(1));
810 for (unsigned i = 0; i != NumPHIValues; ++i) {
811 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
812 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
813 PN->getIncomingBlock(i));
816 assert(isa<CastInst>(I) && "Unary op should be a cast!");
817 const Type *RetTy = I.getType();
818 for (unsigned i = 0; i != NumPHIValues; ++i) {
819 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
820 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
821 PN->getIncomingBlock(i));
824 return ReplaceInstUsesWith(I, NewPN);
827 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
828 bool Changed = SimplifyCommutative(I);
829 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
831 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
832 // X + undef -> undef
833 if (isa<UndefValue>(RHS))
834 return ReplaceInstUsesWith(I, RHS);
837 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
838 if (RHSC->isNullValue())
839 return ReplaceInstUsesWith(I, LHS);
840 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
841 if (CFP->isExactlyValue(-0.0))
842 return ReplaceInstUsesWith(I, LHS);
845 // X + (signbit) --> X ^ signbit
846 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
847 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
848 uint64_t Val = CI->getRawValue() & (~0ULL >> (64- NumBits));
849 if (Val == (1ULL << (NumBits-1)))
850 return BinaryOperator::createXor(LHS, RHS);
853 if (isa<PHINode>(LHS))
854 if (Instruction *NV = FoldOpIntoPhi(I))
857 ConstantInt *XorRHS = 0;
859 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
860 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
861 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
862 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
864 uint64_t C0080Val = 1ULL << 31;
865 int64_t CFF80Val = -C0080Val;
868 if (TySizeBits > Size) {
870 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
871 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
872 if (RHSSExt == CFF80Val) {
873 if (XorRHS->getZExtValue() == C0080Val)
875 } else if (RHSZExt == C0080Val) {
876 if (XorRHS->getSExtValue() == CFF80Val)
880 // This is a sign extend if the top bits are known zero.
881 Constant *Mask = ConstantInt::getAllOnesValue(XorLHS->getType());
882 Mask = ConstantExpr::getShl(Mask,
883 ConstantInt::get(Type::UByteTy, 64-(TySizeBits-Size)));
884 if (!MaskedValueIsZero(XorLHS, cast<ConstantInt>(Mask)))
885 Size = 0; // Not a sign ext, but can't be any others either.
895 const Type *MiddleType = 0;
898 case 32: MiddleType = Type::IntTy; break;
899 case 16: MiddleType = Type::ShortTy; break;
900 case 8: MiddleType = Type::SByteTy; break;
903 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
904 InsertNewInstBefore(NewTrunc, I);
905 return new CastInst(NewTrunc, I.getType());
911 if (I.getType()->isInteger()) {
912 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
914 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
915 if (RHSI->getOpcode() == Instruction::Sub)
916 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
917 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
919 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
920 if (LHSI->getOpcode() == Instruction::Sub)
921 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
922 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
927 if (Value *V = dyn_castNegVal(LHS))
928 return BinaryOperator::createSub(RHS, V);
931 if (!isa<Constant>(RHS))
932 if (Value *V = dyn_castNegVal(RHS))
933 return BinaryOperator::createSub(LHS, V);
937 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
938 if (X == RHS) // X*C + X --> X * (C+1)
939 return BinaryOperator::createMul(RHS, AddOne(C2));
941 // X*C1 + X*C2 --> X * (C1+C2)
943 if (X == dyn_castFoldableMul(RHS, C1))
944 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
947 // X + X*C --> X * (C+1)
948 if (dyn_castFoldableMul(RHS, C2) == LHS)
949 return BinaryOperator::createMul(LHS, AddOne(C2));
952 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
953 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
954 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
956 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
958 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
959 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
960 return BinaryOperator::createSub(C, X);
963 // (X & FF00) + xx00 -> (X+xx00) & FF00
964 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
965 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
967 // See if all bits from the first bit set in the Add RHS up are included
968 // in the mask. First, get the rightmost bit.
969 uint64_t AddRHSV = CRHS->getRawValue();
971 // Form a mask of all bits from the lowest bit added through the top.
972 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
973 AddRHSHighBits &= ~0ULL >> (64-C2->getType()->getPrimitiveSizeInBits());
975 // See if the and mask includes all of these bits.
976 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
978 if (AddRHSHighBits == AddRHSHighBitsAnd) {
979 // Okay, the xform is safe. Insert the new add pronto.
980 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
982 return BinaryOperator::createAnd(NewAdd, C2);
987 // Try to fold constant add into select arguments.
988 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
989 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
993 return Changed ? &I : 0;
996 // isSignBit - Return true if the value represented by the constant only has the
997 // highest order bit set.
998 static bool isSignBit(ConstantInt *CI) {
999 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1000 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1003 /// RemoveNoopCast - Strip off nonconverting casts from the value.
1005 static Value *RemoveNoopCast(Value *V) {
1006 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1007 const Type *CTy = CI->getType();
1008 const Type *OpTy = CI->getOperand(0)->getType();
1009 if (CTy->isInteger() && OpTy->isInteger()) {
1010 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
1011 return RemoveNoopCast(CI->getOperand(0));
1012 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1013 return RemoveNoopCast(CI->getOperand(0));
1018 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1019 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1021 if (Op0 == Op1) // sub X, X -> 0
1022 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1024 // If this is a 'B = x-(-A)', change to B = x+A...
1025 if (Value *V = dyn_castNegVal(Op1))
1026 return BinaryOperator::createAdd(Op0, V);
1028 if (isa<UndefValue>(Op0))
1029 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1030 if (isa<UndefValue>(Op1))
1031 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1033 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1034 // Replace (-1 - A) with (~A)...
1035 if (C->isAllOnesValue())
1036 return BinaryOperator::createNot(Op1);
1038 // C - ~X == X + (1+C)
1040 if (match(Op1, m_Not(m_Value(X))))
1041 return BinaryOperator::createAdd(X,
1042 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1043 // -((uint)X >> 31) -> ((int)X >> 31)
1044 // -((int)X >> 31) -> ((uint)X >> 31)
1045 if (C->isNullValue()) {
1046 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1047 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
1048 if (SI->getOpcode() == Instruction::Shr)
1049 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1051 if (SI->getType()->isSigned())
1052 NewTy = SI->getType()->getUnsignedVersion();
1054 NewTy = SI->getType()->getSignedVersion();
1055 // Check to see if we are shifting out everything but the sign bit.
1056 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
1057 // Ok, the transformation is safe. Insert a cast of the incoming
1058 // value, then the new shift, then the new cast.
1059 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1060 SI->getOperand(0)->getName());
1061 Value *InV = InsertNewInstBefore(FirstCast, I);
1062 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1064 if (NewShift->getType() == I.getType())
1067 InV = InsertNewInstBefore(NewShift, I);
1068 return new CastInst(NewShift, I.getType());
1074 // Try to fold constant sub into select arguments.
1075 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1076 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1079 if (isa<PHINode>(Op0))
1080 if (Instruction *NV = FoldOpIntoPhi(I))
1084 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1085 if (Op1I->getOpcode() == Instruction::Add &&
1086 !Op0->getType()->isFloatingPoint()) {
1087 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
1088 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
1089 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
1090 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
1091 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1092 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1093 // C1-(X+C2) --> (C1-C2)-X
1094 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1095 Op1I->getOperand(0));
1099 if (Op1I->hasOneUse()) {
1100 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1101 // is not used by anyone else...
1103 if (Op1I->getOpcode() == Instruction::Sub &&
1104 !Op1I->getType()->isFloatingPoint()) {
1105 // Swap the two operands of the subexpr...
1106 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1107 Op1I->setOperand(0, IIOp1);
1108 Op1I->setOperand(1, IIOp0);
1110 // Create the new top level add instruction...
1111 return BinaryOperator::createAdd(Op0, Op1);
1114 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1116 if (Op1I->getOpcode() == Instruction::And &&
1117 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1118 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1121 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
1122 return BinaryOperator::createAnd(Op0, NewNot);
1125 // -(X sdiv C) -> (X sdiv -C)
1126 if (Op1I->getOpcode() == Instruction::Div)
1127 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1128 if (CSI->isNullValue())
1129 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
1130 return BinaryOperator::createDiv(Op1I->getOperand(0),
1131 ConstantExpr::getNeg(DivRHS));
1133 // X - X*C --> X * (1-C)
1134 ConstantInt *C2 = 0;
1135 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
1137 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
1138 return BinaryOperator::createMul(Op0, CP1);
1143 if (!Op0->getType()->isFloatingPoint())
1144 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1145 if (Op0I->getOpcode() == Instruction::Add) {
1146 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1147 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1148 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1149 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1150 } else if (Op0I->getOpcode() == Instruction::Sub) {
1151 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1152 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
1156 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1157 if (X == Op1) { // X*C - X --> X * (C-1)
1158 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1159 return BinaryOperator::createMul(Op1, CP1);
1162 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1163 if (X == dyn_castFoldableMul(Op1, C2))
1164 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1169 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1170 /// really just returns true if the most significant (sign) bit is set.
1171 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1172 if (RHS->getType()->isSigned()) {
1173 // True if source is LHS < 0 or LHS <= -1
1174 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1175 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1177 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1178 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1179 // the size of the integer type.
1180 if (Opcode == Instruction::SetGE)
1181 return RHSC->getValue() ==
1182 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
1183 if (Opcode == Instruction::SetGT)
1184 return RHSC->getValue() ==
1185 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
1190 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
1191 bool Changed = SimplifyCommutative(I);
1192 Value *Op0 = I.getOperand(0);
1194 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1195 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1197 // Simplify mul instructions with a constant RHS...
1198 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1199 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1201 // ((X << C1)*C2) == (X * (C2 << C1))
1202 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1203 if (SI->getOpcode() == Instruction::Shl)
1204 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
1205 return BinaryOperator::createMul(SI->getOperand(0),
1206 ConstantExpr::getShl(CI, ShOp));
1208 if (CI->isNullValue())
1209 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1210 if (CI->equalsInt(1)) // X * 1 == X
1211 return ReplaceInstUsesWith(I, Op0);
1212 if (CI->isAllOnesValue()) // X * -1 == 0 - X
1213 return BinaryOperator::createNeg(Op0, I.getName());
1215 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
1216 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1217 uint64_t C = Log2_64(Val);
1218 return new ShiftInst(Instruction::Shl, Op0,
1219 ConstantUInt::get(Type::UByteTy, C));
1221 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
1222 if (Op1F->isNullValue())
1223 return ReplaceInstUsesWith(I, Op1);
1225 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1226 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1227 if (Op1F->getValue() == 1.0)
1228 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1231 // Try to fold constant mul into select arguments.
1232 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1233 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1236 if (isa<PHINode>(Op0))
1237 if (Instruction *NV = FoldOpIntoPhi(I))
1241 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1242 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
1243 return BinaryOperator::createMul(Op0v, Op1v);
1245 // If one of the operands of the multiply is a cast from a boolean value, then
1246 // we know the bool is either zero or one, so this is a 'masking' multiply.
1247 // See if we can simplify things based on how the boolean was originally
1249 CastInst *BoolCast = 0;
1250 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1251 if (CI->getOperand(0)->getType() == Type::BoolTy)
1254 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1255 if (CI->getOperand(0)->getType() == Type::BoolTy)
1258 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1259 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1260 const Type *SCOpTy = SCIOp0->getType();
1262 // If the setcc is true iff the sign bit of X is set, then convert this
1263 // multiply into a shift/and combination.
1264 if (isa<ConstantInt>(SCIOp1) &&
1265 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
1266 // Shift the X value right to turn it into "all signbits".
1267 Constant *Amt = ConstantUInt::get(Type::UByteTy,
1268 SCOpTy->getPrimitiveSizeInBits()-1);
1269 if (SCIOp0->getType()->isUnsigned()) {
1270 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
1271 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1272 SCIOp0->getName()), I);
1276 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1277 BoolCast->getOperand(0)->getName()+
1280 // If the multiply type is not the same as the source type, sign extend
1281 // or truncate to the multiply type.
1282 if (I.getType() != V->getType())
1283 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
1285 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
1286 return BinaryOperator::createAnd(V, OtherOp);
1291 return Changed ? &I : 0;
1294 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
1295 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1297 if (isa<UndefValue>(Op0)) // undef / X -> 0
1298 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1299 if (isa<UndefValue>(Op1))
1300 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1302 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1304 if (RHS->equalsInt(1))
1305 return ReplaceInstUsesWith(I, Op0);
1308 if (RHS->isAllOnesValue())
1309 return BinaryOperator::createNeg(Op0);
1311 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
1312 if (LHS->getOpcode() == Instruction::Div)
1313 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
1314 // (X / C1) / C2 -> X / (C1*C2)
1315 return BinaryOperator::createDiv(LHS->getOperand(0),
1316 ConstantExpr::getMul(RHS, LHSRHS));
1319 // Check to see if this is an unsigned division with an exact power of 2,
1320 // if so, convert to a right shift.
1321 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1322 if (uint64_t Val = C->getValue()) // Don't break X / 0
1323 if (isPowerOf2_64(Val)) {
1324 uint64_t C = Log2_64(Val);
1325 return new ShiftInst(Instruction::Shr, Op0,
1326 ConstantUInt::get(Type::UByteTy, C));
1330 if (RHS->getType()->isSigned())
1331 if (Value *LHSNeg = dyn_castNegVal(Op0))
1332 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1334 if (!RHS->isNullValue()) {
1335 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1336 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1338 if (isa<PHINode>(Op0))
1339 if (Instruction *NV = FoldOpIntoPhi(I))
1344 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1345 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1346 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1347 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1348 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1349 if (STO->getValue() == 0) { // Couldn't be this argument.
1350 I.setOperand(1, SFO);
1352 } else if (SFO->getValue() == 0) {
1353 I.setOperand(1, STO);
1357 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
1358 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1359 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
1360 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1361 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1362 TC, SI->getName()+".t");
1363 TSI = InsertNewInstBefore(TSI, I);
1365 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1366 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1367 FC, SI->getName()+".f");
1368 FSI = InsertNewInstBefore(FSI, I);
1369 return new SelectInst(SI->getOperand(0), TSI, FSI);
1373 // 0 / X == 0, we don't need to preserve faults!
1374 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
1375 if (LHS->equalsInt(0))
1376 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1378 if (I.getType()->isSigned()) {
1379 // If the top bits of both operands are zero (i.e. we can prove they are
1380 // unsigned inputs), turn this into a udiv.
1381 ConstantIntegral *MaskV = ConstantSInt::getMinValue(I.getType());
1382 if (MaskedValueIsZero(Op1, MaskV) && MaskedValueIsZero(Op0, MaskV)) {
1383 const Type *NTy = Op0->getType()->getUnsignedVersion();
1384 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1385 InsertNewInstBefore(LHS, I);
1387 if (Constant *R = dyn_cast<Constant>(Op1))
1388 RHS = ConstantExpr::getCast(R, NTy);
1390 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1391 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1392 InsertNewInstBefore(Div, I);
1393 return new CastInst(Div, I.getType());
1396 // Known to be an unsigned division.
1397 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1398 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1399 if (RHSI->getOpcode() == Instruction::Shl &&
1400 isa<ConstantUInt>(RHSI->getOperand(0))) {
1401 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1402 if (isPowerOf2_64(C1)) {
1403 unsigned C2 = Log2_64(C1);
1404 Value *Add = RHSI->getOperand(1);
1406 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1407 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1410 return new ShiftInst(Instruction::Shr, Op0, Add);
1420 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
1421 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1422 if (I.getType()->isSigned()) {
1423 if (Value *RHSNeg = dyn_castNegVal(Op1))
1424 if (!isa<ConstantSInt>(RHSNeg) ||
1425 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
1427 AddUsesToWorkList(I);
1428 I.setOperand(1, RHSNeg);
1432 // If the top bits of both operands are zero (i.e. we can prove they are
1433 // unsigned inputs), turn this into a urem.
1434 ConstantIntegral *MaskV = ConstantSInt::getMinValue(I.getType());
1435 if (MaskedValueIsZero(Op1, MaskV) && MaskedValueIsZero(Op0, MaskV)) {
1436 const Type *NTy = Op0->getType()->getUnsignedVersion();
1437 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1438 InsertNewInstBefore(LHS, I);
1440 if (Constant *R = dyn_cast<Constant>(Op1))
1441 RHS = ConstantExpr::getCast(R, NTy);
1443 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1444 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1445 InsertNewInstBefore(Rem, I);
1446 return new CastInst(Rem, I.getType());
1450 if (isa<UndefValue>(Op0)) // undef % X -> 0
1451 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1452 if (isa<UndefValue>(Op1))
1453 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
1455 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1456 if (RHS->equalsInt(1)) // X % 1 == 0
1457 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1459 // Check to see if this is an unsigned remainder with an exact power of 2,
1460 // if so, convert to a bitwise and.
1461 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1462 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
1463 if (!(Val & (Val-1))) // Power of 2
1464 return BinaryOperator::createAnd(Op0,
1465 ConstantUInt::get(I.getType(), Val-1));
1467 if (!RHS->isNullValue()) {
1468 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1469 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1471 if (isa<PHINode>(Op0))
1472 if (Instruction *NV = FoldOpIntoPhi(I))
1477 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1478 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1479 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1480 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1481 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1482 if (STO->getValue() == 0) { // Couldn't be this argument.
1483 I.setOperand(1, SFO);
1485 } else if (SFO->getValue() == 0) {
1486 I.setOperand(1, STO);
1490 if (!(STO->getValue() & (STO->getValue()-1)) &&
1491 !(SFO->getValue() & (SFO->getValue()-1))) {
1492 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1493 SubOne(STO), SI->getName()+".t"), I);
1494 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1495 SubOne(SFO), SI->getName()+".f"), I);
1496 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1500 // 0 % X == 0, we don't need to preserve faults!
1501 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
1502 if (LHS->equalsInt(0))
1503 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1506 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1507 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
1508 if (I.getType()->isUnsigned() &&
1509 RHSI->getOpcode() == Instruction::Shl &&
1510 isa<ConstantUInt>(RHSI->getOperand(0))) {
1511 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1512 if (isPowerOf2_64(C1)) {
1513 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
1514 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
1516 return BinaryOperator::createAnd(Op0, Add);
1524 // isMaxValueMinusOne - return true if this is Max-1
1525 static bool isMaxValueMinusOne(const ConstantInt *C) {
1526 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1527 // Calculate -1 casted to the right type...
1528 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
1529 uint64_t Val = ~0ULL; // All ones
1530 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1531 return CU->getValue() == Val-1;
1534 const ConstantSInt *CS = cast<ConstantSInt>(C);
1536 // Calculate 0111111111..11111
1537 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
1538 int64_t Val = INT64_MAX; // All ones
1539 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1540 return CS->getValue() == Val-1;
1543 // isMinValuePlusOne - return true if this is Min+1
1544 static bool isMinValuePlusOne(const ConstantInt *C) {
1545 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1546 return CU->getValue() == 1;
1548 const ConstantSInt *CS = cast<ConstantSInt>(C);
1550 // Calculate 1111111111000000000000
1551 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
1552 int64_t Val = -1; // All ones
1553 Val <<= TypeBits-1; // Shift over to the right spot
1554 return CS->getValue() == Val+1;
1557 // isOneBitSet - Return true if there is exactly one bit set in the specified
1559 static bool isOneBitSet(const ConstantInt *CI) {
1560 uint64_t V = CI->getRawValue();
1561 return V && (V & (V-1)) == 0;
1564 #if 0 // Currently unused
1565 // isLowOnes - Return true if the constant is of the form 0+1+.
1566 static bool isLowOnes(const ConstantInt *CI) {
1567 uint64_t V = CI->getRawValue();
1569 // There won't be bits set in parts that the type doesn't contain.
1570 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1572 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1573 return U && V && (U & V) == 0;
1577 // isHighOnes - Return true if the constant is of the form 1+0+.
1578 // This is the same as lowones(~X).
1579 static bool isHighOnes(const ConstantInt *CI) {
1580 uint64_t V = ~CI->getRawValue();
1581 if (~V == 0) return false; // 0's does not match "1+"
1583 // There won't be bits set in parts that the type doesn't contain.
1584 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1586 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1587 return U && V && (U & V) == 0;
1591 /// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1592 /// are carefully arranged to allow folding of expressions such as:
1594 /// (A < B) | (A > B) --> (A != B)
1596 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1597 /// represents that the comparison is true if A == B, and bit value '1' is true
1600 static unsigned getSetCondCode(const SetCondInst *SCI) {
1601 switch (SCI->getOpcode()) {
1603 case Instruction::SetGT: return 1;
1604 case Instruction::SetEQ: return 2;
1605 case Instruction::SetGE: return 3;
1606 case Instruction::SetLT: return 4;
1607 case Instruction::SetNE: return 5;
1608 case Instruction::SetLE: return 6;
1611 assert(0 && "Invalid SetCC opcode!");
1616 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
1617 /// opcode and two operands into either a constant true or false, or a brand new
1618 /// SetCC instruction.
1619 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1621 case 0: return ConstantBool::False;
1622 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1623 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1624 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1625 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1626 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1627 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1628 case 7: return ConstantBool::True;
1629 default: assert(0 && "Illegal SetCCCode!"); return 0;
1633 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1634 struct FoldSetCCLogical {
1637 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1638 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1639 bool shouldApply(Value *V) const {
1640 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1641 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1642 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1645 Instruction *apply(BinaryOperator &Log) const {
1646 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1647 if (SCI->getOperand(0) != LHS) {
1648 assert(SCI->getOperand(1) == LHS);
1649 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1652 unsigned LHSCode = getSetCondCode(SCI);
1653 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1655 switch (Log.getOpcode()) {
1656 case Instruction::And: Code = LHSCode & RHSCode; break;
1657 case Instruction::Or: Code = LHSCode | RHSCode; break;
1658 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
1659 default: assert(0 && "Illegal logical opcode!"); return 0;
1662 Value *RV = getSetCCValue(Code, LHS, RHS);
1663 if (Instruction *I = dyn_cast<Instruction>(RV))
1665 // Otherwise, it's a constant boolean value...
1666 return IC.ReplaceInstUsesWith(Log, RV);
1670 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1671 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1672 // guaranteed to be either a shift instruction or a binary operator.
1673 Instruction *InstCombiner::OptAndOp(Instruction *Op,
1674 ConstantIntegral *OpRHS,
1675 ConstantIntegral *AndRHS,
1676 BinaryOperator &TheAnd) {
1677 Value *X = Op->getOperand(0);
1678 Constant *Together = 0;
1679 if (!isa<ShiftInst>(Op))
1680 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
1682 switch (Op->getOpcode()) {
1683 case Instruction::Xor:
1684 if (Op->hasOneUse()) {
1685 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1686 std::string OpName = Op->getName(); Op->setName("");
1687 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
1688 InsertNewInstBefore(And, TheAnd);
1689 return BinaryOperator::createXor(And, Together);
1692 case Instruction::Or:
1693 if (Together == AndRHS) // (X | C) & C --> C
1694 return ReplaceInstUsesWith(TheAnd, AndRHS);
1696 if (Op->hasOneUse() && Together != OpRHS) {
1697 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1698 std::string Op0Name = Op->getName(); Op->setName("");
1699 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1700 InsertNewInstBefore(Or, TheAnd);
1701 return BinaryOperator::createAnd(Or, AndRHS);
1704 case Instruction::Add:
1705 if (Op->hasOneUse()) {
1706 // Adding a one to a single bit bit-field should be turned into an XOR
1707 // of the bit. First thing to check is to see if this AND is with a
1708 // single bit constant.
1709 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
1711 // Clear bits that are not part of the constant.
1712 AndRHSV &= ~0ULL >> (64-AndRHS->getType()->getPrimitiveSizeInBits());
1714 // If there is only one bit set...
1715 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
1716 // Ok, at this point, we know that we are masking the result of the
1717 // ADD down to exactly one bit. If the constant we are adding has
1718 // no bits set below this bit, then we can eliminate the ADD.
1719 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
1721 // Check to see if any bits below the one bit set in AndRHSV are set.
1722 if ((AddRHS & (AndRHSV-1)) == 0) {
1723 // If not, the only thing that can effect the output of the AND is
1724 // the bit specified by AndRHSV. If that bit is set, the effect of
1725 // the XOR is to toggle the bit. If it is clear, then the ADD has
1727 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1728 TheAnd.setOperand(0, X);
1731 std::string Name = Op->getName(); Op->setName("");
1732 // Pull the XOR out of the AND.
1733 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
1734 InsertNewInstBefore(NewAnd, TheAnd);
1735 return BinaryOperator::createXor(NewAnd, AndRHS);
1742 case Instruction::Shl: {
1743 // We know that the AND will not produce any of the bits shifted in, so if
1744 // the anded constant includes them, clear them now!
1746 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1747 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1748 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1750 if (CI == ShlMask) { // Masking out bits that the shift already masks
1751 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1752 } else if (CI != AndRHS) { // Reducing bits set in and.
1753 TheAnd.setOperand(1, CI);
1758 case Instruction::Shr:
1759 // We know that the AND will not produce any of the bits shifted in, so if
1760 // the anded constant includes them, clear them now! This only applies to
1761 // unsigned shifts, because a signed shr may bring in set bits!
1763 if (AndRHS->getType()->isUnsigned()) {
1764 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1765 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1766 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1768 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1769 return ReplaceInstUsesWith(TheAnd, Op);
1770 } else if (CI != AndRHS) {
1771 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
1774 } else { // Signed shr.
1775 // See if this is shifting in some sign extension, then masking it out
1777 if (Op->hasOneUse()) {
1778 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1779 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1780 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1781 if (CI == AndRHS) { // Masking out bits shifted in.
1782 // Make the argument unsigned.
1783 Value *ShVal = Op->getOperand(0);
1784 ShVal = InsertCastBefore(ShVal,
1785 ShVal->getType()->getUnsignedVersion(),
1787 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1788 OpRHS, Op->getName()),
1790 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1791 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1794 return new CastInst(ShVal, Op->getType());
1804 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1805 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1806 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1807 /// insert new instructions.
1808 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1809 bool Inside, Instruction &IB) {
1810 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1811 "Lo is not <= Hi in range emission code!");
1813 if (Lo == Hi) // Trivially false.
1814 return new SetCondInst(Instruction::SetNE, V, V);
1815 if (cast<ConstantIntegral>(Lo)->isMinValue())
1816 return new SetCondInst(Instruction::SetLT, V, Hi);
1818 Constant *AddCST = ConstantExpr::getNeg(Lo);
1819 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1820 InsertNewInstBefore(Add, IB);
1821 // Convert to unsigned for the comparison.
1822 const Type *UnsType = Add->getType()->getUnsignedVersion();
1823 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1824 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1825 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1826 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1829 if (Lo == Hi) // Trivially true.
1830 return new SetCondInst(Instruction::SetEQ, V, V);
1832 Hi = SubOne(cast<ConstantInt>(Hi));
1833 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1834 return new SetCondInst(Instruction::SetGT, V, Hi);
1836 // Emit X-Lo > Hi-Lo-1
1837 Constant *AddCST = ConstantExpr::getNeg(Lo);
1838 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1839 InsertNewInstBefore(Add, IB);
1840 // Convert to unsigned for the comparison.
1841 const Type *UnsType = Add->getType()->getUnsignedVersion();
1842 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1843 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1844 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1845 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1848 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
1849 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
1850 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
1851 // not, since all 1s are not contiguous.
1852 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
1853 uint64_t V = Val->getRawValue();
1854 if (!isShiftedMask_64(V)) return false;
1856 // look for the first zero bit after the run of ones
1857 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
1858 // look for the first non-zero bit
1859 ME = 64-CountLeadingZeros_64(V);
1865 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
1866 /// where isSub determines whether the operator is a sub. If we can fold one of
1867 /// the following xforms:
1869 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
1870 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1871 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
1873 /// return (A +/- B).
1875 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
1876 ConstantIntegral *Mask, bool isSub,
1878 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1879 if (!LHSI || LHSI->getNumOperands() != 2 ||
1880 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
1882 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
1884 switch (LHSI->getOpcode()) {
1886 case Instruction::And:
1887 if (ConstantExpr::getAnd(N, Mask) == Mask) {
1888 // If the AndRHS is a power of two minus one (0+1+), this is simple.
1889 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
1892 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
1893 // part, we don't need any explicit masks to take them out of A. If that
1894 // is all N is, ignore it.
1896 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
1897 Constant *Mask = ConstantInt::getAllOnesValue(RHS->getType());
1898 Mask = ConstantExpr::getUShr(Mask,
1899 ConstantInt::get(Type::UByteTy,
1901 if (MaskedValueIsZero(RHS, cast<ConstantIntegral>(Mask)))
1906 case Instruction::Or:
1907 case Instruction::Xor:
1908 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
1909 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
1910 ConstantExpr::getAnd(N, Mask)->isNullValue())
1917 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
1919 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
1920 return InsertNewInstBefore(New, I);
1923 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1924 bool Changed = SimplifyCommutative(I);
1925 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1927 if (isa<UndefValue>(Op1)) // X & undef -> 0
1928 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1932 return ReplaceInstUsesWith(I, Op1);
1934 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
1936 if (AndRHS->isAllOnesValue())
1937 return ReplaceInstUsesWith(I, Op0);
1939 // and (and X, c1), c2 -> and (x, c1&c2). Handle this case here, before
1940 // calling MaskedValueIsZero, to avoid inefficient cases where we traipse
1941 // through many levels of ands.
1943 Value *X = 0; ConstantInt *C1 = 0;
1944 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))))
1945 return BinaryOperator::createAnd(X, ConstantExpr::getAnd(C1, AndRHS));
1948 if (MaskedValueIsZero(Op0, AndRHS)) // LHS & RHS == 0
1949 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1951 // If the mask is not masking out any bits, there is no reason to do the
1952 // and in the first place.
1953 ConstantIntegral *NotAndRHS =
1954 cast<ConstantIntegral>(ConstantExpr::getNot(AndRHS));
1955 if (MaskedValueIsZero(Op0, NotAndRHS))
1956 return ReplaceInstUsesWith(I, Op0);
1958 // See if we can simplify any instructions used by the LHS whose sole
1959 // purpose is to compute bits we don't care about.
1960 if (SimplifyDemandedBits(Op0, AndRHS->getRawValue()))
1963 // Optimize a variety of ((val OP C1) & C2) combinations...
1964 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1965 Instruction *Op0I = cast<Instruction>(Op0);
1966 Value *Op0LHS = Op0I->getOperand(0);
1967 Value *Op0RHS = Op0I->getOperand(1);
1968 switch (Op0I->getOpcode()) {
1969 case Instruction::Xor:
1970 case Instruction::Or:
1971 // (X ^ V) & C2 --> (X & C2) iff (V & C2) == 0
1972 // (X | V) & C2 --> (X & C2) iff (V & C2) == 0
1973 if (MaskedValueIsZero(Op0LHS, AndRHS))
1974 return BinaryOperator::createAnd(Op0RHS, AndRHS);
1975 if (MaskedValueIsZero(Op0RHS, AndRHS))
1976 return BinaryOperator::createAnd(Op0LHS, AndRHS);
1978 // If the mask is only needed on one incoming arm, push it up.
1979 if (Op0I->hasOneUse()) {
1980 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
1981 // Not masking anything out for the LHS, move to RHS.
1982 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
1983 Op0RHS->getName()+".masked");
1984 InsertNewInstBefore(NewRHS, I);
1985 return BinaryOperator::create(
1986 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
1988 if (!isa<Constant>(NotAndRHS) &&
1989 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
1990 // Not masking anything out for the RHS, move to LHS.
1991 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
1992 Op0LHS->getName()+".masked");
1993 InsertNewInstBefore(NewLHS, I);
1994 return BinaryOperator::create(
1995 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2000 case Instruction::And:
2001 // (X & V) & C2 --> 0 iff (V & C2) == 0
2002 if (MaskedValueIsZero(Op0LHS, AndRHS) ||
2003 MaskedValueIsZero(Op0RHS, AndRHS))
2004 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2006 case Instruction::Add:
2007 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2008 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2009 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2010 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2011 return BinaryOperator::createAnd(V, AndRHS);
2012 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2013 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
2016 case Instruction::Sub:
2017 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2018 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2019 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2020 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2021 return BinaryOperator::createAnd(V, AndRHS);
2025 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2026 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
2028 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2029 const Type *SrcTy = CI->getOperand(0)->getType();
2031 // If this is an integer truncation or change from signed-to-unsigned, and
2032 // if the source is an and/or with immediate, transform it. This
2033 // frequently occurs for bitfield accesses.
2034 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2035 if (SrcTy->getPrimitiveSizeInBits() >=
2036 I.getType()->getPrimitiveSizeInBits() &&
2037 CastOp->getNumOperands() == 2)
2038 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1)))
2039 if (CastOp->getOpcode() == Instruction::And) {
2040 // Change: and (cast (and X, C1) to T), C2
2041 // into : and (cast X to T), trunc(C1)&C2
2042 // This will folds the two ands together, which may allow other
2044 Instruction *NewCast =
2045 new CastInst(CastOp->getOperand(0), I.getType(),
2046 CastOp->getName()+".shrunk");
2047 NewCast = InsertNewInstBefore(NewCast, I);
2049 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2050 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2051 return BinaryOperator::createAnd(NewCast, C3);
2052 } else if (CastOp->getOpcode() == Instruction::Or) {
2053 // Change: and (cast (or X, C1) to T), C2
2054 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2055 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2056 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2057 return ReplaceInstUsesWith(I, AndRHS);
2062 // If this is an integer sign or zero extension instruction.
2063 if (SrcTy->isIntegral() &&
2064 SrcTy->getPrimitiveSizeInBits() <
2065 CI->getType()->getPrimitiveSizeInBits()) {
2067 if (SrcTy->isUnsigned()) {
2068 // See if this and is clearing out bits that are known to be zero
2069 // anyway (due to the zero extension).
2070 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
2071 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
2072 Constant *Result = ConstantExpr::getAnd(Mask, AndRHS);
2073 if (Result == Mask) // The "and" isn't doing anything, remove it.
2074 return ReplaceInstUsesWith(I, CI);
2075 if (Result != AndRHS) { // Reduce the and RHS constant.
2076 I.setOperand(1, Result);
2081 if (CI->hasOneUse() && SrcTy->isInteger()) {
2082 // We can only do this if all of the sign bits brought in are masked
2083 // out. Compute this by first getting 0000011111, then inverting
2085 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy);
2086 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType());
2087 Mask = ConstantExpr::getNot(Mask); // 1's in the new bits.
2088 if (ConstantExpr::getAnd(Mask, AndRHS)->isNullValue()) {
2089 // If the and is clearing all of the sign bits, change this to a
2090 // zero extension cast. To do this, cast the cast input to
2091 // unsigned, then to the requested size.
2092 Value *CastOp = CI->getOperand(0);
2094 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
2095 CI->getName()+".uns");
2096 NC = InsertNewInstBefore(NC, I);
2097 // Finally, insert a replacement for CI.
2098 NC = new CastInst(NC, CI->getType(), CI->getName());
2100 NC = InsertNewInstBefore(NC, I);
2101 WorkList.push_back(CI); // Delete CI later.
2102 I.setOperand(0, NC);
2103 return &I; // The AND operand was modified.
2110 // Try to fold constant and into select arguments.
2111 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2112 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2114 if (isa<PHINode>(Op0))
2115 if (Instruction *NV = FoldOpIntoPhi(I))
2119 Value *Op0NotVal = dyn_castNotVal(Op0);
2120 Value *Op1NotVal = dyn_castNotVal(Op1);
2122 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2123 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2125 // (~A & ~B) == (~(A | B)) - De Morgan's Law
2126 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2127 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2128 I.getName()+".demorgan");
2129 InsertNewInstBefore(Or, I);
2130 return BinaryOperator::createNot(Or);
2133 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2134 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2135 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2138 Value *LHSVal, *RHSVal;
2139 ConstantInt *LHSCst, *RHSCst;
2140 Instruction::BinaryOps LHSCC, RHSCC;
2141 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2142 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2143 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2144 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
2145 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
2146 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2147 // Ensure that the larger constant is on the RHS.
2148 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2149 SetCondInst *LHS = cast<SetCondInst>(Op0);
2150 if (cast<ConstantBool>(Cmp)->getValue()) {
2151 std::swap(LHS, RHS);
2152 std::swap(LHSCst, RHSCst);
2153 std::swap(LHSCC, RHSCC);
2156 // At this point, we know we have have two setcc instructions
2157 // comparing a value against two constants and and'ing the result
2158 // together. Because of the above check, we know that we only have
2159 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2160 // FoldSetCCLogical check above), that the two constants are not
2162 assert(LHSCst != RHSCst && "Compares not folded above?");
2165 default: assert(0 && "Unknown integer condition code!");
2166 case Instruction::SetEQ:
2168 default: assert(0 && "Unknown integer condition code!");
2169 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2170 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2171 return ReplaceInstUsesWith(I, ConstantBool::False);
2172 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2173 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2174 return ReplaceInstUsesWith(I, LHS);
2176 case Instruction::SetNE:
2178 default: assert(0 && "Unknown integer condition code!");
2179 case Instruction::SetLT:
2180 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2181 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2182 break; // (X != 13 & X < 15) -> no change
2183 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2184 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2185 return ReplaceInstUsesWith(I, RHS);
2186 case Instruction::SetNE:
2187 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2188 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2189 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2190 LHSVal->getName()+".off");
2191 InsertNewInstBefore(Add, I);
2192 const Type *UnsType = Add->getType()->getUnsignedVersion();
2193 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2194 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2195 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2196 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2198 break; // (X != 13 & X != 15) -> no change
2201 case Instruction::SetLT:
2203 default: assert(0 && "Unknown integer condition code!");
2204 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2205 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2206 return ReplaceInstUsesWith(I, ConstantBool::False);
2207 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2208 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2209 return ReplaceInstUsesWith(I, LHS);
2211 case Instruction::SetGT:
2213 default: assert(0 && "Unknown integer condition code!");
2214 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2215 return ReplaceInstUsesWith(I, LHS);
2216 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2217 return ReplaceInstUsesWith(I, RHS);
2218 case Instruction::SetNE:
2219 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2220 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2221 break; // (X > 13 & X != 15) -> no change
2222 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2223 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
2229 return Changed ? &I : 0;
2232 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
2233 bool Changed = SimplifyCommutative(I);
2234 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2236 if (isa<UndefValue>(Op1))
2237 return ReplaceInstUsesWith(I, // X | undef -> -1
2238 ConstantIntegral::getAllOnesValue(I.getType()));
2240 // or X, X = X or X, 0 == X
2241 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
2242 return ReplaceInstUsesWith(I, Op0);
2245 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
2246 // If X is known to only contain bits that already exist in RHS, just
2247 // replace this instruction with RHS directly.
2248 if (MaskedValueIsZero(Op0,
2249 cast<ConstantIntegral>(ConstantExpr::getNot(RHS))))
2250 return ReplaceInstUsesWith(I, RHS);
2252 ConstantInt *C1 = 0; Value *X = 0;
2253 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2254 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2255 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2257 InsertNewInstBefore(Or, I);
2258 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2261 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2262 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2263 std::string Op0Name = Op0->getName(); Op0->setName("");
2264 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2265 InsertNewInstBefore(Or, I);
2266 return BinaryOperator::createXor(Or,
2267 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
2270 // Try to fold constant and into select arguments.
2271 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2272 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2274 if (isa<PHINode>(Op0))
2275 if (Instruction *NV = FoldOpIntoPhi(I))
2279 Value *A = 0, *B = 0;
2280 ConstantInt *C1 = 0, *C2 = 0;
2282 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2283 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2284 return ReplaceInstUsesWith(I, Op1);
2285 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2286 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2287 return ReplaceInstUsesWith(I, Op0);
2289 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2290 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2291 MaskedValueIsZero(Op1, C1)) {
2292 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2294 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2297 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2298 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2299 MaskedValueIsZero(Op0, C1)) {
2300 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2302 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2305 // (A & C1)|(B & C2)
2306 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2307 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2309 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2310 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2313 // If we have: ((V + N) & C1) | (V & C2)
2314 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2315 // replace with V+N.
2316 if (C1 == ConstantExpr::getNot(C2)) {
2317 Value *V1 = 0, *V2 = 0;
2318 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2319 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2320 // Add commutes, try both ways.
2321 if (V1 == B && MaskedValueIsZero(V2, C2))
2322 return ReplaceInstUsesWith(I, A);
2323 if (V2 == B && MaskedValueIsZero(V1, C2))
2324 return ReplaceInstUsesWith(I, A);
2326 // Or commutes, try both ways.
2327 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2328 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2329 // Add commutes, try both ways.
2330 if (V1 == A && MaskedValueIsZero(V2, C1))
2331 return ReplaceInstUsesWith(I, B);
2332 if (V2 == A && MaskedValueIsZero(V1, C1))
2333 return ReplaceInstUsesWith(I, B);
2338 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2339 if (A == Op1) // ~A | A == -1
2340 return ReplaceInstUsesWith(I,
2341 ConstantIntegral::getAllOnesValue(I.getType()));
2345 // Note, A is still live here!
2346 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2348 return ReplaceInstUsesWith(I,
2349 ConstantIntegral::getAllOnesValue(I.getType()));
2351 // (~A | ~B) == (~(A & B)) - De Morgan's Law
2352 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2353 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2354 I.getName()+".demorgan"), I);
2355 return BinaryOperator::createNot(And);
2359 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
2360 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
2361 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2364 Value *LHSVal, *RHSVal;
2365 ConstantInt *LHSCst, *RHSCst;
2366 Instruction::BinaryOps LHSCC, RHSCC;
2367 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2368 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2369 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2370 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
2371 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
2372 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2373 // Ensure that the larger constant is on the RHS.
2374 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2375 SetCondInst *LHS = cast<SetCondInst>(Op0);
2376 if (cast<ConstantBool>(Cmp)->getValue()) {
2377 std::swap(LHS, RHS);
2378 std::swap(LHSCst, RHSCst);
2379 std::swap(LHSCC, RHSCC);
2382 // At this point, we know we have have two setcc instructions
2383 // comparing a value against two constants and or'ing the result
2384 // together. Because of the above check, we know that we only have
2385 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2386 // FoldSetCCLogical check above), that the two constants are not
2388 assert(LHSCst != RHSCst && "Compares not folded above?");
2391 default: assert(0 && "Unknown integer condition code!");
2392 case Instruction::SetEQ:
2394 default: assert(0 && "Unknown integer condition code!");
2395 case Instruction::SetEQ:
2396 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2397 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2398 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2399 LHSVal->getName()+".off");
2400 InsertNewInstBefore(Add, I);
2401 const Type *UnsType = Add->getType()->getUnsignedVersion();
2402 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2403 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2404 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2405 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2407 break; // (X == 13 | X == 15) -> no change
2409 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2411 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2412 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2413 return ReplaceInstUsesWith(I, RHS);
2416 case Instruction::SetNE:
2418 default: assert(0 && "Unknown integer condition code!");
2419 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2420 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2421 return ReplaceInstUsesWith(I, LHS);
2422 case Instruction::SetNE: // (X != 13 | X != 15) -> true
2423 case Instruction::SetLT: // (X != 13 | X < 15) -> true
2424 return ReplaceInstUsesWith(I, ConstantBool::True);
2427 case Instruction::SetLT:
2429 default: assert(0 && "Unknown integer condition code!");
2430 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2432 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2433 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
2434 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2435 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2436 return ReplaceInstUsesWith(I, RHS);
2439 case Instruction::SetGT:
2441 default: assert(0 && "Unknown integer condition code!");
2442 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2443 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2444 return ReplaceInstUsesWith(I, LHS);
2445 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2446 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2447 return ReplaceInstUsesWith(I, ConstantBool::True);
2453 return Changed ? &I : 0;
2456 // XorSelf - Implements: X ^ X --> 0
2459 XorSelf(Value *rhs) : RHS(rhs) {}
2460 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2461 Instruction *apply(BinaryOperator &Xor) const {
2467 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2468 bool Changed = SimplifyCommutative(I);
2469 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2471 if (isa<UndefValue>(Op1))
2472 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2474 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2475 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2476 assert(Result == &I && "AssociativeOpt didn't work?");
2477 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2480 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
2482 if (RHS->isNullValue())
2483 return ReplaceInstUsesWith(I, Op0);
2485 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2486 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
2487 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
2488 if (RHS == ConstantBool::True && SCI->hasOneUse())
2489 return new SetCondInst(SCI->getInverseCondition(),
2490 SCI->getOperand(0), SCI->getOperand(1));
2492 // ~(c-X) == X-c-1 == X+(-c-1)
2493 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2494 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2495 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2496 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2497 ConstantInt::get(I.getType(), 1));
2498 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
2501 // ~(~X & Y) --> (X | ~Y)
2502 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2503 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2504 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2506 BinaryOperator::createNot(Op0I->getOperand(1),
2507 Op0I->getOperand(1)->getName()+".not");
2508 InsertNewInstBefore(NotY, I);
2509 return BinaryOperator::createOr(Op0NotVal, NotY);
2513 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2514 switch (Op0I->getOpcode()) {
2515 case Instruction::Add:
2516 // ~(X-c) --> (-c-1)-X
2517 if (RHS->isAllOnesValue()) {
2518 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2519 return BinaryOperator::createSub(
2520 ConstantExpr::getSub(NegOp0CI,
2521 ConstantInt::get(I.getType(), 1)),
2522 Op0I->getOperand(0));
2525 case Instruction::And:
2526 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
2527 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
2528 return BinaryOperator::createOr(Op0, RHS);
2530 case Instruction::Or:
2531 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
2532 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
2533 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
2539 // Try to fold constant and into select arguments.
2540 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2541 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2543 if (isa<PHINode>(Op0))
2544 if (Instruction *NV = FoldOpIntoPhi(I))
2548 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
2550 return ReplaceInstUsesWith(I,
2551 ConstantIntegral::getAllOnesValue(I.getType()));
2553 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
2555 return ReplaceInstUsesWith(I,
2556 ConstantIntegral::getAllOnesValue(I.getType()));
2558 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
2559 if (Op1I->getOpcode() == Instruction::Or) {
2560 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2561 cast<BinaryOperator>(Op1I)->swapOperands();
2563 std::swap(Op0, Op1);
2564 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2566 std::swap(Op0, Op1);
2568 } else if (Op1I->getOpcode() == Instruction::Xor) {
2569 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2570 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2571 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2572 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2575 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
2576 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
2577 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
2578 cast<BinaryOperator>(Op0I)->swapOperands();
2579 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
2580 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
2581 Op1->getName()+".not"), I);
2582 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
2584 } else if (Op0I->getOpcode() == Instruction::Xor) {
2585 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
2586 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2587 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
2588 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2591 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
2592 ConstantInt *C1 = 0, *C2 = 0;
2593 if (match(Op0, m_And(m_Value(), m_ConstantInt(C1))) &&
2594 match(Op1, m_And(m_Value(), m_ConstantInt(C2))) &&
2595 ConstantExpr::getAnd(C1, C2)->isNullValue())
2596 return BinaryOperator::createOr(Op0, Op1);
2598 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
2599 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
2600 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2603 return Changed ? &I : 0;
2606 /// MulWithOverflow - Compute Result = In1*In2, returning true if the result
2607 /// overflowed for this type.
2608 static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2610 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
2611 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
2614 static bool isPositive(ConstantInt *C) {
2615 return cast<ConstantSInt>(C)->getValue() >= 0;
2618 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
2619 /// overflowed for this type.
2620 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
2622 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
2624 if (In1->getType()->isUnsigned())
2625 return cast<ConstantUInt>(Result)->getValue() <
2626 cast<ConstantUInt>(In1)->getValue();
2627 if (isPositive(In1) != isPositive(In2))
2629 if (isPositive(In1))
2630 return cast<ConstantSInt>(Result)->getValue() <
2631 cast<ConstantSInt>(In1)->getValue();
2632 return cast<ConstantSInt>(Result)->getValue() >
2633 cast<ConstantSInt>(In1)->getValue();
2636 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2637 /// code necessary to compute the offset from the base pointer (without adding
2638 /// in the base pointer). Return the result as a signed integer of intptr size.
2639 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
2640 TargetData &TD = IC.getTargetData();
2641 gep_type_iterator GTI = gep_type_begin(GEP);
2642 const Type *UIntPtrTy = TD.getIntPtrType();
2643 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
2644 Value *Result = Constant::getNullValue(SIntPtrTy);
2646 // Build a mask for high order bits.
2647 uint64_t PtrSizeMask = ~0ULL;
2648 PtrSizeMask >>= 64-(TD.getPointerSize()*8);
2650 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
2651 Value *Op = GEP->getOperand(i);
2652 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
2653 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
2655 if (Constant *OpC = dyn_cast<Constant>(Op)) {
2656 if (!OpC->isNullValue()) {
2657 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
2658 Scale = ConstantExpr::getMul(OpC, Scale);
2659 if (Constant *RC = dyn_cast<Constant>(Result))
2660 Result = ConstantExpr::getAdd(RC, Scale);
2662 // Emit an add instruction.
2663 Result = IC.InsertNewInstBefore(
2664 BinaryOperator::createAdd(Result, Scale,
2665 GEP->getName()+".offs"), I);
2669 // Convert to correct type.
2670 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
2671 Op->getName()+".c"), I);
2673 // We'll let instcombine(mul) convert this to a shl if possible.
2674 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
2675 GEP->getName()+".idx"), I);
2677 // Emit an add instruction.
2678 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
2679 GEP->getName()+".offs"), I);
2685 /// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
2686 /// else. At this point we know that the GEP is on the LHS of the comparison.
2687 Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
2688 Instruction::BinaryOps Cond,
2690 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
2692 if (CastInst *CI = dyn_cast<CastInst>(RHS))
2693 if (isa<PointerType>(CI->getOperand(0)->getType()))
2694 RHS = CI->getOperand(0);
2696 Value *PtrBase = GEPLHS->getOperand(0);
2697 if (PtrBase == RHS) {
2698 // As an optimization, we don't actually have to compute the actual value of
2699 // OFFSET if this is a seteq or setne comparison, just return whether each
2700 // index is zero or not.
2701 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
2702 Instruction *InVal = 0;
2703 gep_type_iterator GTI = gep_type_begin(GEPLHS);
2704 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
2706 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
2707 if (isa<UndefValue>(C)) // undef index -> undef.
2708 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2709 if (C->isNullValue())
2711 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
2712 EmitIt = false; // This is indexing into a zero sized array?
2713 } else if (isa<ConstantInt>(C))
2714 return ReplaceInstUsesWith(I, // No comparison is needed here.
2715 ConstantBool::get(Cond == Instruction::SetNE));
2720 new SetCondInst(Cond, GEPLHS->getOperand(i),
2721 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
2725 InVal = InsertNewInstBefore(InVal, I);
2726 InsertNewInstBefore(Comp, I);
2727 if (Cond == Instruction::SetNE) // True if any are unequal
2728 InVal = BinaryOperator::createOr(InVal, Comp);
2729 else // True if all are equal
2730 InVal = BinaryOperator::createAnd(InVal, Comp);
2738 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
2739 ConstantBool::get(Cond == Instruction::SetEQ));
2742 // Only lower this if the setcc is the only user of the GEP or if we expect
2743 // the result to fold to a constant!
2744 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
2745 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
2746 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
2747 return new SetCondInst(Cond, Offset,
2748 Constant::getNullValue(Offset->getType()));
2750 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
2751 // If the base pointers are different, but the indices are the same, just
2752 // compare the base pointer.
2753 if (PtrBase != GEPRHS->getOperand(0)) {
2754 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
2755 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
2756 GEPRHS->getOperand(0)->getType();
2758 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2759 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2760 IndicesTheSame = false;
2764 // If all indices are the same, just compare the base pointers.
2766 return new SetCondInst(Cond, GEPLHS->getOperand(0),
2767 GEPRHS->getOperand(0));
2769 // Otherwise, the base pointers are different and the indices are
2770 // different, bail out.
2774 // If one of the GEPs has all zero indices, recurse.
2775 bool AllZeros = true;
2776 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
2777 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
2778 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
2783 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
2784 SetCondInst::getSwappedCondition(Cond), I);
2786 // If the other GEP has all zero indices, recurse.
2788 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2789 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
2790 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
2795 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
2797 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
2798 // If the GEPs only differ by one index, compare it.
2799 unsigned NumDifferences = 0; // Keep track of # differences.
2800 unsigned DiffOperand = 0; // The operand that differs.
2801 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
2802 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
2803 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
2804 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
2805 // Irreconcilable differences.
2809 if (NumDifferences++) break;
2814 if (NumDifferences == 0) // SAME GEP?
2815 return ReplaceInstUsesWith(I, // No comparison is needed here.
2816 ConstantBool::get(Cond == Instruction::SetEQ));
2817 else if (NumDifferences == 1) {
2818 Value *LHSV = GEPLHS->getOperand(DiffOperand);
2819 Value *RHSV = GEPRHS->getOperand(DiffOperand);
2821 // Convert the operands to signed values to make sure to perform a
2822 // signed comparison.
2823 const Type *NewTy = LHSV->getType()->getSignedVersion();
2824 if (LHSV->getType() != NewTy)
2825 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
2826 LHSV->getName()), I);
2827 if (RHSV->getType() != NewTy)
2828 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
2829 RHSV->getName()), I);
2830 return new SetCondInst(Cond, LHSV, RHSV);
2834 // Only lower this if the setcc is the only user of the GEP or if we expect
2835 // the result to fold to a constant!
2836 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
2837 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
2838 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
2839 Value *L = EmitGEPOffset(GEPLHS, I, *this);
2840 Value *R = EmitGEPOffset(GEPRHS, I, *this);
2841 return new SetCondInst(Cond, L, R);
2848 Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
2849 bool Changed = SimplifyCommutative(I);
2850 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2851 const Type *Ty = Op0->getType();
2855 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
2857 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
2858 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
2860 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
2861 // addresses never equal each other! We already know that Op0 != Op1.
2862 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
2863 isa<ConstantPointerNull>(Op0)) &&
2864 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
2865 isa<ConstantPointerNull>(Op1)))
2866 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
2868 // setcc's with boolean values can always be turned into bitwise operations
2869 if (Ty == Type::BoolTy) {
2870 switch (I.getOpcode()) {
2871 default: assert(0 && "Invalid setcc instruction!");
2872 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
2873 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
2874 InsertNewInstBefore(Xor, I);
2875 return BinaryOperator::createNot(Xor);
2877 case Instruction::SetNE:
2878 return BinaryOperator::createXor(Op0, Op1);
2880 case Instruction::SetGT:
2881 std::swap(Op0, Op1); // Change setgt -> setlt
2883 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
2884 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2885 InsertNewInstBefore(Not, I);
2886 return BinaryOperator::createAnd(Not, Op1);
2888 case Instruction::SetGE:
2889 std::swap(Op0, Op1); // Change setge -> setle
2891 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
2892 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
2893 InsertNewInstBefore(Not, I);
2894 return BinaryOperator::createOr(Not, Op1);
2899 // See if we are doing a comparison between a constant and an instruction that
2900 // can be folded into the comparison.
2901 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2902 // Check to see if we are comparing against the minimum or maximum value...
2903 if (CI->isMinValue()) {
2904 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
2905 return ReplaceInstUsesWith(I, ConstantBool::False);
2906 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
2907 return ReplaceInstUsesWith(I, ConstantBool::True);
2908 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
2909 return BinaryOperator::createSetEQ(Op0, Op1);
2910 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
2911 return BinaryOperator::createSetNE(Op0, Op1);
2913 } else if (CI->isMaxValue()) {
2914 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
2915 return ReplaceInstUsesWith(I, ConstantBool::False);
2916 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
2917 return ReplaceInstUsesWith(I, ConstantBool::True);
2918 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
2919 return BinaryOperator::createSetEQ(Op0, Op1);
2920 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
2921 return BinaryOperator::createSetNE(Op0, Op1);
2923 // Comparing against a value really close to min or max?
2924 } else if (isMinValuePlusOne(CI)) {
2925 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
2926 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
2927 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
2928 return BinaryOperator::createSetNE(Op0, SubOne(CI));
2930 } else if (isMaxValueMinusOne(CI)) {
2931 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
2932 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
2933 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
2934 return BinaryOperator::createSetNE(Op0, AddOne(CI));
2937 // If we still have a setle or setge instruction, turn it into the
2938 // appropriate setlt or setgt instruction. Since the border cases have
2939 // already been handled above, this requires little checking.
2941 if (I.getOpcode() == Instruction::SetLE)
2942 return BinaryOperator::createSetLT(Op0, AddOne(CI));
2943 if (I.getOpcode() == Instruction::SetGE)
2944 return BinaryOperator::createSetGT(Op0, SubOne(CI));
2946 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
2947 switch (LHSI->getOpcode()) {
2948 case Instruction::And:
2949 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
2950 LHSI->getOperand(0)->hasOneUse()) {
2951 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
2952 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
2953 // happens a LOT in code produced by the C front-end, for bitfield
2955 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
2956 ConstantUInt *ShAmt;
2957 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
2958 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
2959 const Type *Ty = LHSI->getType();
2961 // We can fold this as long as we can't shift unknown bits
2962 // into the mask. This can only happen with signed shift
2963 // rights, as they sign-extend.
2965 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
2966 Shift->getType()->isUnsigned();
2968 // To test for the bad case of the signed shr, see if any
2969 // of the bits shifted in could be tested after the mask.
2970 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
2971 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
2973 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
2975 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
2976 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2982 if (Shift->getOpcode() == Instruction::Shl)
2983 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2985 NewCst = ConstantExpr::getShl(CI, ShAmt);
2987 // Check to see if we are shifting out any of the bits being
2989 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2990 // If we shifted bits out, the fold is not going to work out.
2991 // As a special case, check to see if this means that the
2992 // result is always true or false now.
2993 if (I.getOpcode() == Instruction::SetEQ)
2994 return ReplaceInstUsesWith(I, ConstantBool::False);
2995 if (I.getOpcode() == Instruction::SetNE)
2996 return ReplaceInstUsesWith(I, ConstantBool::True);
2998 I.setOperand(1, NewCst);
2999 Constant *NewAndCST;
3000 if (Shift->getOpcode() == Instruction::Shl)
3001 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3003 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3004 LHSI->setOperand(1, NewAndCST);
3005 LHSI->setOperand(0, Shift->getOperand(0));
3006 WorkList.push_back(Shift); // Shift is dead.
3007 AddUsesToWorkList(I);
3015 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3016 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3017 switch (I.getOpcode()) {
3019 case Instruction::SetEQ:
3020 case Instruction::SetNE: {
3021 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3023 // Check that the shift amount is in range. If not, don't perform
3024 // undefined shifts. When the shift is visited it will be
3026 if (ShAmt->getValue() >= TypeBits)
3029 // If we are comparing against bits always shifted out, the
3030 // comparison cannot succeed.
3032 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3033 if (Comp != CI) {// Comparing against a bit that we know is zero.
3034 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3035 Constant *Cst = ConstantBool::get(IsSetNE);
3036 return ReplaceInstUsesWith(I, Cst);
3039 if (LHSI->hasOneUse()) {
3040 // Otherwise strength reduce the shift into an and.
3041 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
3042 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3045 if (CI->getType()->isUnsigned()) {
3046 Mask = ConstantUInt::get(CI->getType(), Val);
3047 } else if (ShAmtVal != 0) {
3048 Mask = ConstantSInt::get(CI->getType(), Val);
3050 Mask = ConstantInt::getAllOnesValue(CI->getType());
3054 BinaryOperator::createAnd(LHSI->getOperand(0),
3055 Mask, LHSI->getName()+".mask");
3056 Value *And = InsertNewInstBefore(AndI, I);
3057 return new SetCondInst(I.getOpcode(), And,
3058 ConstantExpr::getUShr(CI, ShAmt));
3065 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
3066 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3067 switch (I.getOpcode()) {
3069 case Instruction::SetEQ:
3070 case Instruction::SetNE: {
3072 // Check that the shift amount is in range. If not, don't perform
3073 // undefined shifts. When the shift is visited it will be
3075 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3076 if (ShAmt->getValue() >= TypeBits)
3079 // If we are comparing against bits always shifted out, the
3080 // comparison cannot succeed.
3082 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
3084 if (Comp != CI) {// Comparing against a bit that we know is zero.
3085 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3086 Constant *Cst = ConstantBool::get(IsSetNE);
3087 return ReplaceInstUsesWith(I, Cst);
3090 if (LHSI->hasOneUse() || CI->isNullValue()) {
3091 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
3093 // Otherwise strength reduce the shift into an and.
3094 uint64_t Val = ~0ULL; // All ones.
3095 Val <<= ShAmtVal; // Shift over to the right spot.
3098 if (CI->getType()->isUnsigned()) {
3099 Val &= ~0ULL >> (64-TypeBits);
3100 Mask = ConstantUInt::get(CI->getType(), Val);
3102 Mask = ConstantSInt::get(CI->getType(), Val);
3106 BinaryOperator::createAnd(LHSI->getOperand(0),
3107 Mask, LHSI->getName()+".mask");
3108 Value *And = InsertNewInstBefore(AndI, I);
3109 return new SetCondInst(I.getOpcode(), And,
3110 ConstantExpr::getShl(CI, ShAmt));
3118 case Instruction::Div:
3119 // Fold: (div X, C1) op C2 -> range check
3120 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3121 // Fold this div into the comparison, producing a range check.
3122 // Determine, based on the divide type, what the range is being
3123 // checked. If there is an overflow on the low or high side, remember
3124 // it, otherwise compute the range [low, hi) bounding the new value.
3125 bool LoOverflow = false, HiOverflow = 0;
3126 ConstantInt *LoBound = 0, *HiBound = 0;
3129 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3131 Instruction::BinaryOps Opcode = I.getOpcode();
3133 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
3134 } else if (LHSI->getType()->isUnsigned()) { // udiv
3136 LoOverflow = ProdOV;
3137 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3138 } else if (isPositive(DivRHS)) { // Divisor is > 0.
3139 if (CI->isNullValue()) { // (X / pos) op 0
3141 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3143 } else if (isPositive(CI)) { // (X / pos) op pos
3145 LoOverflow = ProdOV;
3146 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3147 } else { // (X / pos) op neg
3148 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3149 LoOverflow = AddWithOverflow(LoBound, Prod,
3150 cast<ConstantInt>(DivRHSH));
3152 HiOverflow = ProdOV;
3154 } else { // Divisor is < 0.
3155 if (CI->isNullValue()) { // (X / neg) op 0
3156 LoBound = AddOne(DivRHS);
3157 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
3158 if (HiBound == DivRHS)
3159 LoBound = 0; // - INTMIN = INTMIN
3160 } else if (isPositive(CI)) { // (X / neg) op pos
3161 HiOverflow = LoOverflow = ProdOV;
3163 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3164 HiBound = AddOne(Prod);
3165 } else { // (X / neg) op neg
3167 LoOverflow = HiOverflow = ProdOV;
3168 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3171 // Dividing by a negate swaps the condition.
3172 Opcode = SetCondInst::getSwappedCondition(Opcode);
3176 Value *X = LHSI->getOperand(0);
3178 default: assert(0 && "Unhandled setcc opcode!");
3179 case Instruction::SetEQ:
3180 if (LoOverflow && HiOverflow)
3181 return ReplaceInstUsesWith(I, ConstantBool::False);
3182 else if (HiOverflow)
3183 return new SetCondInst(Instruction::SetGE, X, LoBound);
3184 else if (LoOverflow)
3185 return new SetCondInst(Instruction::SetLT, X, HiBound);
3187 return InsertRangeTest(X, LoBound, HiBound, true, I);
3188 case Instruction::SetNE:
3189 if (LoOverflow && HiOverflow)
3190 return ReplaceInstUsesWith(I, ConstantBool::True);
3191 else if (HiOverflow)
3192 return new SetCondInst(Instruction::SetLT, X, LoBound);
3193 else if (LoOverflow)
3194 return new SetCondInst(Instruction::SetGE, X, HiBound);
3196 return InsertRangeTest(X, LoBound, HiBound, false, I);
3197 case Instruction::SetLT:
3199 return ReplaceInstUsesWith(I, ConstantBool::False);
3200 return new SetCondInst(Instruction::SetLT, X, LoBound);
3201 case Instruction::SetGT:
3203 return ReplaceInstUsesWith(I, ConstantBool::False);
3204 return new SetCondInst(Instruction::SetGE, X, HiBound);
3211 // Simplify seteq and setne instructions...
3212 if (I.getOpcode() == Instruction::SetEQ ||
3213 I.getOpcode() == Instruction::SetNE) {
3214 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3216 // If the first operand is (and|or|xor) with a constant, and the second
3217 // operand is a constant, simplify a bit.
3218 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3219 switch (BO->getOpcode()) {
3220 case Instruction::Rem:
3221 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3222 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3224 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3225 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3226 if (isPowerOf2_64(V)) {
3227 unsigned L2 = Log2_64(V);
3228 const Type *UTy = BO->getType()->getUnsignedVersion();
3229 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3231 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3232 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3233 RHSCst, BO->getName()), I);
3234 return BinaryOperator::create(I.getOpcode(), NewRem,
3235 Constant::getNullValue(UTy));
3240 case Instruction::Add:
3241 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3242 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3243 if (BO->hasOneUse())
3244 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3245 ConstantExpr::getSub(CI, BOp1C));
3246 } else if (CI->isNullValue()) {
3247 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3248 // efficiently invertible, or if the add has just this one use.
3249 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3251 if (Value *NegVal = dyn_castNegVal(BOp1))
3252 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3253 else if (Value *NegVal = dyn_castNegVal(BOp0))
3254 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
3255 else if (BO->hasOneUse()) {
3256 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3258 InsertNewInstBefore(Neg, I);
3259 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3263 case Instruction::Xor:
3264 // For the xor case, we can xor two constants together, eliminating
3265 // the explicit xor.
3266 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3267 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
3268 ConstantExpr::getXor(CI, BOC));
3271 case Instruction::Sub:
3272 // Replace (([sub|xor] A, B) != 0) with (A != B)
3273 if (CI->isNullValue())
3274 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3278 case Instruction::Or:
3279 // If bits are being or'd in that are not present in the constant we
3280 // are comparing against, then the comparison could never succeed!
3281 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
3282 Constant *NotCI = ConstantExpr::getNot(CI);
3283 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
3284 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
3288 case Instruction::And:
3289 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3290 // If bits are being compared against that are and'd out, then the
3291 // comparison can never succeed!
3292 if (!ConstantExpr::getAnd(CI,
3293 ConstantExpr::getNot(BOC))->isNullValue())
3294 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
3296 // If we have ((X & C) == C), turn it into ((X & C) != 0).
3297 if (CI == BOC && isOneBitSet(CI))
3298 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3299 Instruction::SetNE, Op0,
3300 Constant::getNullValue(CI->getType()));
3302 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3303 // to be a signed value as appropriate.
3304 if (isSignBit(BOC)) {
3305 Value *X = BO->getOperand(0);
3306 // If 'X' is not signed, insert a cast now...
3307 if (!BOC->getType()->isSigned()) {
3308 const Type *DestTy = BOC->getType()->getSignedVersion();
3309 X = InsertCastBefore(X, DestTy, I);
3311 return new SetCondInst(isSetNE ? Instruction::SetLT :
3312 Instruction::SetGE, X,
3313 Constant::getNullValue(X->getType()));
3316 // ((X & ~7) == 0) --> X < 8
3317 if (CI->isNullValue() && isHighOnes(BOC)) {
3318 Value *X = BO->getOperand(0);
3319 Constant *NegX = ConstantExpr::getNeg(BOC);
3321 // If 'X' is signed, insert a cast now.
3322 if (NegX->getType()->isSigned()) {
3323 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3324 X = InsertCastBefore(X, DestTy, I);
3325 NegX = ConstantExpr::getCast(NegX, DestTy);
3328 return new SetCondInst(isSetNE ? Instruction::SetGE :
3329 Instruction::SetLT, X, NegX);
3336 } else { // Not a SetEQ/SetNE
3337 // If the LHS is a cast from an integral value of the same size,
3338 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3339 Value *CastOp = Cast->getOperand(0);
3340 const Type *SrcTy = CastOp->getType();
3341 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
3342 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
3343 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
3344 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
3345 "Source and destination signednesses should differ!");
3346 if (Cast->getType()->isSigned()) {
3347 // If this is a signed comparison, check for comparisons in the
3348 // vicinity of zero.
3349 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3351 return BinaryOperator::createSetGT(CastOp,
3352 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
3353 else if (I.getOpcode() == Instruction::SetGT &&
3354 cast<ConstantSInt>(CI)->getValue() == -1)
3355 // X > -1 => x < 128
3356 return BinaryOperator::createSetLT(CastOp,
3357 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
3359 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3360 if (I.getOpcode() == Instruction::SetLT &&
3361 CUI->getValue() == 1ULL << (SrcTySize-1))
3362 // X < 128 => X > -1
3363 return BinaryOperator::createSetGT(CastOp,
3364 ConstantSInt::get(SrcTy, -1));
3365 else if (I.getOpcode() == Instruction::SetGT &&
3366 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
3368 return BinaryOperator::createSetLT(CastOp,
3369 Constant::getNullValue(SrcTy));
3376 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3377 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3378 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3379 switch (LHSI->getOpcode()) {
3380 case Instruction::GetElementPtr:
3381 if (RHSC->isNullValue()) {
3382 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3383 bool isAllZeros = true;
3384 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3385 if (!isa<Constant>(LHSI->getOperand(i)) ||
3386 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3391 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3392 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3396 case Instruction::PHI:
3397 if (Instruction *NV = FoldOpIntoPhi(I))
3400 case Instruction::Select:
3401 // If either operand of the select is a constant, we can fold the
3402 // comparison into the select arms, which will cause one to be
3403 // constant folded and the select turned into a bitwise or.
3404 Value *Op1 = 0, *Op2 = 0;
3405 if (LHSI->hasOneUse()) {
3406 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3407 // Fold the known value into the constant operand.
3408 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3409 // Insert a new SetCC of the other select operand.
3410 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3411 LHSI->getOperand(2), RHSC,
3413 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3414 // Fold the known value into the constant operand.
3415 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3416 // Insert a new SetCC of the other select operand.
3417 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3418 LHSI->getOperand(1), RHSC,
3424 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3429 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3430 if (User *GEP = dyn_castGetElementPtr(Op0))
3431 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3433 if (User *GEP = dyn_castGetElementPtr(Op1))
3434 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3435 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3438 // Test to see if the operands of the setcc are casted versions of other
3439 // values. If the cast can be stripped off both arguments, we do so now.
3440 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3441 Value *CastOp0 = CI->getOperand(0);
3442 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
3443 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
3444 (I.getOpcode() == Instruction::SetEQ ||
3445 I.getOpcode() == Instruction::SetNE)) {
3446 // We keep moving the cast from the left operand over to the right
3447 // operand, where it can often be eliminated completely.
3450 // If operand #1 is a cast instruction, see if we can eliminate it as
3452 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3453 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
3455 Op1 = CI2->getOperand(0);
3457 // If Op1 is a constant, we can fold the cast into the constant.
3458 if (Op1->getType() != Op0->getType())
3459 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3460 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3462 // Otherwise, cast the RHS right before the setcc
3463 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3464 InsertNewInstBefore(cast<Instruction>(Op1), I);
3466 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3469 // Handle the special case of: setcc (cast bool to X), <cst>
3470 // This comes up when you have code like
3473 // For generality, we handle any zero-extension of any operand comparison
3474 // with a constant or another cast from the same type.
3475 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3476 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3479 return Changed ? &I : 0;
3482 // visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
3483 // We only handle extending casts so far.
3485 Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
3486 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
3487 const Type *SrcTy = LHSCIOp->getType();
3488 const Type *DestTy = SCI.getOperand(0)->getType();
3491 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
3494 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
3495 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
3496 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
3498 // Is this a sign or zero extension?
3499 bool isSignSrc = SrcTy->isSigned();
3500 bool isSignDest = DestTy->isSigned();
3502 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
3503 // Not an extension from the same type?
3504 RHSCIOp = CI->getOperand(0);
3505 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
3506 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
3507 // Compute the constant that would happen if we truncated to SrcTy then
3508 // reextended to DestTy.
3509 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
3511 if (ConstantExpr::getCast(Res, DestTy) == CI) {
3514 // If the value cannot be represented in the shorter type, we cannot emit
3515 // a simple comparison.
3516 if (SCI.getOpcode() == Instruction::SetEQ)
3517 return ReplaceInstUsesWith(SCI, ConstantBool::False);
3518 if (SCI.getOpcode() == Instruction::SetNE)
3519 return ReplaceInstUsesWith(SCI, ConstantBool::True);
3521 // Evaluate the comparison for LT.
3523 if (DestTy->isSigned()) {
3524 // We're performing a signed comparison.
3526 // Signed extend and signed comparison.
3527 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
3528 Result = ConstantBool::False;
3530 Result = ConstantBool::True; // X < (large) --> true
3532 // Unsigned extend and signed comparison.
3533 if (cast<ConstantSInt>(CI)->getValue() < 0)
3534 Result = ConstantBool::False;
3536 Result = ConstantBool::True;
3539 // We're performing an unsigned comparison.
3541 // Unsigned extend & compare -> always true.
3542 Result = ConstantBool::True;
3544 // We're performing an unsigned comp with a sign extended value.
3545 // This is true if the input is >= 0. [aka >s -1]
3546 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
3547 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
3548 NegOne, SCI.getName()), SCI);
3552 // Finally, return the value computed.
3553 if (SCI.getOpcode() == Instruction::SetLT) {
3554 return ReplaceInstUsesWith(SCI, Result);
3556 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
3557 if (Constant *CI = dyn_cast<Constant>(Result))
3558 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
3560 return BinaryOperator::createNot(Result);
3567 // Okay, just insert a compare of the reduced operands now!
3568 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
3571 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
3572 assert(I.getOperand(1)->getType() == Type::UByteTy);
3573 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3574 bool isLeftShift = I.getOpcode() == Instruction::Shl;
3576 // shl X, 0 == X and shr X, 0 == X
3577 // shl 0, X == 0 and shr 0, X == 0
3578 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
3579 Op0 == Constant::getNullValue(Op0->getType()))
3580 return ReplaceInstUsesWith(I, Op0);
3582 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
3583 if (!isLeftShift && I.getType()->isSigned())
3584 return ReplaceInstUsesWith(I, Op0);
3585 else // undef << X -> 0 AND undef >>u X -> 0
3586 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3588 if (isa<UndefValue>(Op1)) {
3589 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
3590 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3592 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
3595 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
3597 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
3598 if (CSI->isAllOnesValue())
3599 return ReplaceInstUsesWith(I, CSI);
3601 // Try to fold constant and into select arguments.
3602 if (isa<Constant>(Op0))
3603 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3604 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3607 // See if we can turn a signed shr into an unsigned shr.
3608 if (!isLeftShift && I.getType()->isSigned()) {
3609 if (MaskedValueIsZero(Op0, ConstantInt::getMinValue(I.getType()))) {
3610 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
3611 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
3613 return new CastInst(V, I.getType());
3617 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
3618 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
3623 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
3625 bool isLeftShift = I.getOpcode() == Instruction::Shl;
3626 bool isSignedShift = Op0->getType()->isSigned();
3627 bool isUnsignedShift = !isSignedShift;
3629 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
3630 // of a signed value.
3632 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
3633 if (Op1->getValue() >= TypeBits) {
3634 if (isUnsignedShift || isLeftShift)
3635 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
3637 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
3642 // ((X*C1) << C2) == (X * (C1 << C2))
3643 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
3644 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
3645 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
3646 return BinaryOperator::createMul(BO->getOperand(0),
3647 ConstantExpr::getShl(BOOp, Op1));
3649 // Try to fold constant and into select arguments.
3650 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3651 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3653 if (isa<PHINode>(Op0))
3654 if (Instruction *NV = FoldOpIntoPhi(I))
3657 if (Op0->hasOneUse()) {
3658 // If this is a SHL of a sign-extending cast, see if we can turn the input
3659 // into a zero extending cast (a simple strength reduction).
3660 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3661 const Type *SrcTy = CI->getOperand(0)->getType();
3662 if (isLeftShift && SrcTy->isInteger() && SrcTy->isSigned() &&
3663 SrcTy->getPrimitiveSizeInBits() <
3664 CI->getType()->getPrimitiveSizeInBits()) {
3665 // We can change it to a zero extension if we are shifting out all of
3666 // the sign extended bits. To check this, form a mask of all of the
3667 // sign extend bits, then shift them left and see if we have anything
3669 Constant *Mask = ConstantIntegral::getAllOnesValue(SrcTy); // 1111
3670 Mask = ConstantExpr::getZeroExtend(Mask, CI->getType()); // 00001111
3671 Mask = ConstantExpr::getNot(Mask); // 1's in the sign bits: 11110000
3672 if (ConstantExpr::getShl(Mask, Op1)->isNullValue()) {
3673 // If the shift is nuking all of the sign bits, change this to a
3674 // zero extension cast. To do this, cast the cast input to
3675 // unsigned, then to the requested size.
3676 Value *CastOp = CI->getOperand(0);
3678 new CastInst(CastOp, CastOp->getType()->getUnsignedVersion(),
3679 CI->getName()+".uns");
3680 NC = InsertNewInstBefore(NC, I);
3681 // Finally, insert a replacement for CI.
3682 NC = new CastInst(NC, CI->getType(), CI->getName());
3684 NC = InsertNewInstBefore(NC, I);
3685 WorkList.push_back(CI); // Delete CI later.
3686 I.setOperand(0, NC);
3687 return &I; // The SHL operand was modified.
3692 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
3693 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
3696 switch (Op0BO->getOpcode()) {
3698 case Instruction::Add:
3699 case Instruction::And:
3700 case Instruction::Or:
3701 case Instruction::Xor:
3702 // These operators commute.
3703 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
3704 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3705 match(Op0BO->getOperand(1),
3706 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
3707 Instruction *YS = new ShiftInst(Instruction::Shl,
3708 Op0BO->getOperand(0), Op1,
3710 InsertNewInstBefore(YS, I); // (Y << C)
3711 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3713 Op0BO->getOperand(1)->getName());
3714 InsertNewInstBefore(X, I); // (X + (Y << C))
3715 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3716 C2 = ConstantExpr::getShl(C2, Op1);
3717 return BinaryOperator::createAnd(X, C2);
3720 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
3721 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
3722 match(Op0BO->getOperand(1),
3723 m_And(m_Shr(m_Value(V1), m_Value(V2)),
3724 m_ConstantInt(CC))) && V2 == Op1 &&
3725 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
3726 Instruction *YS = new ShiftInst(Instruction::Shl,
3727 Op0BO->getOperand(0), Op1,
3729 InsertNewInstBefore(YS, I); // (Y << C)
3731 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
3732 V1->getName()+".mask");
3733 InsertNewInstBefore(XM, I); // X & (CC << C)
3735 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3739 case Instruction::Sub:
3740 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
3741 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3742 match(Op0BO->getOperand(0),
3743 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
3744 Instruction *YS = new ShiftInst(Instruction::Shl,
3745 Op0BO->getOperand(1), Op1,
3747 InsertNewInstBefore(YS, I); // (Y << C)
3748 Instruction *X = BinaryOperator::create(Op0BO->getOpcode(), YS,
3750 Op0BO->getOperand(0)->getName());
3751 InsertNewInstBefore(X, I); // (X + (Y << C))
3752 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
3753 C2 = ConstantExpr::getShl(C2, Op1);
3754 return BinaryOperator::createAnd(X, C2);
3757 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
3758 match(Op0BO->getOperand(0),
3759 m_And(m_Shr(m_Value(V1), m_Value(V2)),
3760 m_ConstantInt(CC))) && V2 == Op1 &&
3761 cast<BinaryOperator>(Op0BO->getOperand(0))->getOperand(0)->hasOneUse()) {
3762 Instruction *YS = new ShiftInst(Instruction::Shl,
3763 Op0BO->getOperand(1), Op1,
3765 InsertNewInstBefore(YS, I); // (Y << C)
3767 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
3768 V1->getName()+".mask");
3769 InsertNewInstBefore(XM, I); // X & (CC << C)
3771 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
3778 // If the operand is an bitwise operator with a constant RHS, and the
3779 // shift is the only use, we can pull it out of the shift.
3780 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
3781 bool isValid = true; // Valid only for And, Or, Xor
3782 bool highBitSet = false; // Transform if high bit of constant set?
3784 switch (Op0BO->getOpcode()) {
3785 default: isValid = false; break; // Do not perform transform!
3786 case Instruction::Add:
3787 isValid = isLeftShift;
3789 case Instruction::Or:
3790 case Instruction::Xor:
3793 case Instruction::And:
3798 // If this is a signed shift right, and the high bit is modified
3799 // by the logical operation, do not perform the transformation.
3800 // The highBitSet boolean indicates the value of the high bit of
3801 // the constant which would cause it to be modified for this
3804 if (isValid && !isLeftShift && isSignedShift) {
3805 uint64_t Val = Op0C->getRawValue();
3806 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
3810 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
3812 Instruction *NewShift =
3813 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
3816 InsertNewInstBefore(NewShift, I);
3818 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
3825 // Find out if this is a shift of a shift by a constant.
3826 ShiftInst *ShiftOp = 0;
3827 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
3829 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3830 // If this is a noop-integer case of a shift instruction, use the shift.
3831 if (CI->getOperand(0)->getType()->isInteger() &&
3832 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3833 CI->getType()->getPrimitiveSizeInBits() &&
3834 isa<ShiftInst>(CI->getOperand(0))) {
3835 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
3839 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
3840 // Find the operands and properties of the input shift. Note that the
3841 // signedness of the input shift may differ from the current shift if there
3842 // is a noop cast between the two.
3843 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
3844 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
3845 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
3847 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
3849 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
3850 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
3852 // Check for (A << c1) << c2 and (A >> c1) >> c2.
3853 if (isLeftShift == isShiftOfLeftShift) {
3854 // Do not fold these shifts if the first one is signed and the second one
3855 // is unsigned and this is a right shift. Further, don't do any folding
3857 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
3860 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
3861 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
3862 Amt = Op0->getType()->getPrimitiveSizeInBits();
3864 Value *Op = ShiftOp->getOperand(0);
3865 if (isShiftOfSignedShift != isSignedShift)
3866 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
3867 return new ShiftInst(I.getOpcode(), Op,
3868 ConstantUInt::get(Type::UByteTy, Amt));
3871 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
3872 // signed types, we can only support the (A >> c1) << c2 configuration,
3873 // because it can not turn an arbitrary bit of A into a sign bit.
3874 if (isUnsignedShift || isLeftShift) {
3875 // Calculate bitmask for what gets shifted off the edge.
3876 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
3878 C = ConstantExpr::getShl(C, ShiftAmt1C);
3880 C = ConstantExpr::getUShr(C, ShiftAmt1C);
3882 Value *Op = ShiftOp->getOperand(0);
3883 if (isShiftOfSignedShift != isSignedShift)
3884 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
3887 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
3888 InsertNewInstBefore(Mask, I);
3890 // Figure out what flavor of shift we should use...
3891 if (ShiftAmt1 == ShiftAmt2) {
3892 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
3893 } else if (ShiftAmt1 < ShiftAmt2) {
3894 return new ShiftInst(I.getOpcode(), Mask,
3895 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
3896 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
3897 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
3898 // Make sure to emit an unsigned shift right, not a signed one.
3899 Mask = InsertNewInstBefore(new CastInst(Mask,
3900 Mask->getType()->getUnsignedVersion(),
3902 Mask = new ShiftInst(Instruction::Shr, Mask,
3903 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3904 InsertNewInstBefore(Mask, I);
3905 return new CastInst(Mask, I.getType());
3907 return new ShiftInst(ShiftOp->getOpcode(), Mask,
3908 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3911 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
3912 Op = InsertNewInstBefore(new CastInst(Mask,
3913 I.getType()->getSignedVersion(),
3914 Mask->getName()), I);
3915 Instruction *Shift =
3916 new ShiftInst(ShiftOp->getOpcode(), Op,
3917 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
3918 InsertNewInstBefore(Shift, I);
3920 C = ConstantIntegral::getAllOnesValue(Shift->getType());
3921 C = ConstantExpr::getShl(C, Op1);
3922 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
3923 InsertNewInstBefore(Mask, I);
3924 return new CastInst(Mask, I.getType());
3927 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
3928 // this case, C1 == C2 and C1 is 8, 16, or 32.
3929 if (ShiftAmt1 == ShiftAmt2) {
3930 const Type *SExtType = 0;
3931 switch (ShiftAmt1) {
3932 case 8 : SExtType = Type::SByteTy; break;
3933 case 16: SExtType = Type::ShortTy; break;
3934 case 32: SExtType = Type::IntTy; break;
3938 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
3940 InsertNewInstBefore(NewTrunc, I);
3941 return new CastInst(NewTrunc, I.getType());
3956 /// getCastType - In the future, we will split the cast instruction into these
3957 /// various types. Until then, we have to do the analysis here.
3958 static CastType getCastType(const Type *Src, const Type *Dest) {
3959 assert(Src->isIntegral() && Dest->isIntegral() &&
3960 "Only works on integral types!");
3961 unsigned SrcSize = Src->getPrimitiveSizeInBits();
3962 unsigned DestSize = Dest->getPrimitiveSizeInBits();
3964 if (SrcSize == DestSize) return Noop;
3965 if (SrcSize > DestSize) return Truncate;
3966 if (Src->isSigned()) return Signext;
3971 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
3974 static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
3975 const Type *DstTy, TargetData *TD) {
3977 // It is legal to eliminate the instruction if casting A->B->A if the sizes
3978 // are identical and the bits don't get reinterpreted (for example
3979 // int->float->int would not be allowed).
3980 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
3983 // If we are casting between pointer and integer types, treat pointers as
3984 // integers of the appropriate size for the code below.
3985 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
3986 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
3987 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
3989 // Allow free casting and conversion of sizes as long as the sign doesn't
3991 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
3992 CastType FirstCast = getCastType(SrcTy, MidTy);
3993 CastType SecondCast = getCastType(MidTy, DstTy);
3995 // Capture the effect of these two casts. If the result is a legal cast,
3996 // the CastType is stored here, otherwise a special code is used.
3997 static const unsigned CastResult[] = {
3998 // First cast is noop
4000 // First cast is a truncate
4001 1, 1, 4, 4, // trunc->extend is not safe to eliminate
4002 // First cast is a sign ext
4003 2, 5, 2, 4, // signext->zeroext never ok
4004 // First cast is a zero ext
4008 unsigned Result = CastResult[FirstCast*4+SecondCast];
4010 default: assert(0 && "Illegal table value!");
4015 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
4016 // truncates, we could eliminate more casts.
4017 return (unsigned)getCastType(SrcTy, DstTy) == Result;
4019 return false; // Not possible to eliminate this here.
4021 // Sign or zero extend followed by truncate is always ok if the result
4022 // is a truncate or noop.
4023 CastType ResultCast = getCastType(SrcTy, DstTy);
4024 if (ResultCast == Noop || ResultCast == Truncate)
4026 // Otherwise we are still growing the value, we are only safe if the
4027 // result will match the sign/zeroextendness of the result.
4028 return ResultCast == FirstCast;
4032 // If this is a cast from 'float -> double -> integer', cast from
4033 // 'float -> integer' directly, as the value isn't changed by the
4034 // float->double conversion.
4035 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
4036 DstTy->isIntegral() &&
4037 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
4043 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
4044 if (V->getType() == Ty || isa<Constant>(V)) return false;
4045 if (const CastInst *CI = dyn_cast<CastInst>(V))
4046 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
4052 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
4053 /// InsertBefore instruction. This is specialized a bit to avoid inserting
4054 /// casts that are known to not do anything...
4056 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
4057 Instruction *InsertBefore) {
4058 if (V->getType() == DestTy) return V;
4059 if (Constant *C = dyn_cast<Constant>(V))
4060 return ConstantExpr::getCast(C, DestTy);
4062 CastInst *CI = new CastInst(V, DestTy, V->getName());
4063 InsertNewInstBefore(CI, *InsertBefore);
4067 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4068 /// expression. If so, decompose it, returning some value X, such that Val is
4071 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4073 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4074 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4075 Offset = CI->getValue();
4077 return ConstantUInt::get(Type::UIntTy, 0);
4078 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4079 if (I->getNumOperands() == 2) {
4080 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4081 if (I->getOpcode() == Instruction::Shl) {
4082 // This is a value scaled by '1 << the shift amt'.
4083 Scale = 1U << CUI->getValue();
4085 return I->getOperand(0);
4086 } else if (I->getOpcode() == Instruction::Mul) {
4087 // This value is scaled by 'CUI'.
4088 Scale = CUI->getValue();
4090 return I->getOperand(0);
4091 } else if (I->getOpcode() == Instruction::Add) {
4092 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4095 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4097 Offset += CUI->getValue();
4098 if (SubScale > 1 && (Offset % SubScale == 0)) {
4107 // Otherwise, we can't look past this.
4114 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4115 /// try to eliminate the cast by moving the type information into the alloc.
4116 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4117 AllocationInst &AI) {
4118 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
4119 if (!PTy) return 0; // Not casting the allocation to a pointer type.
4121 // Remove any uses of AI that are dead.
4122 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4123 std::vector<Instruction*> DeadUsers;
4124 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4125 Instruction *User = cast<Instruction>(*UI++);
4126 if (isInstructionTriviallyDead(User)) {
4127 while (UI != E && *UI == User)
4128 ++UI; // If this instruction uses AI more than once, don't break UI.
4130 // Add operands to the worklist.
4131 AddUsesToWorkList(*User);
4133 DEBUG(std::cerr << "IC: DCE: " << *User);
4135 User->eraseFromParent();
4136 removeFromWorkList(User);
4140 // Get the type really allocated and the type casted to.
4141 const Type *AllocElTy = AI.getAllocatedType();
4142 const Type *CastElTy = PTy->getElementType();
4143 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
4145 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4146 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4147 if (CastElTyAlign < AllocElTyAlign) return 0;
4149 // If the allocation has multiple uses, only promote it if we are strictly
4150 // increasing the alignment of the resultant allocation. If we keep it the
4151 // same, we open the door to infinite loops of various kinds.
4152 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4154 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4155 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
4156 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
4158 // See if we can satisfy the modulus by pulling a scale out of the array
4160 unsigned ArraySizeScale, ArrayOffset;
4161 Value *NumElements = // See if the array size is a decomposable linear expr.
4162 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4164 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4166 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4167 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
4169 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4174 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4175 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4176 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4177 else if (Scale != 1) {
4178 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4179 Amt = InsertNewInstBefore(Tmp, AI);
4183 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4184 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4185 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4186 Amt = InsertNewInstBefore(Tmp, AI);
4189 std::string Name = AI.getName(); AI.setName("");
4190 AllocationInst *New;
4191 if (isa<MallocInst>(AI))
4192 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
4194 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
4195 InsertNewInstBefore(New, AI);
4197 // If the allocation has multiple uses, insert a cast and change all things
4198 // that used it to use the new cast. This will also hack on CI, but it will
4200 if (!AI.hasOneUse()) {
4201 AddUsesToWorkList(AI);
4202 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4203 InsertNewInstBefore(NewCast, AI);
4204 AI.replaceAllUsesWith(NewCast);
4206 return ReplaceInstUsesWith(CI, New);
4210 // CastInst simplification
4212 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
4213 Value *Src = CI.getOperand(0);
4215 // If the user is casting a value to the same type, eliminate this cast
4217 if (CI.getType() == Src->getType())
4218 return ReplaceInstUsesWith(CI, Src);
4220 if (isa<UndefValue>(Src)) // cast undef -> undef
4221 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4223 // If casting the result of another cast instruction, try to eliminate this
4226 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4227 Value *A = CSrc->getOperand(0);
4228 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4229 CI.getType(), TD)) {
4230 // This instruction now refers directly to the cast's src operand. This
4231 // has a good chance of making CSrc dead.
4232 CI.setOperand(0, CSrc->getOperand(0));
4236 // If this is an A->B->A cast, and we are dealing with integral types, try
4237 // to convert this into a logical 'and' instruction.
4239 if (A->getType()->isInteger() &&
4240 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
4241 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
4242 CSrc->getType()->getPrimitiveSizeInBits() <
4243 CI.getType()->getPrimitiveSizeInBits()&&
4244 A->getType()->getPrimitiveSizeInBits() ==
4245 CI.getType()->getPrimitiveSizeInBits()) {
4246 assert(CSrc->getType() != Type::ULongTy &&
4247 "Cannot have type bigger than ulong!");
4248 uint64_t AndValue = ~0ULL>>(64-CSrc->getType()->getPrimitiveSizeInBits());
4249 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4251 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4252 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4253 if (And->getType() != CI.getType()) {
4254 And->setName(CSrc->getName()+".mask");
4255 InsertNewInstBefore(And, CI);
4256 And = new CastInst(And, CI.getType());
4262 // If this is a cast to bool, turn it into the appropriate setne instruction.
4263 if (CI.getType() == Type::BoolTy)
4264 return BinaryOperator::createSetNE(CI.getOperand(0),
4265 Constant::getNullValue(CI.getOperand(0)->getType()));
4267 // See if we can simplify any instructions used by the LHS whose sole
4268 // purpose is to compute bits we don't care about.
4269 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral() &&
4270 SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask()))
4273 // If casting the result of a getelementptr instruction with no offset, turn
4274 // this into a cast of the original pointer!
4276 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
4277 bool AllZeroOperands = true;
4278 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4279 if (!isa<Constant>(GEP->getOperand(i)) ||
4280 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4281 AllZeroOperands = false;
4284 if (AllZeroOperands) {
4285 CI.setOperand(0, GEP->getOperand(0));
4290 // If we are casting a malloc or alloca to a pointer to a type of the same
4291 // size, rewrite the allocation instruction to allocate the "right" type.
4293 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
4294 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4297 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4298 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4300 if (isa<PHINode>(Src))
4301 if (Instruction *NV = FoldOpIntoPhi(CI))
4304 // If the source value is an instruction with only this use, we can attempt to
4305 // propagate the cast into the instruction. Also, only handle integral types
4307 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
4308 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
4309 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4310 const Type *DestTy = CI.getType();
4311 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4312 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
4314 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4315 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4317 switch (SrcI->getOpcode()) {
4318 case Instruction::Add:
4319 case Instruction::Mul:
4320 case Instruction::And:
4321 case Instruction::Or:
4322 case Instruction::Xor:
4323 // If we are discarding information, or just changing the sign, rewrite.
4324 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4325 // Don't insert two casts if they cannot be eliminated. We allow two
4326 // casts to be inserted if the sizes are the same. This could only be
4327 // converting signedness, which is a noop.
4328 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4329 !ValueRequiresCast(Op0, DestTy, TD)) {
4330 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4331 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4332 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4333 ->getOpcode(), Op0c, Op1c);
4337 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4338 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4339 Op1 == ConstantBool::True &&
4340 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4341 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4342 return BinaryOperator::createXor(New,
4343 ConstantInt::get(CI.getType(), 1));
4346 case Instruction::Shl:
4347 // Allow changing the sign of the source operand. Do not allow changing
4348 // the size of the shift, UNLESS the shift amount is a constant. We
4349 // mush not change variable sized shifts to a smaller size, because it
4350 // is undefined to shift more bits out than exist in the value.
4351 if (DestBitSize == SrcBitSize ||
4352 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4353 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4354 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4357 case Instruction::Shr:
4358 // If this is a signed shr, and if all bits shifted in are about to be
4359 // truncated off, turn it into an unsigned shr to allow greater
4361 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4362 isa<ConstantInt>(Op1)) {
4363 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4364 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4365 // Convert to unsigned.
4366 Value *N1 = InsertOperandCastBefore(Op0,
4367 Op0->getType()->getUnsignedVersion(), &CI);
4368 // Insert the new shift, which is now unsigned.
4369 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4370 Op1, Src->getName()), CI);
4371 return new CastInst(N1, CI.getType());
4376 case Instruction::SetNE:
4377 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4378 if (Op1C->getRawValue() == 0) {
4379 // If the input only has the low bit set, simplify directly.
4381 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
4382 // cast (X != 0) to int --> X if X&~1 == 0
4383 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
4384 if (CI.getType() == Op0->getType())
4385 return ReplaceInstUsesWith(CI, Op0);
4387 return new CastInst(Op0, CI.getType());
4390 // If the input is an and with a single bit, shift then simplify.
4391 ConstantInt *AndRHS;
4392 if (match(Op0, m_And(m_Value(), m_ConstantInt(AndRHS))))
4393 if (AndRHS->getRawValue() &&
4394 (AndRHS->getRawValue() & (AndRHS->getRawValue()-1)) == 0) {
4395 unsigned ShiftAmt = Log2_64(AndRHS->getRawValue());
4396 // Perform an unsigned shr by shiftamt. Convert input to
4397 // unsigned if it is signed.
4399 if (In->getType()->isSigned())
4400 In = InsertNewInstBefore(new CastInst(In,
4401 In->getType()->getUnsignedVersion(), In->getName()),CI);
4402 // Insert the shift to put the result in the low bit.
4403 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
4404 ConstantInt::get(Type::UByteTy, ShiftAmt),
4405 In->getName()+".lobit"), CI);
4406 if (CI.getType() == In->getType())
4407 return ReplaceInstUsesWith(CI, In);
4409 return new CastInst(In, CI.getType());
4414 case Instruction::SetEQ:
4415 // We if we are just checking for a seteq of a single bit and casting it
4416 // to an integer. If so, shift the bit to the appropriate place then
4417 // cast to integer to avoid the comparison.
4418 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4419 // Is Op1C a power of two or zero?
4420 if ((Op1C->getRawValue() & Op1C->getRawValue()-1) == 0) {
4421 // cast (X == 1) to int -> X iff X has only the low bit set.
4422 if (Op1C->getRawValue() == 1) {
4424 ConstantExpr::getNot(ConstantInt::get(Op0->getType(), 1));
4425 if (MaskedValueIsZero(Op0, cast<ConstantIntegral>(Not1))) {
4426 if (CI.getType() == Op0->getType())
4427 return ReplaceInstUsesWith(CI, Op0);
4429 return new CastInst(Op0, CI.getType());
4441 /// GetSelectFoldableOperands - We want to turn code that looks like this:
4443 /// %D = select %cond, %C, %A
4445 /// %C = select %cond, %B, 0
4448 /// Assuming that the specified instruction is an operand to the select, return
4449 /// a bitmask indicating which operands of this instruction are foldable if they
4450 /// equal the other incoming value of the select.
4452 static unsigned GetSelectFoldableOperands(Instruction *I) {
4453 switch (I->getOpcode()) {
4454 case Instruction::Add:
4455 case Instruction::Mul:
4456 case Instruction::And:
4457 case Instruction::Or:
4458 case Instruction::Xor:
4459 return 3; // Can fold through either operand.
4460 case Instruction::Sub: // Can only fold on the amount subtracted.
4461 case Instruction::Shl: // Can only fold on the shift amount.
4462 case Instruction::Shr:
4465 return 0; // Cannot fold
4469 /// GetSelectFoldableConstant - For the same transformation as the previous
4470 /// function, return the identity constant that goes into the select.
4471 static Constant *GetSelectFoldableConstant(Instruction *I) {
4472 switch (I->getOpcode()) {
4473 default: assert(0 && "This cannot happen!"); abort();
4474 case Instruction::Add:
4475 case Instruction::Sub:
4476 case Instruction::Or:
4477 case Instruction::Xor:
4478 return Constant::getNullValue(I->getType());
4479 case Instruction::Shl:
4480 case Instruction::Shr:
4481 return Constant::getNullValue(Type::UByteTy);
4482 case Instruction::And:
4483 return ConstantInt::getAllOnesValue(I->getType());
4484 case Instruction::Mul:
4485 return ConstantInt::get(I->getType(), 1);
4489 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
4490 /// have the same opcode and only one use each. Try to simplify this.
4491 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
4493 if (TI->getNumOperands() == 1) {
4494 // If this is a non-volatile load or a cast from the same type,
4496 if (TI->getOpcode() == Instruction::Cast) {
4497 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
4500 return 0; // unknown unary op.
4503 // Fold this by inserting a select from the input values.
4504 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
4505 FI->getOperand(0), SI.getName()+".v");
4506 InsertNewInstBefore(NewSI, SI);
4507 return new CastInst(NewSI, TI->getType());
4510 // Only handle binary operators here.
4511 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
4514 // Figure out if the operations have any operands in common.
4515 Value *MatchOp, *OtherOpT, *OtherOpF;
4517 if (TI->getOperand(0) == FI->getOperand(0)) {
4518 MatchOp = TI->getOperand(0);
4519 OtherOpT = TI->getOperand(1);
4520 OtherOpF = FI->getOperand(1);
4521 MatchIsOpZero = true;
4522 } else if (TI->getOperand(1) == FI->getOperand(1)) {
4523 MatchOp = TI->getOperand(1);
4524 OtherOpT = TI->getOperand(0);
4525 OtherOpF = FI->getOperand(0);
4526 MatchIsOpZero = false;
4527 } else if (!TI->isCommutative()) {
4529 } else if (TI->getOperand(0) == FI->getOperand(1)) {
4530 MatchOp = TI->getOperand(0);
4531 OtherOpT = TI->getOperand(1);
4532 OtherOpF = FI->getOperand(0);
4533 MatchIsOpZero = true;
4534 } else if (TI->getOperand(1) == FI->getOperand(0)) {
4535 MatchOp = TI->getOperand(1);
4536 OtherOpT = TI->getOperand(0);
4537 OtherOpF = FI->getOperand(1);
4538 MatchIsOpZero = true;
4543 // If we reach here, they do have operations in common.
4544 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
4545 OtherOpF, SI.getName()+".v");
4546 InsertNewInstBefore(NewSI, SI);
4548 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
4550 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
4552 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
4555 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
4557 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
4561 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
4562 Value *CondVal = SI.getCondition();
4563 Value *TrueVal = SI.getTrueValue();
4564 Value *FalseVal = SI.getFalseValue();
4566 // select true, X, Y -> X
4567 // select false, X, Y -> Y
4568 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
4569 if (C == ConstantBool::True)
4570 return ReplaceInstUsesWith(SI, TrueVal);
4572 assert(C == ConstantBool::False);
4573 return ReplaceInstUsesWith(SI, FalseVal);
4576 // select C, X, X -> X
4577 if (TrueVal == FalseVal)
4578 return ReplaceInstUsesWith(SI, TrueVal);
4580 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
4581 return ReplaceInstUsesWith(SI, FalseVal);
4582 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
4583 return ReplaceInstUsesWith(SI, TrueVal);
4584 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
4585 if (isa<Constant>(TrueVal))
4586 return ReplaceInstUsesWith(SI, TrueVal);
4588 return ReplaceInstUsesWith(SI, FalseVal);
4591 if (SI.getType() == Type::BoolTy)
4592 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
4593 if (C == ConstantBool::True) {
4594 // Change: A = select B, true, C --> A = or B, C
4595 return BinaryOperator::createOr(CondVal, FalseVal);
4597 // Change: A = select B, false, C --> A = and !B, C
4599 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4600 "not."+CondVal->getName()), SI);
4601 return BinaryOperator::createAnd(NotCond, FalseVal);
4603 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
4604 if (C == ConstantBool::False) {
4605 // Change: A = select B, C, false --> A = and B, C
4606 return BinaryOperator::createAnd(CondVal, TrueVal);
4608 // Change: A = select B, C, true --> A = or !B, C
4610 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4611 "not."+CondVal->getName()), SI);
4612 return BinaryOperator::createOr(NotCond, TrueVal);
4616 // Selecting between two integer constants?
4617 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
4618 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
4619 // select C, 1, 0 -> cast C to int
4620 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
4621 return new CastInst(CondVal, SI.getType());
4622 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
4623 // select C, 0, 1 -> cast !C to int
4625 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
4626 "not."+CondVal->getName()), SI);
4627 return new CastInst(NotCond, SI.getType());
4630 // If one of the constants is zero (we know they can't both be) and we
4631 // have a setcc instruction with zero, and we have an 'and' with the
4632 // non-constant value, eliminate this whole mess. This corresponds to
4633 // cases like this: ((X & 27) ? 27 : 0)
4634 if (TrueValC->isNullValue() || FalseValC->isNullValue())
4635 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
4636 if ((IC->getOpcode() == Instruction::SetEQ ||
4637 IC->getOpcode() == Instruction::SetNE) &&
4638 isa<ConstantInt>(IC->getOperand(1)) &&
4639 cast<Constant>(IC->getOperand(1))->isNullValue())
4640 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
4641 if (ICA->getOpcode() == Instruction::And &&
4642 isa<ConstantInt>(ICA->getOperand(1)) &&
4643 (ICA->getOperand(1) == TrueValC ||
4644 ICA->getOperand(1) == FalseValC) &&
4645 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
4646 // Okay, now we know that everything is set up, we just don't
4647 // know whether we have a setne or seteq and whether the true or
4648 // false val is the zero.
4649 bool ShouldNotVal = !TrueValC->isNullValue();
4650 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
4653 V = InsertNewInstBefore(BinaryOperator::create(
4654 Instruction::Xor, V, ICA->getOperand(1)), SI);
4655 return ReplaceInstUsesWith(SI, V);
4659 // See if we are selecting two values based on a comparison of the two values.
4660 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
4661 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
4662 // Transform (X == Y) ? X : Y -> Y
4663 if (SCI->getOpcode() == Instruction::SetEQ)
4664 return ReplaceInstUsesWith(SI, FalseVal);
4665 // Transform (X != Y) ? X : Y -> X
4666 if (SCI->getOpcode() == Instruction::SetNE)
4667 return ReplaceInstUsesWith(SI, TrueVal);
4668 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4670 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
4671 // Transform (X == Y) ? Y : X -> X
4672 if (SCI->getOpcode() == Instruction::SetEQ)
4673 return ReplaceInstUsesWith(SI, FalseVal);
4674 // Transform (X != Y) ? Y : X -> Y
4675 if (SCI->getOpcode() == Instruction::SetNE)
4676 return ReplaceInstUsesWith(SI, TrueVal);
4677 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
4681 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
4682 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
4683 if (TI->hasOneUse() && FI->hasOneUse()) {
4684 bool isInverse = false;
4685 Instruction *AddOp = 0, *SubOp = 0;
4687 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
4688 if (TI->getOpcode() == FI->getOpcode())
4689 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
4692 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
4693 // even legal for FP.
4694 if (TI->getOpcode() == Instruction::Sub &&
4695 FI->getOpcode() == Instruction::Add) {
4696 AddOp = FI; SubOp = TI;
4697 } else if (FI->getOpcode() == Instruction::Sub &&
4698 TI->getOpcode() == Instruction::Add) {
4699 AddOp = TI; SubOp = FI;
4703 Value *OtherAddOp = 0;
4704 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
4705 OtherAddOp = AddOp->getOperand(1);
4706 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
4707 OtherAddOp = AddOp->getOperand(0);
4711 // So at this point we know we have:
4712 // select C, (add X, Y), (sub X, ?)
4713 // We can do the transform profitably if either 'Y' = '?' or '?' is
4715 if (SubOp->getOperand(1) == AddOp ||
4716 isa<Constant>(SubOp->getOperand(1))) {
4718 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
4719 NegVal = ConstantExpr::getNeg(C);
4721 NegVal = InsertNewInstBefore(
4722 BinaryOperator::createNeg(SubOp->getOperand(1)), SI);
4725 Value *NewTrueOp = OtherAddOp;
4726 Value *NewFalseOp = NegVal;
4728 std::swap(NewTrueOp, NewFalseOp);
4729 Instruction *NewSel =
4730 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
4732 NewSel = InsertNewInstBefore(NewSel, SI);
4733 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
4739 // See if we can fold the select into one of our operands.
4740 if (SI.getType()->isInteger()) {
4741 // See the comment above GetSelectFoldableOperands for a description of the
4742 // transformation we are doing here.
4743 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
4744 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
4745 !isa<Constant>(FalseVal))
4746 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
4747 unsigned OpToFold = 0;
4748 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
4750 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
4755 Constant *C = GetSelectFoldableConstant(TVI);
4756 std::string Name = TVI->getName(); TVI->setName("");
4757 Instruction *NewSel =
4758 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
4760 InsertNewInstBefore(NewSel, SI);
4761 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
4762 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
4763 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
4764 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
4766 assert(0 && "Unknown instruction!!");
4771 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
4772 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
4773 !isa<Constant>(TrueVal))
4774 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
4775 unsigned OpToFold = 0;
4776 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
4778 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
4783 Constant *C = GetSelectFoldableConstant(FVI);
4784 std::string Name = FVI->getName(); FVI->setName("");
4785 Instruction *NewSel =
4786 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
4788 InsertNewInstBefore(NewSel, SI);
4789 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
4790 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
4791 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
4792 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
4794 assert(0 && "Unknown instruction!!");
4800 if (BinaryOperator::isNot(CondVal)) {
4801 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
4802 SI.setOperand(1, FalseVal);
4803 SI.setOperand(2, TrueVal);
4811 /// visitCallInst - CallInst simplification. This mostly only handles folding
4812 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
4813 /// the heavy lifting.
4815 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
4816 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
4817 if (!II) return visitCallSite(&CI);
4819 // Intrinsics cannot occur in an invoke, so handle them here instead of in
4821 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
4822 bool Changed = false;
4824 // memmove/cpy/set of zero bytes is a noop.
4825 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
4826 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
4828 // FIXME: Increase alignment here.
4830 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
4831 if (CI->getRawValue() == 1) {
4832 // Replace the instruction with just byte operations. We would
4833 // transform other cases to loads/stores, but we don't know if
4834 // alignment is sufficient.
4838 // If we have a memmove and the source operation is a constant global,
4839 // then the source and dest pointers can't alias, so we can change this
4840 // into a call to memcpy.
4841 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II))
4842 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
4843 if (GVSrc->isConstant()) {
4844 Module *M = CI.getParent()->getParent()->getParent();
4845 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
4846 CI.getCalledFunction()->getFunctionType());
4847 CI.setOperand(0, MemCpy);
4851 if (Changed) return II;
4852 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(II)) {
4853 // If this stoppoint is at the same source location as the previous
4854 // stoppoint in the chain, it is not needed.
4855 if (DbgStopPointInst *PrevSPI =
4856 dyn_cast<DbgStopPointInst>(SPI->getChain()))
4857 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
4858 SPI->getColNo() == PrevSPI->getColNo()) {
4859 SPI->replaceAllUsesWith(PrevSPI);
4860 return EraseInstFromFunction(CI);
4863 switch (II->getIntrinsicID()) {
4865 case Intrinsic::stackrestore: {
4866 // If the save is right next to the restore, remove the restore. This can
4867 // happen when variable allocas are DCE'd.
4868 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
4869 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
4870 BasicBlock::iterator BI = SS;
4872 return EraseInstFromFunction(CI);
4876 // If the stack restore is in a return/unwind block and if there are no
4877 // allocas or calls between the restore and the return, nuke the restore.
4878 TerminatorInst *TI = II->getParent()->getTerminator();
4879 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
4880 BasicBlock::iterator BI = II;
4881 bool CannotRemove = false;
4882 for (++BI; &*BI != TI; ++BI) {
4883 if (isa<AllocaInst>(BI) ||
4884 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
4885 CannotRemove = true;
4890 return EraseInstFromFunction(CI);
4897 return visitCallSite(II);
4900 // InvokeInst simplification
4902 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
4903 return visitCallSite(&II);
4906 // visitCallSite - Improvements for call and invoke instructions.
4908 Instruction *InstCombiner::visitCallSite(CallSite CS) {
4909 bool Changed = false;
4911 // If the callee is a constexpr cast of a function, attempt to move the cast
4912 // to the arguments of the call/invoke.
4913 if (transformConstExprCastCall(CS)) return 0;
4915 Value *Callee = CS.getCalledValue();
4917 if (Function *CalleeF = dyn_cast<Function>(Callee))
4918 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
4919 Instruction *OldCall = CS.getInstruction();
4920 // If the call and callee calling conventions don't match, this call must
4921 // be unreachable, as the call is undefined.
4922 new StoreInst(ConstantBool::True,
4923 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
4924 if (!OldCall->use_empty())
4925 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
4926 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
4927 return EraseInstFromFunction(*OldCall);
4931 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
4932 // This instruction is not reachable, just remove it. We insert a store to
4933 // undef so that we know that this code is not reachable, despite the fact
4934 // that we can't modify the CFG here.
4935 new StoreInst(ConstantBool::True,
4936 UndefValue::get(PointerType::get(Type::BoolTy)),
4937 CS.getInstruction());
4939 if (!CS.getInstruction()->use_empty())
4940 CS.getInstruction()->
4941 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
4943 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
4944 // Don't break the CFG, insert a dummy cond branch.
4945 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
4946 ConstantBool::True, II);
4948 return EraseInstFromFunction(*CS.getInstruction());
4951 const PointerType *PTy = cast<PointerType>(Callee->getType());
4952 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
4953 if (FTy->isVarArg()) {
4954 // See if we can optimize any arguments passed through the varargs area of
4956 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
4957 E = CS.arg_end(); I != E; ++I)
4958 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
4959 // If this cast does not effect the value passed through the varargs
4960 // area, we can eliminate the use of the cast.
4961 Value *Op = CI->getOperand(0);
4962 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
4969 return Changed ? CS.getInstruction() : 0;
4972 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
4973 // attempt to move the cast to the arguments of the call/invoke.
4975 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
4976 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
4977 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
4978 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
4980 Function *Callee = cast<Function>(CE->getOperand(0));
4981 Instruction *Caller = CS.getInstruction();
4983 // Okay, this is a cast from a function to a different type. Unless doing so
4984 // would cause a type conversion of one of our arguments, change this call to
4985 // be a direct call with arguments casted to the appropriate types.
4987 const FunctionType *FT = Callee->getFunctionType();
4988 const Type *OldRetTy = Caller->getType();
4990 // Check to see if we are changing the return type...
4991 if (OldRetTy != FT->getReturnType()) {
4992 if (Callee->isExternal() &&
4993 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
4994 !Caller->use_empty())
4995 return false; // Cannot transform this return value...
4997 // If the callsite is an invoke instruction, and the return value is used by
4998 // a PHI node in a successor, we cannot change the return type of the call
4999 // because there is no place to put the cast instruction (without breaking
5000 // the critical edge). Bail out in this case.
5001 if (!Caller->use_empty())
5002 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
5003 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
5005 if (PHINode *PN = dyn_cast<PHINode>(*UI))
5006 if (PN->getParent() == II->getNormalDest() ||
5007 PN->getParent() == II->getUnwindDest())
5011 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5012 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
5014 CallSite::arg_iterator AI = CS.arg_begin();
5015 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5016 const Type *ParamTy = FT->getParamType(i);
5017 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
5018 if (Callee->isExternal() && !isConvertible) return false;
5021 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
5022 Callee->isExternal())
5023 return false; // Do not delete arguments unless we have a function body...
5025 // Okay, we decided that this is a safe thing to do: go ahead and start
5026 // inserting cast instructions as necessary...
5027 std::vector<Value*> Args;
5028 Args.reserve(NumActualArgs);
5030 AI = CS.arg_begin();
5031 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5032 const Type *ParamTy = FT->getParamType(i);
5033 if ((*AI)->getType() == ParamTy) {
5034 Args.push_back(*AI);
5036 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
5041 // If the function takes more arguments than the call was taking, add them
5043 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
5044 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
5046 // If we are removing arguments to the function, emit an obnoxious warning...
5047 if (FT->getNumParams() < NumActualArgs)
5048 if (!FT->isVarArg()) {
5049 std::cerr << "WARNING: While resolving call to function '"
5050 << Callee->getName() << "' arguments were dropped!\n";
5052 // Add all of the arguments in their promoted form to the arg list...
5053 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5054 const Type *PTy = getPromotedType((*AI)->getType());
5055 if (PTy != (*AI)->getType()) {
5056 // Must promote to pass through va_arg area!
5057 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
5058 InsertNewInstBefore(Cast, *Caller);
5059 Args.push_back(Cast);
5061 Args.push_back(*AI);
5066 if (FT->getReturnType() == Type::VoidTy)
5067 Caller->setName(""); // Void type should not have a name...
5070 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5071 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
5072 Args, Caller->getName(), Caller);
5073 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
5075 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
5076 if (cast<CallInst>(Caller)->isTailCall())
5077 cast<CallInst>(NC)->setTailCall();
5078 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
5081 // Insert a cast of the return type as necessary...
5083 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
5084 if (NV->getType() != Type::VoidTy) {
5085 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
5087 // If this is an invoke instruction, we should insert it after the first
5088 // non-phi, instruction in the normal successor block.
5089 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5090 BasicBlock::iterator I = II->getNormalDest()->begin();
5091 while (isa<PHINode>(I)) ++I;
5092 InsertNewInstBefore(NC, *I);
5094 // Otherwise, it's a call, just insert cast right after the call instr
5095 InsertNewInstBefore(NC, *Caller);
5097 AddUsersToWorkList(*Caller);
5099 NV = UndefValue::get(Caller->getType());
5103 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
5104 Caller->replaceAllUsesWith(NV);
5105 Caller->getParent()->getInstList().erase(Caller);
5106 removeFromWorkList(Caller);
5111 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
5112 // operator and they all are only used by the PHI, PHI together their
5113 // inputs, and do the operation once, to the result of the PHI.
5114 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
5115 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
5117 // Scan the instruction, looking for input operations that can be folded away.
5118 // If all input operands to the phi are the same instruction (e.g. a cast from
5119 // the same type or "+42") we can pull the operation through the PHI, reducing
5120 // code size and simplifying code.
5121 Constant *ConstantOp = 0;
5122 const Type *CastSrcTy = 0;
5123 if (isa<CastInst>(FirstInst)) {
5124 CastSrcTy = FirstInst->getOperand(0)->getType();
5125 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
5126 // Can fold binop or shift if the RHS is a constant.
5127 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
5128 if (ConstantOp == 0) return 0;
5130 return 0; // Cannot fold this operation.
5133 // Check to see if all arguments are the same operation.
5134 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5135 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
5136 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
5137 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
5140 if (I->getOperand(0)->getType() != CastSrcTy)
5141 return 0; // Cast operation must match.
5142 } else if (I->getOperand(1) != ConstantOp) {
5147 // Okay, they are all the same operation. Create a new PHI node of the
5148 // correct type, and PHI together all of the LHS's of the instructions.
5149 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
5150 PN.getName()+".in");
5151 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
5153 Value *InVal = FirstInst->getOperand(0);
5154 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
5156 // Add all operands to the new PHI.
5157 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5158 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
5159 if (NewInVal != InVal)
5161 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
5166 // The new PHI unions all of the same values together. This is really
5167 // common, so we handle it intelligently here for compile-time speed.
5171 InsertNewInstBefore(NewPN, PN);
5175 // Insert and return the new operation.
5176 if (isa<CastInst>(FirstInst))
5177 return new CastInst(PhiVal, PN.getType());
5178 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
5179 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
5181 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
5182 PhiVal, ConstantOp);
5185 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
5187 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
5188 if (PN->use_empty()) return true;
5189 if (!PN->hasOneUse()) return false;
5191 // Remember this node, and if we find the cycle, return.
5192 if (!PotentiallyDeadPHIs.insert(PN).second)
5195 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
5196 return DeadPHICycle(PU, PotentiallyDeadPHIs);
5201 // PHINode simplification
5203 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
5204 if (Value *V = PN.hasConstantValue())
5205 return ReplaceInstUsesWith(PN, V);
5207 // If the only user of this instruction is a cast instruction, and all of the
5208 // incoming values are constants, change this PHI to merge together the casted
5211 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
5212 if (CI->getType() != PN.getType()) { // noop casts will be folded
5213 bool AllConstant = true;
5214 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
5215 if (!isa<Constant>(PN.getIncomingValue(i))) {
5216 AllConstant = false;
5220 // Make a new PHI with all casted values.
5221 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5222 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5223 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5224 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5225 PN.getIncomingBlock(i));
5228 // Update the cast instruction.
5229 CI->setOperand(0, New);
5230 WorkList.push_back(CI); // revisit the cast instruction to fold.
5231 WorkList.push_back(New); // Make sure to revisit the new Phi
5232 return &PN; // PN is now dead!
5236 // If all PHI operands are the same operation, pull them through the PHI,
5237 // reducing code size.
5238 if (isa<Instruction>(PN.getIncomingValue(0)) &&
5239 PN.getIncomingValue(0)->hasOneUse())
5240 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5243 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
5244 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
5245 // PHI)... break the cycle.
5247 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
5248 std::set<PHINode*> PotentiallyDeadPHIs;
5249 PotentiallyDeadPHIs.insert(&PN);
5250 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
5251 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
5257 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
5258 Instruction *InsertPoint,
5260 unsigned PS = IC->getTargetData().getPointerSize();
5261 const Type *VTy = V->getType();
5262 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
5263 // We must insert a cast to ensure we sign-extend.
5264 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
5265 V->getName()), *InsertPoint);
5266 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
5271 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
5272 Value *PtrOp = GEP.getOperand(0);
5273 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
5274 // If so, eliminate the noop.
5275 if (GEP.getNumOperands() == 1)
5276 return ReplaceInstUsesWith(GEP, PtrOp);
5278 if (isa<UndefValue>(GEP.getOperand(0)))
5279 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
5281 bool HasZeroPointerIndex = false;
5282 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
5283 HasZeroPointerIndex = C->isNullValue();
5285 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
5286 return ReplaceInstUsesWith(GEP, PtrOp);
5288 // Eliminate unneeded casts for indices.
5289 bool MadeChange = false;
5290 gep_type_iterator GTI = gep_type_begin(GEP);
5291 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
5292 if (isa<SequentialType>(*GTI)) {
5293 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
5294 Value *Src = CI->getOperand(0);
5295 const Type *SrcTy = Src->getType();
5296 const Type *DestTy = CI->getType();
5297 if (Src->getType()->isInteger()) {
5298 if (SrcTy->getPrimitiveSizeInBits() ==
5299 DestTy->getPrimitiveSizeInBits()) {
5300 // We can always eliminate a cast from ulong or long to the other.
5301 // We can always eliminate a cast from uint to int or the other on
5302 // 32-bit pointer platforms.
5303 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
5305 GEP.setOperand(i, Src);
5307 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
5308 SrcTy->getPrimitiveSize() == 4) {
5309 // We can always eliminate a cast from int to [u]long. We can
5310 // eliminate a cast from uint to [u]long iff the target is a 32-bit
5312 if (SrcTy->isSigned() ||
5313 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
5315 GEP.setOperand(i, Src);
5320 // If we are using a wider index than needed for this platform, shrink it
5321 // to what we need. If the incoming value needs a cast instruction,
5322 // insert it. This explicit cast can make subsequent optimizations more
5324 Value *Op = GEP.getOperand(i);
5325 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
5326 if (Constant *C = dyn_cast<Constant>(Op)) {
5327 GEP.setOperand(i, ConstantExpr::getCast(C,
5328 TD->getIntPtrType()->getSignedVersion()));
5331 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
5332 Op->getName()), GEP);
5333 GEP.setOperand(i, Op);
5337 // If this is a constant idx, make sure to canonicalize it to be a signed
5338 // operand, otherwise CSE and other optimizations are pessimized.
5339 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5340 GEP.setOperand(i, ConstantExpr::getCast(CUI,
5341 CUI->getType()->getSignedVersion()));
5345 if (MadeChange) return &GEP;
5347 // Combine Indices - If the source pointer to this getelementptr instruction
5348 // is a getelementptr instruction, combine the indices of the two
5349 // getelementptr instructions into a single instruction.
5351 std::vector<Value*> SrcGEPOperands;
5352 if (User *Src = dyn_castGetElementPtr(PtrOp))
5353 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
5355 if (!SrcGEPOperands.empty()) {
5356 // Note that if our source is a gep chain itself that we wait for that
5357 // chain to be resolved before we perform this transformation. This
5358 // avoids us creating a TON of code in some cases.
5360 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
5361 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
5362 return 0; // Wait until our source is folded to completion.
5364 std::vector<Value *> Indices;
5366 // Find out whether the last index in the source GEP is a sequential idx.
5367 bool EndsWithSequential = false;
5368 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
5369 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
5370 EndsWithSequential = !isa<StructType>(*I);
5372 // Can we combine the two pointer arithmetics offsets?
5373 if (EndsWithSequential) {
5374 // Replace: gep (gep %P, long B), long A, ...
5375 // With: T = long A+B; gep %P, T, ...
5377 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
5378 if (SO1 == Constant::getNullValue(SO1->getType())) {
5380 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
5383 // If they aren't the same type, convert both to an integer of the
5384 // target's pointer size.
5385 if (SO1->getType() != GO1->getType()) {
5386 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
5387 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
5388 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
5389 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
5391 unsigned PS = TD->getPointerSize();
5392 if (SO1->getType()->getPrimitiveSize() == PS) {
5393 // Convert GO1 to SO1's type.
5394 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
5396 } else if (GO1->getType()->getPrimitiveSize() == PS) {
5397 // Convert SO1 to GO1's type.
5398 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
5400 const Type *PT = TD->getIntPtrType();
5401 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
5402 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
5406 if (isa<Constant>(SO1) && isa<Constant>(GO1))
5407 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
5409 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
5410 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
5414 // Recycle the GEP we already have if possible.
5415 if (SrcGEPOperands.size() == 2) {
5416 GEP.setOperand(0, SrcGEPOperands[0]);
5417 GEP.setOperand(1, Sum);
5420 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5421 SrcGEPOperands.end()-1);
5422 Indices.push_back(Sum);
5423 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
5425 } else if (isa<Constant>(*GEP.idx_begin()) &&
5426 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
5427 SrcGEPOperands.size() != 1) {
5428 // Otherwise we can do the fold if the first index of the GEP is a zero
5429 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
5430 SrcGEPOperands.end());
5431 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
5434 if (!Indices.empty())
5435 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
5437 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
5438 // GEP of global variable. If all of the indices for this GEP are
5439 // constants, we can promote this to a constexpr instead of an instruction.
5441 // Scan for nonconstants...
5442 std::vector<Constant*> Indices;
5443 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
5444 for (; I != E && isa<Constant>(*I); ++I)
5445 Indices.push_back(cast<Constant>(*I));
5447 if (I == E) { // If they are all constants...
5448 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
5450 // Replace all uses of the GEP with the new constexpr...
5451 return ReplaceInstUsesWith(GEP, CE);
5453 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
5454 if (!isa<PointerType>(X->getType())) {
5455 // Not interesting. Source pointer must be a cast from pointer.
5456 } else if (HasZeroPointerIndex) {
5457 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
5458 // into : GEP [10 x ubyte]* X, long 0, ...
5460 // This occurs when the program declares an array extern like "int X[];"
5462 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
5463 const PointerType *XTy = cast<PointerType>(X->getType());
5464 if (const ArrayType *XATy =
5465 dyn_cast<ArrayType>(XTy->getElementType()))
5466 if (const ArrayType *CATy =
5467 dyn_cast<ArrayType>(CPTy->getElementType()))
5468 if (CATy->getElementType() == XATy->getElementType()) {
5469 // At this point, we know that the cast source type is a pointer
5470 // to an array of the same type as the destination pointer
5471 // array. Because the array type is never stepped over (there
5472 // is a leading zero) we can fold the cast into this GEP.
5473 GEP.setOperand(0, X);
5476 } else if (GEP.getNumOperands() == 2) {
5477 // Transform things like:
5478 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
5479 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
5480 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
5481 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
5482 if (isa<ArrayType>(SrcElTy) &&
5483 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
5484 TD->getTypeSize(ResElTy)) {
5485 Value *V = InsertNewInstBefore(
5486 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5487 GEP.getOperand(1), GEP.getName()), GEP);
5488 return new CastInst(V, GEP.getType());
5491 // Transform things like:
5492 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
5493 // (where tmp = 8*tmp2) into:
5494 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
5496 if (isa<ArrayType>(SrcElTy) &&
5497 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
5498 uint64_t ArrayEltSize =
5499 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
5501 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
5502 // allow either a mul, shift, or constant here.
5504 ConstantInt *Scale = 0;
5505 if (ArrayEltSize == 1) {
5506 NewIdx = GEP.getOperand(1);
5507 Scale = ConstantInt::get(NewIdx->getType(), 1);
5508 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
5509 NewIdx = ConstantInt::get(CI->getType(), 1);
5511 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
5512 if (Inst->getOpcode() == Instruction::Shl &&
5513 isa<ConstantInt>(Inst->getOperand(1))) {
5514 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
5515 if (Inst->getType()->isSigned())
5516 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
5518 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
5519 NewIdx = Inst->getOperand(0);
5520 } else if (Inst->getOpcode() == Instruction::Mul &&
5521 isa<ConstantInt>(Inst->getOperand(1))) {
5522 Scale = cast<ConstantInt>(Inst->getOperand(1));
5523 NewIdx = Inst->getOperand(0);
5527 // If the index will be to exactly the right offset with the scale taken
5528 // out, perform the transformation.
5529 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
5530 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
5531 Scale = ConstantSInt::get(C->getType(),
5532 (int64_t)C->getRawValue() /
5533 (int64_t)ArrayEltSize);
5535 Scale = ConstantUInt::get(Scale->getType(),
5536 Scale->getRawValue() / ArrayEltSize);
5537 if (Scale->getRawValue() != 1) {
5538 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
5539 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
5540 NewIdx = InsertNewInstBefore(Sc, GEP);
5543 // Insert the new GEP instruction.
5545 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
5546 NewIdx, GEP.getName());
5547 Idx = InsertNewInstBefore(Idx, GEP);
5548 return new CastInst(Idx, GEP.getType());
5557 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
5558 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
5559 if (AI.isArrayAllocation()) // Check C != 1
5560 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
5561 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
5562 AllocationInst *New = 0;
5564 // Create and insert the replacement instruction...
5565 if (isa<MallocInst>(AI))
5566 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
5568 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
5569 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
5572 InsertNewInstBefore(New, AI);
5574 // Scan to the end of the allocation instructions, to skip over a block of
5575 // allocas if possible...
5577 BasicBlock::iterator It = New;
5578 while (isa<AllocationInst>(*It)) ++It;
5580 // Now that I is pointing to the first non-allocation-inst in the block,
5581 // insert our getelementptr instruction...
5583 Value *NullIdx = Constant::getNullValue(Type::IntTy);
5584 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
5585 New->getName()+".sub", It);
5587 // Now make everything use the getelementptr instead of the original
5589 return ReplaceInstUsesWith(AI, V);
5590 } else if (isa<UndefValue>(AI.getArraySize())) {
5591 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5594 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
5595 // Note that we only do this for alloca's, because malloc should allocate and
5596 // return a unique pointer, even for a zero byte allocation.
5597 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
5598 TD->getTypeSize(AI.getAllocatedType()) == 0)
5599 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
5604 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
5605 Value *Op = FI.getOperand(0);
5607 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
5608 if (CastInst *CI = dyn_cast<CastInst>(Op))
5609 if (isa<PointerType>(CI->getOperand(0)->getType())) {
5610 FI.setOperand(0, CI->getOperand(0));
5614 // free undef -> unreachable.
5615 if (isa<UndefValue>(Op)) {
5616 // Insert a new store to null because we cannot modify the CFG here.
5617 new StoreInst(ConstantBool::True,
5618 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
5619 return EraseInstFromFunction(FI);
5622 // If we have 'free null' delete the instruction. This can happen in stl code
5623 // when lots of inlining happens.
5624 if (isa<ConstantPointerNull>(Op))
5625 return EraseInstFromFunction(FI);
5631 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
5632 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
5633 User *CI = cast<User>(LI.getOperand(0));
5634 Value *CastOp = CI->getOperand(0);
5636 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5637 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5638 const Type *SrcPTy = SrcTy->getElementType();
5640 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5641 // If the source is an array, the code below will not succeed. Check to
5642 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5644 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5645 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5646 if (ASrcTy->getNumElements() != 0) {
5647 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5648 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5649 SrcTy = cast<PointerType>(CastOp->getType());
5650 SrcPTy = SrcTy->getElementType();
5653 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
5654 // Do not allow turning this into a load of an integer, which is then
5655 // casted to a pointer, this pessimizes pointer analysis a lot.
5656 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
5657 IC.getTargetData().getTypeSize(SrcPTy) ==
5658 IC.getTargetData().getTypeSize(DestPTy)) {
5660 // Okay, we are casting from one integer or pointer type to another of
5661 // the same size. Instead of casting the pointer before the load, cast
5662 // the result of the loaded value.
5663 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
5665 LI.isVolatile()),LI);
5666 // Now cast the result of the load.
5667 return new CastInst(NewLoad, LI.getType());
5674 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
5675 /// from this value cannot trap. If it is not obviously safe to load from the
5676 /// specified pointer, we do a quick local scan of the basic block containing
5677 /// ScanFrom, to determine if the address is already accessed.
5678 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
5679 // If it is an alloca or global variable, it is always safe to load from.
5680 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
5682 // Otherwise, be a little bit agressive by scanning the local block where we
5683 // want to check to see if the pointer is already being loaded or stored
5684 // from/to. If so, the previous load or store would have already trapped,
5685 // so there is no harm doing an extra load (also, CSE will later eliminate
5686 // the load entirely).
5687 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
5692 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
5693 if (LI->getOperand(0) == V) return true;
5694 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5695 if (SI->getOperand(1) == V) return true;
5701 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
5702 Value *Op = LI.getOperand(0);
5704 // load (cast X) --> cast (load X) iff safe
5705 if (CastInst *CI = dyn_cast<CastInst>(Op))
5706 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5709 // None of the following transforms are legal for volatile loads.
5710 if (LI.isVolatile()) return 0;
5712 if (&LI.getParent()->front() != &LI) {
5713 BasicBlock::iterator BBI = &LI; --BBI;
5714 // If the instruction immediately before this is a store to the same
5715 // address, do a simple form of store->load forwarding.
5716 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
5717 if (SI->getOperand(1) == LI.getOperand(0))
5718 return ReplaceInstUsesWith(LI, SI->getOperand(0));
5719 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
5720 if (LIB->getOperand(0) == LI.getOperand(0))
5721 return ReplaceInstUsesWith(LI, LIB);
5724 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
5725 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
5726 isa<UndefValue>(GEPI->getOperand(0))) {
5727 // Insert a new store to null instruction before the load to indicate
5728 // that this code is not reachable. We do this instead of inserting
5729 // an unreachable instruction directly because we cannot modify the
5731 new StoreInst(UndefValue::get(LI.getType()),
5732 Constant::getNullValue(Op->getType()), &LI);
5733 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5736 if (Constant *C = dyn_cast<Constant>(Op)) {
5737 // load null/undef -> undef
5738 if ((C->isNullValue() || isa<UndefValue>(C))) {
5739 // Insert a new store to null instruction before the load to indicate that
5740 // this code is not reachable. We do this instead of inserting an
5741 // unreachable instruction directly because we cannot modify the CFG.
5742 new StoreInst(UndefValue::get(LI.getType()),
5743 Constant::getNullValue(Op->getType()), &LI);
5744 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5747 // Instcombine load (constant global) into the value loaded.
5748 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
5749 if (GV->isConstant() && !GV->isExternal())
5750 return ReplaceInstUsesWith(LI, GV->getInitializer());
5752 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
5753 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
5754 if (CE->getOpcode() == Instruction::GetElementPtr) {
5755 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
5756 if (GV->isConstant() && !GV->isExternal())
5758 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
5759 return ReplaceInstUsesWith(LI, V);
5760 if (CE->getOperand(0)->isNullValue()) {
5761 // Insert a new store to null instruction before the load to indicate
5762 // that this code is not reachable. We do this instead of inserting
5763 // an unreachable instruction directly because we cannot modify the
5765 new StoreInst(UndefValue::get(LI.getType()),
5766 Constant::getNullValue(Op->getType()), &LI);
5767 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
5770 } else if (CE->getOpcode() == Instruction::Cast) {
5771 if (Instruction *Res = InstCombineLoadCast(*this, LI))
5776 if (Op->hasOneUse()) {
5777 // Change select and PHI nodes to select values instead of addresses: this
5778 // helps alias analysis out a lot, allows many others simplifications, and
5779 // exposes redundancy in the code.
5781 // Note that we cannot do the transformation unless we know that the
5782 // introduced loads cannot trap! Something like this is valid as long as
5783 // the condition is always false: load (select bool %C, int* null, int* %G),
5784 // but it would not be valid if we transformed it to load from null
5787 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
5788 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
5789 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
5790 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
5791 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
5792 SI->getOperand(1)->getName()+".val"), LI);
5793 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
5794 SI->getOperand(2)->getName()+".val"), LI);
5795 return new SelectInst(SI->getCondition(), V1, V2);
5798 // load (select (cond, null, P)) -> load P
5799 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
5800 if (C->isNullValue()) {
5801 LI.setOperand(0, SI->getOperand(2));
5805 // load (select (cond, P, null)) -> load P
5806 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
5807 if (C->isNullValue()) {
5808 LI.setOperand(0, SI->getOperand(1));
5812 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
5813 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
5814 bool Safe = PN->getParent() == LI.getParent();
5816 // Scan all of the instructions between the PHI and the load to make
5817 // sure there are no instructions that might possibly alter the value
5818 // loaded from the PHI.
5820 BasicBlock::iterator I = &LI;
5821 for (--I; !isa<PHINode>(I); --I)
5822 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
5828 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
5829 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
5830 PN->getIncomingBlock(i)->getTerminator()))
5835 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
5836 InsertNewInstBefore(NewPN, *PN);
5837 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
5839 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
5840 BasicBlock *BB = PN->getIncomingBlock(i);
5841 Value *&TheLoad = LoadMap[BB];
5843 Value *InVal = PN->getIncomingValue(i);
5844 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
5845 InVal->getName()+".val"),
5846 *BB->getTerminator());
5848 NewPN->addIncoming(TheLoad, BB);
5850 return ReplaceInstUsesWith(LI, NewPN);
5857 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
5859 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
5860 User *CI = cast<User>(SI.getOperand(1));
5861 Value *CastOp = CI->getOperand(0);
5863 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
5864 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
5865 const Type *SrcPTy = SrcTy->getElementType();
5867 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
5868 // If the source is an array, the code below will not succeed. Check to
5869 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
5871 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
5872 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
5873 if (ASrcTy->getNumElements() != 0) {
5874 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
5875 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
5876 SrcTy = cast<PointerType>(CastOp->getType());
5877 SrcPTy = SrcTy->getElementType();
5880 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
5881 IC.getTargetData().getTypeSize(SrcPTy) ==
5882 IC.getTargetData().getTypeSize(DestPTy)) {
5884 // Okay, we are casting from one integer or pointer type to another of
5885 // the same size. Instead of casting the pointer before the store, cast
5886 // the value to be stored.
5888 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
5889 NewCast = ConstantExpr::getCast(C, SrcPTy);
5891 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
5893 SI.getOperand(0)->getName()+".c"), SI);
5895 return new StoreInst(NewCast, CastOp);
5902 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
5903 Value *Val = SI.getOperand(0);
5904 Value *Ptr = SI.getOperand(1);
5906 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
5907 removeFromWorkList(&SI);
5908 SI.eraseFromParent();
5913 if (SI.isVolatile()) return 0; // Don't hack volatile loads.
5915 // store X, null -> turns into 'unreachable' in SimplifyCFG
5916 if (isa<ConstantPointerNull>(Ptr)) {
5917 if (!isa<UndefValue>(Val)) {
5918 SI.setOperand(0, UndefValue::get(Val->getType()));
5919 if (Instruction *U = dyn_cast<Instruction>(Val))
5920 WorkList.push_back(U); // Dropped a use.
5923 return 0; // Do not modify these!
5926 // store undef, Ptr -> noop
5927 if (isa<UndefValue>(Val)) {
5928 removeFromWorkList(&SI);
5929 SI.eraseFromParent();
5934 // If the pointer destination is a cast, see if we can fold the cast into the
5936 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
5937 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5939 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
5940 if (CE->getOpcode() == Instruction::Cast)
5941 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
5945 // If this store is the last instruction in the basic block, and if the block
5946 // ends with an unconditional branch, try to move it to the successor block.
5947 BasicBlock::iterator BBI = &SI; ++BBI;
5948 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
5949 if (BI->isUnconditional()) {
5950 // Check to see if the successor block has exactly two incoming edges. If
5951 // so, see if the other predecessor contains a store to the same location.
5952 // if so, insert a PHI node (if needed) and move the stores down.
5953 BasicBlock *Dest = BI->getSuccessor(0);
5955 pred_iterator PI = pred_begin(Dest);
5956 BasicBlock *Other = 0;
5957 if (*PI != BI->getParent())
5960 if (PI != pred_end(Dest)) {
5961 if (*PI != BI->getParent())
5966 if (++PI != pred_end(Dest))
5969 if (Other) { // If only one other pred...
5970 BBI = Other->getTerminator();
5971 // Make sure this other block ends in an unconditional branch and that
5972 // there is an instruction before the branch.
5973 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
5974 BBI != Other->begin()) {
5976 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
5978 // If this instruction is a store to the same location.
5979 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
5980 // Okay, we know we can perform this transformation. Insert a PHI
5981 // node now if we need it.
5982 Value *MergedVal = OtherStore->getOperand(0);
5983 if (MergedVal != SI.getOperand(0)) {
5984 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
5985 PN->reserveOperandSpace(2);
5986 PN->addIncoming(SI.getOperand(0), SI.getParent());
5987 PN->addIncoming(OtherStore->getOperand(0), Other);
5988 MergedVal = InsertNewInstBefore(PN, Dest->front());
5991 // Advance to a place where it is safe to insert the new store and
5993 BBI = Dest->begin();
5994 while (isa<PHINode>(BBI)) ++BBI;
5995 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
5996 OtherStore->isVolatile()), *BBI);
5998 // Nuke the old stores.
5999 removeFromWorkList(&SI);
6000 removeFromWorkList(OtherStore);
6001 SI.eraseFromParent();
6002 OtherStore->eraseFromParent();
6014 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
6015 // Change br (not X), label True, label False to: br X, label False, True
6017 BasicBlock *TrueDest;
6018 BasicBlock *FalseDest;
6019 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
6020 !isa<Constant>(X)) {
6021 // Swap Destinations and condition...
6023 BI.setSuccessor(0, FalseDest);
6024 BI.setSuccessor(1, TrueDest);
6028 // Cannonicalize setne -> seteq
6029 Instruction::BinaryOps Op; Value *Y;
6030 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
6031 TrueDest, FalseDest)))
6032 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
6033 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
6034 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
6035 std::string Name = I->getName(); I->setName("");
6036 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
6037 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
6038 // Swap Destinations and condition...
6039 BI.setCondition(NewSCC);
6040 BI.setSuccessor(0, FalseDest);
6041 BI.setSuccessor(1, TrueDest);
6042 removeFromWorkList(I);
6043 I->getParent()->getInstList().erase(I);
6044 WorkList.push_back(cast<Instruction>(NewSCC));
6051 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
6052 Value *Cond = SI.getCondition();
6053 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
6054 if (I->getOpcode() == Instruction::Add)
6055 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6056 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
6057 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
6058 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
6060 SI.setOperand(0, I->getOperand(0));
6061 WorkList.push_back(I);
6068 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
6069 if (ConstantAggregateZero *C =
6070 dyn_cast<ConstantAggregateZero>(EI.getOperand(0))) {
6071 // If packed val is constant 0, replace extract with scalar 0
6072 const Type *Ty = cast<PackedType>(C->getType())->getElementType();
6073 EI.replaceAllUsesWith(Constant::getNullValue(Ty));
6074 return ReplaceInstUsesWith(EI, Constant::getNullValue(Ty));
6076 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
6077 // If packed val is constant with uniform operands, replace EI
6078 // with that operand
6079 Constant *op0 = cast<Constant>(C->getOperand(0));
6080 for (unsigned i = 1; i < C->getNumOperands(); ++i)
6081 if (C->getOperand(i) != op0) return 0;
6082 return ReplaceInstUsesWith(EI, op0);
6084 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
6085 if (I->hasOneUse()) {
6086 // Push extractelement into predecessor operation if legal and
6087 // profitable to do so
6088 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
6089 if (!isa<Constant>(BO->getOperand(0)) &&
6090 !isa<Constant>(BO->getOperand(1)))
6092 ExtractElementInst *newEI0 =
6093 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
6095 ExtractElementInst *newEI1 =
6096 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
6098 InsertNewInstBefore(newEI0, EI);
6099 InsertNewInstBefore(newEI1, EI);
6100 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
6102 switch(I->getOpcode()) {
6103 case Instruction::Load: {
6104 Value *Ptr = InsertCastBefore(I->getOperand(0),
6105 PointerType::get(EI.getType()), EI);
6106 GetElementPtrInst *GEP =
6107 new GetElementPtrInst(Ptr, EI.getOperand(1),
6108 I->getName() + ".gep");
6109 InsertNewInstBefore(GEP, EI);
6110 return new LoadInst(GEP);
6120 void InstCombiner::removeFromWorkList(Instruction *I) {
6121 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
6126 /// TryToSinkInstruction - Try to move the specified instruction from its
6127 /// current block into the beginning of DestBlock, which can only happen if it's
6128 /// safe to move the instruction past all of the instructions between it and the
6129 /// end of its block.
6130 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
6131 assert(I->hasOneUse() && "Invariants didn't hold!");
6133 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
6134 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
6136 // Do not sink alloca instructions out of the entry block.
6137 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
6140 // We can only sink load instructions if there is nothing between the load and
6141 // the end of block that could change the value.
6142 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6143 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
6145 if (Scan->mayWriteToMemory())
6149 BasicBlock::iterator InsertPos = DestBlock->begin();
6150 while (isa<PHINode>(InsertPos)) ++InsertPos;
6152 I->moveBefore(InsertPos);
6157 bool InstCombiner::runOnFunction(Function &F) {
6158 bool Changed = false;
6159 TD = &getAnalysis<TargetData>();
6162 // Populate the worklist with the reachable instructions.
6163 std::set<BasicBlock*> Visited;
6164 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
6165 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
6166 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
6167 WorkList.push_back(I);
6169 // Do a quick scan over the function. If we find any blocks that are
6170 // unreachable, remove any instructions inside of them. This prevents
6171 // the instcombine code from having to deal with some bad special cases.
6172 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
6173 if (!Visited.count(BB)) {
6174 Instruction *Term = BB->getTerminator();
6175 while (Term != BB->begin()) { // Remove instrs bottom-up
6176 BasicBlock::iterator I = Term; --I;
6178 DEBUG(std::cerr << "IC: DCE: " << *I);
6181 if (!I->use_empty())
6182 I->replaceAllUsesWith(UndefValue::get(I->getType()));
6183 I->eraseFromParent();
6188 while (!WorkList.empty()) {
6189 Instruction *I = WorkList.back(); // Get an instruction from the worklist
6190 WorkList.pop_back();
6192 // Check to see if we can DCE or ConstantPropagate the instruction...
6193 // Check to see if we can DIE the instruction...
6194 if (isInstructionTriviallyDead(I)) {
6195 // Add operands to the worklist...
6196 if (I->getNumOperands() < 4)
6197 AddUsesToWorkList(*I);
6200 DEBUG(std::cerr << "IC: DCE: " << *I);
6202 I->eraseFromParent();
6203 removeFromWorkList(I);
6207 // Instruction isn't dead, see if we can constant propagate it...
6208 if (Constant *C = ConstantFoldInstruction(I)) {
6209 Value* Ptr = I->getOperand(0);
6210 if (isa<GetElementPtrInst>(I) &&
6211 cast<Constant>(Ptr)->isNullValue() &&
6212 !isa<ConstantPointerNull>(C) &&
6213 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
6214 // If this is a constant expr gep that is effectively computing an
6215 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
6216 bool isFoldableGEP = true;
6217 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
6218 if (!isa<ConstantInt>(I->getOperand(i)))
6219 isFoldableGEP = false;
6220 if (isFoldableGEP) {
6221 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
6222 std::vector<Value*>(I->op_begin()+1, I->op_end()));
6223 C = ConstantUInt::get(Type::ULongTy, Offset);
6224 C = ConstantExpr::getCast(C, TD->getIntPtrType());
6225 C = ConstantExpr::getCast(C, I->getType());
6229 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
6231 // Add operands to the worklist...
6232 AddUsesToWorkList(*I);
6233 ReplaceInstUsesWith(*I, C);
6236 I->getParent()->getInstList().erase(I);
6237 removeFromWorkList(I);
6241 // See if we can trivially sink this instruction to a successor basic block.
6242 if (I->hasOneUse()) {
6243 BasicBlock *BB = I->getParent();
6244 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
6245 if (UserParent != BB) {
6246 bool UserIsSuccessor = false;
6247 // See if the user is one of our successors.
6248 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
6249 if (*SI == UserParent) {
6250 UserIsSuccessor = true;
6254 // If the user is one of our immediate successors, and if that successor
6255 // only has us as a predecessors (we'd have to split the critical edge
6256 // otherwise), we can keep going.
6257 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
6258 next(pred_begin(UserParent)) == pred_end(UserParent))
6259 // Okay, the CFG is simple enough, try to sink this instruction.
6260 Changed |= TryToSinkInstruction(I, UserParent);
6264 // Now that we have an instruction, try combining it to simplify it...
6265 if (Instruction *Result = visit(*I)) {
6267 // Should we replace the old instruction with a new one?
6269 DEBUG(std::cerr << "IC: Old = " << *I
6270 << " New = " << *Result);
6272 // Everything uses the new instruction now.
6273 I->replaceAllUsesWith(Result);
6275 // Push the new instruction and any users onto the worklist.
6276 WorkList.push_back(Result);
6277 AddUsersToWorkList(*Result);
6279 // Move the name to the new instruction first...
6280 std::string OldName = I->getName(); I->setName("");
6281 Result->setName(OldName);
6283 // Insert the new instruction into the basic block...
6284 BasicBlock *InstParent = I->getParent();
6285 BasicBlock::iterator InsertPos = I;
6287 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
6288 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
6291 InstParent->getInstList().insert(InsertPos, Result);
6293 // Make sure that we reprocess all operands now that we reduced their
6295 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6296 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6297 WorkList.push_back(OpI);
6299 // Instructions can end up on the worklist more than once. Make sure
6300 // we do not process an instruction that has been deleted.
6301 removeFromWorkList(I);
6303 // Erase the old instruction.
6304 InstParent->getInstList().erase(I);
6306 DEBUG(std::cerr << "IC: MOD = " << *I);
6308 // If the instruction was modified, it's possible that it is now dead.
6309 // if so, remove it.
6310 if (isInstructionTriviallyDead(I)) {
6311 // Make sure we process all operands now that we are reducing their
6313 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
6314 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
6315 WorkList.push_back(OpI);
6317 // Instructions may end up in the worklist more than once. Erase all
6318 // occurrences of this instruction.
6319 removeFromWorkList(I);
6320 I->eraseFromParent();
6322 WorkList.push_back(Result);
6323 AddUsersToWorkList(*Result);
6333 FunctionPass *llvm::createInstructionCombiningPass() {
6334 return new InstCombiner();