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/Support/Compiler.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<> NumDeadStore("instcombine", "Number of dead stores eliminated");
64 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
66 class VISIBILITY_HIDDEN InstCombiner
67 : public FunctionPass,
68 public InstVisitor<InstCombiner, Instruction*> {
69 // Worklist of all of the instructions that need to be simplified.
70 std::vector<Instruction*> WorkList;
73 /// AddUsersToWorkList - When an instruction is simplified, add all users of
74 /// the instruction to the work lists because they might get more simplified
77 void AddUsersToWorkList(Value &I) {
78 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
80 WorkList.push_back(cast<Instruction>(*UI));
83 /// AddUsesToWorkList - When an instruction is simplified, add operands to
84 /// the work lists because they might get more simplified now.
86 void AddUsesToWorkList(Instruction &I) {
87 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
88 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
89 WorkList.push_back(Op);
92 // removeFromWorkList - remove all instances of I from the worklist.
93 void removeFromWorkList(Instruction *I);
95 virtual bool runOnFunction(Function &F);
97 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
98 AU.addRequired<TargetData>();
99 AU.addPreservedID(LCSSAID);
100 AU.setPreservesCFG();
103 TargetData &getTargetData() const { return *TD; }
105 // Visitation implementation - Implement instruction combining for different
106 // instruction types. The semantics are as follows:
108 // null - No change was made
109 // I - Change was made, I is still valid, I may be dead though
110 // otherwise - Change was made, replace I with returned instruction
112 Instruction *visitAdd(BinaryOperator &I);
113 Instruction *visitSub(BinaryOperator &I);
114 Instruction *visitMul(BinaryOperator &I);
115 Instruction *visitDiv(BinaryOperator &I);
116 Instruction *visitRem(BinaryOperator &I);
117 Instruction *visitAnd(BinaryOperator &I);
118 Instruction *visitOr (BinaryOperator &I);
119 Instruction *visitXor(BinaryOperator &I);
120 Instruction *visitSetCondInst(SetCondInst &I);
121 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
123 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
124 Instruction::BinaryOps Cond, Instruction &I);
125 Instruction *visitShiftInst(ShiftInst &I);
126 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
128 Instruction *visitCastInst(CastInst &CI);
129 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
131 Instruction *visitSelectInst(SelectInst &CI);
132 Instruction *visitCallInst(CallInst &CI);
133 Instruction *visitInvokeInst(InvokeInst &II);
134 Instruction *visitPHINode(PHINode &PN);
135 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
136 Instruction *visitAllocationInst(AllocationInst &AI);
137 Instruction *visitFreeInst(FreeInst &FI);
138 Instruction *visitLoadInst(LoadInst &LI);
139 Instruction *visitStoreInst(StoreInst &SI);
140 Instruction *visitBranchInst(BranchInst &BI);
141 Instruction *visitSwitchInst(SwitchInst &SI);
142 Instruction *visitInsertElementInst(InsertElementInst &IE);
143 Instruction *visitExtractElementInst(ExtractElementInst &EI);
144 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
146 // visitInstruction - Specify what to return for unhandled instructions...
147 Instruction *visitInstruction(Instruction &I) { return 0; }
150 Instruction *visitCallSite(CallSite CS);
151 bool transformConstExprCastCall(CallSite CS);
154 // InsertNewInstBefore - insert an instruction New before instruction Old
155 // in the program. Add the new instruction to the worklist.
157 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
158 assert(New && New->getParent() == 0 &&
159 "New instruction already inserted into a basic block!");
160 BasicBlock *BB = Old.getParent();
161 BB->getInstList().insert(&Old, New); // Insert inst
162 WorkList.push_back(New); // Add to worklist
166 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
167 /// This also adds the cast to the worklist. Finally, this returns the
169 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
170 if (V->getType() == Ty) return V;
172 if (Constant *CV = dyn_cast<Constant>(V))
173 return ConstantExpr::getCast(CV, Ty);
175 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
176 WorkList.push_back(C);
180 // ReplaceInstUsesWith - This method is to be used when an instruction is
181 // found to be dead, replacable with another preexisting expression. Here
182 // we add all uses of I to the worklist, replace all uses of I with the new
183 // value, then return I, so that the inst combiner will know that I was
186 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
187 AddUsersToWorkList(I); // Add all modified instrs to worklist
189 I.replaceAllUsesWith(V);
192 // If we are replacing the instruction with itself, this must be in a
193 // segment of unreachable code, so just clobber the instruction.
194 I.replaceAllUsesWith(UndefValue::get(I.getType()));
199 // UpdateValueUsesWith - This method is to be used when an value is
200 // found to be replacable with another preexisting expression or was
201 // updated. Here we add all uses of I to the worklist, replace all uses of
202 // I with the new value (unless the instruction was just updated), then
203 // return true, so that the inst combiner will know that I was modified.
205 bool UpdateValueUsesWith(Value *Old, Value *New) {
206 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
208 Old->replaceAllUsesWith(New);
209 if (Instruction *I = dyn_cast<Instruction>(Old))
210 WorkList.push_back(I);
211 if (Instruction *I = dyn_cast<Instruction>(New))
212 WorkList.push_back(I);
216 // EraseInstFromFunction - When dealing with an instruction that has side
217 // effects or produces a void value, we can't rely on DCE to delete the
218 // instruction. Instead, visit methods should return the value returned by
220 Instruction *EraseInstFromFunction(Instruction &I) {
221 assert(I.use_empty() && "Cannot erase instruction that is used!");
222 AddUsesToWorkList(I);
223 removeFromWorkList(&I);
225 return 0; // Don't do anything with FI
229 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
230 /// InsertBefore instruction. This is specialized a bit to avoid inserting
231 /// casts that are known to not do anything...
233 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
234 Instruction *InsertBefore);
236 // SimplifyCommutative - This performs a few simplifications for commutative
238 bool SimplifyCommutative(BinaryOperator &I);
240 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
241 uint64_t &KnownZero, uint64_t &KnownOne,
244 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
245 // PHI node as operand #0, see if we can fold the instruction into the PHI
246 // (which is only possible if all operands to the PHI are constants).
247 Instruction *FoldOpIntoPhi(Instruction &I);
249 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
250 // operator and they all are only used by the PHI, PHI together their
251 // inputs, and do the operation once, to the result of the PHI.
252 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
254 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
255 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
257 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
258 bool isSub, Instruction &I);
259 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
260 bool Inside, Instruction &IB);
261 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
262 Instruction *MatchBSwap(BinaryOperator &I);
264 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
267 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
270 // getComplexity: Assign a complexity or rank value to LLVM Values...
271 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
272 static unsigned getComplexity(Value *V) {
273 if (isa<Instruction>(V)) {
274 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
278 if (isa<Argument>(V)) return 3;
279 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
282 // isOnlyUse - Return true if this instruction will be deleted if we stop using
284 static bool isOnlyUse(Value *V) {
285 return V->hasOneUse() || isa<Constant>(V);
288 // getPromotedType - Return the specified type promoted as it would be to pass
289 // though a va_arg area...
290 static const Type *getPromotedType(const Type *Ty) {
291 switch (Ty->getTypeID()) {
292 case Type::SByteTyID:
293 case Type::ShortTyID: return Type::IntTy;
294 case Type::UByteTyID:
295 case Type::UShortTyID: return Type::UIntTy;
296 case Type::FloatTyID: return Type::DoubleTy;
301 /// isCast - If the specified operand is a CastInst or a constant expr cast,
302 /// return the operand value, otherwise return null.
303 static Value *isCast(Value *V) {
304 if (CastInst *I = dyn_cast<CastInst>(V))
305 return I->getOperand(0);
306 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
307 if (CE->getOpcode() == Instruction::Cast)
308 return CE->getOperand(0);
319 /// getCastType - In the future, we will split the cast instruction into these
320 /// various types. Until then, we have to do the analysis here.
321 static CastType getCastType(const Type *Src, const Type *Dest) {
322 assert(Src->isIntegral() && Dest->isIntegral() &&
323 "Only works on integral types!");
324 unsigned SrcSize = Src->getPrimitiveSizeInBits();
325 unsigned DestSize = Dest->getPrimitiveSizeInBits();
327 if (SrcSize == DestSize) return Noop;
328 if (SrcSize > DestSize) return Truncate;
329 if (Src->isSigned()) return Signext;
334 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
337 static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
338 const Type *DstTy, TargetData *TD) {
340 // It is legal to eliminate the instruction if casting A->B->A if the sizes
341 // are identical and the bits don't get reinterpreted (for example
342 // int->float->int would not be allowed).
343 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
346 // If we are casting between pointer and integer types, treat pointers as
347 // integers of the appropriate size for the code below.
348 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
349 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
350 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
352 // Allow free casting and conversion of sizes as long as the sign doesn't
354 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
355 CastType FirstCast = getCastType(SrcTy, MidTy);
356 CastType SecondCast = getCastType(MidTy, DstTy);
358 // Capture the effect of these two casts. If the result is a legal cast,
359 // the CastType is stored here, otherwise a special code is used.
360 static const unsigned CastResult[] = {
361 // First cast is noop
363 // First cast is a truncate
364 1, 1, 4, 4, // trunc->extend is not safe to eliminate
365 // First cast is a sign ext
366 2, 5, 2, 4, // signext->zeroext never ok
367 // First cast is a zero ext
371 unsigned Result = CastResult[FirstCast*4+SecondCast];
373 default: assert(0 && "Illegal table value!");
378 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
379 // truncates, we could eliminate more casts.
380 return (unsigned)getCastType(SrcTy, DstTy) == Result;
382 return false; // Not possible to eliminate this here.
384 // Sign or zero extend followed by truncate is always ok if the result
385 // is a truncate or noop.
386 CastType ResultCast = getCastType(SrcTy, DstTy);
387 if (ResultCast == Noop || ResultCast == Truncate)
389 // Otherwise we are still growing the value, we are only safe if the
390 // result will match the sign/zeroextendness of the result.
391 return ResultCast == FirstCast;
395 // If this is a cast from 'float -> double -> integer', cast from
396 // 'float -> integer' directly, as the value isn't changed by the
397 // float->double conversion.
398 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
399 DstTy->isIntegral() &&
400 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
403 // Packed type conversions don't modify bits.
404 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
410 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
411 /// in any code being generated. It does not require codegen if V is simple
412 /// enough or if the cast can be folded into other casts.
413 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
414 if (V->getType() == Ty || isa<Constant>(V)) return false;
416 // If this is a noop cast, it isn't real codegen.
417 if (V->getType()->isLosslesslyConvertibleTo(Ty))
420 // If this is another cast that can be eliminated, it isn't codegen either.
421 if (const CastInst *CI = dyn_cast<CastInst>(V))
422 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
428 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
429 /// InsertBefore instruction. This is specialized a bit to avoid inserting
430 /// casts that are known to not do anything...
432 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
433 Instruction *InsertBefore) {
434 if (V->getType() == DestTy) return V;
435 if (Constant *C = dyn_cast<Constant>(V))
436 return ConstantExpr::getCast(C, DestTy);
438 CastInst *CI = new CastInst(V, DestTy, V->getName());
439 InsertNewInstBefore(CI, *InsertBefore);
443 // SimplifyCommutative - This performs a few simplifications for commutative
446 // 1. Order operands such that they are listed from right (least complex) to
447 // left (most complex). This puts constants before unary operators before
450 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
451 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
453 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
454 bool Changed = false;
455 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
456 Changed = !I.swapOperands();
458 if (!I.isAssociative()) return Changed;
459 Instruction::BinaryOps Opcode = I.getOpcode();
460 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
461 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
462 if (isa<Constant>(I.getOperand(1))) {
463 Constant *Folded = ConstantExpr::get(I.getOpcode(),
464 cast<Constant>(I.getOperand(1)),
465 cast<Constant>(Op->getOperand(1)));
466 I.setOperand(0, Op->getOperand(0));
467 I.setOperand(1, Folded);
469 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
470 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
471 isOnlyUse(Op) && isOnlyUse(Op1)) {
472 Constant *C1 = cast<Constant>(Op->getOperand(1));
473 Constant *C2 = cast<Constant>(Op1->getOperand(1));
475 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
476 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
477 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
480 WorkList.push_back(New);
481 I.setOperand(0, New);
482 I.setOperand(1, Folded);
489 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
490 // if the LHS is a constant zero (which is the 'negate' form).
492 static inline Value *dyn_castNegVal(Value *V) {
493 if (BinaryOperator::isNeg(V))
494 return BinaryOperator::getNegArgument(V);
496 // Constants can be considered to be negated values if they can be folded.
497 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
498 return ConstantExpr::getNeg(C);
502 static inline Value *dyn_castNotVal(Value *V) {
503 if (BinaryOperator::isNot(V))
504 return BinaryOperator::getNotArgument(V);
506 // Constants can be considered to be not'ed values...
507 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
508 return ConstantExpr::getNot(C);
512 // dyn_castFoldableMul - If this value is a multiply that can be folded into
513 // other computations (because it has a constant operand), return the
514 // non-constant operand of the multiply, and set CST to point to the multiplier.
515 // Otherwise, return null.
517 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
518 if (V->hasOneUse() && V->getType()->isInteger())
519 if (Instruction *I = dyn_cast<Instruction>(V)) {
520 if (I->getOpcode() == Instruction::Mul)
521 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
522 return I->getOperand(0);
523 if (I->getOpcode() == Instruction::Shl)
524 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
525 // The multiplier is really 1 << CST.
526 Constant *One = ConstantInt::get(V->getType(), 1);
527 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
528 return I->getOperand(0);
534 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
535 /// expression, return it.
536 static User *dyn_castGetElementPtr(Value *V) {
537 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
538 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
539 if (CE->getOpcode() == Instruction::GetElementPtr)
540 return cast<User>(V);
544 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
545 static ConstantInt *AddOne(ConstantInt *C) {
546 return cast<ConstantInt>(ConstantExpr::getAdd(C,
547 ConstantInt::get(C->getType(), 1)));
549 static ConstantInt *SubOne(ConstantInt *C) {
550 return cast<ConstantInt>(ConstantExpr::getSub(C,
551 ConstantInt::get(C->getType(), 1)));
554 /// GetConstantInType - Return a ConstantInt with the specified type and value.
556 static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
557 if (Ty->isUnsigned())
558 return ConstantUInt::get(Ty, Val);
559 else if (Ty->getTypeID() == Type::BoolTyID)
560 return ConstantBool::get(Val);
562 SVal <<= 64-Ty->getPrimitiveSizeInBits();
563 SVal >>= 64-Ty->getPrimitiveSizeInBits();
564 return ConstantSInt::get(Ty, SVal);
568 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
569 /// known to be either zero or one and return them in the KnownZero/KnownOne
570 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
572 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
573 uint64_t &KnownOne, unsigned Depth = 0) {
574 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
575 // we cannot optimize based on the assumption that it is zero without changing
576 // it to be an explicit zero. If we don't change it to zero, other code could
577 // optimized based on the contradictory assumption that it is non-zero.
578 // Because instcombine aggressively folds operations with undef args anyway,
579 // this won't lose us code quality.
580 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
581 // We know all of the bits for a constant!
582 KnownOne = CI->getZExtValue() & Mask;
583 KnownZero = ~KnownOne & Mask;
587 KnownZero = KnownOne = 0; // Don't know anything.
588 if (Depth == 6 || Mask == 0)
589 return; // Limit search depth.
591 uint64_t KnownZero2, KnownOne2;
592 Instruction *I = dyn_cast<Instruction>(V);
595 Mask &= V->getType()->getIntegralTypeMask();
597 switch (I->getOpcode()) {
598 case Instruction::And:
599 // If either the LHS or the RHS are Zero, the result is zero.
600 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
602 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
603 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
604 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
606 // Output known-1 bits are only known if set in both the LHS & RHS.
607 KnownOne &= KnownOne2;
608 // Output known-0 are known to be clear if zero in either the LHS | RHS.
609 KnownZero |= KnownZero2;
611 case Instruction::Or:
612 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
614 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
615 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
616 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
618 // Output known-0 bits are only known if clear in both the LHS & RHS.
619 KnownZero &= KnownZero2;
620 // Output known-1 are known to be set if set in either the LHS | RHS.
621 KnownOne |= KnownOne2;
623 case Instruction::Xor: {
624 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
625 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
626 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
627 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
629 // Output known-0 bits are known if clear or set in both the LHS & RHS.
630 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
631 // Output known-1 are known to be set if set in only one of the LHS, RHS.
632 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
633 KnownZero = KnownZeroOut;
636 case Instruction::Select:
637 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
638 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
639 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
640 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
642 // Only known if known in both the LHS and RHS.
643 KnownOne &= KnownOne2;
644 KnownZero &= KnownZero2;
646 case Instruction::Cast: {
647 const Type *SrcTy = I->getOperand(0)->getType();
648 if (!SrcTy->isIntegral()) return;
650 // If this is an integer truncate or noop, just look in the input.
651 if (SrcTy->getPrimitiveSizeInBits() >=
652 I->getType()->getPrimitiveSizeInBits()) {
653 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
657 // Sign or Zero extension. Compute the bits in the result that are not
658 // present in the input.
659 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
660 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
662 // Handle zero extension.
663 if (!SrcTy->isSigned()) {
664 Mask &= SrcTy->getIntegralTypeMask();
665 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
666 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
667 // The top bits are known to be zero.
668 KnownZero |= NewBits;
671 Mask &= SrcTy->getIntegralTypeMask();
672 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
673 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
675 // If the sign bit of the input is known set or clear, then we know the
676 // top bits of the result.
677 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
678 if (KnownZero & InSignBit) { // Input sign bit known zero
679 KnownZero |= NewBits;
680 KnownOne &= ~NewBits;
681 } else if (KnownOne & InSignBit) { // Input sign bit known set
683 KnownZero &= ~NewBits;
684 } else { // Input sign bit unknown
685 KnownZero &= ~NewBits;
686 KnownOne &= ~NewBits;
691 case Instruction::Shl:
692 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
693 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
694 Mask >>= SA->getValue();
695 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
696 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
697 KnownZero <<= SA->getValue();
698 KnownOne <<= SA->getValue();
699 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
703 case Instruction::Shr:
704 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
705 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
706 // Compute the new bits that are at the top now.
707 uint64_t HighBits = (1ULL << SA->getValue())-1;
708 HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
710 if (I->getType()->isUnsigned()) { // Unsigned shift right.
711 Mask <<= SA->getValue();
712 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
713 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
714 KnownZero >>= SA->getValue();
715 KnownOne >>= SA->getValue();
716 KnownZero |= HighBits; // high bits known zero.
718 Mask <<= SA->getValue();
719 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
720 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
721 KnownZero >>= SA->getValue();
722 KnownOne >>= SA->getValue();
724 // Handle the sign bits.
725 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
726 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
728 if (KnownZero & SignBit) { // New bits are known zero.
729 KnownZero |= HighBits;
730 } else if (KnownOne & SignBit) { // New bits are known one.
731 KnownOne |= HighBits;
740 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
741 /// this predicate to simplify operations downstream. Mask is known to be zero
742 /// for bits that V cannot have.
743 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
744 uint64_t KnownZero, KnownOne;
745 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
746 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
747 return (KnownZero & Mask) == Mask;
750 /// ShrinkDemandedConstant - Check to see if the specified operand of the
751 /// specified instruction is a constant integer. If so, check to see if there
752 /// are any bits set in the constant that are not demanded. If so, shrink the
753 /// constant and return true.
754 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
756 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
757 if (!OpC) return false;
759 // If there are no bits set that aren't demanded, nothing to do.
760 if ((~Demanded & OpC->getZExtValue()) == 0)
763 // This is producing any bits that are not needed, shrink the RHS.
764 uint64_t Val = Demanded & OpC->getZExtValue();
765 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
769 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
770 // set of known zero and one bits, compute the maximum and minimum values that
771 // could have the specified known zero and known one bits, returning them in
773 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
776 int64_t &Min, int64_t &Max) {
777 uint64_t TypeBits = Ty->getIntegralTypeMask();
778 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
780 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
782 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
783 // bit if it is unknown.
785 Max = KnownOne|UnknownBits;
787 if (SignBit & UnknownBits) { // Sign bit is unknown
792 // Sign extend the min/max values.
793 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
794 Min = (Min << ShAmt) >> ShAmt;
795 Max = (Max << ShAmt) >> ShAmt;
798 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
799 // a set of known zero and one bits, compute the maximum and minimum values that
800 // could have the specified known zero and known one bits, returning them in
802 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
807 uint64_t TypeBits = Ty->getIntegralTypeMask();
808 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
810 // The minimum value is when the unknown bits are all zeros.
812 // The maximum value is when the unknown bits are all ones.
813 Max = KnownOne|UnknownBits;
817 /// SimplifyDemandedBits - Look at V. At this point, we know that only the
818 /// DemandedMask bits of the result of V are ever used downstream. If we can
819 /// use this information to simplify V, do so and return true. Otherwise,
820 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
821 /// the expression (used to simplify the caller). The KnownZero/One bits may
822 /// only be accurate for those bits in the DemandedMask.
823 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
824 uint64_t &KnownZero, uint64_t &KnownOne,
826 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
827 // We know all of the bits for a constant!
828 KnownOne = CI->getZExtValue() & DemandedMask;
829 KnownZero = ~KnownOne & DemandedMask;
833 KnownZero = KnownOne = 0;
834 if (!V->hasOneUse()) { // Other users may use these bits.
835 if (Depth != 0) { // Not at the root.
836 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
837 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
840 // If this is the root being simplified, allow it to have multiple uses,
841 // just set the DemandedMask to all bits.
842 DemandedMask = V->getType()->getIntegralTypeMask();
843 } else if (DemandedMask == 0) { // Not demanding any bits from V.
844 if (V != UndefValue::get(V->getType()))
845 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
847 } else if (Depth == 6) { // Limit search depth.
851 Instruction *I = dyn_cast<Instruction>(V);
852 if (!I) return false; // Only analyze instructions.
854 DemandedMask &= V->getType()->getIntegralTypeMask();
856 uint64_t KnownZero2, KnownOne2;
857 switch (I->getOpcode()) {
859 case Instruction::And:
860 // If either the LHS or the RHS are Zero, the result is zero.
861 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
862 KnownZero, KnownOne, Depth+1))
864 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
866 // If something is known zero on the RHS, the bits aren't demanded on the
868 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
869 KnownZero2, KnownOne2, Depth+1))
871 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
873 // If all of the demanded bits are known one on one side, return the other.
874 // These bits cannot contribute to the result of the 'and'.
875 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
876 return UpdateValueUsesWith(I, I->getOperand(0));
877 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
878 return UpdateValueUsesWith(I, I->getOperand(1));
880 // If all of the demanded bits in the inputs are known zeros, return zero.
881 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
882 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
884 // If the RHS is a constant, see if we can simplify it.
885 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
886 return UpdateValueUsesWith(I, I);
888 // Output known-1 bits are only known if set in both the LHS & RHS.
889 KnownOne &= KnownOne2;
890 // Output known-0 are known to be clear if zero in either the LHS | RHS.
891 KnownZero |= KnownZero2;
893 case Instruction::Or:
894 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
895 KnownZero, KnownOne, Depth+1))
897 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
898 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
899 KnownZero2, KnownOne2, Depth+1))
901 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
903 // If all of the demanded bits are known zero on one side, return the other.
904 // These bits cannot contribute to the result of the 'or'.
905 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
906 return UpdateValueUsesWith(I, I->getOperand(0));
907 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
908 return UpdateValueUsesWith(I, I->getOperand(1));
910 // If all of the potentially set bits on one side are known to be set on
911 // the other side, just use the 'other' side.
912 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
913 (DemandedMask & (~KnownZero)))
914 return UpdateValueUsesWith(I, I->getOperand(0));
915 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
916 (DemandedMask & (~KnownZero2)))
917 return UpdateValueUsesWith(I, I->getOperand(1));
919 // If the RHS is a constant, see if we can simplify it.
920 if (ShrinkDemandedConstant(I, 1, DemandedMask))
921 return UpdateValueUsesWith(I, I);
923 // Output known-0 bits are only known if clear in both the LHS & RHS.
924 KnownZero &= KnownZero2;
925 // Output known-1 are known to be set if set in either the LHS | RHS.
926 KnownOne |= KnownOne2;
928 case Instruction::Xor: {
929 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
930 KnownZero, KnownOne, Depth+1))
932 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
933 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
934 KnownZero2, KnownOne2, Depth+1))
936 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
938 // If all of the demanded bits are known zero on one side, return the other.
939 // These bits cannot contribute to the result of the 'xor'.
940 if ((DemandedMask & KnownZero) == DemandedMask)
941 return UpdateValueUsesWith(I, I->getOperand(0));
942 if ((DemandedMask & KnownZero2) == DemandedMask)
943 return UpdateValueUsesWith(I, I->getOperand(1));
945 // Output known-0 bits are known if clear or set in both the LHS & RHS.
946 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
947 // Output known-1 are known to be set if set in only one of the LHS, RHS.
948 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
950 // If all of the unknown bits are known to be zero on one side or the other
951 // (but not both) turn this into an *inclusive* or.
952 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
953 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
954 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
956 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
958 InsertNewInstBefore(Or, *I);
959 return UpdateValueUsesWith(I, Or);
963 // If all of the demanded bits on one side are known, and all of the set
964 // bits on that side are also known to be set on the other side, turn this
965 // into an AND, as we know the bits will be cleared.
966 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
967 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
968 if ((KnownOne & KnownOne2) == KnownOne) {
969 Constant *AndC = GetConstantInType(I->getType(),
970 ~KnownOne & DemandedMask);
972 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
973 InsertNewInstBefore(And, *I);
974 return UpdateValueUsesWith(I, And);
978 // If the RHS is a constant, see if we can simplify it.
979 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
980 if (ShrinkDemandedConstant(I, 1, DemandedMask))
981 return UpdateValueUsesWith(I, I);
983 KnownZero = KnownZeroOut;
984 KnownOne = KnownOneOut;
987 case Instruction::Select:
988 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
989 KnownZero, KnownOne, Depth+1))
991 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
992 KnownZero2, KnownOne2, Depth+1))
994 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
995 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
997 // If the operands are constants, see if we can simplify them.
998 if (ShrinkDemandedConstant(I, 1, DemandedMask))
999 return UpdateValueUsesWith(I, I);
1000 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1001 return UpdateValueUsesWith(I, I);
1003 // Only known if known in both the LHS and RHS.
1004 KnownOne &= KnownOne2;
1005 KnownZero &= KnownZero2;
1007 case Instruction::Cast: {
1008 const Type *SrcTy = I->getOperand(0)->getType();
1009 if (!SrcTy->isIntegral()) return false;
1011 // If this is an integer truncate or noop, just look in the input.
1012 if (SrcTy->getPrimitiveSizeInBits() >=
1013 I->getType()->getPrimitiveSizeInBits()) {
1014 // Cast to bool is a comparison against 0, which demands all bits. We
1015 // can't propagate anything useful up.
1016 if (I->getType() == Type::BoolTy)
1019 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1020 KnownZero, KnownOne, Depth+1))
1022 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1026 // Sign or Zero extension. Compute the bits in the result that are not
1027 // present in the input.
1028 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1029 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1031 // Handle zero extension.
1032 if (!SrcTy->isSigned()) {
1033 DemandedMask &= SrcTy->getIntegralTypeMask();
1034 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1035 KnownZero, KnownOne, Depth+1))
1037 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1038 // The top bits are known to be zero.
1039 KnownZero |= NewBits;
1042 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1043 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1045 // If any of the sign extended bits are demanded, we know that the sign
1047 if (NewBits & DemandedMask)
1048 InputDemandedBits |= InSignBit;
1050 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1051 KnownZero, KnownOne, Depth+1))
1053 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1055 // If the sign bit of the input is known set or clear, then we know the
1056 // top bits of the result.
1058 // If the input sign bit is known zero, or if the NewBits are not demanded
1059 // convert this into a zero extension.
1060 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1061 // Convert to unsigned first.
1062 Instruction *NewVal;
1063 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
1064 I->getOperand(0)->getName());
1065 InsertNewInstBefore(NewVal, *I);
1066 // Then cast that to the destination type.
1067 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1068 InsertNewInstBefore(NewVal, *I);
1069 return UpdateValueUsesWith(I, NewVal);
1070 } else if (KnownOne & InSignBit) { // Input sign bit known set
1071 KnownOne |= NewBits;
1072 KnownZero &= ~NewBits;
1073 } else { // Input sign bit unknown
1074 KnownZero &= ~NewBits;
1075 KnownOne &= ~NewBits;
1080 case Instruction::Shl:
1081 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1082 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
1083 KnownZero, KnownOne, Depth+1))
1085 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1086 KnownZero <<= SA->getValue();
1087 KnownOne <<= SA->getValue();
1088 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
1091 case Instruction::Shr:
1092 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1093 unsigned ShAmt = SA->getValue();
1095 // Compute the new bits that are at the top now.
1096 uint64_t HighBits = (1ULL << ShAmt)-1;
1097 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
1098 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1099 if (I->getType()->isUnsigned()) { // Unsigned shift right.
1100 if (SimplifyDemandedBits(I->getOperand(0),
1101 (DemandedMask << ShAmt) & TypeMask,
1102 KnownZero, KnownOne, Depth+1))
1104 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1105 KnownZero &= TypeMask;
1106 KnownOne &= TypeMask;
1107 KnownZero >>= ShAmt;
1109 KnownZero |= HighBits; // high bits known zero.
1110 } else { // Signed shift right.
1111 if (SimplifyDemandedBits(I->getOperand(0),
1112 (DemandedMask << ShAmt) & TypeMask,
1113 KnownZero, KnownOne, Depth+1))
1115 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1116 KnownZero &= TypeMask;
1117 KnownOne &= TypeMask;
1118 KnownZero >>= SA->getValue();
1119 KnownOne >>= SA->getValue();
1121 // Handle the sign bits.
1122 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1123 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
1125 // If the input sign bit is known to be zero, or if none of the top bits
1126 // are demanded, turn this into an unsigned shift right.
1127 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1128 // Convert the input to unsigned.
1129 Instruction *NewVal;
1130 NewVal = new CastInst(I->getOperand(0),
1131 I->getType()->getUnsignedVersion(),
1132 I->getOperand(0)->getName());
1133 InsertNewInstBefore(NewVal, *I);
1134 // Perform the unsigned shift right.
1135 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
1136 InsertNewInstBefore(NewVal, *I);
1137 // Then cast that to the destination type.
1138 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1139 InsertNewInstBefore(NewVal, *I);
1140 return UpdateValueUsesWith(I, NewVal);
1141 } else if (KnownOne & SignBit) { // New bits are known one.
1142 KnownOne |= HighBits;
1149 // If the client is only demanding bits that we know, return the known
1151 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1152 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
1156 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
1157 // true when both operands are equal...
1159 static bool isTrueWhenEqual(Instruction &I) {
1160 return I.getOpcode() == Instruction::SetEQ ||
1161 I.getOpcode() == Instruction::SetGE ||
1162 I.getOpcode() == Instruction::SetLE;
1165 /// AssociativeOpt - Perform an optimization on an associative operator. This
1166 /// function is designed to check a chain of associative operators for a
1167 /// potential to apply a certain optimization. Since the optimization may be
1168 /// applicable if the expression was reassociated, this checks the chain, then
1169 /// reassociates the expression as necessary to expose the optimization
1170 /// opportunity. This makes use of a special Functor, which must define
1171 /// 'shouldApply' and 'apply' methods.
1173 template<typename Functor>
1174 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1175 unsigned Opcode = Root.getOpcode();
1176 Value *LHS = Root.getOperand(0);
1178 // Quick check, see if the immediate LHS matches...
1179 if (F.shouldApply(LHS))
1180 return F.apply(Root);
1182 // Otherwise, if the LHS is not of the same opcode as the root, return.
1183 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1184 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1185 // Should we apply this transform to the RHS?
1186 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1188 // If not to the RHS, check to see if we should apply to the LHS...
1189 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1190 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1194 // If the functor wants to apply the optimization to the RHS of LHSI,
1195 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1197 BasicBlock *BB = Root.getParent();
1199 // Now all of the instructions are in the current basic block, go ahead
1200 // and perform the reassociation.
1201 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1203 // First move the selected RHS to the LHS of the root...
1204 Root.setOperand(0, LHSI->getOperand(1));
1206 // Make what used to be the LHS of the root be the user of the root...
1207 Value *ExtraOperand = TmpLHSI->getOperand(1);
1208 if (&Root == TmpLHSI) {
1209 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1212 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1213 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1214 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1215 BasicBlock::iterator ARI = &Root; ++ARI;
1216 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1219 // Now propagate the ExtraOperand down the chain of instructions until we
1221 while (TmpLHSI != LHSI) {
1222 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1223 // Move the instruction to immediately before the chain we are
1224 // constructing to avoid breaking dominance properties.
1225 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1226 BB->getInstList().insert(ARI, NextLHSI);
1229 Value *NextOp = NextLHSI->getOperand(1);
1230 NextLHSI->setOperand(1, ExtraOperand);
1232 ExtraOperand = NextOp;
1235 // Now that the instructions are reassociated, have the functor perform
1236 // the transformation...
1237 return F.apply(Root);
1240 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1246 // AddRHS - Implements: X + X --> X << 1
1249 AddRHS(Value *rhs) : RHS(rhs) {}
1250 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1251 Instruction *apply(BinaryOperator &Add) const {
1252 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1253 ConstantInt::get(Type::UByteTy, 1));
1257 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1259 struct AddMaskingAnd {
1261 AddMaskingAnd(Constant *c) : C2(c) {}
1262 bool shouldApply(Value *LHS) const {
1264 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1265 ConstantExpr::getAnd(C1, C2)->isNullValue();
1267 Instruction *apply(BinaryOperator &Add) const {
1268 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1272 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1274 if (isa<CastInst>(I)) {
1275 if (Constant *SOC = dyn_cast<Constant>(SO))
1276 return ConstantExpr::getCast(SOC, I.getType());
1278 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1279 SO->getName() + ".cast"), I);
1282 // Figure out if the constant is the left or the right argument.
1283 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1284 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1286 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1288 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1289 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1292 Value *Op0 = SO, *Op1 = ConstOperand;
1294 std::swap(Op0, Op1);
1296 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1297 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1298 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1299 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1301 assert(0 && "Unknown binary instruction type!");
1304 return IC->InsertNewInstBefore(New, I);
1307 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1308 // constant as the other operand, try to fold the binary operator into the
1309 // select arguments. This also works for Cast instructions, which obviously do
1310 // not have a second operand.
1311 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1313 // Don't modify shared select instructions
1314 if (!SI->hasOneUse()) return 0;
1315 Value *TV = SI->getOperand(1);
1316 Value *FV = SI->getOperand(2);
1318 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1319 // Bool selects with constant operands can be folded to logical ops.
1320 if (SI->getType() == Type::BoolTy) return 0;
1322 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1323 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1325 return new SelectInst(SI->getCondition(), SelectTrueVal,
1332 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1333 /// node as operand #0, see if we can fold the instruction into the PHI (which
1334 /// is only possible if all operands to the PHI are constants).
1335 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1336 PHINode *PN = cast<PHINode>(I.getOperand(0));
1337 unsigned NumPHIValues = PN->getNumIncomingValues();
1338 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1340 // Check to see if all of the operands of the PHI are constants. If there is
1341 // one non-constant value, remember the BB it is. If there is more than one
1343 BasicBlock *NonConstBB = 0;
1344 for (unsigned i = 0; i != NumPHIValues; ++i)
1345 if (!isa<Constant>(PN->getIncomingValue(i))) {
1346 if (NonConstBB) return 0; // More than one non-const value.
1347 NonConstBB = PN->getIncomingBlock(i);
1349 // If the incoming non-constant value is in I's block, we have an infinite
1351 if (NonConstBB == I.getParent())
1355 // If there is exactly one non-constant value, we can insert a copy of the
1356 // operation in that block. However, if this is a critical edge, we would be
1357 // inserting the computation one some other paths (e.g. inside a loop). Only
1358 // do this if the pred block is unconditionally branching into the phi block.
1360 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1361 if (!BI || !BI->isUnconditional()) return 0;
1364 // Okay, we can do the transformation: create the new PHI node.
1365 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1367 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1368 InsertNewInstBefore(NewPN, *PN);
1370 // Next, add all of the operands to the PHI.
1371 if (I.getNumOperands() == 2) {
1372 Constant *C = cast<Constant>(I.getOperand(1));
1373 for (unsigned i = 0; i != NumPHIValues; ++i) {
1375 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1376 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1378 assert(PN->getIncomingBlock(i) == NonConstBB);
1379 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1380 InV = BinaryOperator::create(BO->getOpcode(),
1381 PN->getIncomingValue(i), C, "phitmp",
1382 NonConstBB->getTerminator());
1383 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1384 InV = new ShiftInst(SI->getOpcode(),
1385 PN->getIncomingValue(i), C, "phitmp",
1386 NonConstBB->getTerminator());
1388 assert(0 && "Unknown binop!");
1390 WorkList.push_back(cast<Instruction>(InV));
1392 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1395 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1396 const Type *RetTy = I.getType();
1397 for (unsigned i = 0; i != NumPHIValues; ++i) {
1399 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1400 InV = ConstantExpr::getCast(InC, RetTy);
1402 assert(PN->getIncomingBlock(i) == NonConstBB);
1403 InV = new CastInst(PN->getIncomingValue(i), I.getType(), "phitmp",
1404 NonConstBB->getTerminator());
1405 WorkList.push_back(cast<Instruction>(InV));
1407 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1410 return ReplaceInstUsesWith(I, NewPN);
1413 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1414 bool Changed = SimplifyCommutative(I);
1415 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1417 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1418 // X + undef -> undef
1419 if (isa<UndefValue>(RHS))
1420 return ReplaceInstUsesWith(I, RHS);
1423 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1424 if (RHSC->isNullValue())
1425 return ReplaceInstUsesWith(I, LHS);
1426 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1427 if (CFP->isExactlyValue(-0.0))
1428 return ReplaceInstUsesWith(I, LHS);
1431 // X + (signbit) --> X ^ signbit
1432 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1433 uint64_t Val = CI->getZExtValue();
1434 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1435 return BinaryOperator::createXor(LHS, RHS);
1438 if (isa<PHINode>(LHS))
1439 if (Instruction *NV = FoldOpIntoPhi(I))
1442 ConstantInt *XorRHS = 0;
1444 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1445 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1446 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1447 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1449 uint64_t C0080Val = 1ULL << 31;
1450 int64_t CFF80Val = -C0080Val;
1453 if (TySizeBits > Size) {
1455 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1456 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1457 if (RHSSExt == CFF80Val) {
1458 if (XorRHS->getZExtValue() == C0080Val)
1460 } else if (RHSZExt == C0080Val) {
1461 if (XorRHS->getSExtValue() == CFF80Val)
1465 // This is a sign extend if the top bits are known zero.
1466 uint64_t Mask = ~0ULL;
1467 Mask <<= 64-(TySizeBits-Size);
1468 Mask &= XorLHS->getType()->getIntegralTypeMask();
1469 if (!MaskedValueIsZero(XorLHS, Mask))
1470 Size = 0; // Not a sign ext, but can't be any others either.
1477 } while (Size >= 8);
1480 const Type *MiddleType = 0;
1483 case 32: MiddleType = Type::IntTy; break;
1484 case 16: MiddleType = Type::ShortTy; break;
1485 case 8: MiddleType = Type::SByteTy; break;
1488 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1489 InsertNewInstBefore(NewTrunc, I);
1490 return new CastInst(NewTrunc, I.getType());
1496 if (I.getType()->isInteger()) {
1497 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1499 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1500 if (RHSI->getOpcode() == Instruction::Sub)
1501 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1502 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1504 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1505 if (LHSI->getOpcode() == Instruction::Sub)
1506 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1507 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1512 if (Value *V = dyn_castNegVal(LHS))
1513 return BinaryOperator::createSub(RHS, V);
1516 if (!isa<Constant>(RHS))
1517 if (Value *V = dyn_castNegVal(RHS))
1518 return BinaryOperator::createSub(LHS, V);
1522 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1523 if (X == RHS) // X*C + X --> X * (C+1)
1524 return BinaryOperator::createMul(RHS, AddOne(C2));
1526 // X*C1 + X*C2 --> X * (C1+C2)
1528 if (X == dyn_castFoldableMul(RHS, C1))
1529 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1532 // X + X*C --> X * (C+1)
1533 if (dyn_castFoldableMul(RHS, C2) == LHS)
1534 return BinaryOperator::createMul(LHS, AddOne(C2));
1537 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1538 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1539 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
1541 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1543 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1544 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1545 return BinaryOperator::createSub(C, X);
1548 // (X & FF00) + xx00 -> (X+xx00) & FF00
1549 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1550 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1551 if (Anded == CRHS) {
1552 // See if all bits from the first bit set in the Add RHS up are included
1553 // in the mask. First, get the rightmost bit.
1554 uint64_t AddRHSV = CRHS->getRawValue();
1556 // Form a mask of all bits from the lowest bit added through the top.
1557 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1558 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
1560 // See if the and mask includes all of these bits.
1561 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
1563 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1564 // Okay, the xform is safe. Insert the new add pronto.
1565 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1566 LHS->getName()), I);
1567 return BinaryOperator::createAnd(NewAdd, C2);
1572 // Try to fold constant add into select arguments.
1573 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1574 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1578 return Changed ? &I : 0;
1581 // isSignBit - Return true if the value represented by the constant only has the
1582 // highest order bit set.
1583 static bool isSignBit(ConstantInt *CI) {
1584 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1585 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1588 /// RemoveNoopCast - Strip off nonconverting casts from the value.
1590 static Value *RemoveNoopCast(Value *V) {
1591 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1592 const Type *CTy = CI->getType();
1593 const Type *OpTy = CI->getOperand(0)->getType();
1594 if (CTy->isInteger() && OpTy->isInteger()) {
1595 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
1596 return RemoveNoopCast(CI->getOperand(0));
1597 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1598 return RemoveNoopCast(CI->getOperand(0));
1603 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1604 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1606 if (Op0 == Op1) // sub X, X -> 0
1607 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1609 // If this is a 'B = x-(-A)', change to B = x+A...
1610 if (Value *V = dyn_castNegVal(Op1))
1611 return BinaryOperator::createAdd(Op0, V);
1613 if (isa<UndefValue>(Op0))
1614 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1615 if (isa<UndefValue>(Op1))
1616 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1618 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1619 // Replace (-1 - A) with (~A)...
1620 if (C->isAllOnesValue())
1621 return BinaryOperator::createNot(Op1);
1623 // C - ~X == X + (1+C)
1625 if (match(Op1, m_Not(m_Value(X))))
1626 return BinaryOperator::createAdd(X,
1627 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1628 // -((uint)X >> 31) -> ((int)X >> 31)
1629 // -((int)X >> 31) -> ((uint)X >> 31)
1630 if (C->isNullValue()) {
1631 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1632 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
1633 if (SI->getOpcode() == Instruction::Shr)
1634 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1636 if (SI->getType()->isSigned())
1637 NewTy = SI->getType()->getUnsignedVersion();
1639 NewTy = SI->getType()->getSignedVersion();
1640 // Check to see if we are shifting out everything but the sign bit.
1641 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
1642 // Ok, the transformation is safe. Insert a cast of the incoming
1643 // value, then the new shift, then the new cast.
1644 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1645 SI->getOperand(0)->getName());
1646 Value *InV = InsertNewInstBefore(FirstCast, I);
1647 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1649 if (NewShift->getType() == I.getType())
1652 InV = InsertNewInstBefore(NewShift, I);
1653 return new CastInst(NewShift, I.getType());
1659 // Try to fold constant sub into select arguments.
1660 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1661 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1664 if (isa<PHINode>(Op0))
1665 if (Instruction *NV = FoldOpIntoPhi(I))
1669 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1670 if (Op1I->getOpcode() == Instruction::Add &&
1671 !Op0->getType()->isFloatingPoint()) {
1672 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
1673 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
1674 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
1675 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
1676 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1677 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1678 // C1-(X+C2) --> (C1-C2)-X
1679 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1680 Op1I->getOperand(0));
1684 if (Op1I->hasOneUse()) {
1685 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1686 // is not used by anyone else...
1688 if (Op1I->getOpcode() == Instruction::Sub &&
1689 !Op1I->getType()->isFloatingPoint()) {
1690 // Swap the two operands of the subexpr...
1691 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1692 Op1I->setOperand(0, IIOp1);
1693 Op1I->setOperand(1, IIOp0);
1695 // Create the new top level add instruction...
1696 return BinaryOperator::createAdd(Op0, Op1);
1699 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1701 if (Op1I->getOpcode() == Instruction::And &&
1702 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1703 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1706 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
1707 return BinaryOperator::createAnd(Op0, NewNot);
1710 // -(X sdiv C) -> (X sdiv -C)
1711 if (Op1I->getOpcode() == Instruction::Div)
1712 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1713 if (CSI->isNullValue())
1714 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
1715 return BinaryOperator::createDiv(Op1I->getOperand(0),
1716 ConstantExpr::getNeg(DivRHS));
1718 // X - X*C --> X * (1-C)
1719 ConstantInt *C2 = 0;
1720 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
1722 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
1723 return BinaryOperator::createMul(Op0, CP1);
1728 if (!Op0->getType()->isFloatingPoint())
1729 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1730 if (Op0I->getOpcode() == Instruction::Add) {
1731 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1732 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1733 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1734 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1735 } else if (Op0I->getOpcode() == Instruction::Sub) {
1736 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1737 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
1741 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1742 if (X == Op1) { // X*C - X --> X * (C-1)
1743 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1744 return BinaryOperator::createMul(Op1, CP1);
1747 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1748 if (X == dyn_castFoldableMul(Op1, C2))
1749 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1754 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1755 /// really just returns true if the most significant (sign) bit is set.
1756 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1757 if (RHS->getType()->isSigned()) {
1758 // True if source is LHS < 0 or LHS <= -1
1759 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1760 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1762 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1763 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1764 // the size of the integer type.
1765 if (Opcode == Instruction::SetGE)
1766 return RHSC->getValue() ==
1767 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
1768 if (Opcode == Instruction::SetGT)
1769 return RHSC->getValue() ==
1770 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
1775 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
1776 bool Changed = SimplifyCommutative(I);
1777 Value *Op0 = I.getOperand(0);
1779 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1780 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1782 // Simplify mul instructions with a constant RHS...
1783 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1784 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1786 // ((X << C1)*C2) == (X * (C2 << C1))
1787 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1788 if (SI->getOpcode() == Instruction::Shl)
1789 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
1790 return BinaryOperator::createMul(SI->getOperand(0),
1791 ConstantExpr::getShl(CI, ShOp));
1793 if (CI->isNullValue())
1794 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1795 if (CI->equalsInt(1)) // X * 1 == X
1796 return ReplaceInstUsesWith(I, Op0);
1797 if (CI->isAllOnesValue()) // X * -1 == 0 - X
1798 return BinaryOperator::createNeg(Op0, I.getName());
1800 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
1801 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1802 uint64_t C = Log2_64(Val);
1803 return new ShiftInst(Instruction::Shl, Op0,
1804 ConstantUInt::get(Type::UByteTy, C));
1806 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
1807 if (Op1F->isNullValue())
1808 return ReplaceInstUsesWith(I, Op1);
1810 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1811 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1812 if (Op1F->getValue() == 1.0)
1813 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1816 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1817 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
1818 isa<ConstantInt>(Op0I->getOperand(1))) {
1819 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
1820 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
1822 InsertNewInstBefore(Add, I);
1823 Value *C1C2 = ConstantExpr::getMul(Op1,
1824 cast<Constant>(Op0I->getOperand(1)));
1825 return BinaryOperator::createAdd(Add, C1C2);
1829 // Try to fold constant mul into select arguments.
1830 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1831 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1834 if (isa<PHINode>(Op0))
1835 if (Instruction *NV = FoldOpIntoPhi(I))
1839 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1840 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
1841 return BinaryOperator::createMul(Op0v, Op1v);
1843 // If one of the operands of the multiply is a cast from a boolean value, then
1844 // we know the bool is either zero or one, so this is a 'masking' multiply.
1845 // See if we can simplify things based on how the boolean was originally
1847 CastInst *BoolCast = 0;
1848 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1849 if (CI->getOperand(0)->getType() == Type::BoolTy)
1852 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1853 if (CI->getOperand(0)->getType() == Type::BoolTy)
1856 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1857 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1858 const Type *SCOpTy = SCIOp0->getType();
1860 // If the setcc is true iff the sign bit of X is set, then convert this
1861 // multiply into a shift/and combination.
1862 if (isa<ConstantInt>(SCIOp1) &&
1863 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
1864 // Shift the X value right to turn it into "all signbits".
1865 Constant *Amt = ConstantUInt::get(Type::UByteTy,
1866 SCOpTy->getPrimitiveSizeInBits()-1);
1867 if (SCIOp0->getType()->isUnsigned()) {
1868 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
1869 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1870 SCIOp0->getName()), I);
1874 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1875 BoolCast->getOperand(0)->getName()+
1878 // If the multiply type is not the same as the source type, sign extend
1879 // or truncate to the multiply type.
1880 if (I.getType() != V->getType())
1881 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
1883 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
1884 return BinaryOperator::createAnd(V, OtherOp);
1889 return Changed ? &I : 0;
1892 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
1893 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1895 if (isa<UndefValue>(Op0)) // undef / X -> 0
1896 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1897 if (isa<UndefValue>(Op1))
1898 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1900 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1902 if (RHS->equalsInt(1))
1903 return ReplaceInstUsesWith(I, Op0);
1906 if (RHS->isAllOnesValue())
1907 return BinaryOperator::createNeg(Op0);
1909 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
1910 if (LHS->getOpcode() == Instruction::Div)
1911 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
1912 // (X / C1) / C2 -> X / (C1*C2)
1913 return BinaryOperator::createDiv(LHS->getOperand(0),
1914 ConstantExpr::getMul(RHS, LHSRHS));
1917 // Check to see if this is an unsigned division with an exact power of 2,
1918 // if so, convert to a right shift.
1919 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1920 if (uint64_t Val = C->getValue()) // Don't break X / 0
1921 if (isPowerOf2_64(Val)) {
1922 uint64_t C = Log2_64(Val);
1923 return new ShiftInst(Instruction::Shr, Op0,
1924 ConstantUInt::get(Type::UByteTy, C));
1928 if (RHS->getType()->isSigned())
1929 if (Value *LHSNeg = dyn_castNegVal(Op0))
1930 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1932 if (!RHS->isNullValue()) {
1933 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1934 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1936 if (isa<PHINode>(Op0))
1937 if (Instruction *NV = FoldOpIntoPhi(I))
1942 // Handle div X, Cond?Y:Z
1943 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
1944 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
1945 // same basic block, then we replace the select with Y, and the condition of
1946 // the select with false (if the cond value is in the same BB). If the
1947 // select has uses other than the div, this allows them to be simplified
1949 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
1950 if (ST->isNullValue()) {
1951 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
1952 if (CondI && CondI->getParent() == I.getParent())
1953 UpdateValueUsesWith(CondI, ConstantBool::False);
1954 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
1955 I.setOperand(1, SI->getOperand(2));
1957 UpdateValueUsesWith(SI, SI->getOperand(2));
1960 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
1961 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
1962 if (ST->isNullValue()) {
1963 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
1964 if (CondI && CondI->getParent() == I.getParent())
1965 UpdateValueUsesWith(CondI, ConstantBool::True);
1966 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
1967 I.setOperand(1, SI->getOperand(1));
1969 UpdateValueUsesWith(SI, SI->getOperand(1));
1973 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1974 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1975 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1976 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1977 // STO == 0 and SFO == 0 handled above.
1978 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
1979 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1980 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
1981 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1982 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1983 TC, SI->getName()+".t");
1984 TSI = InsertNewInstBefore(TSI, I);
1986 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1987 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1988 FC, SI->getName()+".f");
1989 FSI = InsertNewInstBefore(FSI, I);
1990 return new SelectInst(SI->getOperand(0), TSI, FSI);
1995 // 0 / X == 0, we don't need to preserve faults!
1996 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
1997 if (LHS->equalsInt(0))
1998 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2000 if (I.getType()->isSigned()) {
2001 // If the sign bits of both operands are zero (i.e. we can prove they are
2002 // unsigned inputs), turn this into a udiv.
2003 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2004 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2005 const Type *NTy = Op0->getType()->getUnsignedVersion();
2006 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2007 InsertNewInstBefore(LHS, I);
2009 if (Constant *R = dyn_cast<Constant>(Op1))
2010 RHS = ConstantExpr::getCast(R, NTy);
2012 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2013 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
2014 InsertNewInstBefore(Div, I);
2015 return new CastInst(Div, I.getType());
2018 // Known to be an unsigned division.
2019 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2020 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
2021 if (RHSI->getOpcode() == Instruction::Shl &&
2022 isa<ConstantUInt>(RHSI->getOperand(0))) {
2023 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
2024 if (isPowerOf2_64(C1)) {
2025 unsigned C2 = Log2_64(C1);
2026 Value *Add = RHSI->getOperand(1);
2028 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
2029 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
2032 return new ShiftInst(Instruction::Shr, Op0, Add);
2042 /// GetFactor - If we can prove that the specified value is at least a multiple
2043 /// of some factor, return that factor.
2044 static Constant *GetFactor(Value *V) {
2045 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2048 // Unless we can be tricky, we know this is a multiple of 1.
2049 Constant *Result = ConstantInt::get(V->getType(), 1);
2051 Instruction *I = dyn_cast<Instruction>(V);
2052 if (!I) return Result;
2054 if (I->getOpcode() == Instruction::Mul) {
2055 // Handle multiplies by a constant, etc.
2056 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2057 GetFactor(I->getOperand(1)));
2058 } else if (I->getOpcode() == Instruction::Shl) {
2059 // (X<<C) -> X * (1 << C)
2060 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2061 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2062 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2064 } else if (I->getOpcode() == Instruction::And) {
2065 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2066 // X & 0xFFF0 is known to be a multiple of 16.
2067 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2068 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2069 return ConstantExpr::getShl(Result,
2070 ConstantUInt::get(Type::UByteTy, Zeros));
2072 } else if (I->getOpcode() == Instruction::Cast) {
2073 Value *Op = I->getOperand(0);
2074 // Only handle int->int casts.
2075 if (!Op->getType()->isInteger()) return Result;
2076 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2081 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
2082 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2084 // 0 % X == 0, we don't need to preserve faults!
2085 if (Constant *LHS = dyn_cast<Constant>(Op0))
2086 if (LHS->isNullValue())
2087 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2089 if (isa<UndefValue>(Op0)) // undef % X -> 0
2090 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2091 if (isa<UndefValue>(Op1))
2092 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2094 if (I.getType()->isSigned()) {
2095 if (Value *RHSNeg = dyn_castNegVal(Op1))
2096 if (!isa<ConstantSInt>(RHSNeg) ||
2097 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
2099 AddUsesToWorkList(I);
2100 I.setOperand(1, RHSNeg);
2104 // If the top bits of both operands are zero (i.e. we can prove they are
2105 // unsigned inputs), turn this into a urem.
2106 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2107 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2108 const Type *NTy = Op0->getType()->getUnsignedVersion();
2109 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2110 InsertNewInstBefore(LHS, I);
2112 if (Constant *R = dyn_cast<Constant>(Op1))
2113 RHS = ConstantExpr::getCast(R, NTy);
2115 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2116 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
2117 InsertNewInstBefore(Rem, I);
2118 return new CastInst(Rem, I.getType());
2122 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2123 // X % 0 == undef, we don't need to preserve faults!
2124 if (RHS->equalsInt(0))
2125 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2127 if (RHS->equalsInt(1)) // X % 1 == 0
2128 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2130 // Check to see if this is an unsigned remainder with an exact power of 2,
2131 // if so, convert to a bitwise and.
2132 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
2133 if (isPowerOf2_64(C->getValue()))
2134 return BinaryOperator::createAnd(Op0, SubOne(C));
2136 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2137 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2138 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2140 } else if (isa<PHINode>(Op0I)) {
2141 if (Instruction *NV = FoldOpIntoPhi(I))
2145 // X*C1%C2 --> 0 iff C1%C2 == 0
2146 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
2147 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2151 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2152 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
2153 if (I.getType()->isUnsigned() &&
2154 RHSI->getOpcode() == Instruction::Shl &&
2155 isa<ConstantUInt>(RHSI->getOperand(0))) {
2156 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
2157 if (isPowerOf2_64(C1)) {
2158 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2159 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2161 return BinaryOperator::createAnd(Op0, Add);
2165 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2166 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
2167 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2168 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2169 // the same basic block, then we replace the select with Y, and the
2170 // condition of the select with false (if the cond value is in the same
2171 // BB). If the select has uses other than the div, this allows them to be
2173 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2174 if (ST->isNullValue()) {
2175 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2176 if (CondI && CondI->getParent() == I.getParent())
2177 UpdateValueUsesWith(CondI, ConstantBool::False);
2178 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2179 I.setOperand(1, SI->getOperand(2));
2181 UpdateValueUsesWith(SI, SI->getOperand(2));
2184 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2185 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2186 if (ST->isNullValue()) {
2187 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2188 if (CondI && CondI->getParent() == I.getParent())
2189 UpdateValueUsesWith(CondI, ConstantBool::True);
2190 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2191 I.setOperand(1, SI->getOperand(1));
2193 UpdateValueUsesWith(SI, SI->getOperand(1));
2198 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
2199 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
2200 // STO == 0 and SFO == 0 handled above.
2202 if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
2203 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2204 SubOne(STO), SI->getName()+".t"), I);
2205 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2206 SubOne(SFO), SI->getName()+".f"), I);
2207 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2216 // isMaxValueMinusOne - return true if this is Max-1
2217 static bool isMaxValueMinusOne(const ConstantInt *C) {
2218 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2219 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
2221 const ConstantSInt *CS = cast<ConstantSInt>(C);
2223 // Calculate 0111111111..11111
2224 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2225 int64_t Val = INT64_MAX; // All ones
2226 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2227 return CS->getValue() == Val-1;
2230 // isMinValuePlusOne - return true if this is Min+1
2231 static bool isMinValuePlusOne(const ConstantInt *C) {
2232 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2233 return CU->getValue() == 1;
2235 const ConstantSInt *CS = cast<ConstantSInt>(C);
2237 // Calculate 1111111111000000000000
2238 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2239 int64_t Val = -1; // All ones
2240 Val <<= TypeBits-1; // Shift over to the right spot
2241 return CS->getValue() == Val+1;
2244 // isOneBitSet - Return true if there is exactly one bit set in the specified
2246 static bool isOneBitSet(const ConstantInt *CI) {
2247 uint64_t V = CI->getRawValue();
2248 return V && (V & (V-1)) == 0;
2251 #if 0 // Currently unused
2252 // isLowOnes - Return true if the constant is of the form 0+1+.
2253 static bool isLowOnes(const ConstantInt *CI) {
2254 uint64_t V = CI->getRawValue();
2256 // There won't be bits set in parts that the type doesn't contain.
2257 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2259 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2260 return U && V && (U & V) == 0;
2264 // isHighOnes - Return true if the constant is of the form 1+0+.
2265 // This is the same as lowones(~X).
2266 static bool isHighOnes(const ConstantInt *CI) {
2267 uint64_t V = ~CI->getRawValue();
2268 if (~V == 0) return false; // 0's does not match "1+"
2270 // There won't be bits set in parts that the type doesn't contain.
2271 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2273 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2274 return U && V && (U & V) == 0;
2278 /// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2279 /// are carefully arranged to allow folding of expressions such as:
2281 /// (A < B) | (A > B) --> (A != B)
2283 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2284 /// represents that the comparison is true if A == B, and bit value '1' is true
2287 static unsigned getSetCondCode(const SetCondInst *SCI) {
2288 switch (SCI->getOpcode()) {
2290 case Instruction::SetGT: return 1;
2291 case Instruction::SetEQ: return 2;
2292 case Instruction::SetGE: return 3;
2293 case Instruction::SetLT: return 4;
2294 case Instruction::SetNE: return 5;
2295 case Instruction::SetLE: return 6;
2298 assert(0 && "Invalid SetCC opcode!");
2303 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
2304 /// opcode and two operands into either a constant true or false, or a brand new
2305 /// SetCC instruction.
2306 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2308 case 0: return ConstantBool::False;
2309 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2310 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2311 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2312 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2313 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2314 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2315 case 7: return ConstantBool::True;
2316 default: assert(0 && "Illegal SetCCCode!"); return 0;
2320 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2321 struct FoldSetCCLogical {
2324 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2325 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2326 bool shouldApply(Value *V) const {
2327 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2328 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2329 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2332 Instruction *apply(BinaryOperator &Log) const {
2333 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2334 if (SCI->getOperand(0) != LHS) {
2335 assert(SCI->getOperand(1) == LHS);
2336 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2339 unsigned LHSCode = getSetCondCode(SCI);
2340 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2342 switch (Log.getOpcode()) {
2343 case Instruction::And: Code = LHSCode & RHSCode; break;
2344 case Instruction::Or: Code = LHSCode | RHSCode; break;
2345 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2346 default: assert(0 && "Illegal logical opcode!"); return 0;
2349 Value *RV = getSetCCValue(Code, LHS, RHS);
2350 if (Instruction *I = dyn_cast<Instruction>(RV))
2352 // Otherwise, it's a constant boolean value...
2353 return IC.ReplaceInstUsesWith(Log, RV);
2357 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2358 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2359 // guaranteed to be either a shift instruction or a binary operator.
2360 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2361 ConstantIntegral *OpRHS,
2362 ConstantIntegral *AndRHS,
2363 BinaryOperator &TheAnd) {
2364 Value *X = Op->getOperand(0);
2365 Constant *Together = 0;
2366 if (!isa<ShiftInst>(Op))
2367 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2369 switch (Op->getOpcode()) {
2370 case Instruction::Xor:
2371 if (Op->hasOneUse()) {
2372 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2373 std::string OpName = Op->getName(); Op->setName("");
2374 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2375 InsertNewInstBefore(And, TheAnd);
2376 return BinaryOperator::createXor(And, Together);
2379 case Instruction::Or:
2380 if (Together == AndRHS) // (X | C) & C --> C
2381 return ReplaceInstUsesWith(TheAnd, AndRHS);
2383 if (Op->hasOneUse() && Together != OpRHS) {
2384 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2385 std::string Op0Name = Op->getName(); Op->setName("");
2386 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2387 InsertNewInstBefore(Or, TheAnd);
2388 return BinaryOperator::createAnd(Or, AndRHS);
2391 case Instruction::Add:
2392 if (Op->hasOneUse()) {
2393 // Adding a one to a single bit bit-field should be turned into an XOR
2394 // of the bit. First thing to check is to see if this AND is with a
2395 // single bit constant.
2396 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
2398 // Clear bits that are not part of the constant.
2399 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
2401 // If there is only one bit set...
2402 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2403 // Ok, at this point, we know that we are masking the result of the
2404 // ADD down to exactly one bit. If the constant we are adding has
2405 // no bits set below this bit, then we can eliminate the ADD.
2406 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
2408 // Check to see if any bits below the one bit set in AndRHSV are set.
2409 if ((AddRHS & (AndRHSV-1)) == 0) {
2410 // If not, the only thing that can effect the output of the AND is
2411 // the bit specified by AndRHSV. If that bit is set, the effect of
2412 // the XOR is to toggle the bit. If it is clear, then the ADD has
2414 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2415 TheAnd.setOperand(0, X);
2418 std::string Name = Op->getName(); Op->setName("");
2419 // Pull the XOR out of the AND.
2420 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2421 InsertNewInstBefore(NewAnd, TheAnd);
2422 return BinaryOperator::createXor(NewAnd, AndRHS);
2429 case Instruction::Shl: {
2430 // We know that the AND will not produce any of the bits shifted in, so if
2431 // the anded constant includes them, clear them now!
2433 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2434 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2435 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2437 if (CI == ShlMask) { // Masking out bits that the shift already masks
2438 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2439 } else if (CI != AndRHS) { // Reducing bits set in and.
2440 TheAnd.setOperand(1, CI);
2445 case Instruction::Shr:
2446 // We know that the AND will not produce any of the bits shifted in, so if
2447 // the anded constant includes them, clear them now! This only applies to
2448 // unsigned shifts, because a signed shr may bring in set bits!
2450 if (AndRHS->getType()->isUnsigned()) {
2451 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2452 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2453 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2455 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2456 return ReplaceInstUsesWith(TheAnd, Op);
2457 } else if (CI != AndRHS) {
2458 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2461 } else { // Signed shr.
2462 // See if this is shifting in some sign extension, then masking it out
2464 if (Op->hasOneUse()) {
2465 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2466 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2467 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2468 if (CI == AndRHS) { // Masking out bits shifted in.
2469 // Make the argument unsigned.
2470 Value *ShVal = Op->getOperand(0);
2471 ShVal = InsertCastBefore(ShVal,
2472 ShVal->getType()->getUnsignedVersion(),
2474 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2475 OpRHS, Op->getName()),
2477 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2478 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2481 return new CastInst(ShVal, Op->getType());
2491 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2492 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2493 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2494 /// insert new instructions.
2495 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2496 bool Inside, Instruction &IB) {
2497 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2498 "Lo is not <= Hi in range emission code!");
2500 if (Lo == Hi) // Trivially false.
2501 return new SetCondInst(Instruction::SetNE, V, V);
2502 if (cast<ConstantIntegral>(Lo)->isMinValue())
2503 return new SetCondInst(Instruction::SetLT, V, Hi);
2505 Constant *AddCST = ConstantExpr::getNeg(Lo);
2506 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2507 InsertNewInstBefore(Add, IB);
2508 // Convert to unsigned for the comparison.
2509 const Type *UnsType = Add->getType()->getUnsignedVersion();
2510 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2511 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2512 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2513 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2516 if (Lo == Hi) // Trivially true.
2517 return new SetCondInst(Instruction::SetEQ, V, V);
2519 Hi = SubOne(cast<ConstantInt>(Hi));
2520 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2521 return new SetCondInst(Instruction::SetGT, V, Hi);
2523 // Emit X-Lo > Hi-Lo-1
2524 Constant *AddCST = ConstantExpr::getNeg(Lo);
2525 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2526 InsertNewInstBefore(Add, IB);
2527 // Convert to unsigned for the comparison.
2528 const Type *UnsType = Add->getType()->getUnsignedVersion();
2529 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2530 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2531 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2532 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2535 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2536 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
2537 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2538 // not, since all 1s are not contiguous.
2539 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2540 uint64_t V = Val->getRawValue();
2541 if (!isShiftedMask_64(V)) return false;
2543 // look for the first zero bit after the run of ones
2544 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2545 // look for the first non-zero bit
2546 ME = 64-CountLeadingZeros_64(V);
2552 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2553 /// where isSub determines whether the operator is a sub. If we can fold one of
2554 /// the following xforms:
2556 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2557 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2558 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2560 /// return (A +/- B).
2562 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2563 ConstantIntegral *Mask, bool isSub,
2565 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2566 if (!LHSI || LHSI->getNumOperands() != 2 ||
2567 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2569 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2571 switch (LHSI->getOpcode()) {
2573 case Instruction::And:
2574 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2575 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2576 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2579 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2580 // part, we don't need any explicit masks to take them out of A. If that
2581 // is all N is, ignore it.
2583 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
2584 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2586 if (MaskedValueIsZero(RHS, Mask))
2591 case Instruction::Or:
2592 case Instruction::Xor:
2593 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2594 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2595 ConstantExpr::getAnd(N, Mask)->isNullValue())
2602 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2604 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2605 return InsertNewInstBefore(New, I);
2608 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
2609 bool Changed = SimplifyCommutative(I);
2610 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2612 if (isa<UndefValue>(Op1)) // X & undef -> 0
2613 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2617 return ReplaceInstUsesWith(I, Op1);
2619 // See if we can simplify any instructions used by the instruction whose sole
2620 // purpose is to compute bits we don't care about.
2621 uint64_t KnownZero, KnownOne;
2622 if (!isa<PackedType>(I.getType()) &&
2623 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2624 KnownZero, KnownOne))
2627 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
2628 uint64_t AndRHSMask = AndRHS->getZExtValue();
2629 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
2630 uint64_t NotAndRHS = AndRHSMask^TypeMask;
2632 // Optimize a variety of ((val OP C1) & C2) combinations...
2633 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2634 Instruction *Op0I = cast<Instruction>(Op0);
2635 Value *Op0LHS = Op0I->getOperand(0);
2636 Value *Op0RHS = Op0I->getOperand(1);
2637 switch (Op0I->getOpcode()) {
2638 case Instruction::Xor:
2639 case Instruction::Or:
2640 // If the mask is only needed on one incoming arm, push it up.
2641 if (Op0I->hasOneUse()) {
2642 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2643 // Not masking anything out for the LHS, move to RHS.
2644 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2645 Op0RHS->getName()+".masked");
2646 InsertNewInstBefore(NewRHS, I);
2647 return BinaryOperator::create(
2648 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
2650 if (!isa<Constant>(Op0RHS) &&
2651 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2652 // Not masking anything out for the RHS, move to LHS.
2653 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2654 Op0LHS->getName()+".masked");
2655 InsertNewInstBefore(NewLHS, I);
2656 return BinaryOperator::create(
2657 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2662 case Instruction::Add:
2663 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2664 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2665 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2666 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2667 return BinaryOperator::createAnd(V, AndRHS);
2668 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2669 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
2672 case Instruction::Sub:
2673 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2674 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2675 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2676 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2677 return BinaryOperator::createAnd(V, AndRHS);
2681 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2682 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
2684 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2685 const Type *SrcTy = CI->getOperand(0)->getType();
2687 // If this is an integer truncation or change from signed-to-unsigned, and
2688 // if the source is an and/or with immediate, transform it. This
2689 // frequently occurs for bitfield accesses.
2690 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2691 if (SrcTy->getPrimitiveSizeInBits() >=
2692 I.getType()->getPrimitiveSizeInBits() &&
2693 CastOp->getNumOperands() == 2)
2694 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
2695 if (CastOp->getOpcode() == Instruction::And) {
2696 // Change: and (cast (and X, C1) to T), C2
2697 // into : and (cast X to T), trunc(C1)&C2
2698 // This will folds the two ands together, which may allow other
2700 Instruction *NewCast =
2701 new CastInst(CastOp->getOperand(0), I.getType(),
2702 CastOp->getName()+".shrunk");
2703 NewCast = InsertNewInstBefore(NewCast, I);
2705 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2706 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2707 return BinaryOperator::createAnd(NewCast, C3);
2708 } else if (CastOp->getOpcode() == Instruction::Or) {
2709 // Change: and (cast (or X, C1) to T), C2
2710 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2711 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2712 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2713 return ReplaceInstUsesWith(I, AndRHS);
2718 // Try to fold constant and into select arguments.
2719 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2720 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2722 if (isa<PHINode>(Op0))
2723 if (Instruction *NV = FoldOpIntoPhi(I))
2727 Value *Op0NotVal = dyn_castNotVal(Op0);
2728 Value *Op1NotVal = dyn_castNotVal(Op1);
2730 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2731 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2733 // (~A & ~B) == (~(A | B)) - De Morgan's Law
2734 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2735 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2736 I.getName()+".demorgan");
2737 InsertNewInstBefore(Or, I);
2738 return BinaryOperator::createNot(Or);
2742 Value *A = 0, *B = 0;
2743 ConstantInt *C1 = 0, *C2 = 0;
2744 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
2745 if (A == Op1 || B == Op1) // (A | ?) & A --> A
2746 return ReplaceInstUsesWith(I, Op1);
2747 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
2748 if (A == Op0 || B == Op0) // A & (A | ?) --> A
2749 return ReplaceInstUsesWith(I, Op0);
2751 if (Op0->hasOneUse() &&
2752 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2753 if (A == Op1) { // (A^B)&A -> A&(A^B)
2754 I.swapOperands(); // Simplify below
2755 std::swap(Op0, Op1);
2756 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2757 cast<BinaryOperator>(Op0)->swapOperands();
2758 I.swapOperands(); // Simplify below
2759 std::swap(Op0, Op1);
2762 if (Op1->hasOneUse() &&
2763 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2764 if (B == Op0) { // B&(A^B) -> B&(B^A)
2765 cast<BinaryOperator>(Op1)->swapOperands();
2768 if (A == Op0) { // A&(A^B) -> A & ~B
2769 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
2770 InsertNewInstBefore(NotB, I);
2771 return BinaryOperator::createAnd(A, NotB);
2777 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2778 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2779 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2782 Value *LHSVal, *RHSVal;
2783 ConstantInt *LHSCst, *RHSCst;
2784 Instruction::BinaryOps LHSCC, RHSCC;
2785 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2786 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2787 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2788 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
2789 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
2790 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2791 // Ensure that the larger constant is on the RHS.
2792 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2793 SetCondInst *LHS = cast<SetCondInst>(Op0);
2794 if (cast<ConstantBool>(Cmp)->getValue()) {
2795 std::swap(LHS, RHS);
2796 std::swap(LHSCst, RHSCst);
2797 std::swap(LHSCC, RHSCC);
2800 // At this point, we know we have have two setcc instructions
2801 // comparing a value against two constants and and'ing the result
2802 // together. Because of the above check, we know that we only have
2803 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2804 // FoldSetCCLogical check above), that the two constants are not
2806 assert(LHSCst != RHSCst && "Compares not folded above?");
2809 default: assert(0 && "Unknown integer condition code!");
2810 case Instruction::SetEQ:
2812 default: assert(0 && "Unknown integer condition code!");
2813 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2814 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2815 return ReplaceInstUsesWith(I, ConstantBool::False);
2816 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2817 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2818 return ReplaceInstUsesWith(I, LHS);
2820 case Instruction::SetNE:
2822 default: assert(0 && "Unknown integer condition code!");
2823 case Instruction::SetLT:
2824 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2825 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2826 break; // (X != 13 & X < 15) -> no change
2827 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2828 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2829 return ReplaceInstUsesWith(I, RHS);
2830 case Instruction::SetNE:
2831 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2832 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2833 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2834 LHSVal->getName()+".off");
2835 InsertNewInstBefore(Add, I);
2836 const Type *UnsType = Add->getType()->getUnsignedVersion();
2837 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2838 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2839 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2840 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2842 break; // (X != 13 & X != 15) -> no change
2845 case Instruction::SetLT:
2847 default: assert(0 && "Unknown integer condition code!");
2848 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2849 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2850 return ReplaceInstUsesWith(I, ConstantBool::False);
2851 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2852 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2853 return ReplaceInstUsesWith(I, LHS);
2855 case Instruction::SetGT:
2857 default: assert(0 && "Unknown integer condition code!");
2858 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2859 return ReplaceInstUsesWith(I, LHS);
2860 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2861 return ReplaceInstUsesWith(I, RHS);
2862 case Instruction::SetNE:
2863 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2864 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2865 break; // (X > 13 & X != 15) -> no change
2866 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2867 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
2873 // fold (and (cast A), (cast B)) -> (cast (and A, B))
2874 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
2875 const Type *SrcTy = Op0C->getOperand(0)->getType();
2876 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
2877 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
2878 // Only do this if the casts both really cause code to be generated.
2879 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
2880 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
2881 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
2882 Op1C->getOperand(0),
2884 InsertNewInstBefore(NewOp, I);
2885 return new CastInst(NewOp, I.getType());
2889 return Changed ? &I : 0;
2892 /// CollectBSwapParts - Look to see if the specified value defines a single byte
2893 /// in the result. If it does, and if the specified byte hasn't been filled in
2894 /// yet, fill it in and return false.
2895 static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
2896 Instruction *I = dyn_cast<Instruction>(V);
2897 if (I == 0) return true;
2899 // If this is an or instruction, it is an inner node of the bswap.
2900 if (I->getOpcode() == Instruction::Or)
2901 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
2902 CollectBSwapParts(I->getOperand(1), ByteValues);
2904 // If this is a shift by a constant int, and it is "24", then its operand
2905 // defines a byte. We only handle unsigned types here.
2906 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
2907 // Not shifting the entire input by N-1 bytes?
2908 if (cast<ConstantInt>(I->getOperand(1))->getRawValue() !=
2909 8*(ByteValues.size()-1))
2913 if (I->getOpcode() == Instruction::Shl) {
2914 // X << 24 defines the top byte with the lowest of the input bytes.
2915 DestNo = ByteValues.size()-1;
2917 // X >>u 24 defines the low byte with the highest of the input bytes.
2921 // If the destination byte value is already defined, the values are or'd
2922 // together, which isn't a bswap (unless it's an or of the same bits).
2923 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
2925 ByteValues[DestNo] = I->getOperand(0);
2929 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
2931 Value *Shift = 0, *ShiftLHS = 0;
2932 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
2933 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
2934 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
2936 Instruction *SI = cast<Instruction>(Shift);
2938 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
2939 if (ShiftAmt->getRawValue() & 7 ||
2940 ShiftAmt->getRawValue() > 8*ByteValues.size())
2943 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
2945 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
2946 if (AndAmt->getRawValue() == uint64_t(0xFF) << 8*DestByte)
2948 // Unknown mask for bswap.
2949 if (DestByte == ByteValues.size()) return true;
2951 unsigned ShiftBytes = ShiftAmt->getRawValue()/8;
2953 if (SI->getOpcode() == Instruction::Shl)
2954 SrcByte = DestByte - ShiftBytes;
2956 SrcByte = DestByte + ShiftBytes;
2958 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
2959 if (SrcByte != ByteValues.size()-DestByte-1)
2962 // If the destination byte value is already defined, the values are or'd
2963 // together, which isn't a bswap (unless it's an or of the same bits).
2964 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
2966 ByteValues[DestByte] = SI->getOperand(0);
2970 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
2971 /// If so, insert the new bswap intrinsic and return it.
2972 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
2973 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
2974 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
2977 /// ByteValues - For each byte of the result, we keep track of which value
2978 /// defines each byte.
2979 std::vector<Value*> ByteValues;
2980 ByteValues.resize(I.getType()->getPrimitiveSize());
2982 // Try to find all the pieces corresponding to the bswap.
2983 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
2984 CollectBSwapParts(I.getOperand(1), ByteValues))
2987 // Check to see if all of the bytes come from the same value.
2988 Value *V = ByteValues[0];
2989 if (V == 0) return 0; // Didn't find a byte? Must be zero.
2991 // Check to make sure that all of the bytes come from the same value.
2992 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
2993 if (ByteValues[i] != V)
2996 // If they do then *success* we can turn this into a bswap. Figure out what
2997 // bswap to make it into.
2998 Module *M = I.getParent()->getParent()->getParent();
2999 const char *FnName = 0;
3000 if (I.getType() == Type::UShortTy)
3001 FnName = "llvm.bswap.i16";
3002 else if (I.getType() == Type::UIntTy)
3003 FnName = "llvm.bswap.i32";
3004 else if (I.getType() == Type::ULongTy)
3005 FnName = "llvm.bswap.i64";
3007 assert(0 && "Unknown integer type!");
3008 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3010 return new CallInst(F, V);
3014 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3015 bool Changed = SimplifyCommutative(I);
3016 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3018 if (isa<UndefValue>(Op1))
3019 return ReplaceInstUsesWith(I, // X | undef -> -1
3020 ConstantIntegral::getAllOnesValue(I.getType()));
3024 return ReplaceInstUsesWith(I, Op0);
3026 // See if we can simplify any instructions used by the instruction whose sole
3027 // purpose is to compute bits we don't care about.
3028 uint64_t KnownZero, KnownOne;
3029 if (!isa<PackedType>(I.getType()) &&
3030 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3031 KnownZero, KnownOne))
3035 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3036 ConstantInt *C1 = 0; Value *X = 0;
3037 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3038 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3039 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3041 InsertNewInstBefore(Or, I);
3042 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3045 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3046 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3047 std::string Op0Name = Op0->getName(); Op0->setName("");
3048 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3049 InsertNewInstBefore(Or, I);
3050 return BinaryOperator::createXor(Or,
3051 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3054 // Try to fold constant and into select arguments.
3055 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3056 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3058 if (isa<PHINode>(Op0))
3059 if (Instruction *NV = FoldOpIntoPhi(I))
3063 Value *A = 0, *B = 0;
3064 ConstantInt *C1 = 0, *C2 = 0;
3066 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3067 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3068 return ReplaceInstUsesWith(I, Op1);
3069 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3070 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3071 return ReplaceInstUsesWith(I, Op0);
3073 // (A | B) | C and A | (B | C) -> bswap if possible.
3074 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
3075 if (match(Op0, m_Or(m_Value(), m_Value())) ||
3076 match(Op1, m_Or(m_Value(), m_Value())) ||
3077 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3078 match(Op1, m_Shift(m_Value(), m_Value())))) {
3079 if (Instruction *BSwap = MatchBSwap(I))
3083 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3084 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3085 MaskedValueIsZero(Op1, C1->getZExtValue())) {
3086 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3088 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3091 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3092 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3093 MaskedValueIsZero(Op0, C1->getZExtValue())) {
3094 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3096 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3099 // (A & C1)|(B & C2)
3100 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3101 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3103 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3104 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3107 // If we have: ((V + N) & C1) | (V & C2)
3108 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3109 // replace with V+N.
3110 if (C1 == ConstantExpr::getNot(C2)) {
3111 Value *V1 = 0, *V2 = 0;
3112 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
3113 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3114 // Add commutes, try both ways.
3115 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3116 return ReplaceInstUsesWith(I, A);
3117 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3118 return ReplaceInstUsesWith(I, A);
3120 // Or commutes, try both ways.
3121 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
3122 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3123 // Add commutes, try both ways.
3124 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3125 return ReplaceInstUsesWith(I, B);
3126 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3127 return ReplaceInstUsesWith(I, B);
3132 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3133 if (A == Op1) // ~A | A == -1
3134 return ReplaceInstUsesWith(I,
3135 ConstantIntegral::getAllOnesValue(I.getType()));
3139 // Note, A is still live here!
3140 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3142 return ReplaceInstUsesWith(I,
3143 ConstantIntegral::getAllOnesValue(I.getType()));
3145 // (~A | ~B) == (~(A & B)) - De Morgan's Law
3146 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3147 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3148 I.getName()+".demorgan"), I);
3149 return BinaryOperator::createNot(And);
3153 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
3154 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
3155 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3158 Value *LHSVal, *RHSVal;
3159 ConstantInt *LHSCst, *RHSCst;
3160 Instruction::BinaryOps LHSCC, RHSCC;
3161 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3162 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3163 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3164 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
3165 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
3166 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3167 // Ensure that the larger constant is on the RHS.
3168 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3169 SetCondInst *LHS = cast<SetCondInst>(Op0);
3170 if (cast<ConstantBool>(Cmp)->getValue()) {
3171 std::swap(LHS, RHS);
3172 std::swap(LHSCst, RHSCst);
3173 std::swap(LHSCC, RHSCC);
3176 // At this point, we know we have have two setcc instructions
3177 // comparing a value against two constants and or'ing the result
3178 // together. Because of the above check, we know that we only have
3179 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3180 // FoldSetCCLogical check above), that the two constants are not
3182 assert(LHSCst != RHSCst && "Compares not folded above?");
3185 default: assert(0 && "Unknown integer condition code!");
3186 case Instruction::SetEQ:
3188 default: assert(0 && "Unknown integer condition code!");
3189 case Instruction::SetEQ:
3190 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3191 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3192 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3193 LHSVal->getName()+".off");
3194 InsertNewInstBefore(Add, I);
3195 const Type *UnsType = Add->getType()->getUnsignedVersion();
3196 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3197 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3198 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3199 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3201 break; // (X == 13 | X == 15) -> no change
3203 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3205 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3206 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3207 return ReplaceInstUsesWith(I, RHS);
3210 case Instruction::SetNE:
3212 default: assert(0 && "Unknown integer condition code!");
3213 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3214 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3215 return ReplaceInstUsesWith(I, LHS);
3216 case Instruction::SetNE: // (X != 13 | X != 15) -> true
3217 case Instruction::SetLT: // (X != 13 | X < 15) -> true
3218 return ReplaceInstUsesWith(I, ConstantBool::True);
3221 case Instruction::SetLT:
3223 default: assert(0 && "Unknown integer condition code!");
3224 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3226 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3227 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
3228 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3229 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3230 return ReplaceInstUsesWith(I, RHS);
3233 case Instruction::SetGT:
3235 default: assert(0 && "Unknown integer condition code!");
3236 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3237 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3238 return ReplaceInstUsesWith(I, LHS);
3239 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3240 case Instruction::SetLT: // (X > 13 | X < 15) -> true
3241 return ReplaceInstUsesWith(I, ConstantBool::True);
3247 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3248 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3249 const Type *SrcTy = Op0C->getOperand(0)->getType();
3250 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3251 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3252 // Only do this if the casts both really cause code to be generated.
3253 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3254 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3255 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3256 Op1C->getOperand(0),
3258 InsertNewInstBefore(NewOp, I);
3259 return new CastInst(NewOp, I.getType());
3264 return Changed ? &I : 0;
3267 // XorSelf - Implements: X ^ X --> 0
3270 XorSelf(Value *rhs) : RHS(rhs) {}
3271 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3272 Instruction *apply(BinaryOperator &Xor) const {
3278 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3279 bool Changed = SimplifyCommutative(I);
3280 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3282 if (isa<UndefValue>(Op1))
3283 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3285 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3286 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3287 assert(Result == &I && "AssociativeOpt didn't work?");
3288 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3291 // See if we can simplify any instructions used by the instruction whose sole
3292 // purpose is to compute bits we don't care about.
3293 uint64_t KnownZero, KnownOne;
3294 if (!isa<PackedType>(I.getType()) &&
3295 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3296 KnownZero, KnownOne))
3299 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3300 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3301 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
3302 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
3303 if (RHS == ConstantBool::True && SCI->hasOneUse())
3304 return new SetCondInst(SCI->getInverseCondition(),
3305 SCI->getOperand(0), SCI->getOperand(1));
3307 // ~(c-X) == X-c-1 == X+(-c-1)
3308 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3309 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3310 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3311 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3312 ConstantInt::get(I.getType(), 1));
3313 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3316 // ~(~X & Y) --> (X | ~Y)
3317 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3318 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3319 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3321 BinaryOperator::createNot(Op0I->getOperand(1),
3322 Op0I->getOperand(1)->getName()+".not");
3323 InsertNewInstBefore(NotY, I);
3324 return BinaryOperator::createOr(Op0NotVal, NotY);
3328 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3329 if (Op0I->getOpcode() == Instruction::Add) {
3330 // ~(X-c) --> (-c-1)-X
3331 if (RHS->isAllOnesValue()) {
3332 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3333 return BinaryOperator::createSub(
3334 ConstantExpr::getSub(NegOp0CI,
3335 ConstantInt::get(I.getType(), 1)),
3336 Op0I->getOperand(0));
3338 } else if (Op0I->getOpcode() == Instruction::Or) {
3339 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3340 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3341 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3342 // Anything in both C1 and C2 is known to be zero, remove it from
3344 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3345 NewRHS = ConstantExpr::getAnd(NewRHS,
3346 ConstantExpr::getNot(CommonBits));
3347 WorkList.push_back(Op0I);
3348 I.setOperand(0, Op0I->getOperand(0));
3349 I.setOperand(1, NewRHS);
3355 // Try to fold constant and into select arguments.
3356 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3357 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3359 if (isa<PHINode>(Op0))
3360 if (Instruction *NV = FoldOpIntoPhi(I))
3364 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
3366 return ReplaceInstUsesWith(I,
3367 ConstantIntegral::getAllOnesValue(I.getType()));
3369 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
3371 return ReplaceInstUsesWith(I,
3372 ConstantIntegral::getAllOnesValue(I.getType()));
3374 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
3375 if (Op1I->getOpcode() == Instruction::Or) {
3376 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
3377 Op1I->swapOperands();
3379 std::swap(Op0, Op1);
3380 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
3381 I.swapOperands(); // Simplified below.
3382 std::swap(Op0, Op1);
3384 } else if (Op1I->getOpcode() == Instruction::Xor) {
3385 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3386 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3387 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3388 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
3389 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3390 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3391 Op1I->swapOperands();
3392 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3393 I.swapOperands(); // Simplified below.
3394 std::swap(Op0, Op1);
3398 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3399 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
3400 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
3401 Op0I->swapOperands();
3402 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
3403 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3404 InsertNewInstBefore(NotB, I);
3405 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
3407 } else if (Op0I->getOpcode() == Instruction::Xor) {
3408 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3409 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3410 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3411 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3412 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3413 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3414 Op0I->swapOperands();
3415 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3416 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
3417 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3418 InsertNewInstBefore(N, I);
3419 return BinaryOperator::createAnd(N, Op1);
3423 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3424 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3425 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3428 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3429 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3430 const Type *SrcTy = Op0C->getOperand(0)->getType();
3431 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3432 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3433 // Only do this if the casts both really cause code to be generated.
3434 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3435 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3436 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3437 Op1C->getOperand(0),
3439 InsertNewInstBefore(NewOp, I);
3440 return new CastInst(NewOp, I.getType());
3444 return Changed ? &I : 0;
3447 /// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3448 /// overflowed for this type.
3449 static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3451 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3452 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3455 static bool isPositive(ConstantInt *C) {
3456 return cast<ConstantSInt>(C)->getValue() >= 0;
3459 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3460 /// overflowed for this type.
3461 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3463 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3465 if (In1->getType()->isUnsigned())
3466 return cast<ConstantUInt>(Result)->getValue() <
3467 cast<ConstantUInt>(In1)->getValue();
3468 if (isPositive(In1) != isPositive(In2))
3470 if (isPositive(In1))
3471 return cast<ConstantSInt>(Result)->getValue() <
3472 cast<ConstantSInt>(In1)->getValue();
3473 return cast<ConstantSInt>(Result)->getValue() >
3474 cast<ConstantSInt>(In1)->getValue();
3477 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3478 /// code necessary to compute the offset from the base pointer (without adding
3479 /// in the base pointer). Return the result as a signed integer of intptr size.
3480 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3481 TargetData &TD = IC.getTargetData();
3482 gep_type_iterator GTI = gep_type_begin(GEP);
3483 const Type *UIntPtrTy = TD.getIntPtrType();
3484 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3485 Value *Result = Constant::getNullValue(SIntPtrTy);
3487 // Build a mask for high order bits.
3488 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
3490 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3491 Value *Op = GEP->getOperand(i);
3492 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
3493 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3495 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3496 if (!OpC->isNullValue()) {
3497 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
3498 Scale = ConstantExpr::getMul(OpC, Scale);
3499 if (Constant *RC = dyn_cast<Constant>(Result))
3500 Result = ConstantExpr::getAdd(RC, Scale);
3502 // Emit an add instruction.
3503 Result = IC.InsertNewInstBefore(
3504 BinaryOperator::createAdd(Result, Scale,
3505 GEP->getName()+".offs"), I);
3509 // Convert to correct type.
3510 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3511 Op->getName()+".c"), I);
3513 // We'll let instcombine(mul) convert this to a shl if possible.
3514 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3515 GEP->getName()+".idx"), I);
3517 // Emit an add instruction.
3518 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
3519 GEP->getName()+".offs"), I);
3525 /// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3526 /// else. At this point we know that the GEP is on the LHS of the comparison.
3527 Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3528 Instruction::BinaryOps Cond,
3530 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
3532 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3533 if (isa<PointerType>(CI->getOperand(0)->getType()))
3534 RHS = CI->getOperand(0);
3536 Value *PtrBase = GEPLHS->getOperand(0);
3537 if (PtrBase == RHS) {
3538 // As an optimization, we don't actually have to compute the actual value of
3539 // OFFSET if this is a seteq or setne comparison, just return whether each
3540 // index is zero or not.
3541 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3542 Instruction *InVal = 0;
3543 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3544 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
3546 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3547 if (isa<UndefValue>(C)) // undef index -> undef.
3548 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3549 if (C->isNullValue())
3551 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3552 EmitIt = false; // This is indexing into a zero sized array?
3553 } else if (isa<ConstantInt>(C))
3554 return ReplaceInstUsesWith(I, // No comparison is needed here.
3555 ConstantBool::get(Cond == Instruction::SetNE));
3560 new SetCondInst(Cond, GEPLHS->getOperand(i),
3561 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3565 InVal = InsertNewInstBefore(InVal, I);
3566 InsertNewInstBefore(Comp, I);
3567 if (Cond == Instruction::SetNE) // True if any are unequal
3568 InVal = BinaryOperator::createOr(InVal, Comp);
3569 else // True if all are equal
3570 InVal = BinaryOperator::createAnd(InVal, Comp);
3578 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3579 ConstantBool::get(Cond == Instruction::SetEQ));
3582 // Only lower this if the setcc is the only user of the GEP or if we expect
3583 // the result to fold to a constant!
3584 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3585 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3586 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3587 return new SetCondInst(Cond, Offset,
3588 Constant::getNullValue(Offset->getType()));
3590 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
3591 // If the base pointers are different, but the indices are the same, just
3592 // compare the base pointer.
3593 if (PtrBase != GEPRHS->getOperand(0)) {
3594 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
3595 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
3596 GEPRHS->getOperand(0)->getType();
3598 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3599 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3600 IndicesTheSame = false;
3604 // If all indices are the same, just compare the base pointers.
3606 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3607 GEPRHS->getOperand(0));
3609 // Otherwise, the base pointers are different and the indices are
3610 // different, bail out.
3614 // If one of the GEPs has all zero indices, recurse.
3615 bool AllZeros = true;
3616 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3617 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3618 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3623 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3624 SetCondInst::getSwappedCondition(Cond), I);
3626 // If the other GEP has all zero indices, recurse.
3628 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3629 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3630 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3635 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3637 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3638 // If the GEPs only differ by one index, compare it.
3639 unsigned NumDifferences = 0; // Keep track of # differences.
3640 unsigned DiffOperand = 0; // The operand that differs.
3641 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3642 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3643 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3644 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
3645 // Irreconcilable differences.
3649 if (NumDifferences++) break;
3654 if (NumDifferences == 0) // SAME GEP?
3655 return ReplaceInstUsesWith(I, // No comparison is needed here.
3656 ConstantBool::get(Cond == Instruction::SetEQ));
3657 else if (NumDifferences == 1) {
3658 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3659 Value *RHSV = GEPRHS->getOperand(DiffOperand);
3661 // Convert the operands to signed values to make sure to perform a
3662 // signed comparison.
3663 const Type *NewTy = LHSV->getType()->getSignedVersion();
3664 if (LHSV->getType() != NewTy)
3665 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3666 LHSV->getName()), I);
3667 if (RHSV->getType() != NewTy)
3668 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3669 RHSV->getName()), I);
3670 return new SetCondInst(Cond, LHSV, RHSV);
3674 // Only lower this if the setcc is the only user of the GEP or if we expect
3675 // the result to fold to a constant!
3676 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3677 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3678 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3679 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3680 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3681 return new SetCondInst(Cond, L, R);
3688 Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
3689 bool Changed = SimplifyCommutative(I);
3690 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3691 const Type *Ty = Op0->getType();
3695 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
3697 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3698 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3700 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3701 // addresses never equal each other! We already know that Op0 != Op1.
3702 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3703 isa<ConstantPointerNull>(Op0)) &&
3704 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
3705 isa<ConstantPointerNull>(Op1)))
3706 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3708 // setcc's with boolean values can always be turned into bitwise operations
3709 if (Ty == Type::BoolTy) {
3710 switch (I.getOpcode()) {
3711 default: assert(0 && "Invalid setcc instruction!");
3712 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
3713 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
3714 InsertNewInstBefore(Xor, I);
3715 return BinaryOperator::createNot(Xor);
3717 case Instruction::SetNE:
3718 return BinaryOperator::createXor(Op0, Op1);
3720 case Instruction::SetGT:
3721 std::swap(Op0, Op1); // Change setgt -> setlt
3723 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3724 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3725 InsertNewInstBefore(Not, I);
3726 return BinaryOperator::createAnd(Not, Op1);
3728 case Instruction::SetGE:
3729 std::swap(Op0, Op1); // Change setge -> setle
3731 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3732 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3733 InsertNewInstBefore(Not, I);
3734 return BinaryOperator::createOr(Not, Op1);
3739 // See if we are doing a comparison between a constant and an instruction that
3740 // can be folded into the comparison.
3741 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3742 // Check to see if we are comparing against the minimum or maximum value...
3743 if (CI->isMinValue()) {
3744 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3745 return ReplaceInstUsesWith(I, ConstantBool::False);
3746 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3747 return ReplaceInstUsesWith(I, ConstantBool::True);
3748 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3749 return BinaryOperator::createSetEQ(Op0, Op1);
3750 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3751 return BinaryOperator::createSetNE(Op0, Op1);
3753 } else if (CI->isMaxValue()) {
3754 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3755 return ReplaceInstUsesWith(I, ConstantBool::False);
3756 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3757 return ReplaceInstUsesWith(I, ConstantBool::True);
3758 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3759 return BinaryOperator::createSetEQ(Op0, Op1);
3760 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3761 return BinaryOperator::createSetNE(Op0, Op1);
3763 // Comparing against a value really close to min or max?
3764 } else if (isMinValuePlusOne(CI)) {
3765 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3766 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3767 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3768 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3770 } else if (isMaxValueMinusOne(CI)) {
3771 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3772 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3773 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3774 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3777 // If we still have a setle or setge instruction, turn it into the
3778 // appropriate setlt or setgt instruction. Since the border cases have
3779 // already been handled above, this requires little checking.
3781 if (I.getOpcode() == Instruction::SetLE)
3782 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3783 if (I.getOpcode() == Instruction::SetGE)
3784 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3787 // See if we can fold the comparison based on bits known to be zero or one
3789 uint64_t KnownZero, KnownOne;
3790 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3791 KnownZero, KnownOne, 0))
3794 // Given the known and unknown bits, compute a range that the LHS could be
3796 if (KnownOne | KnownZero) {
3797 if (Ty->isUnsigned()) { // Unsigned comparison.
3799 uint64_t RHSVal = CI->getZExtValue();
3800 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3802 switch (I.getOpcode()) { // LE/GE have been folded already.
3803 default: assert(0 && "Unknown setcc opcode!");
3804 case Instruction::SetEQ:
3805 if (Max < RHSVal || Min > RHSVal)
3806 return ReplaceInstUsesWith(I, ConstantBool::False);
3808 case Instruction::SetNE:
3809 if (Max < RHSVal || Min > RHSVal)
3810 return ReplaceInstUsesWith(I, ConstantBool::True);
3812 case Instruction::SetLT:
3813 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3814 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3816 case Instruction::SetGT:
3817 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3818 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3821 } else { // Signed comparison.
3823 int64_t RHSVal = CI->getSExtValue();
3824 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3826 switch (I.getOpcode()) { // LE/GE have been folded already.
3827 default: assert(0 && "Unknown setcc opcode!");
3828 case Instruction::SetEQ:
3829 if (Max < RHSVal || Min > RHSVal)
3830 return ReplaceInstUsesWith(I, ConstantBool::False);
3832 case Instruction::SetNE:
3833 if (Max < RHSVal || Min > RHSVal)
3834 return ReplaceInstUsesWith(I, ConstantBool::True);
3836 case Instruction::SetLT:
3837 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3838 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3840 case Instruction::SetGT:
3841 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3842 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3849 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3850 switch (LHSI->getOpcode()) {
3851 case Instruction::And:
3852 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3853 LHSI->getOperand(0)->hasOneUse()) {
3854 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3855 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3856 // happens a LOT in code produced by the C front-end, for bitfield
3858 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
3859 Constant *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3861 // Check to see if there is a noop-cast between the shift and the and.
3863 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3864 if (CI->getOperand(0)->getType()->isIntegral() &&
3865 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3866 CI->getType()->getPrimitiveSizeInBits())
3867 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3870 ConstantUInt *ShAmt;
3871 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
3872 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
3873 const Type *AndTy = AndCST->getType(); // Type of the and.
3875 // We can fold this as long as we can't shift unknown bits
3876 // into the mask. This can only happen with signed shift
3877 // rights, as they sign-extend.
3879 bool CanFold = Shift->isLogicalShift();
3881 // To test for the bad case of the signed shr, see if any
3882 // of the bits shifted in could be tested after the mask.
3883 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3884 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3886 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
3888 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
3890 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3896 if (Shift->getOpcode() == Instruction::Shl)
3897 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3899 NewCst = ConstantExpr::getShl(CI, ShAmt);
3901 // Check to see if we are shifting out any of the bits being
3903 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3904 // If we shifted bits out, the fold is not going to work out.
3905 // As a special case, check to see if this means that the
3906 // result is always true or false now.
3907 if (I.getOpcode() == Instruction::SetEQ)
3908 return ReplaceInstUsesWith(I, ConstantBool::False);
3909 if (I.getOpcode() == Instruction::SetNE)
3910 return ReplaceInstUsesWith(I, ConstantBool::True);
3912 I.setOperand(1, NewCst);
3913 Constant *NewAndCST;
3914 if (Shift->getOpcode() == Instruction::Shl)
3915 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3917 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3918 LHSI->setOperand(1, NewAndCST);
3920 LHSI->setOperand(0, Shift->getOperand(0));
3922 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
3924 LHSI->setOperand(0, NewCast);
3926 WorkList.push_back(Shift); // Shift is dead.
3927 AddUsesToWorkList(I);
3933 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
3934 // preferable because it allows the C<<Y expression to be hoisted out
3935 // of a loop if Y is invariant and X is not.
3936 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
3937 I.isEquality() && !Shift->isArithmeticShift()) {
3940 if (Shift->getOpcode() == Instruction::Shr) {
3941 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
3944 // Make sure we insert a logical shift.
3945 if (AndCST->getType()->isSigned())
3946 AndCST = ConstantExpr::getCast(AndCST,
3947 AndCST->getType()->getUnsignedVersion());
3948 NS = new ShiftInst(Instruction::Shr, AndCST, Shift->getOperand(1),
3951 InsertNewInstBefore(cast<Instruction>(NS), I);
3953 // If C's sign doesn't agree with the and, insert a cast now.
3954 if (NS->getType() != LHSI->getType())
3955 NS = InsertCastBefore(NS, LHSI->getType(), I);
3957 Value *ShiftOp = Shift->getOperand(0);
3958 if (ShiftOp->getType() != LHSI->getType())
3959 ShiftOp = InsertCastBefore(ShiftOp, LHSI->getType(), I);
3961 // Compute X & (C << Y).
3962 Instruction *NewAnd =
3963 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
3964 InsertNewInstBefore(NewAnd, I);
3966 I.setOperand(0, NewAnd);
3972 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3973 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3974 if (I.isEquality()) {
3975 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3977 // Check that the shift amount is in range. If not, don't perform
3978 // undefined shifts. When the shift is visited it will be
3980 if (ShAmt->getValue() >= TypeBits)
3983 // If we are comparing against bits always shifted out, the
3984 // comparison cannot succeed.
3986 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3987 if (Comp != CI) {// Comparing against a bit that we know is zero.
3988 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3989 Constant *Cst = ConstantBool::get(IsSetNE);
3990 return ReplaceInstUsesWith(I, Cst);
3993 if (LHSI->hasOneUse()) {
3994 // Otherwise strength reduce the shift into an and.
3995 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
3996 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3999 if (CI->getType()->isUnsigned()) {
4000 Mask = ConstantUInt::get(CI->getType(), Val);
4001 } else if (ShAmtVal != 0) {
4002 Mask = ConstantSInt::get(CI->getType(), Val);
4004 Mask = ConstantInt::getAllOnesValue(CI->getType());
4008 BinaryOperator::createAnd(LHSI->getOperand(0),
4009 Mask, LHSI->getName()+".mask");
4010 Value *And = InsertNewInstBefore(AndI, I);
4011 return new SetCondInst(I.getOpcode(), And,
4012 ConstantExpr::getUShr(CI, ShAmt));
4018 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
4019 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
4020 if (I.isEquality()) {
4021 // Check that the shift amount is in range. If not, don't perform
4022 // undefined shifts. When the shift is visited it will be
4024 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4025 if (ShAmt->getValue() >= TypeBits)
4028 // If we are comparing against bits always shifted out, the
4029 // comparison cannot succeed.
4031 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
4033 if (Comp != CI) {// Comparing against a bit that we know is zero.
4034 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4035 Constant *Cst = ConstantBool::get(IsSetNE);
4036 return ReplaceInstUsesWith(I, Cst);
4039 if (LHSI->hasOneUse() || CI->isNullValue()) {
4040 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
4042 // Otherwise strength reduce the shift into an and.
4043 uint64_t Val = ~0ULL; // All ones.
4044 Val <<= ShAmtVal; // Shift over to the right spot.
4047 if (CI->getType()->isUnsigned()) {
4048 Val &= ~0ULL >> (64-TypeBits);
4049 Mask = ConstantUInt::get(CI->getType(), Val);
4051 Mask = ConstantSInt::get(CI->getType(), Val);
4055 BinaryOperator::createAnd(LHSI->getOperand(0),
4056 Mask, LHSI->getName()+".mask");
4057 Value *And = InsertNewInstBefore(AndI, I);
4058 return new SetCondInst(I.getOpcode(), And,
4059 ConstantExpr::getShl(CI, ShAmt));
4065 case Instruction::Div:
4066 // Fold: (div X, C1) op C2 -> range check
4067 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4068 // Fold this div into the comparison, producing a range check.
4069 // Determine, based on the divide type, what the range is being
4070 // checked. If there is an overflow on the low or high side, remember
4071 // it, otherwise compute the range [low, hi) bounding the new value.
4072 bool LoOverflow = false, HiOverflow = 0;
4073 ConstantInt *LoBound = 0, *HiBound = 0;
4076 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
4078 Instruction::BinaryOps Opcode = I.getOpcode();
4080 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
4081 } else if (LHSI->getType()->isUnsigned()) { // udiv
4083 LoOverflow = ProdOV;
4084 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4085 } else if (isPositive(DivRHS)) { // Divisor is > 0.
4086 if (CI->isNullValue()) { // (X / pos) op 0
4088 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4090 } else if (isPositive(CI)) { // (X / pos) op pos
4092 LoOverflow = ProdOV;
4093 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4094 } else { // (X / pos) op neg
4095 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4096 LoOverflow = AddWithOverflow(LoBound, Prod,
4097 cast<ConstantInt>(DivRHSH));
4099 HiOverflow = ProdOV;
4101 } else { // Divisor is < 0.
4102 if (CI->isNullValue()) { // (X / neg) op 0
4103 LoBound = AddOne(DivRHS);
4104 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
4105 if (HiBound == DivRHS)
4106 LoBound = 0; // - INTMIN = INTMIN
4107 } else if (isPositive(CI)) { // (X / neg) op pos
4108 HiOverflow = LoOverflow = ProdOV;
4110 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4111 HiBound = AddOne(Prod);
4112 } else { // (X / neg) op neg
4114 LoOverflow = HiOverflow = ProdOV;
4115 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4118 // Dividing by a negate swaps the condition.
4119 Opcode = SetCondInst::getSwappedCondition(Opcode);
4123 Value *X = LHSI->getOperand(0);
4125 default: assert(0 && "Unhandled setcc opcode!");
4126 case Instruction::SetEQ:
4127 if (LoOverflow && HiOverflow)
4128 return ReplaceInstUsesWith(I, ConstantBool::False);
4129 else if (HiOverflow)
4130 return new SetCondInst(Instruction::SetGE, X, LoBound);
4131 else if (LoOverflow)
4132 return new SetCondInst(Instruction::SetLT, X, HiBound);
4134 return InsertRangeTest(X, LoBound, HiBound, true, I);
4135 case Instruction::SetNE:
4136 if (LoOverflow && HiOverflow)
4137 return ReplaceInstUsesWith(I, ConstantBool::True);
4138 else if (HiOverflow)
4139 return new SetCondInst(Instruction::SetLT, X, LoBound);
4140 else if (LoOverflow)
4141 return new SetCondInst(Instruction::SetGE, X, HiBound);
4143 return InsertRangeTest(X, LoBound, HiBound, false, I);
4144 case Instruction::SetLT:
4146 return ReplaceInstUsesWith(I, ConstantBool::False);
4147 return new SetCondInst(Instruction::SetLT, X, LoBound);
4148 case Instruction::SetGT:
4150 return ReplaceInstUsesWith(I, ConstantBool::False);
4151 return new SetCondInst(Instruction::SetGE, X, HiBound);
4158 // Simplify seteq and setne instructions...
4159 if (I.isEquality()) {
4160 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4162 // If the first operand is (and|or|xor) with a constant, and the second
4163 // operand is a constant, simplify a bit.
4164 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4165 switch (BO->getOpcode()) {
4166 case Instruction::Rem:
4167 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4168 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
4170 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
4171 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
4172 if (isPowerOf2_64(V)) {
4173 unsigned L2 = Log2_64(V);
4174 const Type *UTy = BO->getType()->getUnsignedVersion();
4175 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
4177 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
4178 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
4179 RHSCst, BO->getName()), I);
4180 return BinaryOperator::create(I.getOpcode(), NewRem,
4181 Constant::getNullValue(UTy));
4186 case Instruction::Add:
4187 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4188 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4189 if (BO->hasOneUse())
4190 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4191 ConstantExpr::getSub(CI, BOp1C));
4192 } else if (CI->isNullValue()) {
4193 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4194 // efficiently invertible, or if the add has just this one use.
4195 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
4197 if (Value *NegVal = dyn_castNegVal(BOp1))
4198 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4199 else if (Value *NegVal = dyn_castNegVal(BOp0))
4200 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
4201 else if (BO->hasOneUse()) {
4202 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4204 InsertNewInstBefore(Neg, I);
4205 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4209 case Instruction::Xor:
4210 // For the xor case, we can xor two constants together, eliminating
4211 // the explicit xor.
4212 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4213 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
4214 ConstantExpr::getXor(CI, BOC));
4217 case Instruction::Sub:
4218 // Replace (([sub|xor] A, B) != 0) with (A != B)
4219 if (CI->isNullValue())
4220 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4224 case Instruction::Or:
4225 // If bits are being or'd in that are not present in the constant we
4226 // are comparing against, then the comparison could never succeed!
4227 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
4228 Constant *NotCI = ConstantExpr::getNot(CI);
4229 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
4230 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
4234 case Instruction::And:
4235 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4236 // If bits are being compared against that are and'd out, then the
4237 // comparison can never succeed!
4238 if (!ConstantExpr::getAnd(CI,
4239 ConstantExpr::getNot(BOC))->isNullValue())
4240 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
4242 // If we have ((X & C) == C), turn it into ((X & C) != 0).
4243 if (CI == BOC && isOneBitSet(CI))
4244 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4245 Instruction::SetNE, Op0,
4246 Constant::getNullValue(CI->getType()));
4248 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4249 // to be a signed value as appropriate.
4250 if (isSignBit(BOC)) {
4251 Value *X = BO->getOperand(0);
4252 // If 'X' is not signed, insert a cast now...
4253 if (!BOC->getType()->isSigned()) {
4254 const Type *DestTy = BOC->getType()->getSignedVersion();
4255 X = InsertCastBefore(X, DestTy, I);
4257 return new SetCondInst(isSetNE ? Instruction::SetLT :
4258 Instruction::SetGE, X,
4259 Constant::getNullValue(X->getType()));
4262 // ((X & ~7) == 0) --> X < 8
4263 if (CI->isNullValue() && isHighOnes(BOC)) {
4264 Value *X = BO->getOperand(0);
4265 Constant *NegX = ConstantExpr::getNeg(BOC);
4267 // If 'X' is signed, insert a cast now.
4268 if (NegX->getType()->isSigned()) {
4269 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4270 X = InsertCastBefore(X, DestTy, I);
4271 NegX = ConstantExpr::getCast(NegX, DestTy);
4274 return new SetCondInst(isSetNE ? Instruction::SetGE :
4275 Instruction::SetLT, X, NegX);
4282 } else { // Not a SetEQ/SetNE
4283 // If the LHS is a cast from an integral value of the same size,
4284 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4285 Value *CastOp = Cast->getOperand(0);
4286 const Type *SrcTy = CastOp->getType();
4287 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
4288 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
4289 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
4290 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
4291 "Source and destination signednesses should differ!");
4292 if (Cast->getType()->isSigned()) {
4293 // If this is a signed comparison, check for comparisons in the
4294 // vicinity of zero.
4295 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4297 return BinaryOperator::createSetGT(CastOp,
4298 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
4299 else if (I.getOpcode() == Instruction::SetGT &&
4300 cast<ConstantSInt>(CI)->getValue() == -1)
4301 // X > -1 => x < 128
4302 return BinaryOperator::createSetLT(CastOp,
4303 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
4305 ConstantUInt *CUI = cast<ConstantUInt>(CI);
4306 if (I.getOpcode() == Instruction::SetLT &&
4307 CUI->getValue() == 1ULL << (SrcTySize-1))
4308 // X < 128 => X > -1
4309 return BinaryOperator::createSetGT(CastOp,
4310 ConstantSInt::get(SrcTy, -1));
4311 else if (I.getOpcode() == Instruction::SetGT &&
4312 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
4314 return BinaryOperator::createSetLT(CastOp,
4315 Constant::getNullValue(SrcTy));
4322 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4323 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4324 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4325 switch (LHSI->getOpcode()) {
4326 case Instruction::GetElementPtr:
4327 if (RHSC->isNullValue()) {
4328 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4329 bool isAllZeros = true;
4330 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4331 if (!isa<Constant>(LHSI->getOperand(i)) ||
4332 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4337 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4338 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4342 case Instruction::PHI:
4343 if (Instruction *NV = FoldOpIntoPhi(I))
4346 case Instruction::Select:
4347 // If either operand of the select is a constant, we can fold the
4348 // comparison into the select arms, which will cause one to be
4349 // constant folded and the select turned into a bitwise or.
4350 Value *Op1 = 0, *Op2 = 0;
4351 if (LHSI->hasOneUse()) {
4352 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4353 // Fold the known value into the constant operand.
4354 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4355 // Insert a new SetCC of the other select operand.
4356 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4357 LHSI->getOperand(2), RHSC,
4359 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4360 // Fold the known value into the constant operand.
4361 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4362 // Insert a new SetCC of the other select operand.
4363 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4364 LHSI->getOperand(1), RHSC,
4370 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4375 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4376 if (User *GEP = dyn_castGetElementPtr(Op0))
4377 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4379 if (User *GEP = dyn_castGetElementPtr(Op1))
4380 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4381 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4384 // Test to see if the operands of the setcc are casted versions of other
4385 // values. If the cast can be stripped off both arguments, we do so now.
4386 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4387 Value *CastOp0 = CI->getOperand(0);
4388 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
4389 (isa<Constant>(Op1) || isa<CastInst>(Op1)) && I.isEquality()) {
4390 // We keep moving the cast from the left operand over to the right
4391 // operand, where it can often be eliminated completely.
4394 // If operand #1 is a cast instruction, see if we can eliminate it as
4396 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4397 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
4399 Op1 = CI2->getOperand(0);
4401 // If Op1 is a constant, we can fold the cast into the constant.
4402 if (Op1->getType() != Op0->getType())
4403 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4404 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4406 // Otherwise, cast the RHS right before the setcc
4407 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
4408 InsertNewInstBefore(cast<Instruction>(Op1), I);
4410 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4413 // Handle the special case of: setcc (cast bool to X), <cst>
4414 // This comes up when you have code like
4417 // For generality, we handle any zero-extension of any operand comparison
4418 // with a constant or another cast from the same type.
4419 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4420 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4424 if (I.isEquality()) {
4426 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4427 (A == Op1 || B == Op1)) {
4428 // (A^B) == A -> B == 0
4429 Value *OtherVal = A == Op1 ? B : A;
4430 return BinaryOperator::create(I.getOpcode(), OtherVal,
4431 Constant::getNullValue(A->getType()));
4432 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4433 (A == Op0 || B == Op0)) {
4434 // A == (A^B) -> B == 0
4435 Value *OtherVal = A == Op0 ? B : A;
4436 return BinaryOperator::create(I.getOpcode(), OtherVal,
4437 Constant::getNullValue(A->getType()));
4438 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4439 // (A-B) == A -> B == 0
4440 return BinaryOperator::create(I.getOpcode(), B,
4441 Constant::getNullValue(B->getType()));
4442 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4443 // A == (A-B) -> B == 0
4444 return BinaryOperator::create(I.getOpcode(), B,
4445 Constant::getNullValue(B->getType()));
4448 return Changed ? &I : 0;
4451 // visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4452 // We only handle extending casts so far.
4454 Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4455 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4456 const Type *SrcTy = LHSCIOp->getType();
4457 const Type *DestTy = SCI.getOperand(0)->getType();
4460 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
4463 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4464 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4465 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4467 // Is this a sign or zero extension?
4468 bool isSignSrc = SrcTy->isSigned();
4469 bool isSignDest = DestTy->isSigned();
4471 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4472 // Not an extension from the same type?
4473 RHSCIOp = CI->getOperand(0);
4474 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4475 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4476 // Compute the constant that would happen if we truncated to SrcTy then
4477 // reextended to DestTy.
4478 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4480 if (ConstantExpr::getCast(Res, DestTy) == CI) {
4483 // If the value cannot be represented in the shorter type, we cannot emit
4484 // a simple comparison.
4485 if (SCI.getOpcode() == Instruction::SetEQ)
4486 return ReplaceInstUsesWith(SCI, ConstantBool::False);
4487 if (SCI.getOpcode() == Instruction::SetNE)
4488 return ReplaceInstUsesWith(SCI, ConstantBool::True);
4490 // Evaluate the comparison for LT.
4492 if (DestTy->isSigned()) {
4493 // We're performing a signed comparison.
4495 // Signed extend and signed comparison.
4496 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
4497 Result = ConstantBool::False;
4499 Result = ConstantBool::True; // X < (large) --> true
4501 // Unsigned extend and signed comparison.
4502 if (cast<ConstantSInt>(CI)->getValue() < 0)
4503 Result = ConstantBool::False;
4505 Result = ConstantBool::True;
4508 // We're performing an unsigned comparison.
4510 // Unsigned extend & compare -> always true.
4511 Result = ConstantBool::True;
4513 // We're performing an unsigned comp with a sign extended value.
4514 // This is true if the input is >= 0. [aka >s -1]
4515 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4516 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4517 NegOne, SCI.getName()), SCI);
4521 // Finally, return the value computed.
4522 if (SCI.getOpcode() == Instruction::SetLT) {
4523 return ReplaceInstUsesWith(SCI, Result);
4525 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4526 if (Constant *CI = dyn_cast<Constant>(Result))
4527 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4529 return BinaryOperator::createNot(Result);
4536 // Okay, just insert a compare of the reduced operands now!
4537 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4540 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
4541 assert(I.getOperand(1)->getType() == Type::UByteTy);
4542 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4543 bool isLeftShift = I.getOpcode() == Instruction::Shl;
4545 // shl X, 0 == X and shr X, 0 == X
4546 // shl 0, X == 0 and shr 0, X == 0
4547 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
4548 Op0 == Constant::getNullValue(Op0->getType()))
4549 return ReplaceInstUsesWith(I, Op0);
4551 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4552 if (!isLeftShift && I.getType()->isSigned())
4553 return ReplaceInstUsesWith(I, Op0);
4554 else // undef << X -> 0 AND undef >>u X -> 0
4555 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4557 if (isa<UndefValue>(Op1)) {
4558 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
4559 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4561 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4564 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4566 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4567 if (CSI->isAllOnesValue())
4568 return ReplaceInstUsesWith(I, CSI);
4570 // Try to fold constant and into select arguments.
4571 if (isa<Constant>(Op0))
4572 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
4573 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4576 // See if we can turn a signed shr into an unsigned shr.
4577 if (I.isArithmeticShift()) {
4578 if (MaskedValueIsZero(Op0,
4579 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
4580 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4581 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4583 return new CastInst(V, I.getType());
4587 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4588 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4593 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4595 bool isLeftShift = I.getOpcode() == Instruction::Shl;
4596 bool isSignedShift = Op0->getType()->isSigned();
4597 bool isUnsignedShift = !isSignedShift;
4599 // See if we can simplify any instructions used by the instruction whose sole
4600 // purpose is to compute bits we don't care about.
4601 uint64_t KnownZero, KnownOne;
4602 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4603 KnownZero, KnownOne))
4606 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4607 // of a signed value.
4609 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4610 if (Op1->getValue() >= TypeBits) {
4611 if (isUnsignedShift || isLeftShift)
4612 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4614 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4619 // ((X*C1) << C2) == (X * (C1 << C2))
4620 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4621 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4622 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4623 return BinaryOperator::createMul(BO->getOperand(0),
4624 ConstantExpr::getShl(BOOp, Op1));
4626 // Try to fold constant and into select arguments.
4627 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4628 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4630 if (isa<PHINode>(Op0))
4631 if (Instruction *NV = FoldOpIntoPhi(I))
4634 if (Op0->hasOneUse()) {
4635 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4636 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4639 switch (Op0BO->getOpcode()) {
4641 case Instruction::Add:
4642 case Instruction::And:
4643 case Instruction::Or:
4644 case Instruction::Xor:
4645 // These operators commute.
4646 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
4647 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4648 match(Op0BO->getOperand(1),
4649 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
4650 Instruction *YS = new ShiftInst(Instruction::Shl,
4651 Op0BO->getOperand(0), Op1,
4653 InsertNewInstBefore(YS, I); // (Y << C)
4655 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4656 Op0BO->getOperand(1)->getName());
4657 InsertNewInstBefore(X, I); // (X + (Y << C))
4658 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
4659 C2 = ConstantExpr::getShl(C2, Op1);
4660 return BinaryOperator::createAnd(X, C2);
4663 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4664 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4665 match(Op0BO->getOperand(1),
4666 m_And(m_Shr(m_Value(V1), m_Value(V2)),
4667 m_ConstantInt(CC))) && V2 == Op1 &&
4668 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
4669 Instruction *YS = new ShiftInst(Instruction::Shl,
4670 Op0BO->getOperand(0), Op1,
4672 InsertNewInstBefore(YS, I); // (Y << C)
4674 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
4675 V1->getName()+".mask");
4676 InsertNewInstBefore(XM, I); // X & (CC << C)
4678 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4682 case Instruction::Sub:
4683 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4684 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4685 match(Op0BO->getOperand(0),
4686 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
4687 Instruction *YS = new ShiftInst(Instruction::Shl,
4688 Op0BO->getOperand(1), Op1,
4690 InsertNewInstBefore(YS, I); // (Y << C)
4692 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
4693 Op0BO->getOperand(0)->getName());
4694 InsertNewInstBefore(X, I); // (X + (Y << C))
4695 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
4696 C2 = ConstantExpr::getShl(C2, Op1);
4697 return BinaryOperator::createAnd(X, C2);
4700 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
4701 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4702 match(Op0BO->getOperand(0),
4703 m_And(m_Shr(m_Value(V1), m_Value(V2)),
4704 m_ConstantInt(CC))) && V2 == Op1 &&
4705 cast<BinaryOperator>(Op0BO->getOperand(0))
4706 ->getOperand(0)->hasOneUse()) {
4707 Instruction *YS = new ShiftInst(Instruction::Shl,
4708 Op0BO->getOperand(1), Op1,
4710 InsertNewInstBefore(YS, I); // (Y << C)
4712 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
4713 V1->getName()+".mask");
4714 InsertNewInstBefore(XM, I); // X & (CC << C)
4716 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
4723 // If the operand is an bitwise operator with a constant RHS, and the
4724 // shift is the only use, we can pull it out of the shift.
4725 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4726 bool isValid = true; // Valid only for And, Or, Xor
4727 bool highBitSet = false; // Transform if high bit of constant set?
4729 switch (Op0BO->getOpcode()) {
4730 default: isValid = false; break; // Do not perform transform!
4731 case Instruction::Add:
4732 isValid = isLeftShift;
4734 case Instruction::Or:
4735 case Instruction::Xor:
4738 case Instruction::And:
4743 // If this is a signed shift right, and the high bit is modified
4744 // by the logical operation, do not perform the transformation.
4745 // The highBitSet boolean indicates the value of the high bit of
4746 // the constant which would cause it to be modified for this
4749 if (isValid && !isLeftShift && isSignedShift) {
4750 uint64_t Val = Op0C->getRawValue();
4751 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4755 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4757 Instruction *NewShift =
4758 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4761 InsertNewInstBefore(NewShift, I);
4763 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4770 // Find out if this is a shift of a shift by a constant.
4771 ShiftInst *ShiftOp = 0;
4772 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
4774 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4775 // If this is a noop-integer case of a shift instruction, use the shift.
4776 if (CI->getOperand(0)->getType()->isInteger() &&
4777 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4778 CI->getType()->getPrimitiveSizeInBits() &&
4779 isa<ShiftInst>(CI->getOperand(0))) {
4780 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4784 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4785 // Find the operands and properties of the input shift. Note that the
4786 // signedness of the input shift may differ from the current shift if there
4787 // is a noop cast between the two.
4788 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4789 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
4790 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
4792 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4794 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4795 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4797 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4798 if (isLeftShift == isShiftOfLeftShift) {
4799 // Do not fold these shifts if the first one is signed and the second one
4800 // is unsigned and this is a right shift. Further, don't do any folding
4802 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4805 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4806 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4807 Amt = Op0->getType()->getPrimitiveSizeInBits();
4809 Value *Op = ShiftOp->getOperand(0);
4810 if (isShiftOfSignedShift != isSignedShift)
4811 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4812 return new ShiftInst(I.getOpcode(), Op,
4813 ConstantUInt::get(Type::UByteTy, Amt));
4816 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4817 // signed types, we can only support the (A >> c1) << c2 configuration,
4818 // because it can not turn an arbitrary bit of A into a sign bit.
4819 if (isUnsignedShift || isLeftShift) {
4820 // Calculate bitmask for what gets shifted off the edge.
4821 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4823 C = ConstantExpr::getShl(C, ShiftAmt1C);
4825 C = ConstantExpr::getUShr(C, ShiftAmt1C);
4827 Value *Op = ShiftOp->getOperand(0);
4828 if (isShiftOfSignedShift != isSignedShift)
4829 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4832 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4833 InsertNewInstBefore(Mask, I);
4835 // Figure out what flavor of shift we should use...
4836 if (ShiftAmt1 == ShiftAmt2) {
4837 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
4838 } else if (ShiftAmt1 < ShiftAmt2) {
4839 return new ShiftInst(I.getOpcode(), Mask,
4840 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
4841 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4842 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4843 // Make sure to emit an unsigned shift right, not a signed one.
4844 Mask = InsertNewInstBefore(new CastInst(Mask,
4845 Mask->getType()->getUnsignedVersion(),
4847 Mask = new ShiftInst(Instruction::Shr, Mask,
4848 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4849 InsertNewInstBefore(Mask, I);
4850 return new CastInst(Mask, I.getType());
4852 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4853 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4856 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4857 Op = InsertNewInstBefore(new CastInst(Mask,
4858 I.getType()->getSignedVersion(),
4859 Mask->getName()), I);
4860 Instruction *Shift =
4861 new ShiftInst(ShiftOp->getOpcode(), Op,
4862 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4863 InsertNewInstBefore(Shift, I);
4865 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4866 C = ConstantExpr::getShl(C, Op1);
4867 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4868 InsertNewInstBefore(Mask, I);
4869 return new CastInst(Mask, I.getType());
4872 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
4873 // this case, C1 == C2 and C1 is 8, 16, or 32.
4874 if (ShiftAmt1 == ShiftAmt2) {
4875 const Type *SExtType = 0;
4876 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
4877 case 8 : SExtType = Type::SByteTy; break;
4878 case 16: SExtType = Type::ShortTy; break;
4879 case 32: SExtType = Type::IntTy; break;
4883 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4885 InsertNewInstBefore(NewTrunc, I);
4886 return new CastInst(NewTrunc, I.getType());
4895 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4896 /// expression. If so, decompose it, returning some value X, such that Val is
4899 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4901 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4902 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4903 Offset = CI->getValue();
4905 return ConstantUInt::get(Type::UIntTy, 0);
4906 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4907 if (I->getNumOperands() == 2) {
4908 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4909 if (I->getOpcode() == Instruction::Shl) {
4910 // This is a value scaled by '1 << the shift amt'.
4911 Scale = 1U << CUI->getValue();
4913 return I->getOperand(0);
4914 } else if (I->getOpcode() == Instruction::Mul) {
4915 // This value is scaled by 'CUI'.
4916 Scale = CUI->getValue();
4918 return I->getOperand(0);
4919 } else if (I->getOpcode() == Instruction::Add) {
4920 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4923 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4925 Offset += CUI->getValue();
4926 if (SubScale > 1 && (Offset % SubScale == 0)) {
4935 // Otherwise, we can't look past this.
4942 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4943 /// try to eliminate the cast by moving the type information into the alloc.
4944 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4945 AllocationInst &AI) {
4946 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
4947 if (!PTy) return 0; // Not casting the allocation to a pointer type.
4949 // Remove any uses of AI that are dead.
4950 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4951 std::vector<Instruction*> DeadUsers;
4952 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4953 Instruction *User = cast<Instruction>(*UI++);
4954 if (isInstructionTriviallyDead(User)) {
4955 while (UI != E && *UI == User)
4956 ++UI; // If this instruction uses AI more than once, don't break UI.
4958 // Add operands to the worklist.
4959 AddUsesToWorkList(*User);
4961 DEBUG(std::cerr << "IC: DCE: " << *User);
4963 User->eraseFromParent();
4964 removeFromWorkList(User);
4968 // Get the type really allocated and the type casted to.
4969 const Type *AllocElTy = AI.getAllocatedType();
4970 const Type *CastElTy = PTy->getElementType();
4971 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
4973 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4974 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4975 if (CastElTyAlign < AllocElTyAlign) return 0;
4977 // If the allocation has multiple uses, only promote it if we are strictly
4978 // increasing the alignment of the resultant allocation. If we keep it the
4979 // same, we open the door to infinite loops of various kinds.
4980 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4982 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4983 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
4984 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
4986 // See if we can satisfy the modulus by pulling a scale out of the array
4988 unsigned ArraySizeScale, ArrayOffset;
4989 Value *NumElements = // See if the array size is a decomposable linear expr.
4990 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4992 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4994 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4995 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
4997 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5002 Amt = ConstantUInt::get(Type::UIntTy, Scale);
5003 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
5004 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
5005 else if (Scale != 1) {
5006 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5007 Amt = InsertNewInstBefore(Tmp, AI);
5011 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5012 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
5013 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5014 Amt = InsertNewInstBefore(Tmp, AI);
5017 std::string Name = AI.getName(); AI.setName("");
5018 AllocationInst *New;
5019 if (isa<MallocInst>(AI))
5020 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
5022 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
5023 InsertNewInstBefore(New, AI);
5025 // If the allocation has multiple uses, insert a cast and change all things
5026 // that used it to use the new cast. This will also hack on CI, but it will
5028 if (!AI.hasOneUse()) {
5029 AddUsesToWorkList(AI);
5030 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
5031 InsertNewInstBefore(NewCast, AI);
5032 AI.replaceAllUsesWith(NewCast);
5034 return ReplaceInstUsesWith(CI, New);
5037 /// CanEvaluateInDifferentType - Return true if we can take the specified value
5038 /// and return it without inserting any new casts. This is used by code that
5039 /// tries to decide whether promoting or shrinking integer operations to wider
5040 /// or smaller types will allow us to eliminate a truncate or extend.
5041 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5042 int &NumCastsRemoved) {
5043 if (isa<Constant>(V)) return true;
5045 Instruction *I = dyn_cast<Instruction>(V);
5046 if (!I || !I->hasOneUse()) return false;
5048 switch (I->getOpcode()) {
5049 case Instruction::And:
5050 case Instruction::Or:
5051 case Instruction::Xor:
5052 // These operators can all arbitrarily be extended or truncated.
5053 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5054 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5055 case Instruction::Cast:
5056 // If this is a cast from the destination type, we can trivially eliminate
5057 // it, and this will remove a cast overall.
5058 if (I->getOperand(0)->getType() == Ty) {
5059 // If the first operand is itself a cast, and is eliminable, do not count
5060 // this as an eliminable cast. We would prefer to eliminate those two
5062 if (CastInst *OpCast = dyn_cast<CastInst>(I->getOperand(0)))
5068 // TODO: Can handle more cases here.
5075 /// EvaluateInDifferentType - Given an expression that
5076 /// CanEvaluateInDifferentType returns true for, actually insert the code to
5077 /// evaluate the expression.
5078 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5079 if (Constant *C = dyn_cast<Constant>(V))
5080 return ConstantExpr::getCast(C, Ty);
5082 // Otherwise, it must be an instruction.
5083 Instruction *I = cast<Instruction>(V);
5084 Instruction *Res = 0;
5085 switch (I->getOpcode()) {
5086 case Instruction::And:
5087 case Instruction::Or:
5088 case Instruction::Xor: {
5089 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5090 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5091 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5092 LHS, RHS, I->getName());
5095 case Instruction::Cast:
5096 // If this is a cast from the destination type, return the input.
5097 if (I->getOperand(0)->getType() == Ty)
5098 return I->getOperand(0);
5100 // TODO: Can handle more cases here.
5101 assert(0 && "Unreachable!");
5105 return InsertNewInstBefore(Res, *I);
5109 // CastInst simplification
5111 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
5112 Value *Src = CI.getOperand(0);
5114 // If the user is casting a value to the same type, eliminate this cast
5116 if (CI.getType() == Src->getType())
5117 return ReplaceInstUsesWith(CI, Src);
5119 if (isa<UndefValue>(Src)) // cast undef -> undef
5120 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5122 // If casting the result of another cast instruction, try to eliminate this
5125 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5126 Value *A = CSrc->getOperand(0);
5127 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5128 CI.getType(), TD)) {
5129 // This instruction now refers directly to the cast's src operand. This
5130 // has a good chance of making CSrc dead.
5131 CI.setOperand(0, CSrc->getOperand(0));
5135 // If this is an A->B->A cast, and we are dealing with integral types, try
5136 // to convert this into a logical 'and' instruction.
5138 if (A->getType()->isInteger() &&
5139 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
5140 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
5141 CSrc->getType()->getPrimitiveSizeInBits() <
5142 CI.getType()->getPrimitiveSizeInBits()&&
5143 A->getType()->getPrimitiveSizeInBits() ==
5144 CI.getType()->getPrimitiveSizeInBits()) {
5145 assert(CSrc->getType() != Type::ULongTy &&
5146 "Cannot have type bigger than ulong!");
5147 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
5148 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
5150 AndOp = ConstantExpr::getCast(AndOp, A->getType());
5151 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5152 if (And->getType() != CI.getType()) {
5153 And->setName(CSrc->getName()+".mask");
5154 InsertNewInstBefore(And, CI);
5155 And = new CastInst(And, CI.getType());
5161 // If this is a cast to bool, turn it into the appropriate setne instruction.
5162 if (CI.getType() == Type::BoolTy)
5163 return BinaryOperator::createSetNE(CI.getOperand(0),
5164 Constant::getNullValue(CI.getOperand(0)->getType()));
5166 // See if we can simplify any instructions used by the LHS whose sole
5167 // purpose is to compute bits we don't care about.
5168 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5169 uint64_t KnownZero, KnownOne;
5170 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5171 KnownZero, KnownOne))
5175 // If casting the result of a getelementptr instruction with no offset, turn
5176 // this into a cast of the original pointer!
5178 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
5179 bool AllZeroOperands = true;
5180 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5181 if (!isa<Constant>(GEP->getOperand(i)) ||
5182 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5183 AllZeroOperands = false;
5186 if (AllZeroOperands) {
5187 CI.setOperand(0, GEP->getOperand(0));
5192 // If we are casting a malloc or alloca to a pointer to a type of the same
5193 // size, rewrite the allocation instruction to allocate the "right" type.
5195 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
5196 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5199 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5200 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5202 if (isa<PHINode>(Src))
5203 if (Instruction *NV = FoldOpIntoPhi(CI))
5206 // If the source and destination are pointers, and this cast is equivalent to
5207 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
5208 // This can enhance SROA and other transforms that want type-safe pointers.
5209 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5210 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5211 const Type *DstTy = DstPTy->getElementType();
5212 const Type *SrcTy = SrcPTy->getElementType();
5214 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5215 unsigned NumZeros = 0;
5216 while (SrcTy != DstTy &&
5217 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy) &&
5218 SrcTy->getNumContainedTypes() /* not "{}" */) {
5219 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5223 // If we found a path from the src to dest, create the getelementptr now.
5224 if (SrcTy == DstTy) {
5225 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5226 return new GetElementPtrInst(Src, Idxs);
5230 // If the source value is an instruction with only this use, we can attempt to
5231 // propagate the cast into the instruction. Also, only handle integral types
5233 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
5234 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
5235 CI.getType()->isInteger()) { // Don't mess with casts to bool here
5237 int NumCastsRemoved = 0;
5238 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5239 // If this cast is a truncate, evaluting in a different type always
5240 // eliminates the cast, so it is always a win. If this is a noop-cast
5241 // this just removes a noop cast which isn't pointful, but simplifies
5242 // the code. If this is a zero-extension, we need to do an AND to
5243 // maintain the clear top-part of the computation, so we require that
5244 // the input have eliminated at least one cast. If this is a sign
5245 // extension, we insert two new casts (to do the extension) so we
5246 // require that two casts have been eliminated.
5248 switch (getCastType(Src->getType(), CI.getType())) {
5249 default: assert(0 && "Unknown cast type!");
5255 DoXForm = NumCastsRemoved >= 1;
5258 DoXForm = NumCastsRemoved >= 2;
5263 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5264 assert(Res->getType() == CI.getType());
5265 switch (getCastType(Src->getType(), CI.getType())) {
5266 default: assert(0 && "Unknown cast type!");
5269 // Just replace this cast with the result.
5270 return ReplaceInstUsesWith(CI, Res);
5272 // We need to emit an AND to clear the high bits.
5273 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5274 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5275 assert(SrcBitSize < DestBitSize && "Not a zext?");
5276 Constant *C = ConstantUInt::get(Type::ULongTy, (1 << SrcBitSize)-1);
5277 C = ConstantExpr::getCast(C, CI.getType());
5278 return BinaryOperator::createAnd(Res, C);
5281 // We need to emit a cast to truncate, then a cast to sext.
5282 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5288 const Type *DestTy = CI.getType();
5289 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5290 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
5292 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5293 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5295 switch (SrcI->getOpcode()) {
5296 case Instruction::Add:
5297 case Instruction::Mul:
5298 case Instruction::And:
5299 case Instruction::Or:
5300 case Instruction::Xor:
5301 // If we are discarding information, or just changing the sign, rewrite.
5302 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5303 // Don't insert two casts if they cannot be eliminated. We allow two
5304 // casts to be inserted if the sizes are the same. This could only be
5305 // converting signedness, which is a noop.
5306 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5307 !ValueRequiresCast(Op0, DestTy, TD)) {
5308 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5309 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5310 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5311 ->getOpcode(), Op0c, Op1c);
5315 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5316 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
5317 Op1 == ConstantBool::True &&
5318 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5319 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5320 return BinaryOperator::createXor(New,
5321 ConstantInt::get(CI.getType(), 1));
5324 case Instruction::Shl:
5325 // Allow changing the sign of the source operand. Do not allow changing
5326 // the size of the shift, UNLESS the shift amount is a constant. We
5327 // mush not change variable sized shifts to a smaller size, because it
5328 // is undefined to shift more bits out than exist in the value.
5329 if (DestBitSize == SrcBitSize ||
5330 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5331 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5332 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5335 case Instruction::Shr:
5336 // If this is a signed shr, and if all bits shifted in are about to be
5337 // truncated off, turn it into an unsigned shr to allow greater
5339 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
5340 isa<ConstantInt>(Op1)) {
5341 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
5342 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5343 // Convert to unsigned.
5344 Value *N1 = InsertOperandCastBefore(Op0,
5345 Op0->getType()->getUnsignedVersion(), &CI);
5346 // Insert the new shift, which is now unsigned.
5347 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
5348 Op1, Src->getName()), CI);
5349 return new CastInst(N1, CI.getType());
5354 case Instruction::SetEQ:
5355 case Instruction::SetNE:
5356 // We if we are just checking for a seteq of a single bit and casting it
5357 // to an integer. If so, shift the bit to the appropriate place then
5358 // cast to integer to avoid the comparison.
5359 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
5360 uint64_t Op1CV = Op1C->getZExtValue();
5361 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5362 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5363 // cast (X == 1) to int --> X iff X has only the low bit set.
5364 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5365 // cast (X != 0) to int --> X iff X has only the low bit set.
5366 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5367 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5368 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5369 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5370 // If Op1C some other power of two, convert:
5371 uint64_t KnownZero, KnownOne;
5372 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5373 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5375 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5376 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5377 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5378 // (X&4) == 2 --> false
5379 // (X&4) != 2 --> true
5380 Constant *Res = ConstantBool::get(isSetNE);
5381 Res = ConstantExpr::getCast(Res, CI.getType());
5382 return ReplaceInstUsesWith(CI, Res);
5385 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5388 // Perform an unsigned shr by shiftamt. Convert input to
5389 // unsigned if it is signed.
5390 if (In->getType()->isSigned())
5391 In = InsertNewInstBefore(new CastInst(In,
5392 In->getType()->getUnsignedVersion(), In->getName()),CI);
5393 // Insert the shift to put the result in the low bit.
5394 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
5395 ConstantInt::get(Type::UByteTy, ShiftAmt),
5396 In->getName()+".lobit"), CI);
5399 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5400 Constant *One = ConstantInt::get(In->getType(), 1);
5401 In = BinaryOperator::createXor(In, One, "tmp");
5402 InsertNewInstBefore(cast<Instruction>(In), CI);
5405 if (CI.getType() == In->getType())
5406 return ReplaceInstUsesWith(CI, In);
5408 return new CastInst(In, CI.getType());
5416 if (SrcI->hasOneUse()) {
5417 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
5418 // Okay, we have (cast (shuffle ..)). We know this cast is a bitconvert
5419 // because the inputs are known to be a vector. Check to see if this is
5420 // a cast to a vector with the same # elts.
5421 if (isa<PackedType>(CI.getType()) &&
5422 cast<PackedType>(CI.getType())->getNumElements() ==
5423 SVI->getType()->getNumElements()) {
5425 // If either of the operands is a cast from CI.getType(), then
5426 // evaluating the shuffle in the casted destination's type will allow
5427 // us to eliminate at least one cast.
5428 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
5429 Tmp->getOperand(0)->getType() == CI.getType()) ||
5430 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
5431 Tmp->getOperand(0)->getType() == CI.getType())) {
5432 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
5434 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
5436 // Return a new shuffle vector. Use the same element ID's, as we
5437 // know the vector types match #elts.
5438 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
5448 /// GetSelectFoldableOperands - We want to turn code that looks like this:
5450 /// %D = select %cond, %C, %A
5452 /// %C = select %cond, %B, 0
5455 /// Assuming that the specified instruction is an operand to the select, return
5456 /// a bitmask indicating which operands of this instruction are foldable if they
5457 /// equal the other incoming value of the select.
5459 static unsigned GetSelectFoldableOperands(Instruction *I) {
5460 switch (I->getOpcode()) {
5461 case Instruction::Add:
5462 case Instruction::Mul:
5463 case Instruction::And:
5464 case Instruction::Or:
5465 case Instruction::Xor:
5466 return 3; // Can fold through either operand.
5467 case Instruction::Sub: // Can only fold on the amount subtracted.
5468 case Instruction::Shl: // Can only fold on the shift amount.
5469 case Instruction::Shr:
5472 return 0; // Cannot fold
5476 /// GetSelectFoldableConstant - For the same transformation as the previous
5477 /// function, return the identity constant that goes into the select.
5478 static Constant *GetSelectFoldableConstant(Instruction *I) {
5479 switch (I->getOpcode()) {
5480 default: assert(0 && "This cannot happen!"); abort();
5481 case Instruction::Add:
5482 case Instruction::Sub:
5483 case Instruction::Or:
5484 case Instruction::Xor:
5485 return Constant::getNullValue(I->getType());
5486 case Instruction::Shl:
5487 case Instruction::Shr:
5488 return Constant::getNullValue(Type::UByteTy);
5489 case Instruction::And:
5490 return ConstantInt::getAllOnesValue(I->getType());
5491 case Instruction::Mul:
5492 return ConstantInt::get(I->getType(), 1);
5496 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5497 /// have the same opcode and only one use each. Try to simplify this.
5498 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5500 if (TI->getNumOperands() == 1) {
5501 // If this is a non-volatile load or a cast from the same type,
5503 if (TI->getOpcode() == Instruction::Cast) {
5504 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5507 return 0; // unknown unary op.
5510 // Fold this by inserting a select from the input values.
5511 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5512 FI->getOperand(0), SI.getName()+".v");
5513 InsertNewInstBefore(NewSI, SI);
5514 return new CastInst(NewSI, TI->getType());
5517 // Only handle binary operators here.
5518 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5521 // Figure out if the operations have any operands in common.
5522 Value *MatchOp, *OtherOpT, *OtherOpF;
5524 if (TI->getOperand(0) == FI->getOperand(0)) {
5525 MatchOp = TI->getOperand(0);
5526 OtherOpT = TI->getOperand(1);
5527 OtherOpF = FI->getOperand(1);
5528 MatchIsOpZero = true;
5529 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5530 MatchOp = TI->getOperand(1);
5531 OtherOpT = TI->getOperand(0);
5532 OtherOpF = FI->getOperand(0);
5533 MatchIsOpZero = false;
5534 } else if (!TI->isCommutative()) {
5536 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5537 MatchOp = TI->getOperand(0);
5538 OtherOpT = TI->getOperand(1);
5539 OtherOpF = FI->getOperand(0);
5540 MatchIsOpZero = true;
5541 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5542 MatchOp = TI->getOperand(1);
5543 OtherOpT = TI->getOperand(0);
5544 OtherOpF = FI->getOperand(1);
5545 MatchIsOpZero = true;
5550 // If we reach here, they do have operations in common.
5551 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5552 OtherOpF, SI.getName()+".v");
5553 InsertNewInstBefore(NewSI, SI);
5555 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5557 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5559 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5562 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5564 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5568 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
5569 Value *CondVal = SI.getCondition();
5570 Value *TrueVal = SI.getTrueValue();
5571 Value *FalseVal = SI.getFalseValue();
5573 // select true, X, Y -> X
5574 // select false, X, Y -> Y
5575 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
5576 if (C == ConstantBool::True)
5577 return ReplaceInstUsesWith(SI, TrueVal);
5579 assert(C == ConstantBool::False);
5580 return ReplaceInstUsesWith(SI, FalseVal);
5583 // select C, X, X -> X
5584 if (TrueVal == FalseVal)
5585 return ReplaceInstUsesWith(SI, TrueVal);
5587 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5588 return ReplaceInstUsesWith(SI, FalseVal);
5589 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5590 return ReplaceInstUsesWith(SI, TrueVal);
5591 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5592 if (isa<Constant>(TrueVal))
5593 return ReplaceInstUsesWith(SI, TrueVal);
5595 return ReplaceInstUsesWith(SI, FalseVal);
5598 if (SI.getType() == Type::BoolTy)
5599 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5600 if (C == ConstantBool::True) {
5601 // Change: A = select B, true, C --> A = or B, C
5602 return BinaryOperator::createOr(CondVal, FalseVal);
5604 // Change: A = select B, false, C --> A = and !B, C
5606 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5607 "not."+CondVal->getName()), SI);
5608 return BinaryOperator::createAnd(NotCond, FalseVal);
5610 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5611 if (C == ConstantBool::False) {
5612 // Change: A = select B, C, false --> A = and B, C
5613 return BinaryOperator::createAnd(CondVal, TrueVal);
5615 // Change: A = select B, C, true --> A = or !B, C
5617 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5618 "not."+CondVal->getName()), SI);
5619 return BinaryOperator::createOr(NotCond, TrueVal);
5623 // Selecting between two integer constants?
5624 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5625 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5626 // select C, 1, 0 -> cast C to int
5627 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5628 return new CastInst(CondVal, SI.getType());
5629 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5630 // select C, 0, 1 -> cast !C to int
5632 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5633 "not."+CondVal->getName()), SI);
5634 return new CastInst(NotCond, SI.getType());
5637 // If one of the constants is zero (we know they can't both be) and we
5638 // have a setcc instruction with zero, and we have an 'and' with the
5639 // non-constant value, eliminate this whole mess. This corresponds to
5640 // cases like this: ((X & 27) ? 27 : 0)
5641 if (TrueValC->isNullValue() || FalseValC->isNullValue())
5642 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition()))
5643 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
5644 cast<Constant>(IC->getOperand(1))->isNullValue())
5645 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5646 if (ICA->getOpcode() == Instruction::And &&
5647 isa<ConstantInt>(ICA->getOperand(1)) &&
5648 (ICA->getOperand(1) == TrueValC ||
5649 ICA->getOperand(1) == FalseValC) &&
5650 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5651 // Okay, now we know that everything is set up, we just don't
5652 // know whether we have a setne or seteq and whether the true or
5653 // false val is the zero.
5654 bool ShouldNotVal = !TrueValC->isNullValue();
5655 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5658 V = InsertNewInstBefore(BinaryOperator::create(
5659 Instruction::Xor, V, ICA->getOperand(1)), SI);
5660 return ReplaceInstUsesWith(SI, V);
5664 // See if we are selecting two values based on a comparison of the two values.
5665 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5666 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5667 // Transform (X == Y) ? X : Y -> Y
5668 if (SCI->getOpcode() == Instruction::SetEQ)
5669 return ReplaceInstUsesWith(SI, FalseVal);
5670 // Transform (X != Y) ? X : Y -> X
5671 if (SCI->getOpcode() == Instruction::SetNE)
5672 return ReplaceInstUsesWith(SI, TrueVal);
5673 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5675 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5676 // Transform (X == Y) ? Y : X -> X
5677 if (SCI->getOpcode() == Instruction::SetEQ)
5678 return ReplaceInstUsesWith(SI, FalseVal);
5679 // Transform (X != Y) ? Y : X -> Y
5680 if (SCI->getOpcode() == Instruction::SetNE)
5681 return ReplaceInstUsesWith(SI, TrueVal);
5682 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5686 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5687 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5688 if (TI->hasOneUse() && FI->hasOneUse()) {
5689 bool isInverse = false;
5690 Instruction *AddOp = 0, *SubOp = 0;
5692 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5693 if (TI->getOpcode() == FI->getOpcode())
5694 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5697 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5698 // even legal for FP.
5699 if (TI->getOpcode() == Instruction::Sub &&
5700 FI->getOpcode() == Instruction::Add) {
5701 AddOp = FI; SubOp = TI;
5702 } else if (FI->getOpcode() == Instruction::Sub &&
5703 TI->getOpcode() == Instruction::Add) {
5704 AddOp = TI; SubOp = FI;
5708 Value *OtherAddOp = 0;
5709 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5710 OtherAddOp = AddOp->getOperand(1);
5711 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5712 OtherAddOp = AddOp->getOperand(0);
5716 // So at this point we know we have (Y -> OtherAddOp):
5717 // select C, (add X, Y), (sub X, Z)
5718 Value *NegVal; // Compute -Z
5719 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5720 NegVal = ConstantExpr::getNeg(C);
5722 NegVal = InsertNewInstBefore(
5723 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
5726 Value *NewTrueOp = OtherAddOp;
5727 Value *NewFalseOp = NegVal;
5729 std::swap(NewTrueOp, NewFalseOp);
5730 Instruction *NewSel =
5731 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
5733 NewSel = InsertNewInstBefore(NewSel, SI);
5734 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
5739 // See if we can fold the select into one of our operands.
5740 if (SI.getType()->isInteger()) {
5741 // See the comment above GetSelectFoldableOperands for a description of the
5742 // transformation we are doing here.
5743 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5744 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5745 !isa<Constant>(FalseVal))
5746 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5747 unsigned OpToFold = 0;
5748 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5750 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5755 Constant *C = GetSelectFoldableConstant(TVI);
5756 std::string Name = TVI->getName(); TVI->setName("");
5757 Instruction *NewSel =
5758 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5760 InsertNewInstBefore(NewSel, SI);
5761 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5762 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5763 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5764 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5766 assert(0 && "Unknown instruction!!");
5771 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5772 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5773 !isa<Constant>(TrueVal))
5774 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5775 unsigned OpToFold = 0;
5776 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5778 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5783 Constant *C = GetSelectFoldableConstant(FVI);
5784 std::string Name = FVI->getName(); FVI->setName("");
5785 Instruction *NewSel =
5786 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5788 InsertNewInstBefore(NewSel, SI);
5789 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5790 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5791 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5792 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5794 assert(0 && "Unknown instruction!!");
5800 if (BinaryOperator::isNot(CondVal)) {
5801 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5802 SI.setOperand(1, FalseVal);
5803 SI.setOperand(2, TrueVal);
5810 /// GetKnownAlignment - If the specified pointer has an alignment that we can
5811 /// determine, return it, otherwise return 0.
5812 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
5813 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
5814 unsigned Align = GV->getAlignment();
5815 if (Align == 0 && TD)
5816 Align = TD->getTypeAlignment(GV->getType()->getElementType());
5818 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
5819 unsigned Align = AI->getAlignment();
5820 if (Align == 0 && TD) {
5821 if (isa<AllocaInst>(AI))
5822 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5823 else if (isa<MallocInst>(AI)) {
5824 // Malloc returns maximally aligned memory.
5825 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5826 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
5827 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
5831 } else if (isa<CastInst>(V) ||
5832 (isa<ConstantExpr>(V) &&
5833 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
5834 User *CI = cast<User>(V);
5835 if (isa<PointerType>(CI->getOperand(0)->getType()))
5836 return GetKnownAlignment(CI->getOperand(0), TD);
5838 } else if (isa<GetElementPtrInst>(V) ||
5839 (isa<ConstantExpr>(V) &&
5840 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
5841 User *GEPI = cast<User>(V);
5842 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
5843 if (BaseAlignment == 0) return 0;
5845 // If all indexes are zero, it is just the alignment of the base pointer.
5846 bool AllZeroOperands = true;
5847 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
5848 if (!isa<Constant>(GEPI->getOperand(i)) ||
5849 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
5850 AllZeroOperands = false;
5853 if (AllZeroOperands)
5854 return BaseAlignment;
5856 // Otherwise, if the base alignment is >= the alignment we expect for the
5857 // base pointer type, then we know that the resultant pointer is aligned at
5858 // least as much as its type requires.
5861 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
5862 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
5864 const Type *GEPTy = GEPI->getType();
5865 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
5873 /// visitCallInst - CallInst simplification. This mostly only handles folding
5874 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5875 /// the heavy lifting.
5877 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
5878 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5879 if (!II) return visitCallSite(&CI);
5881 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5883 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
5884 bool Changed = false;
5886 // memmove/cpy/set of zero bytes is a noop.
5887 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5888 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5890 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
5891 if (CI->getRawValue() == 1) {
5892 // Replace the instruction with just byte operations. We would
5893 // transform other cases to loads/stores, but we don't know if
5894 // alignment is sufficient.
5898 // If we have a memmove and the source operation is a constant global,
5899 // then the source and dest pointers can't alias, so we can change this
5900 // into a call to memcpy.
5901 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
5902 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5903 if (GVSrc->isConstant()) {
5904 Module *M = CI.getParent()->getParent()->getParent();
5906 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
5908 Name = "llvm.memcpy.i32";
5910 Name = "llvm.memcpy.i64";
5911 Function *MemCpy = M->getOrInsertFunction(Name,
5912 CI.getCalledFunction()->getFunctionType());
5913 CI.setOperand(0, MemCpy);
5918 // If we can determine a pointer alignment that is bigger than currently
5919 // set, update the alignment.
5920 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
5921 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
5922 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
5923 unsigned Align = std::min(Alignment1, Alignment2);
5924 if (MI->getAlignment()->getRawValue() < Align) {
5925 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Align));
5928 } else if (isa<MemSetInst>(MI)) {
5929 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
5930 if (MI->getAlignment()->getRawValue() < Alignment) {
5931 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Alignment));
5936 if (Changed) return II;
5938 switch (II->getIntrinsicID()) {
5940 case Intrinsic::ppc_altivec_lvx:
5941 case Intrinsic::ppc_altivec_lvxl:
5942 case Intrinsic::x86_sse_loadu_ps:
5943 case Intrinsic::x86_sse2_loadu_pd:
5944 case Intrinsic::x86_sse2_loadu_dq:
5945 // Turn PPC lvx -> load if the pointer is known aligned.
5946 // Turn X86 loadups -> load if the pointer is known aligned.
5947 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
5948 Value *Ptr = InsertCastBefore(II->getOperand(1),
5949 PointerType::get(II->getType()), CI);
5950 return new LoadInst(Ptr);
5953 case Intrinsic::ppc_altivec_stvx:
5954 case Intrinsic::ppc_altivec_stvxl:
5955 // Turn stvx -> store if the pointer is known aligned.
5956 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
5957 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
5958 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
5959 return new StoreInst(II->getOperand(1), Ptr);
5962 case Intrinsic::x86_sse_storeu_ps:
5963 case Intrinsic::x86_sse2_storeu_pd:
5964 case Intrinsic::x86_sse2_storeu_dq:
5965 case Intrinsic::x86_sse2_storel_dq:
5966 // Turn X86 storeu -> store if the pointer is known aligned.
5967 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
5968 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
5969 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
5970 return new StoreInst(II->getOperand(2), Ptr);
5973 case Intrinsic::ppc_altivec_vperm:
5974 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
5975 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
5976 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
5978 // Check that all of the elements are integer constants or undefs.
5979 bool AllEltsOk = true;
5980 for (unsigned i = 0; i != 16; ++i) {
5981 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
5982 !isa<UndefValue>(Mask->getOperand(i))) {
5989 // Cast the input vectors to byte vectors.
5990 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
5991 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
5992 Value *Result = UndefValue::get(Op0->getType());
5994 // Only extract each element once.
5995 Value *ExtractedElts[32];
5996 memset(ExtractedElts, 0, sizeof(ExtractedElts));
5998 for (unsigned i = 0; i != 16; ++i) {
5999 if (isa<UndefValue>(Mask->getOperand(i)))
6001 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getRawValue();
6002 Idx &= 31; // Match the hardware behavior.
6004 if (ExtractedElts[Idx] == 0) {
6006 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
6007 ConstantUInt::get(Type::UIntTy, Idx&15),
6009 InsertNewInstBefore(Elt, CI);
6010 ExtractedElts[Idx] = Elt;
6013 // Insert this value into the result vector.
6014 Result = new InsertElementInst(Result, ExtractedElts[Idx],
6015 ConstantUInt::get(Type::UIntTy, i),
6017 InsertNewInstBefore(cast<Instruction>(Result), CI);
6019 return new CastInst(Result, CI.getType());
6024 case Intrinsic::stackrestore: {
6025 // If the save is right next to the restore, remove the restore. This can
6026 // happen when variable allocas are DCE'd.
6027 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6028 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6029 BasicBlock::iterator BI = SS;
6031 return EraseInstFromFunction(CI);
6035 // If the stack restore is in a return/unwind block and if there are no
6036 // allocas or calls between the restore and the return, nuke the restore.
6037 TerminatorInst *TI = II->getParent()->getTerminator();
6038 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6039 BasicBlock::iterator BI = II;
6040 bool CannotRemove = false;
6041 for (++BI; &*BI != TI; ++BI) {
6042 if (isa<AllocaInst>(BI) ||
6043 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6044 CannotRemove = true;
6049 return EraseInstFromFunction(CI);
6056 return visitCallSite(II);
6059 // InvokeInst simplification
6061 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
6062 return visitCallSite(&II);
6065 // visitCallSite - Improvements for call and invoke instructions.
6067 Instruction *InstCombiner::visitCallSite(CallSite CS) {
6068 bool Changed = false;
6070 // If the callee is a constexpr cast of a function, attempt to move the cast
6071 // to the arguments of the call/invoke.
6072 if (transformConstExprCastCall(CS)) return 0;
6074 Value *Callee = CS.getCalledValue();
6076 if (Function *CalleeF = dyn_cast<Function>(Callee))
6077 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6078 Instruction *OldCall = CS.getInstruction();
6079 // If the call and callee calling conventions don't match, this call must
6080 // be unreachable, as the call is undefined.
6081 new StoreInst(ConstantBool::True,
6082 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6083 if (!OldCall->use_empty())
6084 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6085 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6086 return EraseInstFromFunction(*OldCall);
6090 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6091 // This instruction is not reachable, just remove it. We insert a store to
6092 // undef so that we know that this code is not reachable, despite the fact
6093 // that we can't modify the CFG here.
6094 new StoreInst(ConstantBool::True,
6095 UndefValue::get(PointerType::get(Type::BoolTy)),
6096 CS.getInstruction());
6098 if (!CS.getInstruction()->use_empty())
6099 CS.getInstruction()->
6100 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6102 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6103 // Don't break the CFG, insert a dummy cond branch.
6104 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
6105 ConstantBool::True, II);
6107 return EraseInstFromFunction(*CS.getInstruction());
6110 const PointerType *PTy = cast<PointerType>(Callee->getType());
6111 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6112 if (FTy->isVarArg()) {
6113 // See if we can optimize any arguments passed through the varargs area of
6115 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6116 E = CS.arg_end(); I != E; ++I)
6117 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6118 // If this cast does not effect the value passed through the varargs
6119 // area, we can eliminate the use of the cast.
6120 Value *Op = CI->getOperand(0);
6121 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6128 return Changed ? CS.getInstruction() : 0;
6131 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
6132 // attempt to move the cast to the arguments of the call/invoke.
6134 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6135 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6136 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
6137 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
6139 Function *Callee = cast<Function>(CE->getOperand(0));
6140 Instruction *Caller = CS.getInstruction();
6142 // Okay, this is a cast from a function to a different type. Unless doing so
6143 // would cause a type conversion of one of our arguments, change this call to
6144 // be a direct call with arguments casted to the appropriate types.
6146 const FunctionType *FT = Callee->getFunctionType();
6147 const Type *OldRetTy = Caller->getType();
6149 // Check to see if we are changing the return type...
6150 if (OldRetTy != FT->getReturnType()) {
6151 if (Callee->isExternal() &&
6152 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6153 (isa<PointerType>(FT->getReturnType()) &&
6154 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
6155 && !Caller->use_empty())
6156 return false; // Cannot transform this return value...
6158 // If the callsite is an invoke instruction, and the return value is used by
6159 // a PHI node in a successor, we cannot change the return type of the call
6160 // because there is no place to put the cast instruction (without breaking
6161 // the critical edge). Bail out in this case.
6162 if (!Caller->use_empty())
6163 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6164 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6166 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6167 if (PN->getParent() == II->getNormalDest() ||
6168 PN->getParent() == II->getUnwindDest())
6172 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6173 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
6175 CallSite::arg_iterator AI = CS.arg_begin();
6176 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6177 const Type *ParamTy = FT->getParamType(i);
6178 const Type *ActTy = (*AI)->getType();
6179 ConstantSInt* c = dyn_cast<ConstantSInt>(*AI);
6180 //Either we can cast directly, or we can upconvert the argument
6181 bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6182 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6183 ParamTy->isSigned() == ActTy->isSigned() &&
6184 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6185 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
6187 if (Callee->isExternal() && !isConvertible) return false;
6190 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6191 Callee->isExternal())
6192 return false; // Do not delete arguments unless we have a function body...
6194 // Okay, we decided that this is a safe thing to do: go ahead and start
6195 // inserting cast instructions as necessary...
6196 std::vector<Value*> Args;
6197 Args.reserve(NumActualArgs);
6199 AI = CS.arg_begin();
6200 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6201 const Type *ParamTy = FT->getParamType(i);
6202 if ((*AI)->getType() == ParamTy) {
6203 Args.push_back(*AI);
6205 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6210 // If the function takes more arguments than the call was taking, add them
6212 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6213 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6215 // If we are removing arguments to the function, emit an obnoxious warning...
6216 if (FT->getNumParams() < NumActualArgs)
6217 if (!FT->isVarArg()) {
6218 std::cerr << "WARNING: While resolving call to function '"
6219 << Callee->getName() << "' arguments were dropped!\n";
6221 // Add all of the arguments in their promoted form to the arg list...
6222 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6223 const Type *PTy = getPromotedType((*AI)->getType());
6224 if (PTy != (*AI)->getType()) {
6225 // Must promote to pass through va_arg area!
6226 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6227 InsertNewInstBefore(Cast, *Caller);
6228 Args.push_back(Cast);
6230 Args.push_back(*AI);
6235 if (FT->getReturnType() == Type::VoidTy)
6236 Caller->setName(""); // Void type should not have a name...
6239 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6240 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
6241 Args, Caller->getName(), Caller);
6242 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
6244 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
6245 if (cast<CallInst>(Caller)->isTailCall())
6246 cast<CallInst>(NC)->setTailCall();
6247 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
6250 // Insert a cast of the return type as necessary...
6252 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6253 if (NV->getType() != Type::VoidTy) {
6254 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
6256 // If this is an invoke instruction, we should insert it after the first
6257 // non-phi, instruction in the normal successor block.
6258 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6259 BasicBlock::iterator I = II->getNormalDest()->begin();
6260 while (isa<PHINode>(I)) ++I;
6261 InsertNewInstBefore(NC, *I);
6263 // Otherwise, it's a call, just insert cast right after the call instr
6264 InsertNewInstBefore(NC, *Caller);
6266 AddUsersToWorkList(*Caller);
6268 NV = UndefValue::get(Caller->getType());
6272 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6273 Caller->replaceAllUsesWith(NV);
6274 Caller->getParent()->getInstList().erase(Caller);
6275 removeFromWorkList(Caller);
6280 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6281 // operator and they all are only used by the PHI, PHI together their
6282 // inputs, and do the operation once, to the result of the PHI.
6283 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6284 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6286 // Scan the instruction, looking for input operations that can be folded away.
6287 // If all input operands to the phi are the same instruction (e.g. a cast from
6288 // the same type or "+42") we can pull the operation through the PHI, reducing
6289 // code size and simplifying code.
6290 Constant *ConstantOp = 0;
6291 const Type *CastSrcTy = 0;
6292 if (isa<CastInst>(FirstInst)) {
6293 CastSrcTy = FirstInst->getOperand(0)->getType();
6294 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
6295 // Can fold binop or shift if the RHS is a constant.
6296 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
6297 if (ConstantOp == 0) return 0;
6299 return 0; // Cannot fold this operation.
6302 // Check to see if all arguments are the same operation.
6303 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6304 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6305 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6306 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6309 if (I->getOperand(0)->getType() != CastSrcTy)
6310 return 0; // Cast operation must match.
6311 } else if (I->getOperand(1) != ConstantOp) {
6316 // Okay, they are all the same operation. Create a new PHI node of the
6317 // correct type, and PHI together all of the LHS's of the instructions.
6318 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
6319 PN.getName()+".in");
6320 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
6322 Value *InVal = FirstInst->getOperand(0);
6323 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
6325 // Add all operands to the new PHI.
6326 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6327 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6328 if (NewInVal != InVal)
6330 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6335 // The new PHI unions all of the same values together. This is really
6336 // common, so we handle it intelligently here for compile-time speed.
6340 InsertNewInstBefore(NewPN, PN);
6344 // Insert and return the new operation.
6345 if (isa<CastInst>(FirstInst))
6346 return new CastInst(PhiVal, PN.getType());
6347 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
6348 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
6350 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
6351 PhiVal, ConstantOp);
6354 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6356 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
6357 if (PN->use_empty()) return true;
6358 if (!PN->hasOneUse()) return false;
6360 // Remember this node, and if we find the cycle, return.
6361 if (!PotentiallyDeadPHIs.insert(PN).second)
6364 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6365 return DeadPHICycle(PU, PotentiallyDeadPHIs);
6370 // PHINode simplification
6372 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
6373 // If LCSSA is around, don't mess with Phi nodes
6374 if (mustPreserveAnalysisID(LCSSAID)) return 0;
6376 if (Value *V = PN.hasConstantValue())
6377 return ReplaceInstUsesWith(PN, V);
6379 // If the only user of this instruction is a cast instruction, and all of the
6380 // incoming values are constants, change this PHI to merge together the casted
6383 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
6384 if (CI->getType() != PN.getType()) { // noop casts will be folded
6385 bool AllConstant = true;
6386 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
6387 if (!isa<Constant>(PN.getIncomingValue(i))) {
6388 AllConstant = false;
6392 // Make a new PHI with all casted values.
6393 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
6394 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
6395 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
6396 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
6397 PN.getIncomingBlock(i));
6400 // Update the cast instruction.
6401 CI->setOperand(0, New);
6402 WorkList.push_back(CI); // revisit the cast instruction to fold.
6403 WorkList.push_back(New); // Make sure to revisit the new Phi
6404 return &PN; // PN is now dead!
6408 // If all PHI operands are the same operation, pull them through the PHI,
6409 // reducing code size.
6410 if (isa<Instruction>(PN.getIncomingValue(0)) &&
6411 PN.getIncomingValue(0)->hasOneUse())
6412 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
6415 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
6416 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
6417 // PHI)... break the cycle.
6419 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
6420 std::set<PHINode*> PotentiallyDeadPHIs;
6421 PotentiallyDeadPHIs.insert(&PN);
6422 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
6423 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
6429 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
6430 Instruction *InsertPoint,
6432 unsigned PS = IC->getTargetData().getPointerSize();
6433 const Type *VTy = V->getType();
6434 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
6435 // We must insert a cast to ensure we sign-extend.
6436 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
6437 V->getName()), *InsertPoint);
6438 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
6443 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
6444 Value *PtrOp = GEP.getOperand(0);
6445 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
6446 // If so, eliminate the noop.
6447 if (GEP.getNumOperands() == 1)
6448 return ReplaceInstUsesWith(GEP, PtrOp);
6450 if (isa<UndefValue>(GEP.getOperand(0)))
6451 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
6453 bool HasZeroPointerIndex = false;
6454 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
6455 HasZeroPointerIndex = C->isNullValue();
6457 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
6458 return ReplaceInstUsesWith(GEP, PtrOp);
6460 // Eliminate unneeded casts for indices.
6461 bool MadeChange = false;
6462 gep_type_iterator GTI = gep_type_begin(GEP);
6463 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
6464 if (isa<SequentialType>(*GTI)) {
6465 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
6466 Value *Src = CI->getOperand(0);
6467 const Type *SrcTy = Src->getType();
6468 const Type *DestTy = CI->getType();
6469 if (Src->getType()->isInteger()) {
6470 if (SrcTy->getPrimitiveSizeInBits() ==
6471 DestTy->getPrimitiveSizeInBits()) {
6472 // We can always eliminate a cast from ulong or long to the other.
6473 // We can always eliminate a cast from uint to int or the other on
6474 // 32-bit pointer platforms.
6475 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
6477 GEP.setOperand(i, Src);
6479 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
6480 SrcTy->getPrimitiveSize() == 4) {
6481 // We can always eliminate a cast from int to [u]long. We can
6482 // eliminate a cast from uint to [u]long iff the target is a 32-bit
6484 if (SrcTy->isSigned() ||
6485 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
6487 GEP.setOperand(i, Src);
6492 // If we are using a wider index than needed for this platform, shrink it
6493 // to what we need. If the incoming value needs a cast instruction,
6494 // insert it. This explicit cast can make subsequent optimizations more
6496 Value *Op = GEP.getOperand(i);
6497 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
6498 if (Constant *C = dyn_cast<Constant>(Op)) {
6499 GEP.setOperand(i, ConstantExpr::getCast(C,
6500 TD->getIntPtrType()->getSignedVersion()));
6503 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
6504 Op->getName()), GEP);
6505 GEP.setOperand(i, Op);
6509 // If this is a constant idx, make sure to canonicalize it to be a signed
6510 // operand, otherwise CSE and other optimizations are pessimized.
6511 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
6512 GEP.setOperand(i, ConstantExpr::getCast(CUI,
6513 CUI->getType()->getSignedVersion()));
6517 if (MadeChange) return &GEP;
6519 // Combine Indices - If the source pointer to this getelementptr instruction
6520 // is a getelementptr instruction, combine the indices of the two
6521 // getelementptr instructions into a single instruction.
6523 std::vector<Value*> SrcGEPOperands;
6524 if (User *Src = dyn_castGetElementPtr(PtrOp))
6525 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
6527 if (!SrcGEPOperands.empty()) {
6528 // Note that if our source is a gep chain itself that we wait for that
6529 // chain to be resolved before we perform this transformation. This
6530 // avoids us creating a TON of code in some cases.
6532 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
6533 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
6534 return 0; // Wait until our source is folded to completion.
6536 std::vector<Value *> Indices;
6538 // Find out whether the last index in the source GEP is a sequential idx.
6539 bool EndsWithSequential = false;
6540 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
6541 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
6542 EndsWithSequential = !isa<StructType>(*I);
6544 // Can we combine the two pointer arithmetics offsets?
6545 if (EndsWithSequential) {
6546 // Replace: gep (gep %P, long B), long A, ...
6547 // With: T = long A+B; gep %P, T, ...
6549 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
6550 if (SO1 == Constant::getNullValue(SO1->getType())) {
6552 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
6555 // If they aren't the same type, convert both to an integer of the
6556 // target's pointer size.
6557 if (SO1->getType() != GO1->getType()) {
6558 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
6559 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
6560 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
6561 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
6563 unsigned PS = TD->getPointerSize();
6564 if (SO1->getType()->getPrimitiveSize() == PS) {
6565 // Convert GO1 to SO1's type.
6566 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
6568 } else if (GO1->getType()->getPrimitiveSize() == PS) {
6569 // Convert SO1 to GO1's type.
6570 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6572 const Type *PT = TD->getIntPtrType();
6573 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6574 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6578 if (isa<Constant>(SO1) && isa<Constant>(GO1))
6579 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6581 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6582 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
6586 // Recycle the GEP we already have if possible.
6587 if (SrcGEPOperands.size() == 2) {
6588 GEP.setOperand(0, SrcGEPOperands[0]);
6589 GEP.setOperand(1, Sum);
6592 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6593 SrcGEPOperands.end()-1);
6594 Indices.push_back(Sum);
6595 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
6597 } else if (isa<Constant>(*GEP.idx_begin()) &&
6598 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
6599 SrcGEPOperands.size() != 1) {
6600 // Otherwise we can do the fold if the first index of the GEP is a zero
6601 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6602 SrcGEPOperands.end());
6603 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
6606 if (!Indices.empty())
6607 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
6609 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
6610 // GEP of global variable. If all of the indices for this GEP are
6611 // constants, we can promote this to a constexpr instead of an instruction.
6613 // Scan for nonconstants...
6614 std::vector<Constant*> Indices;
6615 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
6616 for (; I != E && isa<Constant>(*I); ++I)
6617 Indices.push_back(cast<Constant>(*I));
6619 if (I == E) { // If they are all constants...
6620 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
6622 // Replace all uses of the GEP with the new constexpr...
6623 return ReplaceInstUsesWith(GEP, CE);
6625 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
6626 if (!isa<PointerType>(X->getType())) {
6627 // Not interesting. Source pointer must be a cast from pointer.
6628 } else if (HasZeroPointerIndex) {
6629 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
6630 // into : GEP [10 x ubyte]* X, long 0, ...
6632 // This occurs when the program declares an array extern like "int X[];"
6634 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
6635 const PointerType *XTy = cast<PointerType>(X->getType());
6636 if (const ArrayType *XATy =
6637 dyn_cast<ArrayType>(XTy->getElementType()))
6638 if (const ArrayType *CATy =
6639 dyn_cast<ArrayType>(CPTy->getElementType()))
6640 if (CATy->getElementType() == XATy->getElementType()) {
6641 // At this point, we know that the cast source type is a pointer
6642 // to an array of the same type as the destination pointer
6643 // array. Because the array type is never stepped over (there
6644 // is a leading zero) we can fold the cast into this GEP.
6645 GEP.setOperand(0, X);
6648 } else if (GEP.getNumOperands() == 2) {
6649 // Transform things like:
6650 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
6651 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
6652 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
6653 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
6654 if (isa<ArrayType>(SrcElTy) &&
6655 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
6656 TD->getTypeSize(ResElTy)) {
6657 Value *V = InsertNewInstBefore(
6658 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6659 GEP.getOperand(1), GEP.getName()), GEP);
6660 return new CastInst(V, GEP.getType());
6663 // Transform things like:
6664 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
6665 // (where tmp = 8*tmp2) into:
6666 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
6668 if (isa<ArrayType>(SrcElTy) &&
6669 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
6670 uint64_t ArrayEltSize =
6671 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
6673 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
6674 // allow either a mul, shift, or constant here.
6676 ConstantInt *Scale = 0;
6677 if (ArrayEltSize == 1) {
6678 NewIdx = GEP.getOperand(1);
6679 Scale = ConstantInt::get(NewIdx->getType(), 1);
6680 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
6681 NewIdx = ConstantInt::get(CI->getType(), 1);
6683 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
6684 if (Inst->getOpcode() == Instruction::Shl &&
6685 isa<ConstantInt>(Inst->getOperand(1))) {
6686 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
6687 if (Inst->getType()->isSigned())
6688 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
6690 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
6691 NewIdx = Inst->getOperand(0);
6692 } else if (Inst->getOpcode() == Instruction::Mul &&
6693 isa<ConstantInt>(Inst->getOperand(1))) {
6694 Scale = cast<ConstantInt>(Inst->getOperand(1));
6695 NewIdx = Inst->getOperand(0);
6699 // If the index will be to exactly the right offset with the scale taken
6700 // out, perform the transformation.
6701 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
6702 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
6703 Scale = ConstantSInt::get(C->getType(),
6704 (int64_t)C->getRawValue() /
6705 (int64_t)ArrayEltSize);
6707 Scale = ConstantUInt::get(Scale->getType(),
6708 Scale->getRawValue() / ArrayEltSize);
6709 if (Scale->getRawValue() != 1) {
6710 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
6711 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
6712 NewIdx = InsertNewInstBefore(Sc, GEP);
6715 // Insert the new GEP instruction.
6717 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6718 NewIdx, GEP.getName());
6719 Idx = InsertNewInstBefore(Idx, GEP);
6720 return new CastInst(Idx, GEP.getType());
6729 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
6730 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
6731 if (AI.isArrayAllocation()) // Check C != 1
6732 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
6733 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
6734 AllocationInst *New = 0;
6736 // Create and insert the replacement instruction...
6737 if (isa<MallocInst>(AI))
6738 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
6740 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
6741 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
6744 InsertNewInstBefore(New, AI);
6746 // Scan to the end of the allocation instructions, to skip over a block of
6747 // allocas if possible...
6749 BasicBlock::iterator It = New;
6750 while (isa<AllocationInst>(*It)) ++It;
6752 // Now that I is pointing to the first non-allocation-inst in the block,
6753 // insert our getelementptr instruction...
6755 Value *NullIdx = Constant::getNullValue(Type::IntTy);
6756 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
6757 New->getName()+".sub", It);
6759 // Now make everything use the getelementptr instead of the original
6761 return ReplaceInstUsesWith(AI, V);
6762 } else if (isa<UndefValue>(AI.getArraySize())) {
6763 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6766 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
6767 // Note that we only do this for alloca's, because malloc should allocate and
6768 // return a unique pointer, even for a zero byte allocation.
6769 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
6770 TD->getTypeSize(AI.getAllocatedType()) == 0)
6771 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6776 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6777 Value *Op = FI.getOperand(0);
6779 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6780 if (CastInst *CI = dyn_cast<CastInst>(Op))
6781 if (isa<PointerType>(CI->getOperand(0)->getType())) {
6782 FI.setOperand(0, CI->getOperand(0));
6786 // free undef -> unreachable.
6787 if (isa<UndefValue>(Op)) {
6788 // Insert a new store to null because we cannot modify the CFG here.
6789 new StoreInst(ConstantBool::True,
6790 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6791 return EraseInstFromFunction(FI);
6794 // If we have 'free null' delete the instruction. This can happen in stl code
6795 // when lots of inlining happens.
6796 if (isa<ConstantPointerNull>(Op))
6797 return EraseInstFromFunction(FI);
6803 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
6804 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6805 User *CI = cast<User>(LI.getOperand(0));
6806 Value *CastOp = CI->getOperand(0);
6808 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6809 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6810 const Type *SrcPTy = SrcTy->getElementType();
6812 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
6813 isa<PackedType>(DestPTy)) {
6814 // If the source is an array, the code below will not succeed. Check to
6815 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6817 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6818 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6819 if (ASrcTy->getNumElements() != 0) {
6820 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6821 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6822 SrcTy = cast<PointerType>(CastOp->getType());
6823 SrcPTy = SrcTy->getElementType();
6826 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
6827 isa<PackedType>(SrcPTy)) &&
6828 // Do not allow turning this into a load of an integer, which is then
6829 // casted to a pointer, this pessimizes pointer analysis a lot.
6830 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
6831 IC.getTargetData().getTypeSize(SrcPTy) ==
6832 IC.getTargetData().getTypeSize(DestPTy)) {
6834 // Okay, we are casting from one integer or pointer type to another of
6835 // the same size. Instead of casting the pointer before the load, cast
6836 // the result of the loaded value.
6837 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6839 LI.isVolatile()),LI);
6840 // Now cast the result of the load.
6841 return new CastInst(NewLoad, LI.getType());
6848 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
6849 /// from this value cannot trap. If it is not obviously safe to load from the
6850 /// specified pointer, we do a quick local scan of the basic block containing
6851 /// ScanFrom, to determine if the address is already accessed.
6852 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6853 // If it is an alloca or global variable, it is always safe to load from.
6854 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6856 // Otherwise, be a little bit agressive by scanning the local block where we
6857 // want to check to see if the pointer is already being loaded or stored
6858 // from/to. If so, the previous load or store would have already trapped,
6859 // so there is no harm doing an extra load (also, CSE will later eliminate
6860 // the load entirely).
6861 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6866 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6867 if (LI->getOperand(0) == V) return true;
6868 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6869 if (SI->getOperand(1) == V) return true;
6875 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6876 Value *Op = LI.getOperand(0);
6878 // load (cast X) --> cast (load X) iff safe
6879 if (CastInst *CI = dyn_cast<CastInst>(Op))
6880 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6883 // None of the following transforms are legal for volatile loads.
6884 if (LI.isVolatile()) return 0;
6886 if (&LI.getParent()->front() != &LI) {
6887 BasicBlock::iterator BBI = &LI; --BBI;
6888 // If the instruction immediately before this is a store to the same
6889 // address, do a simple form of store->load forwarding.
6890 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6891 if (SI->getOperand(1) == LI.getOperand(0))
6892 return ReplaceInstUsesWith(LI, SI->getOperand(0));
6893 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
6894 if (LIB->getOperand(0) == LI.getOperand(0))
6895 return ReplaceInstUsesWith(LI, LIB);
6898 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
6899 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
6900 isa<UndefValue>(GEPI->getOperand(0))) {
6901 // Insert a new store to null instruction before the load to indicate
6902 // that this code is not reachable. We do this instead of inserting
6903 // an unreachable instruction directly because we cannot modify the
6905 new StoreInst(UndefValue::get(LI.getType()),
6906 Constant::getNullValue(Op->getType()), &LI);
6907 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6910 if (Constant *C = dyn_cast<Constant>(Op)) {
6911 // load null/undef -> undef
6912 if ((C->isNullValue() || isa<UndefValue>(C))) {
6913 // Insert a new store to null instruction before the load to indicate that
6914 // this code is not reachable. We do this instead of inserting an
6915 // unreachable instruction directly because we cannot modify the CFG.
6916 new StoreInst(UndefValue::get(LI.getType()),
6917 Constant::getNullValue(Op->getType()), &LI);
6918 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6921 // Instcombine load (constant global) into the value loaded.
6922 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
6923 if (GV->isConstant() && !GV->isExternal())
6924 return ReplaceInstUsesWith(LI, GV->getInitializer());
6926 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
6927 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
6928 if (CE->getOpcode() == Instruction::GetElementPtr) {
6929 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
6930 if (GV->isConstant() && !GV->isExternal())
6932 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
6933 return ReplaceInstUsesWith(LI, V);
6934 if (CE->getOperand(0)->isNullValue()) {
6935 // Insert a new store to null instruction before the load to indicate
6936 // that this code is not reachable. We do this instead of inserting
6937 // an unreachable instruction directly because we cannot modify the
6939 new StoreInst(UndefValue::get(LI.getType()),
6940 Constant::getNullValue(Op->getType()), &LI);
6941 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6944 } else if (CE->getOpcode() == Instruction::Cast) {
6945 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6950 if (Op->hasOneUse()) {
6951 // Change select and PHI nodes to select values instead of addresses: this
6952 // helps alias analysis out a lot, allows many others simplifications, and
6953 // exposes redundancy in the code.
6955 // Note that we cannot do the transformation unless we know that the
6956 // introduced loads cannot trap! Something like this is valid as long as
6957 // the condition is always false: load (select bool %C, int* null, int* %G),
6958 // but it would not be valid if we transformed it to load from null
6961 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
6962 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
6963 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
6964 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
6965 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
6966 SI->getOperand(1)->getName()+".val"), LI);
6967 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
6968 SI->getOperand(2)->getName()+".val"), LI);
6969 return new SelectInst(SI->getCondition(), V1, V2);
6972 // load (select (cond, null, P)) -> load P
6973 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
6974 if (C->isNullValue()) {
6975 LI.setOperand(0, SI->getOperand(2));
6979 // load (select (cond, P, null)) -> load P
6980 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
6981 if (C->isNullValue()) {
6982 LI.setOperand(0, SI->getOperand(1));
6986 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
6987 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
6988 bool Safe = PN->getParent() == LI.getParent();
6990 // Scan all of the instructions between the PHI and the load to make
6991 // sure there are no instructions that might possibly alter the value
6992 // loaded from the PHI.
6994 BasicBlock::iterator I = &LI;
6995 for (--I; !isa<PHINode>(I); --I)
6996 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
7002 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
7003 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
7004 PN->getIncomingBlock(i)->getTerminator()))
7009 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
7010 InsertNewInstBefore(NewPN, *PN);
7011 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
7013 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7014 BasicBlock *BB = PN->getIncomingBlock(i);
7015 Value *&TheLoad = LoadMap[BB];
7017 Value *InVal = PN->getIncomingValue(i);
7018 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
7019 InVal->getName()+".val"),
7020 *BB->getTerminator());
7022 NewPN->addIncoming(TheLoad, BB);
7024 return ReplaceInstUsesWith(LI, NewPN);
7031 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7033 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7034 User *CI = cast<User>(SI.getOperand(1));
7035 Value *CastOp = CI->getOperand(0);
7037 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7038 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7039 const Type *SrcPTy = SrcTy->getElementType();
7041 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7042 // If the source is an array, the code below will not succeed. Check to
7043 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7045 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7046 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7047 if (ASrcTy->getNumElements() != 0) {
7048 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7049 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7050 SrcTy = cast<PointerType>(CastOp->getType());
7051 SrcPTy = SrcTy->getElementType();
7054 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
7055 IC.getTargetData().getTypeSize(SrcPTy) ==
7056 IC.getTargetData().getTypeSize(DestPTy)) {
7058 // Okay, we are casting from one integer or pointer type to another of
7059 // the same size. Instead of casting the pointer before the store, cast
7060 // the value to be stored.
7062 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7063 NewCast = ConstantExpr::getCast(C, SrcPTy);
7065 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
7067 SI.getOperand(0)->getName()+".c"), SI);
7069 return new StoreInst(NewCast, CastOp);
7076 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7077 Value *Val = SI.getOperand(0);
7078 Value *Ptr = SI.getOperand(1);
7080 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
7081 EraseInstFromFunction(SI);
7086 // Do really simple DSE, to catch cases where there are several consequtive
7087 // stores to the same location, separated by a few arithmetic operations. This
7088 // situation often occurs with bitfield accesses.
7089 BasicBlock::iterator BBI = &SI;
7090 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7094 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7095 // Prev store isn't volatile, and stores to the same location?
7096 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7099 EraseInstFromFunction(*PrevSI);
7105 // If this is a load, we have to stop. However, if the loaded value is from
7106 // the pointer we're loading and is producing the pointer we're storing,
7107 // then *this* store is dead (X = load P; store X -> P).
7108 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7109 if (LI == Val && LI->getOperand(0) == Ptr) {
7110 EraseInstFromFunction(SI);
7114 // Otherwise, this is a load from some other location. Stores before it
7119 // Don't skip over loads or things that can modify memory.
7120 if (BBI->mayWriteToMemory())
7125 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
7127 // store X, null -> turns into 'unreachable' in SimplifyCFG
7128 if (isa<ConstantPointerNull>(Ptr)) {
7129 if (!isa<UndefValue>(Val)) {
7130 SI.setOperand(0, UndefValue::get(Val->getType()));
7131 if (Instruction *U = dyn_cast<Instruction>(Val))
7132 WorkList.push_back(U); // Dropped a use.
7135 return 0; // Do not modify these!
7138 // store undef, Ptr -> noop
7139 if (isa<UndefValue>(Val)) {
7140 EraseInstFromFunction(SI);
7145 // If the pointer destination is a cast, see if we can fold the cast into the
7147 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
7148 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7150 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7151 if (CE->getOpcode() == Instruction::Cast)
7152 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7156 // If this store is the last instruction in the basic block, and if the block
7157 // ends with an unconditional branch, try to move it to the successor block.
7159 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7160 if (BI->isUnconditional()) {
7161 // Check to see if the successor block has exactly two incoming edges. If
7162 // so, see if the other predecessor contains a store to the same location.
7163 // if so, insert a PHI node (if needed) and move the stores down.
7164 BasicBlock *Dest = BI->getSuccessor(0);
7166 pred_iterator PI = pred_begin(Dest);
7167 BasicBlock *Other = 0;
7168 if (*PI != BI->getParent())
7171 if (PI != pred_end(Dest)) {
7172 if (*PI != BI->getParent())
7177 if (++PI != pred_end(Dest))
7180 if (Other) { // If only one other pred...
7181 BBI = Other->getTerminator();
7182 // Make sure this other block ends in an unconditional branch and that
7183 // there is an instruction before the branch.
7184 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7185 BBI != Other->begin()) {
7187 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7189 // If this instruction is a store to the same location.
7190 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7191 // Okay, we know we can perform this transformation. Insert a PHI
7192 // node now if we need it.
7193 Value *MergedVal = OtherStore->getOperand(0);
7194 if (MergedVal != SI.getOperand(0)) {
7195 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7196 PN->reserveOperandSpace(2);
7197 PN->addIncoming(SI.getOperand(0), SI.getParent());
7198 PN->addIncoming(OtherStore->getOperand(0), Other);
7199 MergedVal = InsertNewInstBefore(PN, Dest->front());
7202 // Advance to a place where it is safe to insert the new store and
7204 BBI = Dest->begin();
7205 while (isa<PHINode>(BBI)) ++BBI;
7206 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7207 OtherStore->isVolatile()), *BBI);
7209 // Nuke the old stores.
7210 EraseInstFromFunction(SI);
7211 EraseInstFromFunction(*OtherStore);
7223 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7224 // Change br (not X), label True, label False to: br X, label False, True
7226 BasicBlock *TrueDest;
7227 BasicBlock *FalseDest;
7228 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7229 !isa<Constant>(X)) {
7230 // Swap Destinations and condition...
7232 BI.setSuccessor(0, FalseDest);
7233 BI.setSuccessor(1, TrueDest);
7237 // Cannonicalize setne -> seteq
7238 Instruction::BinaryOps Op; Value *Y;
7239 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7240 TrueDest, FalseDest)))
7241 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7242 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7243 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7244 std::string Name = I->getName(); I->setName("");
7245 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7246 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
7247 // Swap Destinations and condition...
7248 BI.setCondition(NewSCC);
7249 BI.setSuccessor(0, FalseDest);
7250 BI.setSuccessor(1, TrueDest);
7251 removeFromWorkList(I);
7252 I->getParent()->getInstList().erase(I);
7253 WorkList.push_back(cast<Instruction>(NewSCC));
7260 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7261 Value *Cond = SI.getCondition();
7262 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7263 if (I->getOpcode() == Instruction::Add)
7264 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7265 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7266 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
7267 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
7269 SI.setOperand(0, I->getOperand(0));
7270 WorkList.push_back(I);
7277 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7278 /// is to leave as a vector operation.
7279 static bool CheapToScalarize(Value *V, bool isConstant) {
7280 if (isa<ConstantAggregateZero>(V))
7282 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7283 if (isConstant) return true;
7284 // If all elts are the same, we can extract.
7285 Constant *Op0 = C->getOperand(0);
7286 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7287 if (C->getOperand(i) != Op0)
7291 Instruction *I = dyn_cast<Instruction>(V);
7292 if (!I) return false;
7294 // Insert element gets simplified to the inserted element or is deleted if
7295 // this is constant idx extract element and its a constant idx insertelt.
7296 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7297 isa<ConstantInt>(I->getOperand(2)))
7299 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7301 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7302 if (BO->hasOneUse() &&
7303 (CheapToScalarize(BO->getOperand(0), isConstant) ||
7304 CheapToScalarize(BO->getOperand(1), isConstant)))
7310 /// getShuffleMask - Read and decode a shufflevector mask. It turns undef
7311 /// elements into values that are larger than the #elts in the input.
7312 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
7313 unsigned NElts = SVI->getType()->getNumElements();
7314 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
7315 return std::vector<unsigned>(NElts, 0);
7316 if (isa<UndefValue>(SVI->getOperand(2)))
7317 return std::vector<unsigned>(NElts, 2*NElts);
7319 std::vector<unsigned> Result;
7320 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
7321 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
7322 if (isa<UndefValue>(CP->getOperand(i)))
7323 Result.push_back(NElts*2); // undef -> 8
7325 Result.push_back(cast<ConstantUInt>(CP->getOperand(i))->getValue());
7329 /// FindScalarElement - Given a vector and an element number, see if the scalar
7330 /// value is already around as a register, for example if it were inserted then
7331 /// extracted from the vector.
7332 static Value *FindScalarElement(Value *V, unsigned EltNo) {
7333 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7334 const PackedType *PTy = cast<PackedType>(V->getType());
7335 unsigned Width = PTy->getNumElements();
7336 if (EltNo >= Width) // Out of range access.
7337 return UndefValue::get(PTy->getElementType());
7339 if (isa<UndefValue>(V))
7340 return UndefValue::get(PTy->getElementType());
7341 else if (isa<ConstantAggregateZero>(V))
7342 return Constant::getNullValue(PTy->getElementType());
7343 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7344 return CP->getOperand(EltNo);
7345 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7346 // If this is an insert to a variable element, we don't know what it is.
7347 if (!isa<ConstantUInt>(III->getOperand(2))) return 0;
7348 unsigned IIElt = cast<ConstantUInt>(III->getOperand(2))->getValue();
7350 // If this is an insert to the element we are looking for, return the
7352 if (EltNo == IIElt) return III->getOperand(1);
7354 // Otherwise, the insertelement doesn't modify the value, recurse on its
7356 return FindScalarElement(III->getOperand(0), EltNo);
7357 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
7358 unsigned InEl = getShuffleMask(SVI)[EltNo];
7360 return FindScalarElement(SVI->getOperand(0), InEl);
7361 else if (InEl < Width*2)
7362 return FindScalarElement(SVI->getOperand(1), InEl - Width);
7364 return UndefValue::get(PTy->getElementType());
7367 // Otherwise, we don't know.
7371 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
7373 // If packed val is undef, replace extract with scalar undef.
7374 if (isa<UndefValue>(EI.getOperand(0)))
7375 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7377 // If packed val is constant 0, replace extract with scalar 0.
7378 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
7379 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
7381 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
7382 // If packed val is constant with uniform operands, replace EI
7383 // with that operand
7384 Constant *op0 = C->getOperand(0);
7385 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7386 if (C->getOperand(i) != op0) {
7391 return ReplaceInstUsesWith(EI, op0);
7394 // If extracting a specified index from the vector, see if we can recursively
7395 // find a previously computed scalar that was inserted into the vector.
7396 if (ConstantUInt *IdxC = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
7397 if (Value *Elt = FindScalarElement(EI.getOperand(0), IdxC->getValue()))
7398 return ReplaceInstUsesWith(EI, Elt);
7401 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
7402 if (I->hasOneUse()) {
7403 // Push extractelement into predecessor operation if legal and
7404 // profitable to do so
7405 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
7406 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
7407 if (CheapToScalarize(BO, isConstantElt)) {
7408 ExtractElementInst *newEI0 =
7409 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
7410 EI.getName()+".lhs");
7411 ExtractElementInst *newEI1 =
7412 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
7413 EI.getName()+".rhs");
7414 InsertNewInstBefore(newEI0, EI);
7415 InsertNewInstBefore(newEI1, EI);
7416 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
7418 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7419 Value *Ptr = InsertCastBefore(I->getOperand(0),
7420 PointerType::get(EI.getType()), EI);
7421 GetElementPtrInst *GEP =
7422 new GetElementPtrInst(Ptr, EI.getOperand(1),
7423 I->getName() + ".gep");
7424 InsertNewInstBefore(GEP, EI);
7425 return new LoadInst(GEP);
7428 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
7429 // Extracting the inserted element?
7430 if (IE->getOperand(2) == EI.getOperand(1))
7431 return ReplaceInstUsesWith(EI, IE->getOperand(1));
7432 // If the inserted and extracted elements are constants, they must not
7433 // be the same value, extract from the pre-inserted value instead.
7434 if (isa<Constant>(IE->getOperand(2)) &&
7435 isa<Constant>(EI.getOperand(1))) {
7436 AddUsesToWorkList(EI);
7437 EI.setOperand(0, IE->getOperand(0));
7440 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
7441 // If this is extracting an element from a shufflevector, figure out where
7442 // it came from and extract from the appropriate input element instead.
7443 if (ConstantUInt *Elt = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
7444 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getValue()];
7446 if (SrcIdx < SVI->getType()->getNumElements())
7447 Src = SVI->getOperand(0);
7448 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
7449 SrcIdx -= SVI->getType()->getNumElements();
7450 Src = SVI->getOperand(1);
7452 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7454 return new ExtractElementInst(Src,
7455 ConstantUInt::get(Type::UIntTy, SrcIdx));
7462 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
7463 /// elements from either LHS or RHS, return the shuffle mask and true.
7464 /// Otherwise, return false.
7465 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
7466 std::vector<Constant*> &Mask) {
7467 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
7468 "Invalid CollectSingleShuffleElements");
7469 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7471 if (isa<UndefValue>(V)) {
7472 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7474 } else if (V == LHS) {
7475 for (unsigned i = 0; i != NumElts; ++i)
7476 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7478 } else if (V == RHS) {
7479 for (unsigned i = 0; i != NumElts; ++i)
7480 Mask.push_back(ConstantUInt::get(Type::UIntTy, i+NumElts));
7482 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7483 // If this is an insert of an extract from some other vector, include it.
7484 Value *VecOp = IEI->getOperand(0);
7485 Value *ScalarOp = IEI->getOperand(1);
7486 Value *IdxOp = IEI->getOperand(2);
7488 if (!isa<ConstantInt>(IdxOp))
7490 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7492 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
7493 // Okay, we can handle this if the vector we are insertinting into is
7495 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7496 // If so, update the mask to reflect the inserted undef.
7497 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
7500 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
7501 if (isa<ConstantInt>(EI->getOperand(1)) &&
7502 EI->getOperand(0)->getType() == V->getType()) {
7503 unsigned ExtractedIdx =
7504 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7506 // This must be extracting from either LHS or RHS.
7507 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
7508 // Okay, we can handle this if the vector we are insertinting into is
7510 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7511 // If so, update the mask to reflect the inserted value.
7512 if (EI->getOperand(0) == LHS) {
7513 Mask[InsertedIdx & (NumElts-1)] =
7514 ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7516 assert(EI->getOperand(0) == RHS);
7517 Mask[InsertedIdx & (NumElts-1)] =
7518 ConstantUInt::get(Type::UIntTy, ExtractedIdx+NumElts);
7527 // TODO: Handle shufflevector here!
7532 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
7533 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
7534 /// that computes V and the LHS value of the shuffle.
7535 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
7537 assert(isa<PackedType>(V->getType()) &&
7538 (RHS == 0 || V->getType() == RHS->getType()) &&
7539 "Invalid shuffle!");
7540 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7542 if (isa<UndefValue>(V)) {
7543 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7545 } else if (isa<ConstantAggregateZero>(V)) {
7546 Mask.assign(NumElts, ConstantUInt::get(Type::UIntTy, 0));
7548 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7549 // If this is an insert of an extract from some other vector, include it.
7550 Value *VecOp = IEI->getOperand(0);
7551 Value *ScalarOp = IEI->getOperand(1);
7552 Value *IdxOp = IEI->getOperand(2);
7554 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7555 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7556 EI->getOperand(0)->getType() == V->getType()) {
7557 unsigned ExtractedIdx =
7558 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7559 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7561 // Either the extracted from or inserted into vector must be RHSVec,
7562 // otherwise we'd end up with a shuffle of three inputs.
7563 if (EI->getOperand(0) == RHS || RHS == 0) {
7564 RHS = EI->getOperand(0);
7565 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
7566 Mask[InsertedIdx & (NumElts-1)] =
7567 ConstantUInt::get(Type::UIntTy, NumElts+ExtractedIdx);
7572 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
7573 // Everything but the extracted element is replaced with the RHS.
7574 for (unsigned i = 0; i != NumElts; ++i) {
7575 if (i != InsertedIdx)
7576 Mask[i] = ConstantUInt::get(Type::UIntTy, NumElts+i);
7581 // If this insertelement is a chain that comes from exactly these two
7582 // vectors, return the vector and the effective shuffle.
7583 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
7584 return EI->getOperand(0);
7589 // TODO: Handle shufflevector here!
7591 // Otherwise, can't do anything fancy. Return an identity vector.
7592 for (unsigned i = 0; i != NumElts; ++i)
7593 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7597 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
7598 Value *VecOp = IE.getOperand(0);
7599 Value *ScalarOp = IE.getOperand(1);
7600 Value *IdxOp = IE.getOperand(2);
7602 // If the inserted element was extracted from some other vector, and if the
7603 // indexes are constant, try to turn this into a shufflevector operation.
7604 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7605 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7606 EI->getOperand(0)->getType() == IE.getType()) {
7607 unsigned NumVectorElts = IE.getType()->getNumElements();
7608 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7609 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7611 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
7612 return ReplaceInstUsesWith(IE, VecOp);
7614 if (InsertedIdx >= NumVectorElts) // Out of range insert.
7615 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
7617 // If we are extracting a value from a vector, then inserting it right
7618 // back into the same place, just use the input vector.
7619 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
7620 return ReplaceInstUsesWith(IE, VecOp);
7622 // We could theoretically do this for ANY input. However, doing so could
7623 // turn chains of insertelement instructions into a chain of shufflevector
7624 // instructions, and right now we do not merge shufflevectors. As such,
7625 // only do this in a situation where it is clear that there is benefit.
7626 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
7627 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
7628 // the values of VecOp, except then one read from EIOp0.
7629 // Build a new shuffle mask.
7630 std::vector<Constant*> Mask;
7631 if (isa<UndefValue>(VecOp))
7632 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
7634 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
7635 Mask.assign(NumVectorElts, ConstantUInt::get(Type::UIntTy,
7638 Mask[InsertedIdx] = ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7639 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
7640 ConstantPacked::get(Mask));
7643 // If this insertelement isn't used by some other insertelement, turn it
7644 // (and any insertelements it points to), into one big shuffle.
7645 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
7646 std::vector<Constant*> Mask;
7648 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
7649 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
7650 // We now have a shuffle of LHS, RHS, Mask.
7651 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
7660 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
7661 Value *LHS = SVI.getOperand(0);
7662 Value *RHS = SVI.getOperand(1);
7663 std::vector<unsigned> Mask = getShuffleMask(&SVI);
7665 bool MadeChange = false;
7667 if (isa<UndefValue>(SVI.getOperand(2)))
7668 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
7670 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
7671 // the undef, change them to undefs.
7673 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
7674 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
7675 if (LHS == RHS || isa<UndefValue>(LHS)) {
7676 if (isa<UndefValue>(LHS) && LHS == RHS) {
7677 // shuffle(undef,undef,mask) -> undef.
7678 return ReplaceInstUsesWith(SVI, LHS);
7681 // Remap any references to RHS to use LHS.
7682 std::vector<Constant*> Elts;
7683 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
7685 Elts.push_back(UndefValue::get(Type::UIntTy));
7687 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
7688 (Mask[i] < e && isa<UndefValue>(LHS)))
7689 Mask[i] = 2*e; // Turn into undef.
7691 Mask[i] &= (e-1); // Force to LHS.
7692 Elts.push_back(ConstantUInt::get(Type::UIntTy, Mask[i]));
7695 SVI.setOperand(0, SVI.getOperand(1));
7696 SVI.setOperand(1, UndefValue::get(RHS->getType()));
7697 SVI.setOperand(2, ConstantPacked::get(Elts));
7698 LHS = SVI.getOperand(0);
7699 RHS = SVI.getOperand(1);
7703 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
7704 bool isLHSID = true, isRHSID = true;
7706 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
7707 if (Mask[i] >= e*2) continue; // Ignore undef values.
7708 // Is this an identity shuffle of the LHS value?
7709 isLHSID &= (Mask[i] == i);
7711 // Is this an identity shuffle of the RHS value?
7712 isRHSID &= (Mask[i]-e == i);
7715 // Eliminate identity shuffles.
7716 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
7717 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
7719 // If the LHS is a shufflevector itself, see if we can combine it with this
7720 // one without producing an unusual shuffle. Here we are really conservative:
7721 // we are absolutely afraid of producing a shuffle mask not in the input
7722 // program, because the code gen may not be smart enough to turn a merged
7723 // shuffle into two specific shuffles: it may produce worse code. As such,
7724 // we only merge two shuffles if the result is one of the two input shuffle
7725 // masks. In this case, merging the shuffles just removes one instruction,
7726 // which we know is safe. This is good for things like turning:
7727 // (splat(splat)) -> splat.
7728 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
7729 if (isa<UndefValue>(RHS)) {
7730 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
7732 std::vector<unsigned> NewMask;
7733 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
7735 NewMask.push_back(2*e);
7737 NewMask.push_back(LHSMask[Mask[i]]);
7739 // If the result mask is equal to the src shuffle or this shuffle mask, do
7741 if (NewMask == LHSMask || NewMask == Mask) {
7742 std::vector<Constant*> Elts;
7743 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
7744 if (NewMask[i] >= e*2) {
7745 Elts.push_back(UndefValue::get(Type::UIntTy));
7747 Elts.push_back(ConstantUInt::get(Type::UIntTy, NewMask[i]));
7750 return new ShuffleVectorInst(LHSSVI->getOperand(0),
7751 LHSSVI->getOperand(1),
7752 ConstantPacked::get(Elts));
7757 return MadeChange ? &SVI : 0;
7762 void InstCombiner::removeFromWorkList(Instruction *I) {
7763 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
7768 /// TryToSinkInstruction - Try to move the specified instruction from its
7769 /// current block into the beginning of DestBlock, which can only happen if it's
7770 /// safe to move the instruction past all of the instructions between it and the
7771 /// end of its block.
7772 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
7773 assert(I->hasOneUse() && "Invariants didn't hold!");
7775 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
7776 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
7778 // Do not sink alloca instructions out of the entry block.
7779 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
7782 // We can only sink load instructions if there is nothing between the load and
7783 // the end of block that could change the value.
7784 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7785 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
7787 if (Scan->mayWriteToMemory())
7791 BasicBlock::iterator InsertPos = DestBlock->begin();
7792 while (isa<PHINode>(InsertPos)) ++InsertPos;
7794 I->moveBefore(InsertPos);
7799 /// OptimizeConstantExpr - Given a constant expression and target data layout
7800 /// information, symbolically evaluation the constant expr to something simpler
7802 static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
7805 Constant *Ptr = CE->getOperand(0);
7806 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
7807 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
7808 // If this is a constant expr gep that is effectively computing an
7809 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
7810 bool isFoldableGEP = true;
7811 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
7812 if (!isa<ConstantInt>(CE->getOperand(i)))
7813 isFoldableGEP = false;
7814 if (isFoldableGEP) {
7815 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
7816 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
7817 Constant *C = ConstantUInt::get(Type::ULongTy, Offset);
7818 C = ConstantExpr::getCast(C, TD->getIntPtrType());
7819 return ConstantExpr::getCast(C, CE->getType());
7827 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
7828 /// all reachable code to the worklist.
7830 /// This has a couple of tricks to make the code faster and more powerful. In
7831 /// particular, we constant fold and DCE instructions as we go, to avoid adding
7832 /// them to the worklist (this significantly speeds up instcombine on code where
7833 /// many instructions are dead or constant). Additionally, if we find a branch
7834 /// whose condition is a known constant, we only visit the reachable successors.
7836 static void AddReachableCodeToWorklist(BasicBlock *BB,
7837 std::set<BasicBlock*> &Visited,
7838 std::vector<Instruction*> &WorkList,
7839 const TargetData *TD) {
7840 // We have now visited this block! If we've already been here, bail out.
7841 if (!Visited.insert(BB).second) return;
7843 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
7844 Instruction *Inst = BBI++;
7846 // DCE instruction if trivially dead.
7847 if (isInstructionTriviallyDead(Inst)) {
7849 DEBUG(std::cerr << "IC: DCE: " << *Inst);
7850 Inst->eraseFromParent();
7854 // ConstantProp instruction if trivially constant.
7855 if (Constant *C = ConstantFoldInstruction(Inst)) {
7856 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
7857 C = OptimizeConstantExpr(CE, TD);
7858 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
7859 Inst->replaceAllUsesWith(C);
7861 Inst->eraseFromParent();
7865 WorkList.push_back(Inst);
7868 // Recursively visit successors. If this is a branch or switch on a constant,
7869 // only visit the reachable successor.
7870 TerminatorInst *TI = BB->getTerminator();
7871 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
7872 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
7873 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
7874 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
7878 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
7879 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
7880 // See if this is an explicit destination.
7881 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
7882 if (SI->getCaseValue(i) == Cond) {
7883 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
7887 // Otherwise it is the default destination.
7888 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
7893 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
7894 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
7897 bool InstCombiner::runOnFunction(Function &F) {
7898 bool Changed = false;
7899 TD = &getAnalysis<TargetData>();
7902 // Do a depth-first traversal of the function, populate the worklist with
7903 // the reachable instructions. Ignore blocks that are not reachable. Keep
7904 // track of which blocks we visit.
7905 std::set<BasicBlock*> Visited;
7906 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
7908 // Do a quick scan over the function. If we find any blocks that are
7909 // unreachable, remove any instructions inside of them. This prevents
7910 // the instcombine code from having to deal with some bad special cases.
7911 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
7912 if (!Visited.count(BB)) {
7913 Instruction *Term = BB->getTerminator();
7914 while (Term != BB->begin()) { // Remove instrs bottom-up
7915 BasicBlock::iterator I = Term; --I;
7917 DEBUG(std::cerr << "IC: DCE: " << *I);
7920 if (!I->use_empty())
7921 I->replaceAllUsesWith(UndefValue::get(I->getType()));
7922 I->eraseFromParent();
7927 while (!WorkList.empty()) {
7928 Instruction *I = WorkList.back(); // Get an instruction from the worklist
7929 WorkList.pop_back();
7931 // Check to see if we can DCE the instruction.
7932 if (isInstructionTriviallyDead(I)) {
7933 // Add operands to the worklist.
7934 if (I->getNumOperands() < 4)
7935 AddUsesToWorkList(*I);
7938 DEBUG(std::cerr << "IC: DCE: " << *I);
7940 I->eraseFromParent();
7941 removeFromWorkList(I);
7945 // Instruction isn't dead, see if we can constant propagate it.
7946 if (Constant *C = ConstantFoldInstruction(I)) {
7947 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
7948 C = OptimizeConstantExpr(CE, TD);
7949 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
7951 // Add operands to the worklist.
7952 AddUsesToWorkList(*I);
7953 ReplaceInstUsesWith(*I, C);
7956 I->eraseFromParent();
7957 removeFromWorkList(I);
7961 // See if we can trivially sink this instruction to a successor basic block.
7962 if (I->hasOneUse()) {
7963 BasicBlock *BB = I->getParent();
7964 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
7965 if (UserParent != BB) {
7966 bool UserIsSuccessor = false;
7967 // See if the user is one of our successors.
7968 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
7969 if (*SI == UserParent) {
7970 UserIsSuccessor = true;
7974 // If the user is one of our immediate successors, and if that successor
7975 // only has us as a predecessors (we'd have to split the critical edge
7976 // otherwise), we can keep going.
7977 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
7978 next(pred_begin(UserParent)) == pred_end(UserParent))
7979 // Okay, the CFG is simple enough, try to sink this instruction.
7980 Changed |= TryToSinkInstruction(I, UserParent);
7984 // Now that we have an instruction, try combining it to simplify it...
7985 if (Instruction *Result = visit(*I)) {
7987 // Should we replace the old instruction with a new one?
7989 DEBUG(std::cerr << "IC: Old = " << *I
7990 << " New = " << *Result);
7992 // Everything uses the new instruction now.
7993 I->replaceAllUsesWith(Result);
7995 // Push the new instruction and any users onto the worklist.
7996 WorkList.push_back(Result);
7997 AddUsersToWorkList(*Result);
7999 // Move the name to the new instruction first...
8000 std::string OldName = I->getName(); I->setName("");
8001 Result->setName(OldName);
8003 // Insert the new instruction into the basic block...
8004 BasicBlock *InstParent = I->getParent();
8005 BasicBlock::iterator InsertPos = I;
8007 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8008 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8011 InstParent->getInstList().insert(InsertPos, Result);
8013 // Make sure that we reprocess all operands now that we reduced their
8015 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8016 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8017 WorkList.push_back(OpI);
8019 // Instructions can end up on the worklist more than once. Make sure
8020 // we do not process an instruction that has been deleted.
8021 removeFromWorkList(I);
8023 // Erase the old instruction.
8024 InstParent->getInstList().erase(I);
8026 DEBUG(std::cerr << "IC: MOD = " << *I);
8028 // If the instruction was modified, it's possible that it is now dead.
8029 // if so, remove it.
8030 if (isInstructionTriviallyDead(I)) {
8031 // Make sure we process all operands now that we are reducing their
8033 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8034 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8035 WorkList.push_back(OpI);
8037 // Instructions may end up in the worklist more than once. Erase all
8038 // occurrences of this instruction.
8039 removeFromWorkList(I);
8040 I->eraseFromParent();
8042 WorkList.push_back(Result);
8043 AddUsersToWorkList(*Result);
8053 FunctionPass *llvm::createInstructionCombiningPass() {
8054 return new InstCombiner();