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 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
93 /// dead. Add all of its operands to the worklist, turning them into
94 /// undef's to reduce the number of uses of those instructions.
96 /// Return the specified operand before it is turned into an undef.
98 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
99 Value *R = I.getOperand(op);
101 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
102 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
103 WorkList.push_back(Op);
104 // Set the operand to undef to drop the use.
105 I.setOperand(i, UndefValue::get(Op->getType()));
111 // removeFromWorkList - remove all instances of I from the worklist.
112 void removeFromWorkList(Instruction *I);
114 virtual bool runOnFunction(Function &F);
116 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
117 AU.addRequired<TargetData>();
118 AU.addPreservedID(LCSSAID);
119 AU.setPreservesCFG();
122 TargetData &getTargetData() const { return *TD; }
124 // Visitation implementation - Implement instruction combining for different
125 // instruction types. The semantics are as follows:
127 // null - No change was made
128 // I - Change was made, I is still valid, I may be dead though
129 // otherwise - Change was made, replace I with returned instruction
131 Instruction *visitAdd(BinaryOperator &I);
132 Instruction *visitSub(BinaryOperator &I);
133 Instruction *visitMul(BinaryOperator &I);
134 Instruction *visitDiv(BinaryOperator &I);
135 Instruction *visitRem(BinaryOperator &I);
136 Instruction *visitAnd(BinaryOperator &I);
137 Instruction *visitOr (BinaryOperator &I);
138 Instruction *visitXor(BinaryOperator &I);
139 Instruction *visitSetCondInst(SetCondInst &I);
140 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
142 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
143 Instruction::BinaryOps Cond, Instruction &I);
144 Instruction *visitShiftInst(ShiftInst &I);
145 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
147 Instruction *visitCastInst(CastInst &CI);
148 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
150 Instruction *visitSelectInst(SelectInst &CI);
151 Instruction *visitCallInst(CallInst &CI);
152 Instruction *visitInvokeInst(InvokeInst &II);
153 Instruction *visitPHINode(PHINode &PN);
154 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
155 Instruction *visitAllocationInst(AllocationInst &AI);
156 Instruction *visitFreeInst(FreeInst &FI);
157 Instruction *visitLoadInst(LoadInst &LI);
158 Instruction *visitStoreInst(StoreInst &SI);
159 Instruction *visitBranchInst(BranchInst &BI);
160 Instruction *visitSwitchInst(SwitchInst &SI);
161 Instruction *visitInsertElementInst(InsertElementInst &IE);
162 Instruction *visitExtractElementInst(ExtractElementInst &EI);
163 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
165 // visitInstruction - Specify what to return for unhandled instructions...
166 Instruction *visitInstruction(Instruction &I) { return 0; }
169 Instruction *visitCallSite(CallSite CS);
170 bool transformConstExprCastCall(CallSite CS);
173 // InsertNewInstBefore - insert an instruction New before instruction Old
174 // in the program. Add the new instruction to the worklist.
176 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
177 assert(New && New->getParent() == 0 &&
178 "New instruction already inserted into a basic block!");
179 BasicBlock *BB = Old.getParent();
180 BB->getInstList().insert(&Old, New); // Insert inst
181 WorkList.push_back(New); // Add to worklist
185 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
186 /// This also adds the cast to the worklist. Finally, this returns the
188 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
189 if (V->getType() == Ty) return V;
191 if (Constant *CV = dyn_cast<Constant>(V))
192 return ConstantExpr::getCast(CV, Ty);
194 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
195 WorkList.push_back(C);
199 // ReplaceInstUsesWith - This method is to be used when an instruction is
200 // found to be dead, replacable with another preexisting expression. Here
201 // we add all uses of I to the worklist, replace all uses of I with the new
202 // value, then return I, so that the inst combiner will know that I was
205 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
206 AddUsersToWorkList(I); // Add all modified instrs to worklist
208 I.replaceAllUsesWith(V);
211 // If we are replacing the instruction with itself, this must be in a
212 // segment of unreachable code, so just clobber the instruction.
213 I.replaceAllUsesWith(UndefValue::get(I.getType()));
218 // UpdateValueUsesWith - This method is to be used when an value is
219 // found to be replacable with another preexisting expression or was
220 // updated. Here we add all uses of I to the worklist, replace all uses of
221 // I with the new value (unless the instruction was just updated), then
222 // return true, so that the inst combiner will know that I was modified.
224 bool UpdateValueUsesWith(Value *Old, Value *New) {
225 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
227 Old->replaceAllUsesWith(New);
228 if (Instruction *I = dyn_cast<Instruction>(Old))
229 WorkList.push_back(I);
230 if (Instruction *I = dyn_cast<Instruction>(New))
231 WorkList.push_back(I);
235 // EraseInstFromFunction - When dealing with an instruction that has side
236 // effects or produces a void value, we can't rely on DCE to delete the
237 // instruction. Instead, visit methods should return the value returned by
239 Instruction *EraseInstFromFunction(Instruction &I) {
240 assert(I.use_empty() && "Cannot erase instruction that is used!");
241 AddUsesToWorkList(I);
242 removeFromWorkList(&I);
244 return 0; // Don't do anything with FI
248 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
249 /// InsertBefore instruction. This is specialized a bit to avoid inserting
250 /// casts that are known to not do anything...
252 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
253 Instruction *InsertBefore);
255 // SimplifyCommutative - This performs a few simplifications for commutative
257 bool SimplifyCommutative(BinaryOperator &I);
259 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
260 uint64_t &KnownZero, uint64_t &KnownOne,
263 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
264 uint64_t &UndefElts, unsigned Depth = 0);
266 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
267 // PHI node as operand #0, see if we can fold the instruction into the PHI
268 // (which is only possible if all operands to the PHI are constants).
269 Instruction *FoldOpIntoPhi(Instruction &I);
271 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
272 // operator and they all are only used by the PHI, PHI together their
273 // inputs, and do the operation once, to the result of the PHI.
274 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
276 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
277 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
279 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
280 bool isSub, Instruction &I);
281 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
282 bool Inside, Instruction &IB);
283 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
284 Instruction *MatchBSwap(BinaryOperator &I);
286 Value *EvaluateInDifferentType(Value *V, const Type *Ty);
289 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
292 // getComplexity: Assign a complexity or rank value to LLVM Values...
293 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
294 static unsigned getComplexity(Value *V) {
295 if (isa<Instruction>(V)) {
296 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
300 if (isa<Argument>(V)) return 3;
301 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
304 // isOnlyUse - Return true if this instruction will be deleted if we stop using
306 static bool isOnlyUse(Value *V) {
307 return V->hasOneUse() || isa<Constant>(V);
310 // getPromotedType - Return the specified type promoted as it would be to pass
311 // though a va_arg area...
312 static const Type *getPromotedType(const Type *Ty) {
313 switch (Ty->getTypeID()) {
314 case Type::SByteTyID:
315 case Type::ShortTyID: return Type::IntTy;
316 case Type::UByteTyID:
317 case Type::UShortTyID: return Type::UIntTy;
318 case Type::FloatTyID: return Type::DoubleTy;
323 /// isCast - If the specified operand is a CastInst or a constant expr cast,
324 /// return the operand value, otherwise return null.
325 static Value *isCast(Value *V) {
326 if (CastInst *I = dyn_cast<CastInst>(V))
327 return I->getOperand(0);
328 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
329 if (CE->getOpcode() == Instruction::Cast)
330 return CE->getOperand(0);
341 /// getCastType - In the future, we will split the cast instruction into these
342 /// various types. Until then, we have to do the analysis here.
343 static CastType getCastType(const Type *Src, const Type *Dest) {
344 assert(Src->isIntegral() && Dest->isIntegral() &&
345 "Only works on integral types!");
346 unsigned SrcSize = Src->getPrimitiveSizeInBits();
347 unsigned DestSize = Dest->getPrimitiveSizeInBits();
349 if (SrcSize == DestSize) return Noop;
350 if (SrcSize > DestSize) return Truncate;
351 if (Src->isSigned()) return Signext;
356 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
359 static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
360 const Type *DstTy, TargetData *TD) {
362 // It is legal to eliminate the instruction if casting A->B->A if the sizes
363 // are identical and the bits don't get reinterpreted (for example
364 // int->float->int would not be allowed).
365 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
368 // If we are casting between pointer and integer types, treat pointers as
369 // integers of the appropriate size for the code below.
370 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
371 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
372 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
374 // Allow free casting and conversion of sizes as long as the sign doesn't
376 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
377 CastType FirstCast = getCastType(SrcTy, MidTy);
378 CastType SecondCast = getCastType(MidTy, DstTy);
380 // Capture the effect of these two casts. If the result is a legal cast,
381 // the CastType is stored here, otherwise a special code is used.
382 static const unsigned CastResult[] = {
383 // First cast is noop
385 // First cast is a truncate
386 1, 1, 4, 4, // trunc->extend is not safe to eliminate
387 // First cast is a sign ext
388 2, 5, 2, 4, // signext->zeroext never ok
389 // First cast is a zero ext
393 unsigned Result = CastResult[FirstCast*4+SecondCast];
395 default: assert(0 && "Illegal table value!");
400 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
401 // truncates, we could eliminate more casts.
402 return (unsigned)getCastType(SrcTy, DstTy) == Result;
404 return false; // Not possible to eliminate this here.
406 // Sign or zero extend followed by truncate is always ok if the result
407 // is a truncate or noop.
408 CastType ResultCast = getCastType(SrcTy, DstTy);
409 if (ResultCast == Noop || ResultCast == Truncate)
411 // Otherwise we are still growing the value, we are only safe if the
412 // result will match the sign/zeroextendness of the result.
413 return ResultCast == FirstCast;
417 // If this is a cast from 'float -> double -> integer', cast from
418 // 'float -> integer' directly, as the value isn't changed by the
419 // float->double conversion.
420 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
421 DstTy->isIntegral() &&
422 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
425 // Packed type conversions don't modify bits.
426 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
432 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
433 /// in any code being generated. It does not require codegen if V is simple
434 /// enough or if the cast can be folded into other casts.
435 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
436 if (V->getType() == Ty || isa<Constant>(V)) return false;
438 // If this is a noop cast, it isn't real codegen.
439 if (V->getType()->isLosslesslyConvertibleTo(Ty))
442 // If this is another cast that can be eliminated, it isn't codegen either.
443 if (const CastInst *CI = dyn_cast<CastInst>(V))
444 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
450 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
451 /// InsertBefore instruction. This is specialized a bit to avoid inserting
452 /// casts that are known to not do anything...
454 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
455 Instruction *InsertBefore) {
456 if (V->getType() == DestTy) return V;
457 if (Constant *C = dyn_cast<Constant>(V))
458 return ConstantExpr::getCast(C, DestTy);
460 CastInst *CI = new CastInst(V, DestTy, V->getName());
461 InsertNewInstBefore(CI, *InsertBefore);
465 // SimplifyCommutative - This performs a few simplifications for commutative
468 // 1. Order operands such that they are listed from right (least complex) to
469 // left (most complex). This puts constants before unary operators before
472 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
473 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
475 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
476 bool Changed = false;
477 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
478 Changed = !I.swapOperands();
480 if (!I.isAssociative()) return Changed;
481 Instruction::BinaryOps Opcode = I.getOpcode();
482 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
483 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
484 if (isa<Constant>(I.getOperand(1))) {
485 Constant *Folded = ConstantExpr::get(I.getOpcode(),
486 cast<Constant>(I.getOperand(1)),
487 cast<Constant>(Op->getOperand(1)));
488 I.setOperand(0, Op->getOperand(0));
489 I.setOperand(1, Folded);
491 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
492 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
493 isOnlyUse(Op) && isOnlyUse(Op1)) {
494 Constant *C1 = cast<Constant>(Op->getOperand(1));
495 Constant *C2 = cast<Constant>(Op1->getOperand(1));
497 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
498 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
499 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
502 WorkList.push_back(New);
503 I.setOperand(0, New);
504 I.setOperand(1, Folded);
511 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
512 // if the LHS is a constant zero (which is the 'negate' form).
514 static inline Value *dyn_castNegVal(Value *V) {
515 if (BinaryOperator::isNeg(V))
516 return BinaryOperator::getNegArgument(V);
518 // Constants can be considered to be negated values if they can be folded.
519 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
520 return ConstantExpr::getNeg(C);
524 static inline Value *dyn_castNotVal(Value *V) {
525 if (BinaryOperator::isNot(V))
526 return BinaryOperator::getNotArgument(V);
528 // Constants can be considered to be not'ed values...
529 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
530 return ConstantExpr::getNot(C);
534 // dyn_castFoldableMul - If this value is a multiply that can be folded into
535 // other computations (because it has a constant operand), return the
536 // non-constant operand of the multiply, and set CST to point to the multiplier.
537 // Otherwise, return null.
539 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
540 if (V->hasOneUse() && V->getType()->isInteger())
541 if (Instruction *I = dyn_cast<Instruction>(V)) {
542 if (I->getOpcode() == Instruction::Mul)
543 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
544 return I->getOperand(0);
545 if (I->getOpcode() == Instruction::Shl)
546 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
547 // The multiplier is really 1 << CST.
548 Constant *One = ConstantInt::get(V->getType(), 1);
549 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
550 return I->getOperand(0);
556 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
557 /// expression, return it.
558 static User *dyn_castGetElementPtr(Value *V) {
559 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
560 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
561 if (CE->getOpcode() == Instruction::GetElementPtr)
562 return cast<User>(V);
566 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
567 static ConstantInt *AddOne(ConstantInt *C) {
568 return cast<ConstantInt>(ConstantExpr::getAdd(C,
569 ConstantInt::get(C->getType(), 1)));
571 static ConstantInt *SubOne(ConstantInt *C) {
572 return cast<ConstantInt>(ConstantExpr::getSub(C,
573 ConstantInt::get(C->getType(), 1)));
576 /// GetConstantInType - Return a ConstantInt with the specified type and value.
578 static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
579 if (Ty->isUnsigned())
580 return ConstantUInt::get(Ty, Val);
581 else if (Ty->getTypeID() == Type::BoolTyID)
582 return ConstantBool::get(Val);
584 SVal <<= 64-Ty->getPrimitiveSizeInBits();
585 SVal >>= 64-Ty->getPrimitiveSizeInBits();
586 return ConstantSInt::get(Ty, SVal);
590 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
591 /// known to be either zero or one and return them in the KnownZero/KnownOne
592 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
594 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
595 uint64_t &KnownOne, unsigned Depth = 0) {
596 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
597 // we cannot optimize based on the assumption that it is zero without changing
598 // it to be an explicit zero. If we don't change it to zero, other code could
599 // optimized based on the contradictory assumption that it is non-zero.
600 // Because instcombine aggressively folds operations with undef args anyway,
601 // this won't lose us code quality.
602 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
603 // We know all of the bits for a constant!
604 KnownOne = CI->getZExtValue() & Mask;
605 KnownZero = ~KnownOne & Mask;
609 KnownZero = KnownOne = 0; // Don't know anything.
610 if (Depth == 6 || Mask == 0)
611 return; // Limit search depth.
613 uint64_t KnownZero2, KnownOne2;
614 Instruction *I = dyn_cast<Instruction>(V);
617 Mask &= V->getType()->getIntegralTypeMask();
619 switch (I->getOpcode()) {
620 case Instruction::And:
621 // If either the LHS or the RHS are Zero, the result is zero.
622 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
624 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
625 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
626 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
628 // Output known-1 bits are only known if set in both the LHS & RHS.
629 KnownOne &= KnownOne2;
630 // Output known-0 are known to be clear if zero in either the LHS | RHS.
631 KnownZero |= KnownZero2;
633 case Instruction::Or:
634 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
636 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
637 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
638 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
640 // Output known-0 bits are only known if clear in both the LHS & RHS.
641 KnownZero &= KnownZero2;
642 // Output known-1 are known to be set if set in either the LHS | RHS.
643 KnownOne |= KnownOne2;
645 case Instruction::Xor: {
646 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
647 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
648 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
649 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
651 // Output known-0 bits are known if clear or set in both the LHS & RHS.
652 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
653 // Output known-1 are known to be set if set in only one of the LHS, RHS.
654 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
655 KnownZero = KnownZeroOut;
658 case Instruction::Select:
659 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
660 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
661 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
662 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
664 // Only known if known in both the LHS and RHS.
665 KnownOne &= KnownOne2;
666 KnownZero &= KnownZero2;
668 case Instruction::Cast: {
669 const Type *SrcTy = I->getOperand(0)->getType();
670 if (!SrcTy->isIntegral()) return;
672 // If this is an integer truncate or noop, just look in the input.
673 if (SrcTy->getPrimitiveSizeInBits() >=
674 I->getType()->getPrimitiveSizeInBits()) {
675 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
679 // Sign or Zero extension. Compute the bits in the result that are not
680 // present in the input.
681 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
682 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
684 // Handle zero extension.
685 if (!SrcTy->isSigned()) {
686 Mask &= SrcTy->getIntegralTypeMask();
687 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
688 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
689 // The top bits are known to be zero.
690 KnownZero |= NewBits;
693 Mask &= SrcTy->getIntegralTypeMask();
694 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
695 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
697 // If the sign bit of the input is known set or clear, then we know the
698 // top bits of the result.
699 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
700 if (KnownZero & InSignBit) { // Input sign bit known zero
701 KnownZero |= NewBits;
702 KnownOne &= ~NewBits;
703 } else if (KnownOne & InSignBit) { // Input sign bit known set
705 KnownZero &= ~NewBits;
706 } else { // Input sign bit unknown
707 KnownZero &= ~NewBits;
708 KnownOne &= ~NewBits;
713 case Instruction::Shl:
714 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
715 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
716 Mask >>= SA->getValue();
717 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
718 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
719 KnownZero <<= SA->getValue();
720 KnownOne <<= SA->getValue();
721 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
725 case Instruction::Shr:
726 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
727 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
728 // Compute the new bits that are at the top now.
729 uint64_t HighBits = (1ULL << SA->getValue())-1;
730 HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
732 if (I->getType()->isUnsigned()) { // Unsigned shift right.
733 Mask <<= SA->getValue();
734 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
735 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
736 KnownZero >>= SA->getValue();
737 KnownOne >>= SA->getValue();
738 KnownZero |= HighBits; // high bits known zero.
740 Mask <<= SA->getValue();
741 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
742 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
743 KnownZero >>= SA->getValue();
744 KnownOne >>= SA->getValue();
746 // Handle the sign bits.
747 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
748 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
750 if (KnownZero & SignBit) { // New bits are known zero.
751 KnownZero |= HighBits;
752 } else if (KnownOne & SignBit) { // New bits are known one.
753 KnownOne |= HighBits;
762 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
763 /// this predicate to simplify operations downstream. Mask is known to be zero
764 /// for bits that V cannot have.
765 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
766 uint64_t KnownZero, KnownOne;
767 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
768 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
769 return (KnownZero & Mask) == Mask;
772 /// ShrinkDemandedConstant - Check to see if the specified operand of the
773 /// specified instruction is a constant integer. If so, check to see if there
774 /// are any bits set in the constant that are not demanded. If so, shrink the
775 /// constant and return true.
776 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
778 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
779 if (!OpC) return false;
781 // If there are no bits set that aren't demanded, nothing to do.
782 if ((~Demanded & OpC->getZExtValue()) == 0)
785 // This is producing any bits that are not needed, shrink the RHS.
786 uint64_t Val = Demanded & OpC->getZExtValue();
787 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
791 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
792 // set of known zero and one bits, compute the maximum and minimum values that
793 // could have the specified known zero and known one bits, returning them in
795 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
798 int64_t &Min, int64_t &Max) {
799 uint64_t TypeBits = Ty->getIntegralTypeMask();
800 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
802 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
804 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
805 // bit if it is unknown.
807 Max = KnownOne|UnknownBits;
809 if (SignBit & UnknownBits) { // Sign bit is unknown
814 // Sign extend the min/max values.
815 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
816 Min = (Min << ShAmt) >> ShAmt;
817 Max = (Max << ShAmt) >> ShAmt;
820 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
821 // a set of known zero and one bits, compute the maximum and minimum values that
822 // could have the specified known zero and known one bits, returning them in
824 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
829 uint64_t TypeBits = Ty->getIntegralTypeMask();
830 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
832 // The minimum value is when the unknown bits are all zeros.
834 // The maximum value is when the unknown bits are all ones.
835 Max = KnownOne|UnknownBits;
839 /// SimplifyDemandedBits - Look at V. At this point, we know that only the
840 /// DemandedMask bits of the result of V are ever used downstream. If we can
841 /// use this information to simplify V, do so and return true. Otherwise,
842 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
843 /// the expression (used to simplify the caller). The KnownZero/One bits may
844 /// only be accurate for those bits in the DemandedMask.
845 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
846 uint64_t &KnownZero, uint64_t &KnownOne,
848 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
849 // We know all of the bits for a constant!
850 KnownOne = CI->getZExtValue() & DemandedMask;
851 KnownZero = ~KnownOne & DemandedMask;
855 KnownZero = KnownOne = 0;
856 if (!V->hasOneUse()) { // Other users may use these bits.
857 if (Depth != 0) { // Not at the root.
858 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
859 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
862 // If this is the root being simplified, allow it to have multiple uses,
863 // just set the DemandedMask to all bits.
864 DemandedMask = V->getType()->getIntegralTypeMask();
865 } else if (DemandedMask == 0) { // Not demanding any bits from V.
866 if (V != UndefValue::get(V->getType()))
867 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
869 } else if (Depth == 6) { // Limit search depth.
873 Instruction *I = dyn_cast<Instruction>(V);
874 if (!I) return false; // Only analyze instructions.
876 DemandedMask &= V->getType()->getIntegralTypeMask();
878 uint64_t KnownZero2, KnownOne2;
879 switch (I->getOpcode()) {
881 case Instruction::And:
882 // If either the LHS or the RHS are Zero, the result is zero.
883 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
884 KnownZero, KnownOne, Depth+1))
886 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
888 // If something is known zero on the RHS, the bits aren't demanded on the
890 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
891 KnownZero2, KnownOne2, Depth+1))
893 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
895 // If all of the demanded bits are known one on one side, return the other.
896 // These bits cannot contribute to the result of the 'and'.
897 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
898 return UpdateValueUsesWith(I, I->getOperand(0));
899 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
900 return UpdateValueUsesWith(I, I->getOperand(1));
902 // If all of the demanded bits in the inputs are known zeros, return zero.
903 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
904 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
906 // If the RHS is a constant, see if we can simplify it.
907 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
908 return UpdateValueUsesWith(I, I);
910 // Output known-1 bits are only known if set in both the LHS & RHS.
911 KnownOne &= KnownOne2;
912 // Output known-0 are known to be clear if zero in either the LHS | RHS.
913 KnownZero |= KnownZero2;
915 case Instruction::Or:
916 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
917 KnownZero, KnownOne, Depth+1))
919 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
920 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
921 KnownZero2, KnownOne2, Depth+1))
923 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
925 // If all of the demanded bits are known zero on one side, return the other.
926 // These bits cannot contribute to the result of the 'or'.
927 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
928 return UpdateValueUsesWith(I, I->getOperand(0));
929 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
930 return UpdateValueUsesWith(I, I->getOperand(1));
932 // If all of the potentially set bits on one side are known to be set on
933 // the other side, just use the 'other' side.
934 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
935 (DemandedMask & (~KnownZero)))
936 return UpdateValueUsesWith(I, I->getOperand(0));
937 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
938 (DemandedMask & (~KnownZero2)))
939 return UpdateValueUsesWith(I, I->getOperand(1));
941 // If the RHS is a constant, see if we can simplify it.
942 if (ShrinkDemandedConstant(I, 1, DemandedMask))
943 return UpdateValueUsesWith(I, I);
945 // Output known-0 bits are only known if clear in both the LHS & RHS.
946 KnownZero &= KnownZero2;
947 // Output known-1 are known to be set if set in either the LHS | RHS.
948 KnownOne |= KnownOne2;
950 case Instruction::Xor: {
951 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
952 KnownZero, KnownOne, Depth+1))
954 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
955 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
956 KnownZero2, KnownOne2, Depth+1))
958 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
960 // If all of the demanded bits are known zero on one side, return the other.
961 // These bits cannot contribute to the result of the 'xor'.
962 if ((DemandedMask & KnownZero) == DemandedMask)
963 return UpdateValueUsesWith(I, I->getOperand(0));
964 if ((DemandedMask & KnownZero2) == DemandedMask)
965 return UpdateValueUsesWith(I, I->getOperand(1));
967 // Output known-0 bits are known if clear or set in both the LHS & RHS.
968 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
969 // Output known-1 are known to be set if set in only one of the LHS, RHS.
970 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
972 // If all of the unknown bits are known to be zero on one side or the other
973 // (but not both) turn this into an *inclusive* or.
974 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
975 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
976 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
978 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
980 InsertNewInstBefore(Or, *I);
981 return UpdateValueUsesWith(I, Or);
985 // If all of the demanded bits on one side are known, and all of the set
986 // bits on that side are also known to be set on the other side, turn this
987 // into an AND, as we know the bits will be cleared.
988 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
989 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
990 if ((KnownOne & KnownOne2) == KnownOne) {
991 Constant *AndC = GetConstantInType(I->getType(),
992 ~KnownOne & DemandedMask);
994 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
995 InsertNewInstBefore(And, *I);
996 return UpdateValueUsesWith(I, And);
1000 // If the RHS is a constant, see if we can simplify it.
1001 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1002 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1003 return UpdateValueUsesWith(I, I);
1005 KnownZero = KnownZeroOut;
1006 KnownOne = KnownOneOut;
1009 case Instruction::Select:
1010 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1011 KnownZero, KnownOne, Depth+1))
1013 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1014 KnownZero2, KnownOne2, Depth+1))
1016 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1017 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1019 // If the operands are constants, see if we can simplify them.
1020 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1021 return UpdateValueUsesWith(I, I);
1022 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1023 return UpdateValueUsesWith(I, I);
1025 // Only known if known in both the LHS and RHS.
1026 KnownOne &= KnownOne2;
1027 KnownZero &= KnownZero2;
1029 case Instruction::Cast: {
1030 const Type *SrcTy = I->getOperand(0)->getType();
1031 if (!SrcTy->isIntegral()) return false;
1033 // If this is an integer truncate or noop, just look in the input.
1034 if (SrcTy->getPrimitiveSizeInBits() >=
1035 I->getType()->getPrimitiveSizeInBits()) {
1036 // Cast to bool is a comparison against 0, which demands all bits. We
1037 // can't propagate anything useful up.
1038 if (I->getType() == Type::BoolTy)
1041 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1042 KnownZero, KnownOne, Depth+1))
1044 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1048 // Sign or Zero extension. Compute the bits in the result that are not
1049 // present in the input.
1050 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
1051 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
1053 // Handle zero extension.
1054 if (!SrcTy->isSigned()) {
1055 DemandedMask &= SrcTy->getIntegralTypeMask();
1056 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1057 KnownZero, KnownOne, Depth+1))
1059 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1060 // The top bits are known to be zero.
1061 KnownZero |= NewBits;
1064 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1065 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
1067 // If any of the sign extended bits are demanded, we know that the sign
1069 if (NewBits & DemandedMask)
1070 InputDemandedBits |= InSignBit;
1072 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1073 KnownZero, KnownOne, Depth+1))
1075 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1077 // If the sign bit of the input is known set or clear, then we know the
1078 // top bits of the result.
1080 // If the input sign bit is known zero, or if the NewBits are not demanded
1081 // convert this into a zero extension.
1082 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1083 // Convert to unsigned first.
1084 Instruction *NewVal;
1085 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
1086 I->getOperand(0)->getName());
1087 InsertNewInstBefore(NewVal, *I);
1088 // Then cast that to the destination type.
1089 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1090 InsertNewInstBefore(NewVal, *I);
1091 return UpdateValueUsesWith(I, NewVal);
1092 } else if (KnownOne & InSignBit) { // Input sign bit known set
1093 KnownOne |= NewBits;
1094 KnownZero &= ~NewBits;
1095 } else { // Input sign bit unknown
1096 KnownZero &= ~NewBits;
1097 KnownOne &= ~NewBits;
1102 case Instruction::Shl:
1103 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1104 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
1105 KnownZero, KnownOne, Depth+1))
1107 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1108 KnownZero <<= SA->getValue();
1109 KnownOne <<= SA->getValue();
1110 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
1113 case Instruction::Shr:
1114 // If this is an arithmetic shift right and only the low-bit is set, we can
1115 // always convert this into a logical shr, even if the shift amount is
1116 // variable. The low bit of the shift cannot be an input sign bit unless
1117 // the shift amount is >= the size of the datatype, which is undefined.
1118 if (DemandedMask == 1 && I->getType()->isSigned()) {
1119 // Convert the input to unsigned.
1120 Instruction *NewVal = new CastInst(I->getOperand(0),
1121 I->getType()->getUnsignedVersion(),
1122 I->getOperand(0)->getName());
1123 InsertNewInstBefore(NewVal, *I);
1124 // Perform the unsigned shift right.
1125 NewVal = new ShiftInst(Instruction::Shr, NewVal, I->getOperand(1),
1127 InsertNewInstBefore(NewVal, *I);
1128 // Then cast that to the destination type.
1129 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1130 InsertNewInstBefore(NewVal, *I);
1131 return UpdateValueUsesWith(I, NewVal);
1134 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
1135 unsigned ShAmt = SA->getValue();
1137 // Compute the new bits that are at the top now.
1138 uint64_t HighBits = (1ULL << ShAmt)-1;
1139 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
1140 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
1141 if (I->getType()->isUnsigned()) { // Unsigned shift right.
1142 if (SimplifyDemandedBits(I->getOperand(0),
1143 (DemandedMask << ShAmt) & TypeMask,
1144 KnownZero, KnownOne, Depth+1))
1146 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1147 KnownZero &= TypeMask;
1148 KnownOne &= TypeMask;
1149 KnownZero >>= ShAmt;
1151 KnownZero |= HighBits; // high bits known zero.
1152 } else { // Signed shift right.
1153 if (SimplifyDemandedBits(I->getOperand(0),
1154 (DemandedMask << ShAmt) & TypeMask,
1155 KnownZero, KnownOne, Depth+1))
1157 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1158 KnownZero &= TypeMask;
1159 KnownOne &= TypeMask;
1160 KnownZero >>= SA->getValue();
1161 KnownOne >>= SA->getValue();
1163 // Handle the sign bits.
1164 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1165 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
1167 // If the input sign bit is known to be zero, or if none of the top bits
1168 // are demanded, turn this into an unsigned shift right.
1169 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1170 // Convert the input to unsigned.
1171 Instruction *NewVal;
1172 NewVal = new CastInst(I->getOperand(0),
1173 I->getType()->getUnsignedVersion(),
1174 I->getOperand(0)->getName());
1175 InsertNewInstBefore(NewVal, *I);
1176 // Perform the unsigned shift right.
1177 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
1178 InsertNewInstBefore(NewVal, *I);
1179 // Then cast that to the destination type.
1180 NewVal = new CastInst(NewVal, I->getType(), I->getName());
1181 InsertNewInstBefore(NewVal, *I);
1182 return UpdateValueUsesWith(I, NewVal);
1183 } else if (KnownOne & SignBit) { // New bits are known one.
1184 KnownOne |= HighBits;
1191 // If the client is only demanding bits that we know, return the known
1193 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1194 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
1199 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1200 /// 64 or fewer elements. DemandedElts contains the set of elements that are
1201 /// actually used by the caller. This method analyzes which elements of the
1202 /// operand are undef and returns that information in UndefElts.
1204 /// If the information about demanded elements can be used to simplify the
1205 /// operation, the operation is simplified, then the resultant value is
1206 /// returned. This returns null if no change was made.
1207 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1208 uint64_t &UndefElts,
1210 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1211 assert(VWidth <= 64 && "Vector too wide to analyze!");
1212 uint64_t EltMask = ~0ULL >> (64-VWidth);
1213 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1214 "Invalid DemandedElts!");
1216 if (isa<UndefValue>(V)) {
1217 // If the entire vector is undefined, just return this info.
1218 UndefElts = EltMask;
1220 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1221 UndefElts = EltMask;
1222 return UndefValue::get(V->getType());
1226 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1227 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1228 Constant *Undef = UndefValue::get(EltTy);
1230 std::vector<Constant*> Elts;
1231 for (unsigned i = 0; i != VWidth; ++i)
1232 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1233 Elts.push_back(Undef);
1234 UndefElts |= (1ULL << i);
1235 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1236 Elts.push_back(Undef);
1237 UndefElts |= (1ULL << i);
1238 } else { // Otherwise, defined.
1239 Elts.push_back(CP->getOperand(i));
1242 // If we changed the constant, return it.
1243 Constant *NewCP = ConstantPacked::get(Elts);
1244 return NewCP != CP ? NewCP : 0;
1245 } else if (isa<ConstantAggregateZero>(V)) {
1246 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1248 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1249 Constant *Zero = Constant::getNullValue(EltTy);
1250 Constant *Undef = UndefValue::get(EltTy);
1251 std::vector<Constant*> Elts;
1252 for (unsigned i = 0; i != VWidth; ++i)
1253 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1254 UndefElts = DemandedElts ^ EltMask;
1255 return ConstantPacked::get(Elts);
1258 if (!V->hasOneUse()) { // Other users may use these bits.
1259 if (Depth != 0) { // Not at the root.
1260 // TODO: Just compute the UndefElts information recursively.
1264 } else if (Depth == 10) { // Limit search depth.
1268 Instruction *I = dyn_cast<Instruction>(V);
1269 if (!I) return false; // Only analyze instructions.
1271 bool MadeChange = false;
1272 uint64_t UndefElts2;
1274 switch (I->getOpcode()) {
1277 case Instruction::InsertElement: {
1278 // If this is a variable index, we don't know which element it overwrites.
1279 // demand exactly the same input as we produce.
1280 ConstantUInt *Idx = dyn_cast<ConstantUInt>(I->getOperand(2));
1282 // Note that we can't propagate undef elt info, because we don't know
1283 // which elt is getting updated.
1284 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1285 UndefElts2, Depth+1);
1286 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1290 // If this is inserting an element that isn't demanded, remove this
1292 unsigned IdxNo = Idx->getValue();
1293 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1294 return AddSoonDeadInstToWorklist(*I, 0);
1296 // Otherwise, the element inserted overwrites whatever was there, so the
1297 // input demanded set is simpler than the output set.
1298 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1299 DemandedElts & ~(1ULL << IdxNo),
1300 UndefElts, Depth+1);
1301 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1303 // The inserted element is defined.
1304 UndefElts |= 1ULL << IdxNo;
1308 case Instruction::And:
1309 case Instruction::Or:
1310 case Instruction::Xor:
1311 case Instruction::Add:
1312 case Instruction::Sub:
1313 case Instruction::Mul:
1314 // div/rem demand all inputs, because they don't want divide by zero.
1315 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1316 UndefElts, Depth+1);
1317 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1318 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1319 UndefElts2, Depth+1);
1320 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1322 // Output elements are undefined if both are undefined. Consider things
1323 // like undef&0. The result is known zero, not undef.
1324 UndefElts &= UndefElts2;
1327 case Instruction::Call: {
1328 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1330 switch (II->getIntrinsicID()) {
1333 // Binary vector operations that work column-wise. A dest element is a
1334 // function of the corresponding input elements from the two inputs.
1335 case Intrinsic::x86_sse_sub_ss:
1336 case Intrinsic::x86_sse_mul_ss:
1337 case Intrinsic::x86_sse_min_ss:
1338 case Intrinsic::x86_sse_max_ss:
1339 case Intrinsic::x86_sse2_sub_sd:
1340 case Intrinsic::x86_sse2_mul_sd:
1341 case Intrinsic::x86_sse2_min_sd:
1342 case Intrinsic::x86_sse2_max_sd:
1343 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1344 UndefElts, Depth+1);
1345 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1346 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1347 UndefElts2, Depth+1);
1348 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1350 // If only the low elt is demanded and this is a scalarizable intrinsic,
1351 // scalarize it now.
1352 if (DemandedElts == 1) {
1353 switch (II->getIntrinsicID()) {
1355 case Intrinsic::x86_sse_sub_ss:
1356 case Intrinsic::x86_sse_mul_ss:
1357 case Intrinsic::x86_sse2_sub_sd:
1358 case Intrinsic::x86_sse2_mul_sd:
1359 // TODO: Lower MIN/MAX/ABS/etc
1360 Value *LHS = II->getOperand(1);
1361 Value *RHS = II->getOperand(2);
1362 // Extract the element as scalars.
1363 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1364 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1366 switch (II->getIntrinsicID()) {
1367 default: assert(0 && "Case stmts out of sync!");
1368 case Intrinsic::x86_sse_sub_ss:
1369 case Intrinsic::x86_sse2_sub_sd:
1370 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1371 II->getName()), *II);
1373 case Intrinsic::x86_sse_mul_ss:
1374 case Intrinsic::x86_sse2_mul_sd:
1375 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1376 II->getName()), *II);
1381 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1383 InsertNewInstBefore(New, *II);
1384 AddSoonDeadInstToWorklist(*II, 0);
1389 // Output elements are undefined if both are undefined. Consider things
1390 // like undef&0. The result is known zero, not undef.
1391 UndefElts &= UndefElts2;
1397 return MadeChange ? I : 0;
1400 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
1401 // true when both operands are equal...
1403 static bool isTrueWhenEqual(Instruction &I) {
1404 return I.getOpcode() == Instruction::SetEQ ||
1405 I.getOpcode() == Instruction::SetGE ||
1406 I.getOpcode() == Instruction::SetLE;
1409 /// AssociativeOpt - Perform an optimization on an associative operator. This
1410 /// function is designed to check a chain of associative operators for a
1411 /// potential to apply a certain optimization. Since the optimization may be
1412 /// applicable if the expression was reassociated, this checks the chain, then
1413 /// reassociates the expression as necessary to expose the optimization
1414 /// opportunity. This makes use of a special Functor, which must define
1415 /// 'shouldApply' and 'apply' methods.
1417 template<typename Functor>
1418 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1419 unsigned Opcode = Root.getOpcode();
1420 Value *LHS = Root.getOperand(0);
1422 // Quick check, see if the immediate LHS matches...
1423 if (F.shouldApply(LHS))
1424 return F.apply(Root);
1426 // Otherwise, if the LHS is not of the same opcode as the root, return.
1427 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1428 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1429 // Should we apply this transform to the RHS?
1430 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1432 // If not to the RHS, check to see if we should apply to the LHS...
1433 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1434 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1438 // If the functor wants to apply the optimization to the RHS of LHSI,
1439 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1441 BasicBlock *BB = Root.getParent();
1443 // Now all of the instructions are in the current basic block, go ahead
1444 // and perform the reassociation.
1445 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1447 // First move the selected RHS to the LHS of the root...
1448 Root.setOperand(0, LHSI->getOperand(1));
1450 // Make what used to be the LHS of the root be the user of the root...
1451 Value *ExtraOperand = TmpLHSI->getOperand(1);
1452 if (&Root == TmpLHSI) {
1453 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1456 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1457 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1458 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1459 BasicBlock::iterator ARI = &Root; ++ARI;
1460 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1463 // Now propagate the ExtraOperand down the chain of instructions until we
1465 while (TmpLHSI != LHSI) {
1466 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1467 // Move the instruction to immediately before the chain we are
1468 // constructing to avoid breaking dominance properties.
1469 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1470 BB->getInstList().insert(ARI, NextLHSI);
1473 Value *NextOp = NextLHSI->getOperand(1);
1474 NextLHSI->setOperand(1, ExtraOperand);
1476 ExtraOperand = NextOp;
1479 // Now that the instructions are reassociated, have the functor perform
1480 // the transformation...
1481 return F.apply(Root);
1484 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1490 // AddRHS - Implements: X + X --> X << 1
1493 AddRHS(Value *rhs) : RHS(rhs) {}
1494 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1495 Instruction *apply(BinaryOperator &Add) const {
1496 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1497 ConstantInt::get(Type::UByteTy, 1));
1501 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1503 struct AddMaskingAnd {
1505 AddMaskingAnd(Constant *c) : C2(c) {}
1506 bool shouldApply(Value *LHS) const {
1508 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1509 ConstantExpr::getAnd(C1, C2)->isNullValue();
1511 Instruction *apply(BinaryOperator &Add) const {
1512 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1516 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1518 if (isa<CastInst>(I)) {
1519 if (Constant *SOC = dyn_cast<Constant>(SO))
1520 return ConstantExpr::getCast(SOC, I.getType());
1522 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1523 SO->getName() + ".cast"), I);
1526 // Figure out if the constant is the left or the right argument.
1527 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1528 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1530 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1532 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1533 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1536 Value *Op0 = SO, *Op1 = ConstOperand;
1538 std::swap(Op0, Op1);
1540 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1541 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1542 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1543 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1545 assert(0 && "Unknown binary instruction type!");
1548 return IC->InsertNewInstBefore(New, I);
1551 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1552 // constant as the other operand, try to fold the binary operator into the
1553 // select arguments. This also works for Cast instructions, which obviously do
1554 // not have a second operand.
1555 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1557 // Don't modify shared select instructions
1558 if (!SI->hasOneUse()) return 0;
1559 Value *TV = SI->getOperand(1);
1560 Value *FV = SI->getOperand(2);
1562 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1563 // Bool selects with constant operands can be folded to logical ops.
1564 if (SI->getType() == Type::BoolTy) return 0;
1566 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1567 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1569 return new SelectInst(SI->getCondition(), SelectTrueVal,
1576 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1577 /// node as operand #0, see if we can fold the instruction into the PHI (which
1578 /// is only possible if all operands to the PHI are constants).
1579 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1580 PHINode *PN = cast<PHINode>(I.getOperand(0));
1581 unsigned NumPHIValues = PN->getNumIncomingValues();
1582 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1584 // Check to see if all of the operands of the PHI are constants. If there is
1585 // one non-constant value, remember the BB it is. If there is more than one
1587 BasicBlock *NonConstBB = 0;
1588 for (unsigned i = 0; i != NumPHIValues; ++i)
1589 if (!isa<Constant>(PN->getIncomingValue(i))) {
1590 if (NonConstBB) return 0; // More than one non-const value.
1591 NonConstBB = PN->getIncomingBlock(i);
1593 // If the incoming non-constant value is in I's block, we have an infinite
1595 if (NonConstBB == I.getParent())
1599 // If there is exactly one non-constant value, we can insert a copy of the
1600 // operation in that block. However, if this is a critical edge, we would be
1601 // inserting the computation one some other paths (e.g. inside a loop). Only
1602 // do this if the pred block is unconditionally branching into the phi block.
1604 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1605 if (!BI || !BI->isUnconditional()) return 0;
1608 // Okay, we can do the transformation: create the new PHI node.
1609 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1611 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1612 InsertNewInstBefore(NewPN, *PN);
1614 // Next, add all of the operands to the PHI.
1615 if (I.getNumOperands() == 2) {
1616 Constant *C = cast<Constant>(I.getOperand(1));
1617 for (unsigned i = 0; i != NumPHIValues; ++i) {
1619 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1620 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1622 assert(PN->getIncomingBlock(i) == NonConstBB);
1623 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1624 InV = BinaryOperator::create(BO->getOpcode(),
1625 PN->getIncomingValue(i), C, "phitmp",
1626 NonConstBB->getTerminator());
1627 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1628 InV = new ShiftInst(SI->getOpcode(),
1629 PN->getIncomingValue(i), C, "phitmp",
1630 NonConstBB->getTerminator());
1632 assert(0 && "Unknown binop!");
1634 WorkList.push_back(cast<Instruction>(InV));
1636 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1639 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1640 const Type *RetTy = I.getType();
1641 for (unsigned i = 0; i != NumPHIValues; ++i) {
1643 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1644 InV = ConstantExpr::getCast(InC, RetTy);
1646 assert(PN->getIncomingBlock(i) == NonConstBB);
1647 InV = new CastInst(PN->getIncomingValue(i), I.getType(), "phitmp",
1648 NonConstBB->getTerminator());
1649 WorkList.push_back(cast<Instruction>(InV));
1651 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1654 return ReplaceInstUsesWith(I, NewPN);
1657 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1658 bool Changed = SimplifyCommutative(I);
1659 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1661 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1662 // X + undef -> undef
1663 if (isa<UndefValue>(RHS))
1664 return ReplaceInstUsesWith(I, RHS);
1667 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1668 if (RHSC->isNullValue())
1669 return ReplaceInstUsesWith(I, LHS);
1670 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1671 if (CFP->isExactlyValue(-0.0))
1672 return ReplaceInstUsesWith(I, LHS);
1675 // X + (signbit) --> X ^ signbit
1676 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1677 uint64_t Val = CI->getZExtValue();
1678 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1679 return BinaryOperator::createXor(LHS, RHS);
1682 if (isa<PHINode>(LHS))
1683 if (Instruction *NV = FoldOpIntoPhi(I))
1686 ConstantInt *XorRHS = 0;
1688 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1689 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1690 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1691 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1693 uint64_t C0080Val = 1ULL << 31;
1694 int64_t CFF80Val = -C0080Val;
1697 if (TySizeBits > Size) {
1699 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1700 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1701 if (RHSSExt == CFF80Val) {
1702 if (XorRHS->getZExtValue() == C0080Val)
1704 } else if (RHSZExt == C0080Val) {
1705 if (XorRHS->getSExtValue() == CFF80Val)
1709 // This is a sign extend if the top bits are known zero.
1710 uint64_t Mask = ~0ULL;
1711 Mask <<= 64-(TySizeBits-Size);
1712 Mask &= XorLHS->getType()->getIntegralTypeMask();
1713 if (!MaskedValueIsZero(XorLHS, Mask))
1714 Size = 0; // Not a sign ext, but can't be any others either.
1721 } while (Size >= 8);
1724 const Type *MiddleType = 0;
1727 case 32: MiddleType = Type::IntTy; break;
1728 case 16: MiddleType = Type::ShortTy; break;
1729 case 8: MiddleType = Type::SByteTy; break;
1732 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1733 InsertNewInstBefore(NewTrunc, I);
1734 return new CastInst(NewTrunc, I.getType());
1740 if (I.getType()->isInteger()) {
1741 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1743 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1744 if (RHSI->getOpcode() == Instruction::Sub)
1745 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1746 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1748 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1749 if (LHSI->getOpcode() == Instruction::Sub)
1750 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1751 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1756 if (Value *V = dyn_castNegVal(LHS))
1757 return BinaryOperator::createSub(RHS, V);
1760 if (!isa<Constant>(RHS))
1761 if (Value *V = dyn_castNegVal(RHS))
1762 return BinaryOperator::createSub(LHS, V);
1766 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1767 if (X == RHS) // X*C + X --> X * (C+1)
1768 return BinaryOperator::createMul(RHS, AddOne(C2));
1770 // X*C1 + X*C2 --> X * (C1+C2)
1772 if (X == dyn_castFoldableMul(RHS, C1))
1773 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1776 // X + X*C --> X * (C+1)
1777 if (dyn_castFoldableMul(RHS, C2) == LHS)
1778 return BinaryOperator::createMul(LHS, AddOne(C2));
1781 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1782 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1783 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
1785 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1787 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1788 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1789 return BinaryOperator::createSub(C, X);
1792 // (X & FF00) + xx00 -> (X+xx00) & FF00
1793 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1794 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1795 if (Anded == CRHS) {
1796 // See if all bits from the first bit set in the Add RHS up are included
1797 // in the mask. First, get the rightmost bit.
1798 uint64_t AddRHSV = CRHS->getRawValue();
1800 // Form a mask of all bits from the lowest bit added through the top.
1801 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1802 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
1804 // See if the and mask includes all of these bits.
1805 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
1807 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1808 // Okay, the xform is safe. Insert the new add pronto.
1809 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1810 LHS->getName()), I);
1811 return BinaryOperator::createAnd(NewAdd, C2);
1816 // Try to fold constant add into select arguments.
1817 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1818 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1822 // add (cast *A to intptrtype) B -> cast (GEP (cast *A to sbyte*) B) -> intptrtype
1824 CastInst* CI = dyn_cast<CastInst>(LHS);
1827 CI = dyn_cast<CastInst>(RHS);
1830 if (CI && CI->getType()->isSized() &&
1831 (CI->getType()->getPrimitiveSize() ==
1832 TD->getIntPtrType()->getPrimitiveSize())
1833 && isa<PointerType>(CI->getOperand(0)->getType())) {
1834 Value* I2 = InsertCastBefore(CI->getOperand(0),
1835 PointerType::get(Type::SByteTy), I);
1836 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1837 return new CastInst(I2, CI->getType());
1841 return Changed ? &I : 0;
1844 // isSignBit - Return true if the value represented by the constant only has the
1845 // highest order bit set.
1846 static bool isSignBit(ConstantInt *CI) {
1847 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1848 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1851 /// RemoveNoopCast - Strip off nonconverting casts from the value.
1853 static Value *RemoveNoopCast(Value *V) {
1854 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1855 const Type *CTy = CI->getType();
1856 const Type *OpTy = CI->getOperand(0)->getType();
1857 if (CTy->isInteger() && OpTy->isInteger()) {
1858 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
1859 return RemoveNoopCast(CI->getOperand(0));
1860 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1861 return RemoveNoopCast(CI->getOperand(0));
1866 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1867 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1869 if (Op0 == Op1) // sub X, X -> 0
1870 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1872 // If this is a 'B = x-(-A)', change to B = x+A...
1873 if (Value *V = dyn_castNegVal(Op1))
1874 return BinaryOperator::createAdd(Op0, V);
1876 if (isa<UndefValue>(Op0))
1877 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1878 if (isa<UndefValue>(Op1))
1879 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1881 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1882 // Replace (-1 - A) with (~A)...
1883 if (C->isAllOnesValue())
1884 return BinaryOperator::createNot(Op1);
1886 // C - ~X == X + (1+C)
1888 if (match(Op1, m_Not(m_Value(X))))
1889 return BinaryOperator::createAdd(X,
1890 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1891 // -((uint)X >> 31) -> ((int)X >> 31)
1892 // -((int)X >> 31) -> ((uint)X >> 31)
1893 if (C->isNullValue()) {
1894 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1895 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
1896 if (SI->getOpcode() == Instruction::Shr)
1897 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1899 if (SI->getType()->isSigned())
1900 NewTy = SI->getType()->getUnsignedVersion();
1902 NewTy = SI->getType()->getSignedVersion();
1903 // Check to see if we are shifting out everything but the sign bit.
1904 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
1905 // Ok, the transformation is safe. Insert a cast of the incoming
1906 // value, then the new shift, then the new cast.
1907 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1908 SI->getOperand(0)->getName());
1909 Value *InV = InsertNewInstBefore(FirstCast, I);
1910 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1912 if (NewShift->getType() == I.getType())
1915 InV = InsertNewInstBefore(NewShift, I);
1916 return new CastInst(NewShift, I.getType());
1922 // Try to fold constant sub into select arguments.
1923 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1924 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1927 if (isa<PHINode>(Op0))
1928 if (Instruction *NV = FoldOpIntoPhi(I))
1932 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1933 if (Op1I->getOpcode() == Instruction::Add &&
1934 !Op0->getType()->isFloatingPoint()) {
1935 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
1936 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
1937 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
1938 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
1939 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1940 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1941 // C1-(X+C2) --> (C1-C2)-X
1942 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1943 Op1I->getOperand(0));
1947 if (Op1I->hasOneUse()) {
1948 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1949 // is not used by anyone else...
1951 if (Op1I->getOpcode() == Instruction::Sub &&
1952 !Op1I->getType()->isFloatingPoint()) {
1953 // Swap the two operands of the subexpr...
1954 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1955 Op1I->setOperand(0, IIOp1);
1956 Op1I->setOperand(1, IIOp0);
1958 // Create the new top level add instruction...
1959 return BinaryOperator::createAdd(Op0, Op1);
1962 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1964 if (Op1I->getOpcode() == Instruction::And &&
1965 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1966 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1969 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
1970 return BinaryOperator::createAnd(Op0, NewNot);
1973 // 0 - (X sdiv C) -> (X sdiv -C)
1974 if (Op1I->getOpcode() == Instruction::Div)
1975 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1976 if (CSI->isNullValue())
1977 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
1978 return BinaryOperator::createDiv(Op1I->getOperand(0),
1979 ConstantExpr::getNeg(DivRHS));
1981 // X - X*C --> X * (1-C)
1982 ConstantInt *C2 = 0;
1983 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
1985 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
1986 return BinaryOperator::createMul(Op0, CP1);
1991 if (!Op0->getType()->isFloatingPoint())
1992 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1993 if (Op0I->getOpcode() == Instruction::Add) {
1994 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1995 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1996 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1997 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1998 } else if (Op0I->getOpcode() == Instruction::Sub) {
1999 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2000 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2004 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2005 if (X == Op1) { // X*C - X --> X * (C-1)
2006 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2007 return BinaryOperator::createMul(Op1, CP1);
2010 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2011 if (X == dyn_castFoldableMul(Op1, C2))
2012 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2017 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
2018 /// really just returns true if the most significant (sign) bit is set.
2019 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
2020 if (RHS->getType()->isSigned()) {
2021 // True if source is LHS < 0 or LHS <= -1
2022 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
2023 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
2025 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
2026 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
2027 // the size of the integer type.
2028 if (Opcode == Instruction::SetGE)
2029 return RHSC->getValue() ==
2030 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
2031 if (Opcode == Instruction::SetGT)
2032 return RHSC->getValue() ==
2033 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2038 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2039 bool Changed = SimplifyCommutative(I);
2040 Value *Op0 = I.getOperand(0);
2042 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2043 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2045 // Simplify mul instructions with a constant RHS...
2046 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2047 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2049 // ((X << C1)*C2) == (X * (C2 << C1))
2050 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2051 if (SI->getOpcode() == Instruction::Shl)
2052 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2053 return BinaryOperator::createMul(SI->getOperand(0),
2054 ConstantExpr::getShl(CI, ShOp));
2056 if (CI->isNullValue())
2057 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2058 if (CI->equalsInt(1)) // X * 1 == X
2059 return ReplaceInstUsesWith(I, Op0);
2060 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2061 return BinaryOperator::createNeg(Op0, I.getName());
2063 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
2064 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2065 uint64_t C = Log2_64(Val);
2066 return new ShiftInst(Instruction::Shl, Op0,
2067 ConstantUInt::get(Type::UByteTy, C));
2069 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2070 if (Op1F->isNullValue())
2071 return ReplaceInstUsesWith(I, Op1);
2073 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2074 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2075 if (Op1F->getValue() == 1.0)
2076 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2079 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2080 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2081 isa<ConstantInt>(Op0I->getOperand(1))) {
2082 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2083 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2085 InsertNewInstBefore(Add, I);
2086 Value *C1C2 = ConstantExpr::getMul(Op1,
2087 cast<Constant>(Op0I->getOperand(1)));
2088 return BinaryOperator::createAdd(Add, C1C2);
2092 // Try to fold constant mul into select arguments.
2093 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2094 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2097 if (isa<PHINode>(Op0))
2098 if (Instruction *NV = FoldOpIntoPhi(I))
2102 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2103 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2104 return BinaryOperator::createMul(Op0v, Op1v);
2106 // If one of the operands of the multiply is a cast from a boolean value, then
2107 // we know the bool is either zero or one, so this is a 'masking' multiply.
2108 // See if we can simplify things based on how the boolean was originally
2110 CastInst *BoolCast = 0;
2111 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
2112 if (CI->getOperand(0)->getType() == Type::BoolTy)
2115 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
2116 if (CI->getOperand(0)->getType() == Type::BoolTy)
2119 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
2120 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2121 const Type *SCOpTy = SCIOp0->getType();
2123 // If the setcc is true iff the sign bit of X is set, then convert this
2124 // multiply into a shift/and combination.
2125 if (isa<ConstantInt>(SCIOp1) &&
2126 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
2127 // Shift the X value right to turn it into "all signbits".
2128 Constant *Amt = ConstantUInt::get(Type::UByteTy,
2129 SCOpTy->getPrimitiveSizeInBits()-1);
2130 if (SCIOp0->getType()->isUnsigned()) {
2131 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
2132 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
2133 SCIOp0->getName()), I);
2137 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
2138 BoolCast->getOperand(0)->getName()+
2141 // If the multiply type is not the same as the source type, sign extend
2142 // or truncate to the multiply type.
2143 if (I.getType() != V->getType())
2144 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
2146 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2147 return BinaryOperator::createAnd(V, OtherOp);
2152 return Changed ? &I : 0;
2155 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
2156 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2158 if (isa<UndefValue>(Op0)) // undef / X -> 0
2159 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2160 if (isa<UndefValue>(Op1))
2161 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
2163 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2165 if (RHS->equalsInt(1))
2166 return ReplaceInstUsesWith(I, Op0);
2169 if (RHS->isAllOnesValue())
2170 return BinaryOperator::createNeg(Op0);
2172 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2173 if (LHS->getOpcode() == Instruction::Div)
2174 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2175 // (X / C1) / C2 -> X / (C1*C2)
2176 return BinaryOperator::createDiv(LHS->getOperand(0),
2177 ConstantExpr::getMul(RHS, LHSRHS));
2180 // Check to see if this is an unsigned division with an exact power of 2,
2181 // if so, convert to a right shift.
2182 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
2183 if (uint64_t Val = C->getValue()) // Don't break X / 0
2184 if (isPowerOf2_64(Val)) {
2185 uint64_t C = Log2_64(Val);
2186 return new ShiftInst(Instruction::Shr, Op0,
2187 ConstantUInt::get(Type::UByteTy, C));
2191 if (RHS->getType()->isSigned())
2192 if (Value *LHSNeg = dyn_castNegVal(Op0))
2193 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2195 if (!RHS->isNullValue()) {
2196 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2197 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2199 if (isa<PHINode>(Op0))
2200 if (Instruction *NV = FoldOpIntoPhi(I))
2205 // Handle div X, Cond?Y:Z
2206 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2207 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
2208 // same basic block, then we replace the select with Y, and the condition of
2209 // the select with false (if the cond value is in the same BB). If the
2210 // select has uses other than the div, this allows them to be simplified
2212 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2213 if (ST->isNullValue()) {
2214 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2215 if (CondI && CondI->getParent() == I.getParent())
2216 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2217 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2218 I.setOperand(1, SI->getOperand(2));
2220 UpdateValueUsesWith(SI, SI->getOperand(2));
2223 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2224 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2225 if (ST->isNullValue()) {
2226 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2227 if (CondI && CondI->getParent() == I.getParent())
2228 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2229 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2230 I.setOperand(1, SI->getOperand(1));
2232 UpdateValueUsesWith(SI, SI->getOperand(1));
2236 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2237 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
2238 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
2239 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
2240 // STO == 0 and SFO == 0 handled above.
2241 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
2242 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2243 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2244 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
2245 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
2246 TC, SI->getName()+".t");
2247 TSI = InsertNewInstBefore(TSI, I);
2249 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
2250 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
2251 FC, SI->getName()+".f");
2252 FSI = InsertNewInstBefore(FSI, I);
2253 return new SelectInst(SI->getOperand(0), TSI, FSI);
2258 // 0 / X == 0, we don't need to preserve faults!
2259 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2260 if (LHS->equalsInt(0))
2261 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2263 if (I.getType()->isSigned()) {
2264 // If the sign bits of both operands are zero (i.e. we can prove they are
2265 // unsigned inputs), turn this into a udiv.
2266 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2267 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2268 const Type *NTy = Op0->getType()->getUnsignedVersion();
2269 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2270 InsertNewInstBefore(LHS, I);
2272 if (Constant *R = dyn_cast<Constant>(Op1))
2273 RHS = ConstantExpr::getCast(R, NTy);
2275 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2276 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
2277 InsertNewInstBefore(Div, I);
2278 return new CastInst(Div, I.getType());
2281 // Known to be an unsigned division.
2282 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2283 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
2284 if (RHSI->getOpcode() == Instruction::Shl &&
2285 isa<ConstantUInt>(RHSI->getOperand(0))) {
2286 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
2287 if (isPowerOf2_64(C1)) {
2288 unsigned C2 = Log2_64(C1);
2289 Value *Add = RHSI->getOperand(1);
2291 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
2292 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
2295 return new ShiftInst(Instruction::Shr, Op0, Add);
2305 /// GetFactor - If we can prove that the specified value is at least a multiple
2306 /// of some factor, return that factor.
2307 static Constant *GetFactor(Value *V) {
2308 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2311 // Unless we can be tricky, we know this is a multiple of 1.
2312 Constant *Result = ConstantInt::get(V->getType(), 1);
2314 Instruction *I = dyn_cast<Instruction>(V);
2315 if (!I) return Result;
2317 if (I->getOpcode() == Instruction::Mul) {
2318 // Handle multiplies by a constant, etc.
2319 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2320 GetFactor(I->getOperand(1)));
2321 } else if (I->getOpcode() == Instruction::Shl) {
2322 // (X<<C) -> X * (1 << C)
2323 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2324 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2325 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2327 } else if (I->getOpcode() == Instruction::And) {
2328 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2329 // X & 0xFFF0 is known to be a multiple of 16.
2330 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2331 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2332 return ConstantExpr::getShl(Result,
2333 ConstantUInt::get(Type::UByteTy, Zeros));
2335 } else if (I->getOpcode() == Instruction::Cast) {
2336 Value *Op = I->getOperand(0);
2337 // Only handle int->int casts.
2338 if (!Op->getType()->isInteger()) return Result;
2339 return ConstantExpr::getCast(GetFactor(Op), V->getType());
2344 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
2345 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2347 // 0 % X == 0, we don't need to preserve faults!
2348 if (Constant *LHS = dyn_cast<Constant>(Op0))
2349 if (LHS->isNullValue())
2350 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2352 if (isa<UndefValue>(Op0)) // undef % X -> 0
2353 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2354 if (isa<UndefValue>(Op1))
2355 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2357 if (I.getType()->isSigned()) {
2358 if (Value *RHSNeg = dyn_castNegVal(Op1))
2359 if (!isa<ConstantSInt>(RHSNeg) ||
2360 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
2362 AddUsesToWorkList(I);
2363 I.setOperand(1, RHSNeg);
2367 // If the top bits of both operands are zero (i.e. we can prove they are
2368 // unsigned inputs), turn this into a urem.
2369 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2370 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2371 const Type *NTy = Op0->getType()->getUnsignedVersion();
2372 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
2373 InsertNewInstBefore(LHS, I);
2375 if (Constant *R = dyn_cast<Constant>(Op1))
2376 RHS = ConstantExpr::getCast(R, NTy);
2378 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
2379 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
2380 InsertNewInstBefore(Rem, I);
2381 return new CastInst(Rem, I.getType());
2385 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2386 // X % 0 == undef, we don't need to preserve faults!
2387 if (RHS->equalsInt(0))
2388 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2390 if (RHS->equalsInt(1)) // X % 1 == 0
2391 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2393 // Check to see if this is an unsigned remainder with an exact power of 2,
2394 // if so, convert to a bitwise and.
2395 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
2396 if (isPowerOf2_64(C->getValue()))
2397 return BinaryOperator::createAnd(Op0, SubOne(C));
2399 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2400 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2401 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2403 } else if (isa<PHINode>(Op0I)) {
2404 if (Instruction *NV = FoldOpIntoPhi(I))
2408 // X*C1%C2 --> 0 iff C1%C2 == 0
2409 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
2410 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2414 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2415 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
2416 if (I.getType()->isUnsigned() &&
2417 RHSI->getOpcode() == Instruction::Shl &&
2418 isa<ConstantUInt>(RHSI->getOperand(0))) {
2419 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
2420 if (isPowerOf2_64(C1)) {
2421 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2422 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2424 return BinaryOperator::createAnd(Op0, Add);
2428 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
2429 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
2430 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2431 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2432 // the same basic block, then we replace the select with Y, and the
2433 // condition of the select with false (if the cond value is in the same
2434 // BB). If the select has uses other than the div, this allows them to be
2436 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2437 if (ST->isNullValue()) {
2438 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2439 if (CondI && CondI->getParent() == I.getParent())
2440 UpdateValueUsesWith(CondI, ConstantBool::getFalse());
2441 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2442 I.setOperand(1, SI->getOperand(2));
2444 UpdateValueUsesWith(SI, SI->getOperand(2));
2447 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2448 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2449 if (ST->isNullValue()) {
2450 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2451 if (CondI && CondI->getParent() == I.getParent())
2452 UpdateValueUsesWith(CondI, ConstantBool::getTrue());
2453 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2454 I.setOperand(1, SI->getOperand(1));
2456 UpdateValueUsesWith(SI, SI->getOperand(1));
2461 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
2462 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
2463 // STO == 0 and SFO == 0 handled above.
2465 if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
2466 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2467 SubOne(STO), SI->getName()+".t"), I);
2468 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
2469 SubOne(SFO), SI->getName()+".f"), I);
2470 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2479 // isMaxValueMinusOne - return true if this is Max-1
2480 static bool isMaxValueMinusOne(const ConstantInt *C) {
2481 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2482 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
2484 const ConstantSInt *CS = cast<ConstantSInt>(C);
2486 // Calculate 0111111111..11111
2487 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2488 int64_t Val = INT64_MAX; // All ones
2489 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2490 return CS->getValue() == Val-1;
2493 // isMinValuePlusOne - return true if this is Min+1
2494 static bool isMinValuePlusOne(const ConstantInt *C) {
2495 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
2496 return CU->getValue() == 1;
2498 const ConstantSInt *CS = cast<ConstantSInt>(C);
2500 // Calculate 1111111111000000000000
2501 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2502 int64_t Val = -1; // All ones
2503 Val <<= TypeBits-1; // Shift over to the right spot
2504 return CS->getValue() == Val+1;
2507 // isOneBitSet - Return true if there is exactly one bit set in the specified
2509 static bool isOneBitSet(const ConstantInt *CI) {
2510 uint64_t V = CI->getRawValue();
2511 return V && (V & (V-1)) == 0;
2514 #if 0 // Currently unused
2515 // isLowOnes - Return true if the constant is of the form 0+1+.
2516 static bool isLowOnes(const ConstantInt *CI) {
2517 uint64_t V = CI->getRawValue();
2519 // There won't be bits set in parts that the type doesn't contain.
2520 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2522 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2523 return U && V && (U & V) == 0;
2527 // isHighOnes - Return true if the constant is of the form 1+0+.
2528 // This is the same as lowones(~X).
2529 static bool isHighOnes(const ConstantInt *CI) {
2530 uint64_t V = ~CI->getRawValue();
2531 if (~V == 0) return false; // 0's does not match "1+"
2533 // There won't be bits set in parts that the type doesn't contain.
2534 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2536 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2537 return U && V && (U & V) == 0;
2541 /// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2542 /// are carefully arranged to allow folding of expressions such as:
2544 /// (A < B) | (A > B) --> (A != B)
2546 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2547 /// represents that the comparison is true if A == B, and bit value '1' is true
2550 static unsigned getSetCondCode(const SetCondInst *SCI) {
2551 switch (SCI->getOpcode()) {
2553 case Instruction::SetGT: return 1;
2554 case Instruction::SetEQ: return 2;
2555 case Instruction::SetGE: return 3;
2556 case Instruction::SetLT: return 4;
2557 case Instruction::SetNE: return 5;
2558 case Instruction::SetLE: return 6;
2561 assert(0 && "Invalid SetCC opcode!");
2566 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
2567 /// opcode and two operands into either a constant true or false, or a brand new
2568 /// SetCC instruction.
2569 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2571 case 0: return ConstantBool::getFalse();
2572 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2573 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2574 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2575 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2576 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2577 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2578 case 7: return ConstantBool::getTrue();
2579 default: assert(0 && "Illegal SetCCCode!"); return 0;
2583 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2584 struct FoldSetCCLogical {
2587 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2588 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2589 bool shouldApply(Value *V) const {
2590 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2591 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2592 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2595 Instruction *apply(BinaryOperator &Log) const {
2596 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2597 if (SCI->getOperand(0) != LHS) {
2598 assert(SCI->getOperand(1) == LHS);
2599 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2602 unsigned LHSCode = getSetCondCode(SCI);
2603 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2605 switch (Log.getOpcode()) {
2606 case Instruction::And: Code = LHSCode & RHSCode; break;
2607 case Instruction::Or: Code = LHSCode | RHSCode; break;
2608 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2609 default: assert(0 && "Illegal logical opcode!"); return 0;
2612 Value *RV = getSetCCValue(Code, LHS, RHS);
2613 if (Instruction *I = dyn_cast<Instruction>(RV))
2615 // Otherwise, it's a constant boolean value...
2616 return IC.ReplaceInstUsesWith(Log, RV);
2620 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2621 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2622 // guaranteed to be either a shift instruction or a binary operator.
2623 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2624 ConstantIntegral *OpRHS,
2625 ConstantIntegral *AndRHS,
2626 BinaryOperator &TheAnd) {
2627 Value *X = Op->getOperand(0);
2628 Constant *Together = 0;
2629 if (!isa<ShiftInst>(Op))
2630 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2632 switch (Op->getOpcode()) {
2633 case Instruction::Xor:
2634 if (Op->hasOneUse()) {
2635 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2636 std::string OpName = Op->getName(); Op->setName("");
2637 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2638 InsertNewInstBefore(And, TheAnd);
2639 return BinaryOperator::createXor(And, Together);
2642 case Instruction::Or:
2643 if (Together == AndRHS) // (X | C) & C --> C
2644 return ReplaceInstUsesWith(TheAnd, AndRHS);
2646 if (Op->hasOneUse() && Together != OpRHS) {
2647 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2648 std::string Op0Name = Op->getName(); Op->setName("");
2649 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2650 InsertNewInstBefore(Or, TheAnd);
2651 return BinaryOperator::createAnd(Or, AndRHS);
2654 case Instruction::Add:
2655 if (Op->hasOneUse()) {
2656 // Adding a one to a single bit bit-field should be turned into an XOR
2657 // of the bit. First thing to check is to see if this AND is with a
2658 // single bit constant.
2659 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
2661 // Clear bits that are not part of the constant.
2662 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
2664 // If there is only one bit set...
2665 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2666 // Ok, at this point, we know that we are masking the result of the
2667 // ADD down to exactly one bit. If the constant we are adding has
2668 // no bits set below this bit, then we can eliminate the ADD.
2669 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
2671 // Check to see if any bits below the one bit set in AndRHSV are set.
2672 if ((AddRHS & (AndRHSV-1)) == 0) {
2673 // If not, the only thing that can effect the output of the AND is
2674 // the bit specified by AndRHSV. If that bit is set, the effect of
2675 // the XOR is to toggle the bit. If it is clear, then the ADD has
2677 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2678 TheAnd.setOperand(0, X);
2681 std::string Name = Op->getName(); Op->setName("");
2682 // Pull the XOR out of the AND.
2683 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2684 InsertNewInstBefore(NewAnd, TheAnd);
2685 return BinaryOperator::createXor(NewAnd, AndRHS);
2692 case Instruction::Shl: {
2693 // We know that the AND will not produce any of the bits shifted in, so if
2694 // the anded constant includes them, clear them now!
2696 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2697 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2698 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2700 if (CI == ShlMask) { // Masking out bits that the shift already masks
2701 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2702 } else if (CI != AndRHS) { // Reducing bits set in and.
2703 TheAnd.setOperand(1, CI);
2708 case Instruction::Shr:
2709 // We know that the AND will not produce any of the bits shifted in, so if
2710 // the anded constant includes them, clear them now! This only applies to
2711 // unsigned shifts, because a signed shr may bring in set bits!
2713 if (AndRHS->getType()->isUnsigned()) {
2714 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2715 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2716 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2718 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2719 return ReplaceInstUsesWith(TheAnd, Op);
2720 } else if (CI != AndRHS) {
2721 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2724 } else { // Signed shr.
2725 // See if this is shifting in some sign extension, then masking it out
2727 if (Op->hasOneUse()) {
2728 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2729 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2730 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2731 if (CI == AndRHS) { // Masking out bits shifted in.
2732 // Make the argument unsigned.
2733 Value *ShVal = Op->getOperand(0);
2734 ShVal = InsertCastBefore(ShVal,
2735 ShVal->getType()->getUnsignedVersion(),
2737 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2738 OpRHS, Op->getName()),
2740 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2741 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2744 return new CastInst(ShVal, Op->getType());
2754 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2755 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2756 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2757 /// insert new instructions.
2758 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2759 bool Inside, Instruction &IB) {
2760 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2761 "Lo is not <= Hi in range emission code!");
2763 if (Lo == Hi) // Trivially false.
2764 return new SetCondInst(Instruction::SetNE, V, V);
2765 if (cast<ConstantIntegral>(Lo)->isMinValue())
2766 return new SetCondInst(Instruction::SetLT, V, Hi);
2768 Constant *AddCST = ConstantExpr::getNeg(Lo);
2769 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2770 InsertNewInstBefore(Add, IB);
2771 // Convert to unsigned for the comparison.
2772 const Type *UnsType = Add->getType()->getUnsignedVersion();
2773 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2774 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2775 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2776 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2779 if (Lo == Hi) // Trivially true.
2780 return new SetCondInst(Instruction::SetEQ, V, V);
2782 Hi = SubOne(cast<ConstantInt>(Hi));
2783 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2784 return new SetCondInst(Instruction::SetGT, V, Hi);
2786 // Emit X-Lo > Hi-Lo-1
2787 Constant *AddCST = ConstantExpr::getNeg(Lo);
2788 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2789 InsertNewInstBefore(Add, IB);
2790 // Convert to unsigned for the comparison.
2791 const Type *UnsType = Add->getType()->getUnsignedVersion();
2792 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2793 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2794 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2795 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2798 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2799 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
2800 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2801 // not, since all 1s are not contiguous.
2802 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2803 uint64_t V = Val->getRawValue();
2804 if (!isShiftedMask_64(V)) return false;
2806 // look for the first zero bit after the run of ones
2807 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2808 // look for the first non-zero bit
2809 ME = 64-CountLeadingZeros_64(V);
2815 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2816 /// where isSub determines whether the operator is a sub. If we can fold one of
2817 /// the following xforms:
2819 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2820 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2821 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2823 /// return (A +/- B).
2825 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2826 ConstantIntegral *Mask, bool isSub,
2828 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2829 if (!LHSI || LHSI->getNumOperands() != 2 ||
2830 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2832 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2834 switch (LHSI->getOpcode()) {
2836 case Instruction::And:
2837 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2838 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2839 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2842 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2843 // part, we don't need any explicit masks to take them out of A. If that
2844 // is all N is, ignore it.
2846 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
2847 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2849 if (MaskedValueIsZero(RHS, Mask))
2854 case Instruction::Or:
2855 case Instruction::Xor:
2856 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2857 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2858 ConstantExpr::getAnd(N, Mask)->isNullValue())
2865 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2867 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2868 return InsertNewInstBefore(New, I);
2871 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
2872 bool Changed = SimplifyCommutative(I);
2873 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2875 if (isa<UndefValue>(Op1)) // X & undef -> 0
2876 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2880 return ReplaceInstUsesWith(I, Op1);
2882 // See if we can simplify any instructions used by the instruction whose sole
2883 // purpose is to compute bits we don't care about.
2884 uint64_t KnownZero, KnownOne;
2885 if (!isa<PackedType>(I.getType()) &&
2886 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2887 KnownZero, KnownOne))
2890 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
2891 uint64_t AndRHSMask = AndRHS->getZExtValue();
2892 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
2893 uint64_t NotAndRHS = AndRHSMask^TypeMask;
2895 // Optimize a variety of ((val OP C1) & C2) combinations...
2896 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2897 Instruction *Op0I = cast<Instruction>(Op0);
2898 Value *Op0LHS = Op0I->getOperand(0);
2899 Value *Op0RHS = Op0I->getOperand(1);
2900 switch (Op0I->getOpcode()) {
2901 case Instruction::Xor:
2902 case Instruction::Or:
2903 // If the mask is only needed on one incoming arm, push it up.
2904 if (Op0I->hasOneUse()) {
2905 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2906 // Not masking anything out for the LHS, move to RHS.
2907 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2908 Op0RHS->getName()+".masked");
2909 InsertNewInstBefore(NewRHS, I);
2910 return BinaryOperator::create(
2911 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
2913 if (!isa<Constant>(Op0RHS) &&
2914 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2915 // Not masking anything out for the RHS, move to LHS.
2916 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2917 Op0LHS->getName()+".masked");
2918 InsertNewInstBefore(NewLHS, I);
2919 return BinaryOperator::create(
2920 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2925 case Instruction::Add:
2926 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2927 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2928 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2929 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2930 return BinaryOperator::createAnd(V, AndRHS);
2931 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2932 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
2935 case Instruction::Sub:
2936 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2937 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2938 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2939 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2940 return BinaryOperator::createAnd(V, AndRHS);
2944 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2945 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
2947 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2948 const Type *SrcTy = CI->getOperand(0)->getType();
2950 // If this is an integer truncation or change from signed-to-unsigned, and
2951 // if the source is an and/or with immediate, transform it. This
2952 // frequently occurs for bitfield accesses.
2953 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2954 if (SrcTy->getPrimitiveSizeInBits() >=
2955 I.getType()->getPrimitiveSizeInBits() &&
2956 CastOp->getNumOperands() == 2)
2957 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
2958 if (CastOp->getOpcode() == Instruction::And) {
2959 // Change: and (cast (and X, C1) to T), C2
2960 // into : and (cast X to T), trunc(C1)&C2
2961 // This will folds the two ands together, which may allow other
2963 Instruction *NewCast =
2964 new CastInst(CastOp->getOperand(0), I.getType(),
2965 CastOp->getName()+".shrunk");
2966 NewCast = InsertNewInstBefore(NewCast, I);
2968 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2969 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2970 return BinaryOperator::createAnd(NewCast, C3);
2971 } else if (CastOp->getOpcode() == Instruction::Or) {
2972 // Change: and (cast (or X, C1) to T), C2
2973 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2974 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2975 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2976 return ReplaceInstUsesWith(I, AndRHS);
2981 // Try to fold constant and into select arguments.
2982 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2983 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2985 if (isa<PHINode>(Op0))
2986 if (Instruction *NV = FoldOpIntoPhi(I))
2990 Value *Op0NotVal = dyn_castNotVal(Op0);
2991 Value *Op1NotVal = dyn_castNotVal(Op1);
2993 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2994 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2996 // (~A & ~B) == (~(A | B)) - De Morgan's Law
2997 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2998 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2999 I.getName()+".demorgan");
3000 InsertNewInstBefore(Or, I);
3001 return BinaryOperator::createNot(Or);
3005 Value *A = 0, *B = 0;
3006 ConstantInt *C1 = 0, *C2 = 0;
3007 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3008 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3009 return ReplaceInstUsesWith(I, Op1);
3010 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3011 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3012 return ReplaceInstUsesWith(I, Op0);
3014 if (Op0->hasOneUse() &&
3015 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3016 if (A == Op1) { // (A^B)&A -> A&(A^B)
3017 I.swapOperands(); // Simplify below
3018 std::swap(Op0, Op1);
3019 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3020 cast<BinaryOperator>(Op0)->swapOperands();
3021 I.swapOperands(); // Simplify below
3022 std::swap(Op0, Op1);
3025 if (Op1->hasOneUse() &&
3026 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3027 if (B == Op0) { // B&(A^B) -> B&(B^A)
3028 cast<BinaryOperator>(Op1)->swapOperands();
3031 if (A == Op0) { // A&(A^B) -> A & ~B
3032 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3033 InsertNewInstBefore(NotB, I);
3034 return BinaryOperator::createAnd(A, NotB);
3040 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
3041 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
3042 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3045 Value *LHSVal, *RHSVal;
3046 ConstantInt *LHSCst, *RHSCst;
3047 Instruction::BinaryOps LHSCC, RHSCC;
3048 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3049 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3050 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
3051 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
3052 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
3053 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3054 // Ensure that the larger constant is on the RHS.
3055 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3056 SetCondInst *LHS = cast<SetCondInst>(Op0);
3057 if (cast<ConstantBool>(Cmp)->getValue()) {
3058 std::swap(LHS, RHS);
3059 std::swap(LHSCst, RHSCst);
3060 std::swap(LHSCC, RHSCC);
3063 // At this point, we know we have have two setcc instructions
3064 // comparing a value against two constants and and'ing the result
3065 // together. Because of the above check, we know that we only have
3066 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3067 // FoldSetCCLogical check above), that the two constants are not
3069 assert(LHSCst != RHSCst && "Compares not folded above?");
3072 default: assert(0 && "Unknown integer condition code!");
3073 case Instruction::SetEQ:
3075 default: assert(0 && "Unknown integer condition code!");
3076 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
3077 case Instruction::SetGT: // (X == 13 & X > 15) -> false
3078 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3079 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
3080 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
3081 return ReplaceInstUsesWith(I, LHS);
3083 case Instruction::SetNE:
3085 default: assert(0 && "Unknown integer condition code!");
3086 case Instruction::SetLT:
3087 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
3088 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
3089 break; // (X != 13 & X < 15) -> no change
3090 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
3091 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
3092 return ReplaceInstUsesWith(I, RHS);
3093 case Instruction::SetNE:
3094 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
3095 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3096 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3097 LHSVal->getName()+".off");
3098 InsertNewInstBefore(Add, I);
3099 const Type *UnsType = Add->getType()->getUnsignedVersion();
3100 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3101 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
3102 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3103 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
3105 break; // (X != 13 & X != 15) -> no change
3108 case Instruction::SetLT:
3110 default: assert(0 && "Unknown integer condition code!");
3111 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
3112 case Instruction::SetGT: // (X < 13 & X > 15) -> false
3113 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
3114 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
3115 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
3116 return ReplaceInstUsesWith(I, LHS);
3118 case Instruction::SetGT:
3120 default: assert(0 && "Unknown integer condition code!");
3121 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
3122 return ReplaceInstUsesWith(I, LHS);
3123 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
3124 return ReplaceInstUsesWith(I, RHS);
3125 case Instruction::SetNE:
3126 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
3127 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
3128 break; // (X > 13 & X != 15) -> no change
3129 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
3130 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
3136 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3137 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3138 const Type *SrcTy = Op0C->getOperand(0)->getType();
3139 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3140 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3141 // Only do this if the casts both really cause code to be generated.
3142 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3143 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3144 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3145 Op1C->getOperand(0),
3147 InsertNewInstBefore(NewOp, I);
3148 return new CastInst(NewOp, I.getType());
3152 return Changed ? &I : 0;
3155 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3156 /// in the result. If it does, and if the specified byte hasn't been filled in
3157 /// yet, fill it in and return false.
3158 static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3159 Instruction *I = dyn_cast<Instruction>(V);
3160 if (I == 0) return true;
3162 // If this is an or instruction, it is an inner node of the bswap.
3163 if (I->getOpcode() == Instruction::Or)
3164 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3165 CollectBSwapParts(I->getOperand(1), ByteValues);
3167 // If this is a shift by a constant int, and it is "24", then its operand
3168 // defines a byte. We only handle unsigned types here.
3169 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3170 // Not shifting the entire input by N-1 bytes?
3171 if (cast<ConstantInt>(I->getOperand(1))->getRawValue() !=
3172 8*(ByteValues.size()-1))
3176 if (I->getOpcode() == Instruction::Shl) {
3177 // X << 24 defines the top byte with the lowest of the input bytes.
3178 DestNo = ByteValues.size()-1;
3180 // X >>u 24 defines the low byte with the highest of the input bytes.
3184 // If the destination byte value is already defined, the values are or'd
3185 // together, which isn't a bswap (unless it's an or of the same bits).
3186 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3188 ByteValues[DestNo] = I->getOperand(0);
3192 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3194 Value *Shift = 0, *ShiftLHS = 0;
3195 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3196 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3197 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3199 Instruction *SI = cast<Instruction>(Shift);
3201 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3202 if (ShiftAmt->getRawValue() & 7 ||
3203 ShiftAmt->getRawValue() > 8*ByteValues.size())
3206 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3208 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3209 if (AndAmt->getRawValue() == uint64_t(0xFF) << 8*DestByte)
3211 // Unknown mask for bswap.
3212 if (DestByte == ByteValues.size()) return true;
3214 unsigned ShiftBytes = ShiftAmt->getRawValue()/8;
3216 if (SI->getOpcode() == Instruction::Shl)
3217 SrcByte = DestByte - ShiftBytes;
3219 SrcByte = DestByte + ShiftBytes;
3221 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3222 if (SrcByte != ByteValues.size()-DestByte-1)
3225 // If the destination byte value is already defined, the values are or'd
3226 // together, which isn't a bswap (unless it's an or of the same bits).
3227 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3229 ByteValues[DestByte] = SI->getOperand(0);
3233 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3234 /// If so, insert the new bswap intrinsic and return it.
3235 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3236 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3237 if (!I.getType()->isUnsigned() || I.getType() == Type::UByteTy)
3240 /// ByteValues - For each byte of the result, we keep track of which value
3241 /// defines each byte.
3242 std::vector<Value*> ByteValues;
3243 ByteValues.resize(I.getType()->getPrimitiveSize());
3245 // Try to find all the pieces corresponding to the bswap.
3246 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3247 CollectBSwapParts(I.getOperand(1), ByteValues))
3250 // Check to see if all of the bytes come from the same value.
3251 Value *V = ByteValues[0];
3252 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3254 // Check to make sure that all of the bytes come from the same value.
3255 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3256 if (ByteValues[i] != V)
3259 // If they do then *success* we can turn this into a bswap. Figure out what
3260 // bswap to make it into.
3261 Module *M = I.getParent()->getParent()->getParent();
3262 const char *FnName = 0;
3263 if (I.getType() == Type::UShortTy)
3264 FnName = "llvm.bswap.i16";
3265 else if (I.getType() == Type::UIntTy)
3266 FnName = "llvm.bswap.i32";
3267 else if (I.getType() == Type::ULongTy)
3268 FnName = "llvm.bswap.i64";
3270 assert(0 && "Unknown integer type!");
3271 Function *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3273 return new CallInst(F, V);
3277 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3278 bool Changed = SimplifyCommutative(I);
3279 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3281 if (isa<UndefValue>(Op1))
3282 return ReplaceInstUsesWith(I, // X | undef -> -1
3283 ConstantIntegral::getAllOnesValue(I.getType()));
3287 return ReplaceInstUsesWith(I, Op0);
3289 // See if we can simplify any instructions used by the instruction whose sole
3290 // purpose is to compute bits we don't care about.
3291 uint64_t KnownZero, KnownOne;
3292 if (!isa<PackedType>(I.getType()) &&
3293 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3294 KnownZero, KnownOne))
3298 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3299 ConstantInt *C1 = 0; Value *X = 0;
3300 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3301 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3302 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3304 InsertNewInstBefore(Or, I);
3305 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3308 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3309 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3310 std::string Op0Name = Op0->getName(); Op0->setName("");
3311 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3312 InsertNewInstBefore(Or, I);
3313 return BinaryOperator::createXor(Or,
3314 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3317 // Try to fold constant and into select arguments.
3318 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3319 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3321 if (isa<PHINode>(Op0))
3322 if (Instruction *NV = FoldOpIntoPhi(I))
3326 Value *A = 0, *B = 0;
3327 ConstantInt *C1 = 0, *C2 = 0;
3329 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3330 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3331 return ReplaceInstUsesWith(I, Op1);
3332 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3333 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3334 return ReplaceInstUsesWith(I, Op0);
3336 // (A | B) | C and A | (B | C) -> bswap if possible.
3337 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
3338 if (match(Op0, m_Or(m_Value(), m_Value())) ||
3339 match(Op1, m_Or(m_Value(), m_Value())) ||
3340 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3341 match(Op1, m_Shift(m_Value(), m_Value())))) {
3342 if (Instruction *BSwap = MatchBSwap(I))
3346 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3347 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3348 MaskedValueIsZero(Op1, C1->getZExtValue())) {
3349 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3351 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3354 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3355 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3356 MaskedValueIsZero(Op0, C1->getZExtValue())) {
3357 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3359 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3362 // (A & C1)|(B & C2)
3363 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3364 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3366 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3367 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3370 // If we have: ((V + N) & C1) | (V & C2)
3371 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3372 // replace with V+N.
3373 if (C1 == ConstantExpr::getNot(C2)) {
3374 Value *V1 = 0, *V2 = 0;
3375 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
3376 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3377 // Add commutes, try both ways.
3378 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3379 return ReplaceInstUsesWith(I, A);
3380 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3381 return ReplaceInstUsesWith(I, A);
3383 // Or commutes, try both ways.
3384 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
3385 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3386 // Add commutes, try both ways.
3387 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3388 return ReplaceInstUsesWith(I, B);
3389 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3390 return ReplaceInstUsesWith(I, B);
3395 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3396 if (A == Op1) // ~A | A == -1
3397 return ReplaceInstUsesWith(I,
3398 ConstantIntegral::getAllOnesValue(I.getType()));
3402 // Note, A is still live here!
3403 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3405 return ReplaceInstUsesWith(I,
3406 ConstantIntegral::getAllOnesValue(I.getType()));
3408 // (~A | ~B) == (~(A & B)) - De Morgan's Law
3409 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3410 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3411 I.getName()+".demorgan"), I);
3412 return BinaryOperator::createNot(And);
3416 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
3417 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
3418 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3421 Value *LHSVal, *RHSVal;
3422 ConstantInt *LHSCst, *RHSCst;
3423 Instruction::BinaryOps LHSCC, RHSCC;
3424 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3425 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3426 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
3427 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
3428 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
3429 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
3430 // Ensure that the larger constant is on the RHS.
3431 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
3432 SetCondInst *LHS = cast<SetCondInst>(Op0);
3433 if (cast<ConstantBool>(Cmp)->getValue()) {
3434 std::swap(LHS, RHS);
3435 std::swap(LHSCst, RHSCst);
3436 std::swap(LHSCC, RHSCC);
3439 // At this point, we know we have have two setcc instructions
3440 // comparing a value against two constants and or'ing the result
3441 // together. Because of the above check, we know that we only have
3442 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
3443 // FoldSetCCLogical check above), that the two constants are not
3445 assert(LHSCst != RHSCst && "Compares not folded above?");
3448 default: assert(0 && "Unknown integer condition code!");
3449 case Instruction::SetEQ:
3451 default: assert(0 && "Unknown integer condition code!");
3452 case Instruction::SetEQ:
3453 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3454 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3455 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3456 LHSVal->getName()+".off");
3457 InsertNewInstBefore(Add, I);
3458 const Type *UnsType = Add->getType()->getUnsignedVersion();
3459 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
3460 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3461 AddCST = ConstantExpr::getCast(AddCST, UnsType);
3462 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
3464 break; // (X == 13 | X == 15) -> no change
3466 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
3468 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
3469 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
3470 return ReplaceInstUsesWith(I, RHS);
3473 case Instruction::SetNE:
3475 default: assert(0 && "Unknown integer condition code!");
3476 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
3477 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
3478 return ReplaceInstUsesWith(I, LHS);
3479 case Instruction::SetNE: // (X != 13 | X != 15) -> true
3480 case Instruction::SetLT: // (X != 13 | X < 15) -> true
3481 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3484 case Instruction::SetLT:
3486 default: assert(0 && "Unknown integer condition code!");
3487 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
3489 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
3490 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
3491 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
3492 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
3493 return ReplaceInstUsesWith(I, RHS);
3496 case Instruction::SetGT:
3498 default: assert(0 && "Unknown integer condition code!");
3499 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
3500 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
3501 return ReplaceInstUsesWith(I, LHS);
3502 case Instruction::SetNE: // (X > 13 | X != 15) -> true
3503 case Instruction::SetLT: // (X > 13 | X < 15) -> true
3504 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
3510 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3511 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3512 const Type *SrcTy = Op0C->getOperand(0)->getType();
3513 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3514 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3515 // Only do this if the casts both really cause code to be generated.
3516 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3517 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3518 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3519 Op1C->getOperand(0),
3521 InsertNewInstBefore(NewOp, I);
3522 return new CastInst(NewOp, I.getType());
3527 return Changed ? &I : 0;
3530 // XorSelf - Implements: X ^ X --> 0
3533 XorSelf(Value *rhs) : RHS(rhs) {}
3534 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3535 Instruction *apply(BinaryOperator &Xor) const {
3541 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3542 bool Changed = SimplifyCommutative(I);
3543 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3545 if (isa<UndefValue>(Op1))
3546 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3548 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3549 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3550 assert(Result == &I && "AssociativeOpt didn't work?");
3551 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3554 // See if we can simplify any instructions used by the instruction whose sole
3555 // purpose is to compute bits we don't care about.
3556 uint64_t KnownZero, KnownOne;
3557 if (!isa<PackedType>(I.getType()) &&
3558 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
3559 KnownZero, KnownOne))
3562 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
3563 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3564 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
3565 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
3566 if (RHS == ConstantBool::getTrue() && SCI->hasOneUse())
3567 return new SetCondInst(SCI->getInverseCondition(),
3568 SCI->getOperand(0), SCI->getOperand(1));
3570 // ~(c-X) == X-c-1 == X+(-c-1)
3571 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3572 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3573 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3574 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3575 ConstantInt::get(I.getType(), 1));
3576 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3579 // ~(~X & Y) --> (X | ~Y)
3580 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3581 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3582 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3584 BinaryOperator::createNot(Op0I->getOperand(1),
3585 Op0I->getOperand(1)->getName()+".not");
3586 InsertNewInstBefore(NotY, I);
3587 return BinaryOperator::createOr(Op0NotVal, NotY);
3591 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3592 if (Op0I->getOpcode() == Instruction::Add) {
3593 // ~(X-c) --> (-c-1)-X
3594 if (RHS->isAllOnesValue()) {
3595 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3596 return BinaryOperator::createSub(
3597 ConstantExpr::getSub(NegOp0CI,
3598 ConstantInt::get(I.getType(), 1)),
3599 Op0I->getOperand(0));
3601 } else if (Op0I->getOpcode() == Instruction::Or) {
3602 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3603 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3604 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3605 // Anything in both C1 and C2 is known to be zero, remove it from
3607 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3608 NewRHS = ConstantExpr::getAnd(NewRHS,
3609 ConstantExpr::getNot(CommonBits));
3610 WorkList.push_back(Op0I);
3611 I.setOperand(0, Op0I->getOperand(0));
3612 I.setOperand(1, NewRHS);
3618 // Try to fold constant and into select arguments.
3619 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3620 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3622 if (isa<PHINode>(Op0))
3623 if (Instruction *NV = FoldOpIntoPhi(I))
3627 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
3629 return ReplaceInstUsesWith(I,
3630 ConstantIntegral::getAllOnesValue(I.getType()));
3632 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
3634 return ReplaceInstUsesWith(I,
3635 ConstantIntegral::getAllOnesValue(I.getType()));
3637 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
3638 if (Op1I->getOpcode() == Instruction::Or) {
3639 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
3640 Op1I->swapOperands();
3642 std::swap(Op0, Op1);
3643 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
3644 I.swapOperands(); // Simplified below.
3645 std::swap(Op0, Op1);
3647 } else if (Op1I->getOpcode() == Instruction::Xor) {
3648 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3649 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3650 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3651 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
3652 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3653 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3654 Op1I->swapOperands();
3655 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3656 I.swapOperands(); // Simplified below.
3657 std::swap(Op0, Op1);
3661 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3662 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
3663 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
3664 Op0I->swapOperands();
3665 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
3666 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3667 InsertNewInstBefore(NotB, I);
3668 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
3670 } else if (Op0I->getOpcode() == Instruction::Xor) {
3671 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3672 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3673 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3674 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3675 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3676 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3677 Op0I->swapOperands();
3678 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3679 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
3680 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3681 InsertNewInstBefore(N, I);
3682 return BinaryOperator::createAnd(N, Op1);
3686 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3687 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3688 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3691 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
3692 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
3693 const Type *SrcTy = Op0C->getOperand(0)->getType();
3694 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3695 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isIntegral() &&
3696 // Only do this if the casts both really cause code to be generated.
3697 ValueRequiresCast(Op0C->getOperand(0), I.getType(), TD) &&
3698 ValueRequiresCast(Op1C->getOperand(0), I.getType(), TD)) {
3699 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
3700 Op1C->getOperand(0),
3702 InsertNewInstBefore(NewOp, I);
3703 return new CastInst(NewOp, I.getType());
3707 return Changed ? &I : 0;
3710 /// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3711 /// overflowed for this type.
3712 static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3714 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3715 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3718 static bool isPositive(ConstantInt *C) {
3719 return cast<ConstantSInt>(C)->getValue() >= 0;
3722 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3723 /// overflowed for this type.
3724 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3726 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3728 if (In1->getType()->isUnsigned())
3729 return cast<ConstantUInt>(Result)->getValue() <
3730 cast<ConstantUInt>(In1)->getValue();
3731 if (isPositive(In1) != isPositive(In2))
3733 if (isPositive(In1))
3734 return cast<ConstantSInt>(Result)->getValue() <
3735 cast<ConstantSInt>(In1)->getValue();
3736 return cast<ConstantSInt>(Result)->getValue() >
3737 cast<ConstantSInt>(In1)->getValue();
3740 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3741 /// code necessary to compute the offset from the base pointer (without adding
3742 /// in the base pointer). Return the result as a signed integer of intptr size.
3743 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3744 TargetData &TD = IC.getTargetData();
3745 gep_type_iterator GTI = gep_type_begin(GEP);
3746 const Type *UIntPtrTy = TD.getIntPtrType();
3747 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3748 Value *Result = Constant::getNullValue(SIntPtrTy);
3750 // Build a mask for high order bits.
3751 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
3753 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3754 Value *Op = GEP->getOperand(i);
3755 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
3756 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3758 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3759 if (!OpC->isNullValue()) {
3760 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
3761 Scale = ConstantExpr::getMul(OpC, Scale);
3762 if (Constant *RC = dyn_cast<Constant>(Result))
3763 Result = ConstantExpr::getAdd(RC, Scale);
3765 // Emit an add instruction.
3766 Result = IC.InsertNewInstBefore(
3767 BinaryOperator::createAdd(Result, Scale,
3768 GEP->getName()+".offs"), I);
3772 // Convert to correct type.
3773 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3774 Op->getName()+".c"), I);
3776 // We'll let instcombine(mul) convert this to a shl if possible.
3777 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3778 GEP->getName()+".idx"), I);
3780 // Emit an add instruction.
3781 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
3782 GEP->getName()+".offs"), I);
3788 /// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3789 /// else. At this point we know that the GEP is on the LHS of the comparison.
3790 Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3791 Instruction::BinaryOps Cond,
3793 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
3795 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3796 if (isa<PointerType>(CI->getOperand(0)->getType()))
3797 RHS = CI->getOperand(0);
3799 Value *PtrBase = GEPLHS->getOperand(0);
3800 if (PtrBase == RHS) {
3801 // As an optimization, we don't actually have to compute the actual value of
3802 // OFFSET if this is a seteq or setne comparison, just return whether each
3803 // index is zero or not.
3804 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3805 Instruction *InVal = 0;
3806 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3807 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
3809 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3810 if (isa<UndefValue>(C)) // undef index -> undef.
3811 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3812 if (C->isNullValue())
3814 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3815 EmitIt = false; // This is indexing into a zero sized array?
3816 } else if (isa<ConstantInt>(C))
3817 return ReplaceInstUsesWith(I, // No comparison is needed here.
3818 ConstantBool::get(Cond == Instruction::SetNE));
3823 new SetCondInst(Cond, GEPLHS->getOperand(i),
3824 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3828 InVal = InsertNewInstBefore(InVal, I);
3829 InsertNewInstBefore(Comp, I);
3830 if (Cond == Instruction::SetNE) // True if any are unequal
3831 InVal = BinaryOperator::createOr(InVal, Comp);
3832 else // True if all are equal
3833 InVal = BinaryOperator::createAnd(InVal, Comp);
3841 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3842 ConstantBool::get(Cond == Instruction::SetEQ));
3845 // Only lower this if the setcc is the only user of the GEP or if we expect
3846 // the result to fold to a constant!
3847 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3848 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3849 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3850 return new SetCondInst(Cond, Offset,
3851 Constant::getNullValue(Offset->getType()));
3853 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
3854 // If the base pointers are different, but the indices are the same, just
3855 // compare the base pointer.
3856 if (PtrBase != GEPRHS->getOperand(0)) {
3857 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
3858 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
3859 GEPRHS->getOperand(0)->getType();
3861 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3862 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3863 IndicesTheSame = false;
3867 // If all indices are the same, just compare the base pointers.
3869 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3870 GEPRHS->getOperand(0));
3872 // Otherwise, the base pointers are different and the indices are
3873 // different, bail out.
3877 // If one of the GEPs has all zero indices, recurse.
3878 bool AllZeros = true;
3879 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3880 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3881 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3886 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3887 SetCondInst::getSwappedCondition(Cond), I);
3889 // If the other GEP has all zero indices, recurse.
3891 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3892 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3893 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3898 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3900 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3901 // If the GEPs only differ by one index, compare it.
3902 unsigned NumDifferences = 0; // Keep track of # differences.
3903 unsigned DiffOperand = 0; // The operand that differs.
3904 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3905 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3906 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3907 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
3908 // Irreconcilable differences.
3912 if (NumDifferences++) break;
3917 if (NumDifferences == 0) // SAME GEP?
3918 return ReplaceInstUsesWith(I, // No comparison is needed here.
3919 ConstantBool::get(Cond == Instruction::SetEQ));
3920 else if (NumDifferences == 1) {
3921 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3922 Value *RHSV = GEPRHS->getOperand(DiffOperand);
3924 // Convert the operands to signed values to make sure to perform a
3925 // signed comparison.
3926 const Type *NewTy = LHSV->getType()->getSignedVersion();
3927 if (LHSV->getType() != NewTy)
3928 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3929 LHSV->getName()), I);
3930 if (RHSV->getType() != NewTy)
3931 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3932 RHSV->getName()), I);
3933 return new SetCondInst(Cond, LHSV, RHSV);
3937 // Only lower this if the setcc is the only user of the GEP or if we expect
3938 // the result to fold to a constant!
3939 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3940 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3941 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3942 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3943 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3944 return new SetCondInst(Cond, L, R);
3951 Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
3952 bool Changed = SimplifyCommutative(I);
3953 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3954 const Type *Ty = Op0->getType();
3958 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
3960 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3961 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3963 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3964 // addresses never equal each other! We already know that Op0 != Op1.
3965 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3966 isa<ConstantPointerNull>(Op0)) &&
3967 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
3968 isa<ConstantPointerNull>(Op1)))
3969 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3971 // setcc's with boolean values can always be turned into bitwise operations
3972 if (Ty == Type::BoolTy) {
3973 switch (I.getOpcode()) {
3974 default: assert(0 && "Invalid setcc instruction!");
3975 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
3976 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
3977 InsertNewInstBefore(Xor, I);
3978 return BinaryOperator::createNot(Xor);
3980 case Instruction::SetNE:
3981 return BinaryOperator::createXor(Op0, Op1);
3983 case Instruction::SetGT:
3984 std::swap(Op0, Op1); // Change setgt -> setlt
3986 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3987 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3988 InsertNewInstBefore(Not, I);
3989 return BinaryOperator::createAnd(Not, Op1);
3991 case Instruction::SetGE:
3992 std::swap(Op0, Op1); // Change setge -> setle
3994 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3995 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3996 InsertNewInstBefore(Not, I);
3997 return BinaryOperator::createOr(Not, Op1);
4002 // See if we are doing a comparison between a constant and an instruction that
4003 // can be folded into the comparison.
4004 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4005 // Check to see if we are comparing against the minimum or maximum value...
4006 if (CI->isMinValue()) {
4007 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
4008 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4009 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
4010 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4011 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
4012 return BinaryOperator::createSetEQ(Op0, Op1);
4013 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
4014 return BinaryOperator::createSetNE(Op0, Op1);
4016 } else if (CI->isMaxValue()) {
4017 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
4018 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4019 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
4020 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4021 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
4022 return BinaryOperator::createSetEQ(Op0, Op1);
4023 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
4024 return BinaryOperator::createSetNE(Op0, Op1);
4026 // Comparing against a value really close to min or max?
4027 } else if (isMinValuePlusOne(CI)) {
4028 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
4029 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
4030 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
4031 return BinaryOperator::createSetNE(Op0, SubOne(CI));
4033 } else if (isMaxValueMinusOne(CI)) {
4034 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
4035 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
4036 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
4037 return BinaryOperator::createSetNE(Op0, AddOne(CI));
4040 // If we still have a setle or setge instruction, turn it into the
4041 // appropriate setlt or setgt instruction. Since the border cases have
4042 // already been handled above, this requires little checking.
4044 if (I.getOpcode() == Instruction::SetLE)
4045 return BinaryOperator::createSetLT(Op0, AddOne(CI));
4046 if (I.getOpcode() == Instruction::SetGE)
4047 return BinaryOperator::createSetGT(Op0, SubOne(CI));
4050 // See if we can fold the comparison based on bits known to be zero or one
4052 uint64_t KnownZero, KnownOne;
4053 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
4054 KnownZero, KnownOne, 0))
4057 // Given the known and unknown bits, compute a range that the LHS could be
4059 if (KnownOne | KnownZero) {
4060 if (Ty->isUnsigned()) { // Unsigned comparison.
4062 uint64_t RHSVal = CI->getZExtValue();
4063 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4065 switch (I.getOpcode()) { // LE/GE have been folded already.
4066 default: assert(0 && "Unknown setcc opcode!");
4067 case Instruction::SetEQ:
4068 if (Max < RHSVal || Min > RHSVal)
4069 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4071 case Instruction::SetNE:
4072 if (Max < RHSVal || Min > RHSVal)
4073 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4075 case Instruction::SetLT:
4077 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4079 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4081 case Instruction::SetGT:
4083 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4085 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4088 } else { // Signed comparison.
4090 int64_t RHSVal = CI->getSExtValue();
4091 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
4093 switch (I.getOpcode()) { // LE/GE have been folded already.
4094 default: assert(0 && "Unknown setcc opcode!");
4095 case Instruction::SetEQ:
4096 if (Max < RHSVal || Min > RHSVal)
4097 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4099 case Instruction::SetNE:
4100 if (Max < RHSVal || Min > RHSVal)
4101 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4103 case Instruction::SetLT:
4105 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4107 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4109 case Instruction::SetGT:
4111 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4113 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4120 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4121 switch (LHSI->getOpcode()) {
4122 case Instruction::And:
4123 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4124 LHSI->getOperand(0)->hasOneUse()) {
4125 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4127 // If an operand is an AND of a truncating cast, we can widen the
4128 // and/compare to be the input width without changing the value
4129 // produced, eliminating a cast.
4130 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4131 // We can do this transformation if either the AND constant does not
4132 // have its sign bit set or if it is an equality comparison.
4133 // Extending a relational comparison when we're checking the sign
4134 // bit would not work.
4135 if (Cast->hasOneUse() && Cast->isTruncIntCast() &&
4137 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4138 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4139 ConstantInt *NewCST;
4141 if (Cast->getOperand(0)->getType()->isSigned()) {
4142 NewCST = ConstantSInt::get(Cast->getOperand(0)->getType(),
4143 AndCST->getZExtValue());
4144 NewCI = ConstantSInt::get(Cast->getOperand(0)->getType(),
4145 CI->getZExtValue());
4147 NewCST = ConstantUInt::get(Cast->getOperand(0)->getType(),
4148 AndCST->getZExtValue());
4149 NewCI = ConstantUInt::get(Cast->getOperand(0)->getType(),
4150 CI->getZExtValue());
4152 Instruction *NewAnd =
4153 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4155 InsertNewInstBefore(NewAnd, I);
4156 return new SetCondInst(I.getOpcode(), NewAnd, NewCI);
4160 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4161 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4162 // happens a LOT in code produced by the C front-end, for bitfield
4164 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
4166 // Check to see if there is a noop-cast between the shift and the and.
4168 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4169 if (CI->getOperand(0)->getType()->isIntegral() &&
4170 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4171 CI->getType()->getPrimitiveSizeInBits())
4172 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4175 ConstantUInt *ShAmt;
4176 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
4177 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4178 const Type *AndTy = AndCST->getType(); // Type of the and.
4180 // We can fold this as long as we can't shift unknown bits
4181 // into the mask. This can only happen with signed shift
4182 // rights, as they sign-extend.
4184 bool CanFold = Shift->isLogicalShift();
4186 // To test for the bad case of the signed shr, see if any
4187 // of the bits shifted in could be tested after the mask.
4188 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
4189 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4191 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
4193 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4195 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4201 if (Shift->getOpcode() == Instruction::Shl)
4202 NewCst = ConstantExpr::getUShr(CI, ShAmt);
4204 NewCst = ConstantExpr::getShl(CI, ShAmt);
4206 // Check to see if we are shifting out any of the bits being
4208 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4209 // If we shifted bits out, the fold is not going to work out.
4210 // As a special case, check to see if this means that the
4211 // result is always true or false now.
4212 if (I.getOpcode() == Instruction::SetEQ)
4213 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4214 if (I.getOpcode() == Instruction::SetNE)
4215 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4217 I.setOperand(1, NewCst);
4218 Constant *NewAndCST;
4219 if (Shift->getOpcode() == Instruction::Shl)
4220 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
4222 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4223 LHSI->setOperand(1, NewAndCST);
4225 LHSI->setOperand(0, Shift->getOperand(0));
4227 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
4229 LHSI->setOperand(0, NewCast);
4231 WorkList.push_back(Shift); // Shift is dead.
4232 AddUsesToWorkList(I);
4238 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4239 // preferable because it allows the C<<Y expression to be hoisted out
4240 // of a loop if Y is invariant and X is not.
4241 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
4242 I.isEquality() && !Shift->isArithmeticShift() &&
4243 isa<Instruction>(Shift->getOperand(0))) {
4246 if (Shift->getOpcode() == Instruction::Shr) {
4247 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4250 // Make sure we insert a logical shift.
4251 Constant *NewAndCST = AndCST;
4252 if (AndCST->getType()->isSigned())
4253 NewAndCST = ConstantExpr::getCast(AndCST,
4254 AndCST->getType()->getUnsignedVersion());
4255 NS = new ShiftInst(Instruction::Shr, NewAndCST,
4256 Shift->getOperand(1), "tmp");
4258 InsertNewInstBefore(cast<Instruction>(NS), I);
4260 // If C's sign doesn't agree with the and, insert a cast now.
4261 if (NS->getType() != LHSI->getType())
4262 NS = InsertCastBefore(NS, LHSI->getType(), I);
4264 Value *ShiftOp = Shift->getOperand(0);
4265 if (ShiftOp->getType() != LHSI->getType())
4266 ShiftOp = InsertCastBefore(ShiftOp, LHSI->getType(), I);
4268 // Compute X & (C << Y).
4269 Instruction *NewAnd =
4270 BinaryOperator::createAnd(ShiftOp, NS, LHSI->getName());
4271 InsertNewInstBefore(NewAnd, I);
4273 I.setOperand(0, NewAnd);
4279 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
4280 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
4281 if (I.isEquality()) {
4282 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4284 // Check that the shift amount is in range. If not, don't perform
4285 // undefined shifts. When the shift is visited it will be
4287 if (ShAmt->getValue() >= TypeBits)
4290 // If we are comparing against bits always shifted out, the
4291 // comparison cannot succeed.
4293 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
4294 if (Comp != CI) {// Comparing against a bit that we know is zero.
4295 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4296 Constant *Cst = ConstantBool::get(IsSetNE);
4297 return ReplaceInstUsesWith(I, Cst);
4300 if (LHSI->hasOneUse()) {
4301 // Otherwise strength reduce the shift into an and.
4302 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
4303 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4306 if (CI->getType()->isUnsigned()) {
4307 Mask = ConstantUInt::get(CI->getType(), Val);
4308 } else if (ShAmtVal != 0) {
4309 Mask = ConstantSInt::get(CI->getType(), Val);
4311 Mask = ConstantInt::getAllOnesValue(CI->getType());
4315 BinaryOperator::createAnd(LHSI->getOperand(0),
4316 Mask, LHSI->getName()+".mask");
4317 Value *And = InsertNewInstBefore(AndI, I);
4318 return new SetCondInst(I.getOpcode(), And,
4319 ConstantExpr::getUShr(CI, ShAmt));
4325 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
4326 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
4327 if (I.isEquality()) {
4328 // Check that the shift amount is in range. If not, don't perform
4329 // undefined shifts. When the shift is visited it will be
4331 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4332 if (ShAmt->getValue() >= TypeBits)
4335 // If we are comparing against bits always shifted out, the
4336 // comparison cannot succeed.
4338 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
4340 if (Comp != CI) {// Comparing against a bit that we know is zero.
4341 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
4342 Constant *Cst = ConstantBool::get(IsSetNE);
4343 return ReplaceInstUsesWith(I, Cst);
4346 if (LHSI->hasOneUse() || CI->isNullValue()) {
4347 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
4349 // Otherwise strength reduce the shift into an and.
4350 uint64_t Val = ~0ULL; // All ones.
4351 Val <<= ShAmtVal; // Shift over to the right spot.
4354 if (CI->getType()->isUnsigned()) {
4355 Val &= ~0ULL >> (64-TypeBits);
4356 Mask = ConstantUInt::get(CI->getType(), Val);
4358 Mask = ConstantSInt::get(CI->getType(), Val);
4362 BinaryOperator::createAnd(LHSI->getOperand(0),
4363 Mask, LHSI->getName()+".mask");
4364 Value *And = InsertNewInstBefore(AndI, I);
4365 return new SetCondInst(I.getOpcode(), And,
4366 ConstantExpr::getShl(CI, ShAmt));
4372 case Instruction::Div:
4373 // Fold: (div X, C1) op C2 -> range check
4374 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4375 // Fold this div into the comparison, producing a range check.
4376 // Determine, based on the divide type, what the range is being
4377 // checked. If there is an overflow on the low or high side, remember
4378 // it, otherwise compute the range [low, hi) bounding the new value.
4379 bool LoOverflow = false, HiOverflow = 0;
4380 ConstantInt *LoBound = 0, *HiBound = 0;
4383 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
4385 Instruction::BinaryOps Opcode = I.getOpcode();
4387 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
4388 } else if (LHSI->getType()->isUnsigned()) { // udiv
4390 LoOverflow = ProdOV;
4391 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4392 } else if (isPositive(DivRHS)) { // Divisor is > 0.
4393 if (CI->isNullValue()) { // (X / pos) op 0
4395 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4397 } else if (isPositive(CI)) { // (X / pos) op pos
4399 LoOverflow = ProdOV;
4400 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4401 } else { // (X / pos) op neg
4402 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4403 LoOverflow = AddWithOverflow(LoBound, Prod,
4404 cast<ConstantInt>(DivRHSH));
4406 HiOverflow = ProdOV;
4408 } else { // Divisor is < 0.
4409 if (CI->isNullValue()) { // (X / neg) op 0
4410 LoBound = AddOne(DivRHS);
4411 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
4412 if (HiBound == DivRHS)
4413 LoBound = 0; // - INTMIN = INTMIN
4414 } else if (isPositive(CI)) { // (X / neg) op pos
4415 HiOverflow = LoOverflow = ProdOV;
4417 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4418 HiBound = AddOne(Prod);
4419 } else { // (X / neg) op neg
4421 LoOverflow = HiOverflow = ProdOV;
4422 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4425 // Dividing by a negate swaps the condition.
4426 Opcode = SetCondInst::getSwappedCondition(Opcode);
4430 Value *X = LHSI->getOperand(0);
4432 default: assert(0 && "Unhandled setcc opcode!");
4433 case Instruction::SetEQ:
4434 if (LoOverflow && HiOverflow)
4435 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4436 else if (HiOverflow)
4437 return new SetCondInst(Instruction::SetGE, X, LoBound);
4438 else if (LoOverflow)
4439 return new SetCondInst(Instruction::SetLT, X, HiBound);
4441 return InsertRangeTest(X, LoBound, HiBound, true, I);
4442 case Instruction::SetNE:
4443 if (LoOverflow && HiOverflow)
4444 return ReplaceInstUsesWith(I, ConstantBool::getTrue());
4445 else if (HiOverflow)
4446 return new SetCondInst(Instruction::SetLT, X, LoBound);
4447 else if (LoOverflow)
4448 return new SetCondInst(Instruction::SetGE, X, HiBound);
4450 return InsertRangeTest(X, LoBound, HiBound, false, I);
4451 case Instruction::SetLT:
4453 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4454 return new SetCondInst(Instruction::SetLT, X, LoBound);
4455 case Instruction::SetGT:
4457 return ReplaceInstUsesWith(I, ConstantBool::getFalse());
4458 return new SetCondInst(Instruction::SetGE, X, HiBound);
4465 // Simplify seteq and setne instructions...
4466 if (I.isEquality()) {
4467 bool isSetNE = I.getOpcode() == Instruction::SetNE;
4469 // If the first operand is (and|or|xor) with a constant, and the second
4470 // operand is a constant, simplify a bit.
4471 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4472 switch (BO->getOpcode()) {
4473 case Instruction::Rem:
4474 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4475 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
4477 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
4478 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
4479 if (isPowerOf2_64(V)) {
4480 unsigned L2 = Log2_64(V);
4481 const Type *UTy = BO->getType()->getUnsignedVersion();
4482 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
4484 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
4485 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
4486 RHSCst, BO->getName()), I);
4487 return BinaryOperator::create(I.getOpcode(), NewRem,
4488 Constant::getNullValue(UTy));
4493 case Instruction::Add:
4494 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4495 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4496 if (BO->hasOneUse())
4497 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4498 ConstantExpr::getSub(CI, BOp1C));
4499 } else if (CI->isNullValue()) {
4500 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4501 // efficiently invertible, or if the add has just this one use.
4502 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
4504 if (Value *NegVal = dyn_castNegVal(BOp1))
4505 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
4506 else if (Value *NegVal = dyn_castNegVal(BOp0))
4507 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
4508 else if (BO->hasOneUse()) {
4509 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4511 InsertNewInstBefore(Neg, I);
4512 return new SetCondInst(I.getOpcode(), BOp0, Neg);
4516 case Instruction::Xor:
4517 // For the xor case, we can xor two constants together, eliminating
4518 // the explicit xor.
4519 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4520 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
4521 ConstantExpr::getXor(CI, BOC));
4524 case Instruction::Sub:
4525 // Replace (([sub|xor] A, B) != 0) with (A != B)
4526 if (CI->isNullValue())
4527 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
4531 case Instruction::Or:
4532 // If bits are being or'd in that are not present in the constant we
4533 // are comparing against, then the comparison could never succeed!
4534 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
4535 Constant *NotCI = ConstantExpr::getNot(CI);
4536 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
4537 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
4541 case Instruction::And:
4542 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4543 // If bits are being compared against that are and'd out, then the
4544 // comparison can never succeed!
4545 if (!ConstantExpr::getAnd(CI,
4546 ConstantExpr::getNot(BOC))->isNullValue())
4547 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
4549 // If we have ((X & C) == C), turn it into ((X & C) != 0).
4550 if (CI == BOC && isOneBitSet(CI))
4551 return new SetCondInst(isSetNE ? Instruction::SetEQ :
4552 Instruction::SetNE, Op0,
4553 Constant::getNullValue(CI->getType()));
4555 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
4556 // to be a signed value as appropriate.
4557 if (isSignBit(BOC)) {
4558 Value *X = BO->getOperand(0);
4559 // If 'X' is not signed, insert a cast now...
4560 if (!BOC->getType()->isSigned()) {
4561 const Type *DestTy = BOC->getType()->getSignedVersion();
4562 X = InsertCastBefore(X, DestTy, I);
4564 return new SetCondInst(isSetNE ? Instruction::SetLT :
4565 Instruction::SetGE, X,
4566 Constant::getNullValue(X->getType()));
4569 // ((X & ~7) == 0) --> X < 8
4570 if (CI->isNullValue() && isHighOnes(BOC)) {
4571 Value *X = BO->getOperand(0);
4572 Constant *NegX = ConstantExpr::getNeg(BOC);
4574 // If 'X' is signed, insert a cast now.
4575 if (NegX->getType()->isSigned()) {
4576 const Type *DestTy = NegX->getType()->getUnsignedVersion();
4577 X = InsertCastBefore(X, DestTy, I);
4578 NegX = ConstantExpr::getCast(NegX, DestTy);
4581 return new SetCondInst(isSetNE ? Instruction::SetGE :
4582 Instruction::SetLT, X, NegX);
4589 } else { // Not a SetEQ/SetNE
4590 // If the LHS is a cast from an integral value of the same size,
4591 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
4592 Value *CastOp = Cast->getOperand(0);
4593 const Type *SrcTy = CastOp->getType();
4594 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
4595 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
4596 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
4597 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
4598 "Source and destination signednesses should differ!");
4599 if (Cast->getType()->isSigned()) {
4600 // If this is a signed comparison, check for comparisons in the
4601 // vicinity of zero.
4602 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
4604 return BinaryOperator::createSetGT(CastOp,
4605 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
4606 else if (I.getOpcode() == Instruction::SetGT &&
4607 cast<ConstantSInt>(CI)->getValue() == -1)
4608 // X > -1 => x < 128
4609 return BinaryOperator::createSetLT(CastOp,
4610 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
4612 ConstantUInt *CUI = cast<ConstantUInt>(CI);
4613 if (I.getOpcode() == Instruction::SetLT &&
4614 CUI->getValue() == 1ULL << (SrcTySize-1))
4615 // X < 128 => X > -1
4616 return BinaryOperator::createSetGT(CastOp,
4617 ConstantSInt::get(SrcTy, -1));
4618 else if (I.getOpcode() == Instruction::SetGT &&
4619 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
4621 return BinaryOperator::createSetLT(CastOp,
4622 Constant::getNullValue(SrcTy));
4629 // Handle setcc with constant RHS's that can be integer, FP or pointer.
4630 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4631 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4632 switch (LHSI->getOpcode()) {
4633 case Instruction::GetElementPtr:
4634 if (RHSC->isNullValue()) {
4635 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
4636 bool isAllZeros = true;
4637 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4638 if (!isa<Constant>(LHSI->getOperand(i)) ||
4639 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4644 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
4645 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4649 case Instruction::PHI:
4650 if (Instruction *NV = FoldOpIntoPhi(I))
4653 case Instruction::Select:
4654 // If either operand of the select is a constant, we can fold the
4655 // comparison into the select arms, which will cause one to be
4656 // constant folded and the select turned into a bitwise or.
4657 Value *Op1 = 0, *Op2 = 0;
4658 if (LHSI->hasOneUse()) {
4659 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4660 // Fold the known value into the constant operand.
4661 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4662 // Insert a new SetCC of the other select operand.
4663 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4664 LHSI->getOperand(2), RHSC,
4666 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4667 // Fold the known value into the constant operand.
4668 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
4669 // Insert a new SetCC of the other select operand.
4670 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
4671 LHSI->getOperand(1), RHSC,
4677 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4682 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
4683 if (User *GEP = dyn_castGetElementPtr(Op0))
4684 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
4686 if (User *GEP = dyn_castGetElementPtr(Op1))
4687 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
4688 SetCondInst::getSwappedCondition(I.getOpcode()), I))
4691 // Test to see if the operands of the setcc are casted versions of other
4692 // values. If the cast can be stripped off both arguments, we do so now.
4693 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4694 Value *CastOp0 = CI->getOperand(0);
4695 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
4696 (isa<Constant>(Op1) || isa<CastInst>(Op1)) && I.isEquality()) {
4697 // We keep moving the cast from the left operand over to the right
4698 // operand, where it can often be eliminated completely.
4701 // If operand #1 is a cast instruction, see if we can eliminate it as
4703 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
4704 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
4706 Op1 = CI2->getOperand(0);
4708 // If Op1 is a constant, we can fold the cast into the constant.
4709 if (Op1->getType() != Op0->getType())
4710 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4711 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
4713 // Otherwise, cast the RHS right before the setcc
4714 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
4715 InsertNewInstBefore(cast<Instruction>(Op1), I);
4717 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
4720 // Handle the special case of: setcc (cast bool to X), <cst>
4721 // This comes up when you have code like
4724 // For generality, we handle any zero-extension of any operand comparison
4725 // with a constant or another cast from the same type.
4726 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4727 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
4731 if (I.isEquality()) {
4733 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
4734 (A == Op1 || B == Op1)) {
4735 // (A^B) == A -> B == 0
4736 Value *OtherVal = A == Op1 ? B : A;
4737 return BinaryOperator::create(I.getOpcode(), OtherVal,
4738 Constant::getNullValue(A->getType()));
4739 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4740 (A == Op0 || B == Op0)) {
4741 // A == (A^B) -> B == 0
4742 Value *OtherVal = A == Op0 ? B : A;
4743 return BinaryOperator::create(I.getOpcode(), OtherVal,
4744 Constant::getNullValue(A->getType()));
4745 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4746 // (A-B) == A -> B == 0
4747 return BinaryOperator::create(I.getOpcode(), B,
4748 Constant::getNullValue(B->getType()));
4749 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4750 // A == (A-B) -> B == 0
4751 return BinaryOperator::create(I.getOpcode(), B,
4752 Constant::getNullValue(B->getType()));
4755 return Changed ? &I : 0;
4758 // visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4759 // We only handle extending casts so far.
4761 Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4762 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4763 const Type *SrcTy = LHSCIOp->getType();
4764 const Type *DestTy = SCI.getOperand(0)->getType();
4767 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
4770 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4771 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4772 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4774 // Is this a sign or zero extension?
4775 bool isSignSrc = SrcTy->isSigned();
4776 bool isSignDest = DestTy->isSigned();
4778 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4779 // Not an extension from the same type?
4780 RHSCIOp = CI->getOperand(0);
4781 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4782 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4783 // Compute the constant that would happen if we truncated to SrcTy then
4784 // reextended to DestTy.
4785 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4787 if (ConstantExpr::getCast(Res, DestTy) == CI) {
4788 // Make sure that src sign and dest sign match. For example,
4790 // %A = cast short %X to uint
4791 // %B = setgt uint %A, 1330
4793 // It is incorrect to transformt this into
4795 // %B = setgt short %X, 1330
4797 // because %A may have negative value.
4798 // However, it is OK if SrcTy is bool. See cast-set.ll testcase.
4799 if (isSignSrc == isSignDest || SrcTy == Type::BoolTy)
4804 // If the value cannot be represented in the shorter type, we cannot emit
4805 // a simple comparison.
4806 if (SCI.getOpcode() == Instruction::SetEQ)
4807 return ReplaceInstUsesWith(SCI, ConstantBool::getFalse());
4808 if (SCI.getOpcode() == Instruction::SetNE)
4809 return ReplaceInstUsesWith(SCI, ConstantBool::getTrue());
4811 // Evaluate the comparison for LT.
4813 if (DestTy->isSigned()) {
4814 // We're performing a signed comparison.
4816 // Signed extend and signed comparison.
4817 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
4818 Result = ConstantBool::getFalse();
4820 Result = ConstantBool::getTrue(); // X < (large) --> true
4822 // Unsigned extend and signed comparison.
4823 if (cast<ConstantSInt>(CI)->getValue() < 0)
4824 Result = ConstantBool::getFalse();
4826 Result = ConstantBool::getTrue();
4829 // We're performing an unsigned comparison.
4831 // Unsigned extend & compare -> always true.
4832 Result = ConstantBool::getTrue();
4834 // We're performing an unsigned comp with a sign extended value.
4835 // This is true if the input is >= 0. [aka >s -1]
4836 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4837 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4838 NegOne, SCI.getName()), SCI);
4842 // Finally, return the value computed.
4843 if (SCI.getOpcode() == Instruction::SetLT) {
4844 return ReplaceInstUsesWith(SCI, Result);
4846 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4847 if (Constant *CI = dyn_cast<Constant>(Result))
4848 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4850 return BinaryOperator::createNot(Result);
4857 // Okay, just insert a compare of the reduced operands now!
4858 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4861 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
4862 assert(I.getOperand(1)->getType() == Type::UByteTy);
4863 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4864 bool isLeftShift = I.getOpcode() == Instruction::Shl;
4866 // shl X, 0 == X and shr X, 0 == X
4867 // shl 0, X == 0 and shr 0, X == 0
4868 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
4869 Op0 == Constant::getNullValue(Op0->getType()))
4870 return ReplaceInstUsesWith(I, Op0);
4872 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4873 if (!isLeftShift && I.getType()->isSigned())
4874 return ReplaceInstUsesWith(I, Op0);
4875 else // undef << X -> 0 AND undef >>u X -> 0
4876 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4878 if (isa<UndefValue>(Op1)) {
4879 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
4880 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4882 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4885 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4887 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4888 if (CSI->isAllOnesValue())
4889 return ReplaceInstUsesWith(I, CSI);
4891 // Try to fold constant and into select arguments.
4892 if (isa<Constant>(Op0))
4893 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
4894 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4897 // See if we can turn a signed shr into an unsigned shr.
4898 if (I.isArithmeticShift()) {
4899 if (MaskedValueIsZero(Op0,
4900 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
4901 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4902 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4904 return new CastInst(V, I.getType());
4908 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4909 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4914 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4916 bool isLeftShift = I.getOpcode() == Instruction::Shl;
4917 bool isSignedShift = Op0->getType()->isSigned();
4918 bool isUnsignedShift = !isSignedShift;
4920 // See if we can simplify any instructions used by the instruction whose sole
4921 // purpose is to compute bits we don't care about.
4922 uint64_t KnownZero, KnownOne;
4923 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4924 KnownZero, KnownOne))
4927 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4928 // of a signed value.
4930 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4931 if (Op1->getValue() >= TypeBits) {
4932 if (isUnsignedShift || isLeftShift)
4933 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4935 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4940 // ((X*C1) << C2) == (X * (C1 << C2))
4941 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4942 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4943 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4944 return BinaryOperator::createMul(BO->getOperand(0),
4945 ConstantExpr::getShl(BOOp, Op1));
4947 // Try to fold constant and into select arguments.
4948 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4949 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4951 if (isa<PHINode>(Op0))
4952 if (Instruction *NV = FoldOpIntoPhi(I))
4955 if (Op0->hasOneUse()) {
4956 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4957 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4960 switch (Op0BO->getOpcode()) {
4962 case Instruction::Add:
4963 case Instruction::And:
4964 case Instruction::Or:
4965 case Instruction::Xor:
4966 // These operators commute.
4967 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
4968 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4969 match(Op0BO->getOperand(1),
4970 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
4971 Instruction *YS = new ShiftInst(Instruction::Shl,
4972 Op0BO->getOperand(0), Op1,
4974 InsertNewInstBefore(YS, I); // (Y << C)
4976 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4977 Op0BO->getOperand(1)->getName());
4978 InsertNewInstBefore(X, I); // (X + (Y << C))
4979 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
4980 C2 = ConstantExpr::getShl(C2, Op1);
4981 return BinaryOperator::createAnd(X, C2);
4984 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4985 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4986 match(Op0BO->getOperand(1),
4987 m_And(m_Shr(m_Value(V1), m_Value(V2)),
4988 m_ConstantInt(CC))) && V2 == Op1 &&
4989 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
4990 Instruction *YS = new ShiftInst(Instruction::Shl,
4991 Op0BO->getOperand(0), Op1,
4993 InsertNewInstBefore(YS, I); // (Y << C)
4995 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
4996 V1->getName()+".mask");
4997 InsertNewInstBefore(XM, I); // X & (CC << C)
4999 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5003 case Instruction::Sub:
5004 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5005 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5006 match(Op0BO->getOperand(0),
5007 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5008 Instruction *YS = new ShiftInst(Instruction::Shl,
5009 Op0BO->getOperand(1), Op1,
5011 InsertNewInstBefore(YS, I); // (Y << C)
5013 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5014 Op0BO->getOperand(0)->getName());
5015 InsertNewInstBefore(X, I); // (X + (Y << C))
5016 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5017 C2 = ConstantExpr::getShl(C2, Op1);
5018 return BinaryOperator::createAnd(X, C2);
5021 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
5022 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5023 match(Op0BO->getOperand(0),
5024 m_And(m_Shr(m_Value(V1), m_Value(V2)),
5025 m_ConstantInt(CC))) && V2 == Op1 &&
5026 cast<BinaryOperator>(Op0BO->getOperand(0))
5027 ->getOperand(0)->hasOneUse()) {
5028 Instruction *YS = new ShiftInst(Instruction::Shl,
5029 Op0BO->getOperand(1), Op1,
5031 InsertNewInstBefore(YS, I); // (Y << C)
5033 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5034 V1->getName()+".mask");
5035 InsertNewInstBefore(XM, I); // X & (CC << C)
5037 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5044 // If the operand is an bitwise operator with a constant RHS, and the
5045 // shift is the only use, we can pull it out of the shift.
5046 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5047 bool isValid = true; // Valid only for And, Or, Xor
5048 bool highBitSet = false; // Transform if high bit of constant set?
5050 switch (Op0BO->getOpcode()) {
5051 default: isValid = false; break; // Do not perform transform!
5052 case Instruction::Add:
5053 isValid = isLeftShift;
5055 case Instruction::Or:
5056 case Instruction::Xor:
5059 case Instruction::And:
5064 // If this is a signed shift right, and the high bit is modified
5065 // by the logical operation, do not perform the transformation.
5066 // The highBitSet boolean indicates the value of the high bit of
5067 // the constant which would cause it to be modified for this
5070 if (isValid && !isLeftShift && isSignedShift) {
5071 uint64_t Val = Op0C->getRawValue();
5072 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5076 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5078 Instruction *NewShift =
5079 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5082 InsertNewInstBefore(NewShift, I);
5084 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5091 // Find out if this is a shift of a shift by a constant.
5092 ShiftInst *ShiftOp = 0;
5093 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
5095 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
5096 // If this is a noop-integer case of a shift instruction, use the shift.
5097 if (CI->getOperand(0)->getType()->isInteger() &&
5098 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
5099 CI->getType()->getPrimitiveSizeInBits() &&
5100 isa<ShiftInst>(CI->getOperand(0))) {
5101 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5105 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
5106 // Find the operands and properties of the input shift. Note that the
5107 // signedness of the input shift may differ from the current shift if there
5108 // is a noop cast between the two.
5109 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5110 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
5111 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
5113 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
5115 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
5116 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
5118 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5119 if (isLeftShift == isShiftOfLeftShift) {
5120 // Do not fold these shifts if the first one is signed and the second one
5121 // is unsigned and this is a right shift. Further, don't do any folding
5123 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5126 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5127 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5128 Amt = Op0->getType()->getPrimitiveSizeInBits();
5130 Value *Op = ShiftOp->getOperand(0);
5131 if (isShiftOfSignedShift != isSignedShift)
5132 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
5133 return new ShiftInst(I.getOpcode(), Op,
5134 ConstantUInt::get(Type::UByteTy, Amt));
5137 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5138 // signed types, we can only support the (A >> c1) << c2 configuration,
5139 // because it can not turn an arbitrary bit of A into a sign bit.
5140 if (isUnsignedShift || isLeftShift) {
5141 // Calculate bitmask for what gets shifted off the edge.
5142 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
5144 C = ConstantExpr::getShl(C, ShiftAmt1C);
5146 C = ConstantExpr::getUShr(C, ShiftAmt1C);
5148 Value *Op = ShiftOp->getOperand(0);
5149 if (isShiftOfSignedShift != isSignedShift)
5150 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
5153 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5154 InsertNewInstBefore(Mask, I);
5156 // Figure out what flavor of shift we should use...
5157 if (ShiftAmt1 == ShiftAmt2) {
5158 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
5159 } else if (ShiftAmt1 < ShiftAmt2) {
5160 return new ShiftInst(I.getOpcode(), Mask,
5161 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
5162 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5163 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5164 // Make sure to emit an unsigned shift right, not a signed one.
5165 Mask = InsertNewInstBefore(new CastInst(Mask,
5166 Mask->getType()->getUnsignedVersion(),
5168 Mask = new ShiftInst(Instruction::Shr, Mask,
5169 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5170 InsertNewInstBefore(Mask, I);
5171 return new CastInst(Mask, I.getType());
5173 return new ShiftInst(ShiftOp->getOpcode(), Mask,
5174 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5177 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
5178 Op = InsertNewInstBefore(new CastInst(Mask,
5179 I.getType()->getSignedVersion(),
5180 Mask->getName()), I);
5181 Instruction *Shift =
5182 new ShiftInst(ShiftOp->getOpcode(), Op,
5183 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
5184 InsertNewInstBefore(Shift, I);
5186 C = ConstantIntegral::getAllOnesValue(Shift->getType());
5187 C = ConstantExpr::getShl(C, Op1);
5188 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5189 InsertNewInstBefore(Mask, I);
5190 return new CastInst(Mask, I.getType());
5193 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
5194 // this case, C1 == C2 and C1 is 8, 16, or 32.
5195 if (ShiftAmt1 == ShiftAmt2) {
5196 const Type *SExtType = 0;
5197 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
5198 case 8 : SExtType = Type::SByteTy; break;
5199 case 16: SExtType = Type::ShortTy; break;
5200 case 32: SExtType = Type::IntTy; break;
5204 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
5206 InsertNewInstBefore(NewTrunc, I);
5207 return new CastInst(NewTrunc, I.getType());
5216 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5217 /// expression. If so, decompose it, returning some value X, such that Val is
5220 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5222 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
5223 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
5224 Offset = CI->getValue();
5226 return ConstantUInt::get(Type::UIntTy, 0);
5227 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5228 if (I->getNumOperands() == 2) {
5229 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
5230 if (I->getOpcode() == Instruction::Shl) {
5231 // This is a value scaled by '1 << the shift amt'.
5232 Scale = 1U << CUI->getValue();
5234 return I->getOperand(0);
5235 } else if (I->getOpcode() == Instruction::Mul) {
5236 // This value is scaled by 'CUI'.
5237 Scale = CUI->getValue();
5239 return I->getOperand(0);
5240 } else if (I->getOpcode() == Instruction::Add) {
5241 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
5244 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
5246 Offset += CUI->getValue();
5247 if (SubScale > 1 && (Offset % SubScale == 0)) {
5256 // Otherwise, we can't look past this.
5263 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5264 /// try to eliminate the cast by moving the type information into the alloc.
5265 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5266 AllocationInst &AI) {
5267 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
5268 if (!PTy) return 0; // Not casting the allocation to a pointer type.
5270 // Remove any uses of AI that are dead.
5271 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5272 std::vector<Instruction*> DeadUsers;
5273 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5274 Instruction *User = cast<Instruction>(*UI++);
5275 if (isInstructionTriviallyDead(User)) {
5276 while (UI != E && *UI == User)
5277 ++UI; // If this instruction uses AI more than once, don't break UI.
5279 // Add operands to the worklist.
5280 AddUsesToWorkList(*User);
5282 DEBUG(std::cerr << "IC: DCE: " << *User);
5284 User->eraseFromParent();
5285 removeFromWorkList(User);
5289 // Get the type really allocated and the type casted to.
5290 const Type *AllocElTy = AI.getAllocatedType();
5291 const Type *CastElTy = PTy->getElementType();
5292 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
5294 unsigned AllocElTyAlign = TD->getTypeAlignment(AllocElTy);
5295 unsigned CastElTyAlign = TD->getTypeAlignment(CastElTy);
5296 if (CastElTyAlign < AllocElTyAlign) return 0;
5298 // If the allocation has multiple uses, only promote it if we are strictly
5299 // increasing the alignment of the resultant allocation. If we keep it the
5300 // same, we open the door to infinite loops of various kinds.
5301 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5303 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5304 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
5305 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
5307 // See if we can satisfy the modulus by pulling a scale out of the array
5309 unsigned ArraySizeScale, ArrayOffset;
5310 Value *NumElements = // See if the array size is a decomposable linear expr.
5311 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5313 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5315 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5316 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
5318 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5323 Amt = ConstantUInt::get(Type::UIntTy, Scale);
5324 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
5325 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
5326 else if (Scale != 1) {
5327 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5328 Amt = InsertNewInstBefore(Tmp, AI);
5332 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5333 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
5334 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5335 Amt = InsertNewInstBefore(Tmp, AI);
5338 std::string Name = AI.getName(); AI.setName("");
5339 AllocationInst *New;
5340 if (isa<MallocInst>(AI))
5341 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
5343 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
5344 InsertNewInstBefore(New, AI);
5346 // If the allocation has multiple uses, insert a cast and change all things
5347 // that used it to use the new cast. This will also hack on CI, but it will
5349 if (!AI.hasOneUse()) {
5350 AddUsesToWorkList(AI);
5351 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
5352 InsertNewInstBefore(NewCast, AI);
5353 AI.replaceAllUsesWith(NewCast);
5355 return ReplaceInstUsesWith(CI, New);
5358 /// CanEvaluateInDifferentType - Return true if we can take the specified value
5359 /// and return it without inserting any new casts. This is used by code that
5360 /// tries to decide whether promoting or shrinking integer operations to wider
5361 /// or smaller types will allow us to eliminate a truncate or extend.
5362 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5363 int &NumCastsRemoved) {
5364 if (isa<Constant>(V)) return true;
5366 Instruction *I = dyn_cast<Instruction>(V);
5367 if (!I || !I->hasOneUse()) return false;
5369 switch (I->getOpcode()) {
5370 case Instruction::And:
5371 case Instruction::Or:
5372 case Instruction::Xor:
5373 // These operators can all arbitrarily be extended or truncated.
5374 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5375 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5376 case Instruction::Cast:
5377 // If this is a cast from the destination type, we can trivially eliminate
5378 // it, and this will remove a cast overall.
5379 if (I->getOperand(0)->getType() == Ty) {
5380 // If the first operand is itself a cast, and is eliminable, do not count
5381 // this as an eliminable cast. We would prefer to eliminate those two
5383 if (CastInst *OpCast = dyn_cast<CastInst>(I->getOperand(0)))
5389 // TODO: Can handle more cases here.
5396 /// EvaluateInDifferentType - Given an expression that
5397 /// CanEvaluateInDifferentType returns true for, actually insert the code to
5398 /// evaluate the expression.
5399 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty) {
5400 if (Constant *C = dyn_cast<Constant>(V))
5401 return ConstantExpr::getCast(C, Ty);
5403 // Otherwise, it must be an instruction.
5404 Instruction *I = cast<Instruction>(V);
5405 Instruction *Res = 0;
5406 switch (I->getOpcode()) {
5407 case Instruction::And:
5408 case Instruction::Or:
5409 case Instruction::Xor: {
5410 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty);
5411 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty);
5412 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5413 LHS, RHS, I->getName());
5416 case Instruction::Cast:
5417 // If this is a cast from the destination type, return the input.
5418 if (I->getOperand(0)->getType() == Ty)
5419 return I->getOperand(0);
5421 // TODO: Can handle more cases here.
5422 assert(0 && "Unreachable!");
5426 return InsertNewInstBefore(Res, *I);
5430 // CastInst simplification
5432 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
5433 Value *Src = CI.getOperand(0);
5435 // If the user is casting a value to the same type, eliminate this cast
5437 if (CI.getType() == Src->getType())
5438 return ReplaceInstUsesWith(CI, Src);
5440 if (isa<UndefValue>(Src)) // cast undef -> undef
5441 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5443 // If casting the result of another cast instruction, try to eliminate this
5446 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5447 Value *A = CSrc->getOperand(0);
5448 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
5449 CI.getType(), TD)) {
5450 // This instruction now refers directly to the cast's src operand. This
5451 // has a good chance of making CSrc dead.
5452 CI.setOperand(0, CSrc->getOperand(0));
5456 // If this is an A->B->A cast, and we are dealing with integral types, try
5457 // to convert this into a logical 'and' instruction.
5459 if (A->getType()->isInteger() &&
5460 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
5461 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
5462 CSrc->getType()->getPrimitiveSizeInBits() <
5463 CI.getType()->getPrimitiveSizeInBits()&&
5464 A->getType()->getPrimitiveSizeInBits() ==
5465 CI.getType()->getPrimitiveSizeInBits()) {
5466 assert(CSrc->getType() != Type::ULongTy &&
5467 "Cannot have type bigger than ulong!");
5468 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
5469 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
5471 AndOp = ConstantExpr::getCast(AndOp, A->getType());
5472 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
5473 if (And->getType() != CI.getType()) {
5474 And->setName(CSrc->getName()+".mask");
5475 InsertNewInstBefore(And, CI);
5476 And = new CastInst(And, CI.getType());
5482 // If this is a cast to bool, turn it into the appropriate setne instruction.
5483 if (CI.getType() == Type::BoolTy)
5484 return BinaryOperator::createSetNE(CI.getOperand(0),
5485 Constant::getNullValue(CI.getOperand(0)->getType()));
5487 // See if we can simplify any instructions used by the LHS whose sole
5488 // purpose is to compute bits we don't care about.
5489 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
5490 uint64_t KnownZero, KnownOne;
5491 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
5492 KnownZero, KnownOne))
5496 // If casting the result of a getelementptr instruction with no offset, turn
5497 // this into a cast of the original pointer!
5499 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
5500 bool AllZeroOperands = true;
5501 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5502 if (!isa<Constant>(GEP->getOperand(i)) ||
5503 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5504 AllZeroOperands = false;
5507 if (AllZeroOperands) {
5508 CI.setOperand(0, GEP->getOperand(0));
5513 // If we are casting a malloc or alloca to a pointer to a type of the same
5514 // size, rewrite the allocation instruction to allocate the "right" type.
5516 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
5517 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
5520 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
5521 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
5523 if (isa<PHINode>(Src))
5524 if (Instruction *NV = FoldOpIntoPhi(CI))
5527 // If the source and destination are pointers, and this cast is equivalent to
5528 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
5529 // This can enhance SROA and other transforms that want type-safe pointers.
5530 if (const PointerType *DstPTy = dyn_cast<PointerType>(CI.getType()))
5531 if (const PointerType *SrcPTy = dyn_cast<PointerType>(Src->getType())) {
5532 const Type *DstTy = DstPTy->getElementType();
5533 const Type *SrcTy = SrcPTy->getElementType();
5535 Constant *ZeroUInt = Constant::getNullValue(Type::UIntTy);
5536 unsigned NumZeros = 0;
5537 while (SrcTy != DstTy &&
5538 isa<CompositeType>(SrcTy) && !isa<PointerType>(SrcTy) &&
5539 SrcTy->getNumContainedTypes() /* not "{}" */) {
5540 SrcTy = cast<CompositeType>(SrcTy)->getTypeAtIndex(ZeroUInt);
5544 // If we found a path from the src to dest, create the getelementptr now.
5545 if (SrcTy == DstTy) {
5546 std::vector<Value*> Idxs(NumZeros+1, ZeroUInt);
5547 return new GetElementPtrInst(Src, Idxs);
5551 // If the source value is an instruction with only this use, we can attempt to
5552 // propagate the cast into the instruction. Also, only handle integral types
5554 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
5555 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
5556 CI.getType()->isInteger()) { // Don't mess with casts to bool here
5558 int NumCastsRemoved = 0;
5559 if (CanEvaluateInDifferentType(SrcI, CI.getType(), NumCastsRemoved)) {
5560 // If this cast is a truncate, evaluting in a different type always
5561 // eliminates the cast, so it is always a win. If this is a noop-cast
5562 // this just removes a noop cast which isn't pointful, but simplifies
5563 // the code. If this is a zero-extension, we need to do an AND to
5564 // maintain the clear top-part of the computation, so we require that
5565 // the input have eliminated at least one cast. If this is a sign
5566 // extension, we insert two new casts (to do the extension) so we
5567 // require that two casts have been eliminated.
5569 switch (getCastType(Src->getType(), CI.getType())) {
5570 default: assert(0 && "Unknown cast type!");
5576 DoXForm = NumCastsRemoved >= 1;
5579 DoXForm = NumCastsRemoved >= 2;
5584 Value *Res = EvaluateInDifferentType(SrcI, CI.getType());
5585 assert(Res->getType() == CI.getType());
5586 switch (getCastType(Src->getType(), CI.getType())) {
5587 default: assert(0 && "Unknown cast type!");
5590 // Just replace this cast with the result.
5591 return ReplaceInstUsesWith(CI, Res);
5593 // We need to emit an AND to clear the high bits.
5594 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5595 unsigned DestBitSize = CI.getType()->getPrimitiveSizeInBits();
5596 assert(SrcBitSize < DestBitSize && "Not a zext?");
5597 Constant *C = ConstantUInt::get(Type::ULongTy, (1 << SrcBitSize)-1);
5598 C = ConstantExpr::getCast(C, CI.getType());
5599 return BinaryOperator::createAnd(Res, C);
5602 // We need to emit a cast to truncate, then a cast to sext.
5603 return new CastInst(InsertCastBefore(Res, Src->getType(), CI),
5609 const Type *DestTy = CI.getType();
5610 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
5611 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
5613 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
5614 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
5616 switch (SrcI->getOpcode()) {
5617 case Instruction::Add:
5618 case Instruction::Mul:
5619 case Instruction::And:
5620 case Instruction::Or:
5621 case Instruction::Xor:
5622 // If we are discarding information, or just changing the sign, rewrite.
5623 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
5624 // Don't insert two casts if they cannot be eliminated. We allow two
5625 // casts to be inserted if the sizes are the same. This could only be
5626 // converting signedness, which is a noop.
5627 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
5628 !ValueRequiresCast(Op0, DestTy, TD)) {
5629 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5630 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
5631 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
5632 ->getOpcode(), Op0c, Op1c);
5636 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
5637 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
5638 Op1 == ConstantBool::getTrue() &&
5639 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
5640 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
5641 return BinaryOperator::createXor(New,
5642 ConstantInt::get(CI.getType(), 1));
5645 case Instruction::Shl:
5646 // Allow changing the sign of the source operand. Do not allow changing
5647 // the size of the shift, UNLESS the shift amount is a constant. We
5648 // mush not change variable sized shifts to a smaller size, because it
5649 // is undefined to shift more bits out than exist in the value.
5650 if (DestBitSize == SrcBitSize ||
5651 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
5652 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
5653 return new ShiftInst(Instruction::Shl, Op0c, Op1);
5656 case Instruction::Shr:
5657 // If this is a signed shr, and if all bits shifted in are about to be
5658 // truncated off, turn it into an unsigned shr to allow greater
5660 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
5661 isa<ConstantInt>(Op1)) {
5662 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
5663 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
5664 // Convert to unsigned.
5665 Value *N1 = InsertOperandCastBefore(Op0,
5666 Op0->getType()->getUnsignedVersion(), &CI);
5667 // Insert the new shift, which is now unsigned.
5668 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
5669 Op1, Src->getName()), CI);
5670 return new CastInst(N1, CI.getType());
5675 case Instruction::SetEQ:
5676 case Instruction::SetNE:
5677 // We if we are just checking for a seteq of a single bit and casting it
5678 // to an integer. If so, shift the bit to the appropriate place then
5679 // cast to integer to avoid the comparison.
5680 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
5681 uint64_t Op1CV = Op1C->getZExtValue();
5682 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
5683 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5684 // cast (X == 1) to int --> X iff X has only the low bit set.
5685 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
5686 // cast (X != 0) to int --> X iff X has only the low bit set.
5687 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
5688 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
5689 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
5690 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
5691 // If Op1C some other power of two, convert:
5692 uint64_t KnownZero, KnownOne;
5693 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
5694 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
5696 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
5697 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
5698 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
5699 // (X&4) == 2 --> false
5700 // (X&4) != 2 --> true
5701 Constant *Res = ConstantBool::get(isSetNE);
5702 Res = ConstantExpr::getCast(Res, CI.getType());
5703 return ReplaceInstUsesWith(CI, Res);
5706 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
5709 // Perform an unsigned shr by shiftamt. Convert input to
5710 // unsigned if it is signed.
5711 if (In->getType()->isSigned())
5712 In = InsertNewInstBefore(new CastInst(In,
5713 In->getType()->getUnsignedVersion(), In->getName()),CI);
5714 // Insert the shift to put the result in the low bit.
5715 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
5716 ConstantInt::get(Type::UByteTy, ShiftAmt),
5717 In->getName()+".lobit"), CI);
5720 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
5721 Constant *One = ConstantInt::get(In->getType(), 1);
5722 In = BinaryOperator::createXor(In, One, "tmp");
5723 InsertNewInstBefore(cast<Instruction>(In), CI);
5726 if (CI.getType() == In->getType())
5727 return ReplaceInstUsesWith(CI, In);
5729 return new CastInst(In, CI.getType());
5737 if (SrcI->hasOneUse()) {
5738 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(SrcI)) {
5739 // Okay, we have (cast (shuffle ..)). We know this cast is a bitconvert
5740 // because the inputs are known to be a vector. Check to see if this is
5741 // a cast to a vector with the same # elts.
5742 if (isa<PackedType>(CI.getType()) &&
5743 cast<PackedType>(CI.getType())->getNumElements() ==
5744 SVI->getType()->getNumElements()) {
5746 // If either of the operands is a cast from CI.getType(), then
5747 // evaluating the shuffle in the casted destination's type will allow
5748 // us to eliminate at least one cast.
5749 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
5750 Tmp->getOperand(0)->getType() == CI.getType()) ||
5751 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
5752 Tmp->getOperand(0)->getType() == CI.getType())) {
5753 Value *LHS = InsertOperandCastBefore(SVI->getOperand(0),
5755 Value *RHS = InsertOperandCastBefore(SVI->getOperand(1),
5757 // Return a new shuffle vector. Use the same element ID's, as we
5758 // know the vector types match #elts.
5759 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
5769 /// GetSelectFoldableOperands - We want to turn code that looks like this:
5771 /// %D = select %cond, %C, %A
5773 /// %C = select %cond, %B, 0
5776 /// Assuming that the specified instruction is an operand to the select, return
5777 /// a bitmask indicating which operands of this instruction are foldable if they
5778 /// equal the other incoming value of the select.
5780 static unsigned GetSelectFoldableOperands(Instruction *I) {
5781 switch (I->getOpcode()) {
5782 case Instruction::Add:
5783 case Instruction::Mul:
5784 case Instruction::And:
5785 case Instruction::Or:
5786 case Instruction::Xor:
5787 return 3; // Can fold through either operand.
5788 case Instruction::Sub: // Can only fold on the amount subtracted.
5789 case Instruction::Shl: // Can only fold on the shift amount.
5790 case Instruction::Shr:
5793 return 0; // Cannot fold
5797 /// GetSelectFoldableConstant - For the same transformation as the previous
5798 /// function, return the identity constant that goes into the select.
5799 static Constant *GetSelectFoldableConstant(Instruction *I) {
5800 switch (I->getOpcode()) {
5801 default: assert(0 && "This cannot happen!"); abort();
5802 case Instruction::Add:
5803 case Instruction::Sub:
5804 case Instruction::Or:
5805 case Instruction::Xor:
5806 return Constant::getNullValue(I->getType());
5807 case Instruction::Shl:
5808 case Instruction::Shr:
5809 return Constant::getNullValue(Type::UByteTy);
5810 case Instruction::And:
5811 return ConstantInt::getAllOnesValue(I->getType());
5812 case Instruction::Mul:
5813 return ConstantInt::get(I->getType(), 1);
5817 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5818 /// have the same opcode and only one use each. Try to simplify this.
5819 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5821 if (TI->getNumOperands() == 1) {
5822 // If this is a non-volatile load or a cast from the same type,
5824 if (TI->getOpcode() == Instruction::Cast) {
5825 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5828 return 0; // unknown unary op.
5831 // Fold this by inserting a select from the input values.
5832 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5833 FI->getOperand(0), SI.getName()+".v");
5834 InsertNewInstBefore(NewSI, SI);
5835 return new CastInst(NewSI, TI->getType());
5838 // Only handle binary operators here.
5839 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5842 // Figure out if the operations have any operands in common.
5843 Value *MatchOp, *OtherOpT, *OtherOpF;
5845 if (TI->getOperand(0) == FI->getOperand(0)) {
5846 MatchOp = TI->getOperand(0);
5847 OtherOpT = TI->getOperand(1);
5848 OtherOpF = FI->getOperand(1);
5849 MatchIsOpZero = true;
5850 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5851 MatchOp = TI->getOperand(1);
5852 OtherOpT = TI->getOperand(0);
5853 OtherOpF = FI->getOperand(0);
5854 MatchIsOpZero = false;
5855 } else if (!TI->isCommutative()) {
5857 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5858 MatchOp = TI->getOperand(0);
5859 OtherOpT = TI->getOperand(1);
5860 OtherOpF = FI->getOperand(0);
5861 MatchIsOpZero = true;
5862 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5863 MatchOp = TI->getOperand(1);
5864 OtherOpT = TI->getOperand(0);
5865 OtherOpF = FI->getOperand(1);
5866 MatchIsOpZero = true;
5871 // If we reach here, they do have operations in common.
5872 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5873 OtherOpF, SI.getName()+".v");
5874 InsertNewInstBefore(NewSI, SI);
5876 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5878 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5880 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5883 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5885 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5889 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
5890 Value *CondVal = SI.getCondition();
5891 Value *TrueVal = SI.getTrueValue();
5892 Value *FalseVal = SI.getFalseValue();
5894 // select true, X, Y -> X
5895 // select false, X, Y -> Y
5896 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
5897 return ReplaceInstUsesWith(SI, C->getValue() ? TrueVal : FalseVal);
5899 // select C, X, X -> X
5900 if (TrueVal == FalseVal)
5901 return ReplaceInstUsesWith(SI, TrueVal);
5903 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5904 return ReplaceInstUsesWith(SI, FalseVal);
5905 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5906 return ReplaceInstUsesWith(SI, TrueVal);
5907 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5908 if (isa<Constant>(TrueVal))
5909 return ReplaceInstUsesWith(SI, TrueVal);
5911 return ReplaceInstUsesWith(SI, FalseVal);
5914 if (SI.getType() == Type::BoolTy)
5915 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5916 if (C->getValue()) {
5917 // Change: A = select B, true, C --> A = or B, C
5918 return BinaryOperator::createOr(CondVal, FalseVal);
5920 // Change: A = select B, false, C --> A = and !B, C
5922 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5923 "not."+CondVal->getName()), SI);
5924 return BinaryOperator::createAnd(NotCond, FalseVal);
5926 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5927 if (C->getValue() == false) {
5928 // Change: A = select B, C, false --> A = and B, C
5929 return BinaryOperator::createAnd(CondVal, TrueVal);
5931 // Change: A = select B, C, true --> A = or !B, C
5933 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5934 "not."+CondVal->getName()), SI);
5935 return BinaryOperator::createOr(NotCond, TrueVal);
5939 // Selecting between two integer constants?
5940 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5941 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5942 // select C, 1, 0 -> cast C to int
5943 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5944 return new CastInst(CondVal, SI.getType());
5945 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5946 // select C, 0, 1 -> cast !C to int
5948 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5949 "not."+CondVal->getName()), SI);
5950 return new CastInst(NotCond, SI.getType());
5953 if (SetCondInst *IC = dyn_cast<SetCondInst>(SI.getCondition())) {
5955 // (x <s 0) ? -1 : 0 -> sra x, 31
5956 // (x >u 2147483647) ? -1 : 0 -> sra x, 31
5957 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
5958 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
5959 bool CanXForm = false;
5960 if (CmpCst->getType()->isSigned())
5961 CanXForm = CmpCst->isNullValue() &&
5962 IC->getOpcode() == Instruction::SetLT;
5964 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
5965 CanXForm = (CmpCst->getRawValue() == ~0ULL >> (64-Bits+1)) &&
5966 IC->getOpcode() == Instruction::SetGT;
5970 // The comparison constant and the result are not neccessarily the
5971 // same width. In any case, the first step to do is make sure
5972 // that X is signed.
5973 Value *X = IC->getOperand(0);
5974 if (!X->getType()->isSigned())
5975 X = InsertCastBefore(X, X->getType()->getSignedVersion(), SI);
5977 // Now that X is signed, we have to make the all ones value. Do
5978 // this by inserting a new SRA.
5979 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
5980 Constant *ShAmt = ConstantUInt::get(Type::UByteTy, Bits-1);
5981 Instruction *SRA = new ShiftInst(Instruction::Shr, X,
5983 InsertNewInstBefore(SRA, SI);
5985 // Finally, convert to the type of the select RHS. If this is
5986 // smaller than the compare value, it will truncate the ones to
5987 // fit. If it is larger, it will sext the ones to fit.
5988 return new CastInst(SRA, SI.getType());
5993 // If one of the constants is zero (we know they can't both be) and we
5994 // have a setcc instruction with zero, and we have an 'and' with the
5995 // non-constant value, eliminate this whole mess. This corresponds to
5996 // cases like this: ((X & 27) ? 27 : 0)
5997 if (TrueValC->isNullValue() || FalseValC->isNullValue())
5998 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
5999 cast<Constant>(IC->getOperand(1))->isNullValue())
6000 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6001 if (ICA->getOpcode() == Instruction::And &&
6002 isa<ConstantInt>(ICA->getOperand(1)) &&
6003 (ICA->getOperand(1) == TrueValC ||
6004 ICA->getOperand(1) == FalseValC) &&
6005 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6006 // Okay, now we know that everything is set up, we just don't
6007 // know whether we have a setne or seteq and whether the true or
6008 // false val is the zero.
6009 bool ShouldNotVal = !TrueValC->isNullValue();
6010 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
6013 V = InsertNewInstBefore(BinaryOperator::create(
6014 Instruction::Xor, V, ICA->getOperand(1)), SI);
6015 return ReplaceInstUsesWith(SI, V);
6020 // See if we are selecting two values based on a comparison of the two values.
6021 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
6022 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
6023 // Transform (X == Y) ? X : Y -> Y
6024 if (SCI->getOpcode() == Instruction::SetEQ)
6025 return ReplaceInstUsesWith(SI, FalseVal);
6026 // Transform (X != Y) ? X : Y -> X
6027 if (SCI->getOpcode() == Instruction::SetNE)
6028 return ReplaceInstUsesWith(SI, TrueVal);
6029 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6031 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
6032 // Transform (X == Y) ? Y : X -> X
6033 if (SCI->getOpcode() == Instruction::SetEQ)
6034 return ReplaceInstUsesWith(SI, FalseVal);
6035 // Transform (X != Y) ? Y : X -> Y
6036 if (SCI->getOpcode() == Instruction::SetNE)
6037 return ReplaceInstUsesWith(SI, TrueVal);
6038 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6042 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6043 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6044 if (TI->hasOneUse() && FI->hasOneUse()) {
6045 bool isInverse = false;
6046 Instruction *AddOp = 0, *SubOp = 0;
6048 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6049 if (TI->getOpcode() == FI->getOpcode())
6050 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6053 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6054 // even legal for FP.
6055 if (TI->getOpcode() == Instruction::Sub &&
6056 FI->getOpcode() == Instruction::Add) {
6057 AddOp = FI; SubOp = TI;
6058 } else if (FI->getOpcode() == Instruction::Sub &&
6059 TI->getOpcode() == Instruction::Add) {
6060 AddOp = TI; SubOp = FI;
6064 Value *OtherAddOp = 0;
6065 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6066 OtherAddOp = AddOp->getOperand(1);
6067 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6068 OtherAddOp = AddOp->getOperand(0);
6072 // So at this point we know we have (Y -> OtherAddOp):
6073 // select C, (add X, Y), (sub X, Z)
6074 Value *NegVal; // Compute -Z
6075 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6076 NegVal = ConstantExpr::getNeg(C);
6078 NegVal = InsertNewInstBefore(
6079 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
6082 Value *NewTrueOp = OtherAddOp;
6083 Value *NewFalseOp = NegVal;
6085 std::swap(NewTrueOp, NewFalseOp);
6086 Instruction *NewSel =
6087 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6089 NewSel = InsertNewInstBefore(NewSel, SI);
6090 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
6095 // See if we can fold the select into one of our operands.
6096 if (SI.getType()->isInteger()) {
6097 // See the comment above GetSelectFoldableOperands for a description of the
6098 // transformation we are doing here.
6099 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6100 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6101 !isa<Constant>(FalseVal))
6102 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6103 unsigned OpToFold = 0;
6104 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6106 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6111 Constant *C = GetSelectFoldableConstant(TVI);
6112 std::string Name = TVI->getName(); TVI->setName("");
6113 Instruction *NewSel =
6114 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6116 InsertNewInstBefore(NewSel, SI);
6117 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6118 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6119 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6120 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6122 assert(0 && "Unknown instruction!!");
6127 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6128 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6129 !isa<Constant>(TrueVal))
6130 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6131 unsigned OpToFold = 0;
6132 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6134 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6139 Constant *C = GetSelectFoldableConstant(FVI);
6140 std::string Name = FVI->getName(); FVI->setName("");
6141 Instruction *NewSel =
6142 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6144 InsertNewInstBefore(NewSel, SI);
6145 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6146 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6147 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6148 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6150 assert(0 && "Unknown instruction!!");
6156 if (BinaryOperator::isNot(CondVal)) {
6157 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6158 SI.setOperand(1, FalseVal);
6159 SI.setOperand(2, TrueVal);
6166 /// GetKnownAlignment - If the specified pointer has an alignment that we can
6167 /// determine, return it, otherwise return 0.
6168 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6169 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6170 unsigned Align = GV->getAlignment();
6171 if (Align == 0 && TD)
6172 Align = TD->getTypeAlignment(GV->getType()->getElementType());
6174 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6175 unsigned Align = AI->getAlignment();
6176 if (Align == 0 && TD) {
6177 if (isa<AllocaInst>(AI))
6178 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6179 else if (isa<MallocInst>(AI)) {
6180 // Malloc returns maximally aligned memory.
6181 Align = TD->getTypeAlignment(AI->getType()->getElementType());
6182 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
6183 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
6187 } else if (isa<CastInst>(V) ||
6188 (isa<ConstantExpr>(V) &&
6189 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
6190 User *CI = cast<User>(V);
6191 if (isa<PointerType>(CI->getOperand(0)->getType()))
6192 return GetKnownAlignment(CI->getOperand(0), TD);
6194 } else if (isa<GetElementPtrInst>(V) ||
6195 (isa<ConstantExpr>(V) &&
6196 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6197 User *GEPI = cast<User>(V);
6198 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6199 if (BaseAlignment == 0) return 0;
6201 // If all indexes are zero, it is just the alignment of the base pointer.
6202 bool AllZeroOperands = true;
6203 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6204 if (!isa<Constant>(GEPI->getOperand(i)) ||
6205 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6206 AllZeroOperands = false;
6209 if (AllZeroOperands)
6210 return BaseAlignment;
6212 // Otherwise, if the base alignment is >= the alignment we expect for the
6213 // base pointer type, then we know that the resultant pointer is aligned at
6214 // least as much as its type requires.
6217 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6218 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
6220 const Type *GEPTy = GEPI->getType();
6221 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
6229 /// visitCallInst - CallInst simplification. This mostly only handles folding
6230 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6231 /// the heavy lifting.
6233 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
6234 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6235 if (!II) return visitCallSite(&CI);
6237 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6239 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
6240 bool Changed = false;
6242 // memmove/cpy/set of zero bytes is a noop.
6243 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6244 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6246 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6247 if (CI->getRawValue() == 1) {
6248 // Replace the instruction with just byte operations. We would
6249 // transform other cases to loads/stores, but we don't know if
6250 // alignment is sufficient.
6254 // If we have a memmove and the source operation is a constant global,
6255 // then the source and dest pointers can't alias, so we can change this
6256 // into a call to memcpy.
6257 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
6258 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6259 if (GVSrc->isConstant()) {
6260 Module *M = CI.getParent()->getParent()->getParent();
6262 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
6264 Name = "llvm.memcpy.i32";
6266 Name = "llvm.memcpy.i64";
6267 Function *MemCpy = M->getOrInsertFunction(Name,
6268 CI.getCalledFunction()->getFunctionType());
6269 CI.setOperand(0, MemCpy);
6274 // If we can determine a pointer alignment that is bigger than currently
6275 // set, update the alignment.
6276 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6277 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6278 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6279 unsigned Align = std::min(Alignment1, Alignment2);
6280 if (MI->getAlignment()->getRawValue() < Align) {
6281 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Align));
6284 } else if (isa<MemSetInst>(MI)) {
6285 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
6286 if (MI->getAlignment()->getRawValue() < Alignment) {
6287 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Alignment));
6292 if (Changed) return II;
6294 switch (II->getIntrinsicID()) {
6296 case Intrinsic::ppc_altivec_lvx:
6297 case Intrinsic::ppc_altivec_lvxl:
6298 case Intrinsic::x86_sse_loadu_ps:
6299 case Intrinsic::x86_sse2_loadu_pd:
6300 case Intrinsic::x86_sse2_loadu_dq:
6301 // Turn PPC lvx -> load if the pointer is known aligned.
6302 // Turn X86 loadups -> load if the pointer is known aligned.
6303 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6304 Value *Ptr = InsertCastBefore(II->getOperand(1),
6305 PointerType::get(II->getType()), CI);
6306 return new LoadInst(Ptr);
6309 case Intrinsic::ppc_altivec_stvx:
6310 case Intrinsic::ppc_altivec_stvxl:
6311 // Turn stvx -> store if the pointer is known aligned.
6312 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
6313 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
6314 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
6315 return new StoreInst(II->getOperand(1), Ptr);
6318 case Intrinsic::x86_sse_storeu_ps:
6319 case Intrinsic::x86_sse2_storeu_pd:
6320 case Intrinsic::x86_sse2_storeu_dq:
6321 case Intrinsic::x86_sse2_storel_dq:
6322 // Turn X86 storeu -> store if the pointer is known aligned.
6323 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
6324 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
6325 Value *Ptr = InsertCastBefore(II->getOperand(1), OpPtrTy, CI);
6326 return new StoreInst(II->getOperand(2), Ptr);
6330 case Intrinsic::x86_sse_cvttss2si: {
6331 // These intrinsics only demands the 0th element of its input vector. If
6332 // we can simplify the input based on that, do so now.
6334 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
6336 II->setOperand(1, V);
6342 case Intrinsic::ppc_altivec_vperm:
6343 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
6344 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
6345 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
6347 // Check that all of the elements are integer constants or undefs.
6348 bool AllEltsOk = true;
6349 for (unsigned i = 0; i != 16; ++i) {
6350 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
6351 !isa<UndefValue>(Mask->getOperand(i))) {
6358 // Cast the input vectors to byte vectors.
6359 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
6360 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
6361 Value *Result = UndefValue::get(Op0->getType());
6363 // Only extract each element once.
6364 Value *ExtractedElts[32];
6365 memset(ExtractedElts, 0, sizeof(ExtractedElts));
6367 for (unsigned i = 0; i != 16; ++i) {
6368 if (isa<UndefValue>(Mask->getOperand(i)))
6370 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getRawValue();
6371 Idx &= 31; // Match the hardware behavior.
6373 if (ExtractedElts[Idx] == 0) {
6375 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
6376 InsertNewInstBefore(Elt, CI);
6377 ExtractedElts[Idx] = Elt;
6380 // Insert this value into the result vector.
6381 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
6382 InsertNewInstBefore(cast<Instruction>(Result), CI);
6384 return new CastInst(Result, CI.getType());
6389 case Intrinsic::stackrestore: {
6390 // If the save is right next to the restore, remove the restore. This can
6391 // happen when variable allocas are DCE'd.
6392 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
6393 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
6394 BasicBlock::iterator BI = SS;
6396 return EraseInstFromFunction(CI);
6400 // If the stack restore is in a return/unwind block and if there are no
6401 // allocas or calls between the restore and the return, nuke the restore.
6402 TerminatorInst *TI = II->getParent()->getTerminator();
6403 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
6404 BasicBlock::iterator BI = II;
6405 bool CannotRemove = false;
6406 for (++BI; &*BI != TI; ++BI) {
6407 if (isa<AllocaInst>(BI) ||
6408 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
6409 CannotRemove = true;
6414 return EraseInstFromFunction(CI);
6421 return visitCallSite(II);
6424 // InvokeInst simplification
6426 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
6427 return visitCallSite(&II);
6430 // visitCallSite - Improvements for call and invoke instructions.
6432 Instruction *InstCombiner::visitCallSite(CallSite CS) {
6433 bool Changed = false;
6435 // If the callee is a constexpr cast of a function, attempt to move the cast
6436 // to the arguments of the call/invoke.
6437 if (transformConstExprCastCall(CS)) return 0;
6439 Value *Callee = CS.getCalledValue();
6441 if (Function *CalleeF = dyn_cast<Function>(Callee))
6442 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
6443 Instruction *OldCall = CS.getInstruction();
6444 // If the call and callee calling conventions don't match, this call must
6445 // be unreachable, as the call is undefined.
6446 new StoreInst(ConstantBool::getTrue(),
6447 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
6448 if (!OldCall->use_empty())
6449 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
6450 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
6451 return EraseInstFromFunction(*OldCall);
6455 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
6456 // This instruction is not reachable, just remove it. We insert a store to
6457 // undef so that we know that this code is not reachable, despite the fact
6458 // that we can't modify the CFG here.
6459 new StoreInst(ConstantBool::getTrue(),
6460 UndefValue::get(PointerType::get(Type::BoolTy)),
6461 CS.getInstruction());
6463 if (!CS.getInstruction()->use_empty())
6464 CS.getInstruction()->
6465 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
6467 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
6468 // Don't break the CFG, insert a dummy cond branch.
6469 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
6470 ConstantBool::getTrue(), II);
6472 return EraseInstFromFunction(*CS.getInstruction());
6475 const PointerType *PTy = cast<PointerType>(Callee->getType());
6476 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
6477 if (FTy->isVarArg()) {
6478 // See if we can optimize any arguments passed through the varargs area of
6480 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
6481 E = CS.arg_end(); I != E; ++I)
6482 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
6483 // If this cast does not effect the value passed through the varargs
6484 // area, we can eliminate the use of the cast.
6485 Value *Op = CI->getOperand(0);
6486 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
6493 return Changed ? CS.getInstruction() : 0;
6496 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
6497 // attempt to move the cast to the arguments of the call/invoke.
6499 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
6500 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
6501 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
6502 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
6504 Function *Callee = cast<Function>(CE->getOperand(0));
6505 Instruction *Caller = CS.getInstruction();
6507 // Okay, this is a cast from a function to a different type. Unless doing so
6508 // would cause a type conversion of one of our arguments, change this call to
6509 // be a direct call with arguments casted to the appropriate types.
6511 const FunctionType *FT = Callee->getFunctionType();
6512 const Type *OldRetTy = Caller->getType();
6514 // Check to see if we are changing the return type...
6515 if (OldRetTy != FT->getReturnType()) {
6516 if (Callee->isExternal() &&
6517 !(OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) ||
6518 (isa<PointerType>(FT->getReturnType()) &&
6519 TD->getIntPtrType()->isLosslesslyConvertibleTo(OldRetTy)))
6520 && !Caller->use_empty())
6521 return false; // Cannot transform this return value...
6523 // If the callsite is an invoke instruction, and the return value is used by
6524 // a PHI node in a successor, we cannot change the return type of the call
6525 // because there is no place to put the cast instruction (without breaking
6526 // the critical edge). Bail out in this case.
6527 if (!Caller->use_empty())
6528 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
6529 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
6531 if (PHINode *PN = dyn_cast<PHINode>(*UI))
6532 if (PN->getParent() == II->getNormalDest() ||
6533 PN->getParent() == II->getUnwindDest())
6537 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
6538 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
6540 CallSite::arg_iterator AI = CS.arg_begin();
6541 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
6542 const Type *ParamTy = FT->getParamType(i);
6543 const Type *ActTy = (*AI)->getType();
6544 ConstantSInt* c = dyn_cast<ConstantSInt>(*AI);
6545 //Either we can cast directly, or we can upconvert the argument
6546 bool isConvertible = ActTy->isLosslesslyConvertibleTo(ParamTy) ||
6547 (ParamTy->isIntegral() && ActTy->isIntegral() &&
6548 ParamTy->isSigned() == ActTy->isSigned() &&
6549 ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize()) ||
6550 (c && ParamTy->getPrimitiveSize() >= ActTy->getPrimitiveSize() &&
6552 if (Callee->isExternal() && !isConvertible) return false;
6555 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
6556 Callee->isExternal())
6557 return false; // Do not delete arguments unless we have a function body...
6559 // Okay, we decided that this is a safe thing to do: go ahead and start
6560 // inserting cast instructions as necessary...
6561 std::vector<Value*> Args;
6562 Args.reserve(NumActualArgs);
6564 AI = CS.arg_begin();
6565 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
6566 const Type *ParamTy = FT->getParamType(i);
6567 if ((*AI)->getType() == ParamTy) {
6568 Args.push_back(*AI);
6570 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
6575 // If the function takes more arguments than the call was taking, add them
6577 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
6578 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
6580 // If we are removing arguments to the function, emit an obnoxious warning...
6581 if (FT->getNumParams() < NumActualArgs)
6582 if (!FT->isVarArg()) {
6583 std::cerr << "WARNING: While resolving call to function '"
6584 << Callee->getName() << "' arguments were dropped!\n";
6586 // Add all of the arguments in their promoted form to the arg list...
6587 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
6588 const Type *PTy = getPromotedType((*AI)->getType());
6589 if (PTy != (*AI)->getType()) {
6590 // Must promote to pass through va_arg area!
6591 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
6592 InsertNewInstBefore(Cast, *Caller);
6593 Args.push_back(Cast);
6595 Args.push_back(*AI);
6600 if (FT->getReturnType() == Type::VoidTy)
6601 Caller->setName(""); // Void type should not have a name...
6604 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6605 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
6606 Args, Caller->getName(), Caller);
6607 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
6609 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
6610 if (cast<CallInst>(Caller)->isTailCall())
6611 cast<CallInst>(NC)->setTailCall();
6612 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
6615 // Insert a cast of the return type as necessary...
6617 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
6618 if (NV->getType() != Type::VoidTy) {
6619 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
6621 // If this is an invoke instruction, we should insert it after the first
6622 // non-phi, instruction in the normal successor block.
6623 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
6624 BasicBlock::iterator I = II->getNormalDest()->begin();
6625 while (isa<PHINode>(I)) ++I;
6626 InsertNewInstBefore(NC, *I);
6628 // Otherwise, it's a call, just insert cast right after the call instr
6629 InsertNewInstBefore(NC, *Caller);
6631 AddUsersToWorkList(*Caller);
6633 NV = UndefValue::get(Caller->getType());
6637 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
6638 Caller->replaceAllUsesWith(NV);
6639 Caller->getParent()->getInstList().erase(Caller);
6640 removeFromWorkList(Caller);
6645 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
6646 // operator and they all are only used by the PHI, PHI together their
6647 // inputs, and do the operation once, to the result of the PHI.
6648 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
6649 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
6651 // Scan the instruction, looking for input operations that can be folded away.
6652 // If all input operands to the phi are the same instruction (e.g. a cast from
6653 // the same type or "+42") we can pull the operation through the PHI, reducing
6654 // code size and simplifying code.
6655 Constant *ConstantOp = 0;
6656 const Type *CastSrcTy = 0;
6657 if (isa<CastInst>(FirstInst)) {
6658 CastSrcTy = FirstInst->getOperand(0)->getType();
6659 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
6660 // Can fold binop or shift if the RHS is a constant.
6661 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
6662 if (ConstantOp == 0) return 0;
6664 return 0; // Cannot fold this operation.
6667 // Check to see if all arguments are the same operation.
6668 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6669 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
6670 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
6671 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
6674 if (I->getOperand(0)->getType() != CastSrcTy)
6675 return 0; // Cast operation must match.
6676 } else if (I->getOperand(1) != ConstantOp) {
6681 // Okay, they are all the same operation. Create a new PHI node of the
6682 // correct type, and PHI together all of the LHS's of the instructions.
6683 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
6684 PN.getName()+".in");
6685 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
6687 Value *InVal = FirstInst->getOperand(0);
6688 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
6690 // Add all operands to the new PHI.
6691 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
6692 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
6693 if (NewInVal != InVal)
6695 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
6700 // The new PHI unions all of the same values together. This is really
6701 // common, so we handle it intelligently here for compile-time speed.
6705 InsertNewInstBefore(NewPN, PN);
6709 // Insert and return the new operation.
6710 if (isa<CastInst>(FirstInst))
6711 return new CastInst(PhiVal, PN.getType());
6712 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
6713 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
6715 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
6716 PhiVal, ConstantOp);
6719 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
6721 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
6722 if (PN->use_empty()) return true;
6723 if (!PN->hasOneUse()) return false;
6725 // Remember this node, and if we find the cycle, return.
6726 if (!PotentiallyDeadPHIs.insert(PN).second)
6729 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
6730 return DeadPHICycle(PU, PotentiallyDeadPHIs);
6735 // PHINode simplification
6737 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
6738 // If LCSSA is around, don't mess with Phi nodes
6739 if (mustPreserveAnalysisID(LCSSAID)) return 0;
6741 if (Value *V = PN.hasConstantValue())
6742 return ReplaceInstUsesWith(PN, V);
6744 // If the only user of this instruction is a cast instruction, and all of the
6745 // incoming values are constants, change this PHI to merge together the casted
6748 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
6749 if (CI->getType() != PN.getType()) { // noop casts will be folded
6750 bool AllConstant = true;
6751 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
6752 if (!isa<Constant>(PN.getIncomingValue(i))) {
6753 AllConstant = false;
6757 // Make a new PHI with all casted values.
6758 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
6759 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
6760 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
6761 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
6762 PN.getIncomingBlock(i));
6765 // Update the cast instruction.
6766 CI->setOperand(0, New);
6767 WorkList.push_back(CI); // revisit the cast instruction to fold.
6768 WorkList.push_back(New); // Make sure to revisit the new Phi
6769 return &PN; // PN is now dead!
6773 // If all PHI operands are the same operation, pull them through the PHI,
6774 // reducing code size.
6775 if (isa<Instruction>(PN.getIncomingValue(0)) &&
6776 PN.getIncomingValue(0)->hasOneUse())
6777 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
6780 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
6781 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
6782 // PHI)... break the cycle.
6784 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
6785 std::set<PHINode*> PotentiallyDeadPHIs;
6786 PotentiallyDeadPHIs.insert(&PN);
6787 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
6788 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
6794 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
6795 Instruction *InsertPoint,
6797 unsigned PS = IC->getTargetData().getPointerSize();
6798 const Type *VTy = V->getType();
6799 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
6800 // We must insert a cast to ensure we sign-extend.
6801 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
6802 V->getName()), *InsertPoint);
6803 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
6808 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
6809 Value *PtrOp = GEP.getOperand(0);
6810 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
6811 // If so, eliminate the noop.
6812 if (GEP.getNumOperands() == 1)
6813 return ReplaceInstUsesWith(GEP, PtrOp);
6815 if (isa<UndefValue>(GEP.getOperand(0)))
6816 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
6818 bool HasZeroPointerIndex = false;
6819 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
6820 HasZeroPointerIndex = C->isNullValue();
6822 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
6823 return ReplaceInstUsesWith(GEP, PtrOp);
6825 // Eliminate unneeded casts for indices.
6826 bool MadeChange = false;
6827 gep_type_iterator GTI = gep_type_begin(GEP);
6828 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
6829 if (isa<SequentialType>(*GTI)) {
6830 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
6831 Value *Src = CI->getOperand(0);
6832 const Type *SrcTy = Src->getType();
6833 const Type *DestTy = CI->getType();
6834 if (Src->getType()->isInteger()) {
6835 if (SrcTy->getPrimitiveSizeInBits() ==
6836 DestTy->getPrimitiveSizeInBits()) {
6837 // We can always eliminate a cast from ulong or long to the other.
6838 // We can always eliminate a cast from uint to int or the other on
6839 // 32-bit pointer platforms.
6840 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
6842 GEP.setOperand(i, Src);
6844 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
6845 SrcTy->getPrimitiveSize() == 4) {
6846 // We can always eliminate a cast from int to [u]long. We can
6847 // eliminate a cast from uint to [u]long iff the target is a 32-bit
6849 if (SrcTy->isSigned() ||
6850 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
6852 GEP.setOperand(i, Src);
6857 // If we are using a wider index than needed for this platform, shrink it
6858 // to what we need. If the incoming value needs a cast instruction,
6859 // insert it. This explicit cast can make subsequent optimizations more
6861 Value *Op = GEP.getOperand(i);
6862 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
6863 if (Constant *C = dyn_cast<Constant>(Op)) {
6864 GEP.setOperand(i, ConstantExpr::getCast(C,
6865 TD->getIntPtrType()->getSignedVersion()));
6868 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
6869 Op->getName()), GEP);
6870 GEP.setOperand(i, Op);
6874 // If this is a constant idx, make sure to canonicalize it to be a signed
6875 // operand, otherwise CSE and other optimizations are pessimized.
6876 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
6877 GEP.setOperand(i, ConstantExpr::getCast(CUI,
6878 CUI->getType()->getSignedVersion()));
6882 if (MadeChange) return &GEP;
6884 // Combine Indices - If the source pointer to this getelementptr instruction
6885 // is a getelementptr instruction, combine the indices of the two
6886 // getelementptr instructions into a single instruction.
6888 std::vector<Value*> SrcGEPOperands;
6889 if (User *Src = dyn_castGetElementPtr(PtrOp))
6890 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
6892 if (!SrcGEPOperands.empty()) {
6893 // Note that if our source is a gep chain itself that we wait for that
6894 // chain to be resolved before we perform this transformation. This
6895 // avoids us creating a TON of code in some cases.
6897 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
6898 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
6899 return 0; // Wait until our source is folded to completion.
6901 std::vector<Value *> Indices;
6903 // Find out whether the last index in the source GEP is a sequential idx.
6904 bool EndsWithSequential = false;
6905 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
6906 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
6907 EndsWithSequential = !isa<StructType>(*I);
6909 // Can we combine the two pointer arithmetics offsets?
6910 if (EndsWithSequential) {
6911 // Replace: gep (gep %P, long B), long A, ...
6912 // With: T = long A+B; gep %P, T, ...
6914 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
6915 if (SO1 == Constant::getNullValue(SO1->getType())) {
6917 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
6920 // If they aren't the same type, convert both to an integer of the
6921 // target's pointer size.
6922 if (SO1->getType() != GO1->getType()) {
6923 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
6924 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
6925 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
6926 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
6928 unsigned PS = TD->getPointerSize();
6929 if (SO1->getType()->getPrimitiveSize() == PS) {
6930 // Convert GO1 to SO1's type.
6931 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
6933 } else if (GO1->getType()->getPrimitiveSize() == PS) {
6934 // Convert SO1 to GO1's type.
6935 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6937 const Type *PT = TD->getIntPtrType();
6938 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6939 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6943 if (isa<Constant>(SO1) && isa<Constant>(GO1))
6944 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6946 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6947 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
6951 // Recycle the GEP we already have if possible.
6952 if (SrcGEPOperands.size() == 2) {
6953 GEP.setOperand(0, SrcGEPOperands[0]);
6954 GEP.setOperand(1, Sum);
6957 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6958 SrcGEPOperands.end()-1);
6959 Indices.push_back(Sum);
6960 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
6962 } else if (isa<Constant>(*GEP.idx_begin()) &&
6963 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
6964 SrcGEPOperands.size() != 1) {
6965 // Otherwise we can do the fold if the first index of the GEP is a zero
6966 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6967 SrcGEPOperands.end());
6968 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
6971 if (!Indices.empty())
6972 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
6974 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
6975 // GEP of global variable. If all of the indices for this GEP are
6976 // constants, we can promote this to a constexpr instead of an instruction.
6978 // Scan for nonconstants...
6979 std::vector<Constant*> Indices;
6980 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
6981 for (; I != E && isa<Constant>(*I); ++I)
6982 Indices.push_back(cast<Constant>(*I));
6984 if (I == E) { // If they are all constants...
6985 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
6987 // Replace all uses of the GEP with the new constexpr...
6988 return ReplaceInstUsesWith(GEP, CE);
6990 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
6991 if (!isa<PointerType>(X->getType())) {
6992 // Not interesting. Source pointer must be a cast from pointer.
6993 } else if (HasZeroPointerIndex) {
6994 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
6995 // into : GEP [10 x ubyte]* X, long 0, ...
6997 // This occurs when the program declares an array extern like "int X[];"
6999 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7000 const PointerType *XTy = cast<PointerType>(X->getType());
7001 if (const ArrayType *XATy =
7002 dyn_cast<ArrayType>(XTy->getElementType()))
7003 if (const ArrayType *CATy =
7004 dyn_cast<ArrayType>(CPTy->getElementType()))
7005 if (CATy->getElementType() == XATy->getElementType()) {
7006 // At this point, we know that the cast source type is a pointer
7007 // to an array of the same type as the destination pointer
7008 // array. Because the array type is never stepped over (there
7009 // is a leading zero) we can fold the cast into this GEP.
7010 GEP.setOperand(0, X);
7013 } else if (GEP.getNumOperands() == 2) {
7014 // Transform things like:
7015 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7016 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
7017 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7018 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7019 if (isa<ArrayType>(SrcElTy) &&
7020 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7021 TD->getTypeSize(ResElTy)) {
7022 Value *V = InsertNewInstBefore(
7023 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7024 GEP.getOperand(1), GEP.getName()), GEP);
7025 return new CastInst(V, GEP.getType());
7028 // Transform things like:
7029 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7030 // (where tmp = 8*tmp2) into:
7031 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7033 if (isa<ArrayType>(SrcElTy) &&
7034 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
7035 uint64_t ArrayEltSize =
7036 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7038 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7039 // allow either a mul, shift, or constant here.
7041 ConstantInt *Scale = 0;
7042 if (ArrayEltSize == 1) {
7043 NewIdx = GEP.getOperand(1);
7044 Scale = ConstantInt::get(NewIdx->getType(), 1);
7045 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
7046 NewIdx = ConstantInt::get(CI->getType(), 1);
7048 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7049 if (Inst->getOpcode() == Instruction::Shl &&
7050 isa<ConstantInt>(Inst->getOperand(1))) {
7051 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
7052 if (Inst->getType()->isSigned())
7053 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
7055 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
7056 NewIdx = Inst->getOperand(0);
7057 } else if (Inst->getOpcode() == Instruction::Mul &&
7058 isa<ConstantInt>(Inst->getOperand(1))) {
7059 Scale = cast<ConstantInt>(Inst->getOperand(1));
7060 NewIdx = Inst->getOperand(0);
7064 // If the index will be to exactly the right offset with the scale taken
7065 // out, perform the transformation.
7066 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
7067 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
7068 Scale = ConstantSInt::get(C->getType(),
7069 (int64_t)C->getRawValue() /
7070 (int64_t)ArrayEltSize);
7072 Scale = ConstantUInt::get(Scale->getType(),
7073 Scale->getRawValue() / ArrayEltSize);
7074 if (Scale->getRawValue() != 1) {
7075 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
7076 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7077 NewIdx = InsertNewInstBefore(Sc, GEP);
7080 // Insert the new GEP instruction.
7082 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
7083 NewIdx, GEP.getName());
7084 Idx = InsertNewInstBefore(Idx, GEP);
7085 return new CastInst(Idx, GEP.getType());
7094 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7095 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7096 if (AI.isArrayAllocation()) // Check C != 1
7097 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
7098 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
7099 AllocationInst *New = 0;
7101 // Create and insert the replacement instruction...
7102 if (isa<MallocInst>(AI))
7103 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
7105 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
7106 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
7109 InsertNewInstBefore(New, AI);
7111 // Scan to the end of the allocation instructions, to skip over a block of
7112 // allocas if possible...
7114 BasicBlock::iterator It = New;
7115 while (isa<AllocationInst>(*It)) ++It;
7117 // Now that I is pointing to the first non-allocation-inst in the block,
7118 // insert our getelementptr instruction...
7120 Value *NullIdx = Constant::getNullValue(Type::IntTy);
7121 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7122 New->getName()+".sub", It);
7124 // Now make everything use the getelementptr instead of the original
7126 return ReplaceInstUsesWith(AI, V);
7127 } else if (isa<UndefValue>(AI.getArraySize())) {
7128 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7131 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7132 // Note that we only do this for alloca's, because malloc should allocate and
7133 // return a unique pointer, even for a zero byte allocation.
7134 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
7135 TD->getTypeSize(AI.getAllocatedType()) == 0)
7136 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7141 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7142 Value *Op = FI.getOperand(0);
7144 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7145 if (CastInst *CI = dyn_cast<CastInst>(Op))
7146 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7147 FI.setOperand(0, CI->getOperand(0));
7151 // free undef -> unreachable.
7152 if (isa<UndefValue>(Op)) {
7153 // Insert a new store to null because we cannot modify the CFG here.
7154 new StoreInst(ConstantBool::getTrue(),
7155 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
7156 return EraseInstFromFunction(FI);
7159 // If we have 'free null' delete the instruction. This can happen in stl code
7160 // when lots of inlining happens.
7161 if (isa<ConstantPointerNull>(Op))
7162 return EraseInstFromFunction(FI);
7168 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
7169 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7170 User *CI = cast<User>(LI.getOperand(0));
7171 Value *CastOp = CI->getOperand(0);
7173 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7174 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7175 const Type *SrcPTy = SrcTy->getElementType();
7177 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7178 isa<PackedType>(DestPTy)) {
7179 // If the source is an array, the code below will not succeed. Check to
7180 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7182 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7183 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7184 if (ASrcTy->getNumElements() != 0) {
7185 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7186 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7187 SrcTy = cast<PointerType>(CastOp->getType());
7188 SrcPTy = SrcTy->getElementType();
7191 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
7192 isa<PackedType>(SrcPTy)) &&
7193 // Do not allow turning this into a load of an integer, which is then
7194 // casted to a pointer, this pessimizes pointer analysis a lot.
7195 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
7196 IC.getTargetData().getTypeSize(SrcPTy) ==
7197 IC.getTargetData().getTypeSize(DestPTy)) {
7199 // Okay, we are casting from one integer or pointer type to another of
7200 // the same size. Instead of casting the pointer before the load, cast
7201 // the result of the loaded value.
7202 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
7204 LI.isVolatile()),LI);
7205 // Now cast the result of the load.
7206 return new CastInst(NewLoad, LI.getType());
7213 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
7214 /// from this value cannot trap. If it is not obviously safe to load from the
7215 /// specified pointer, we do a quick local scan of the basic block containing
7216 /// ScanFrom, to determine if the address is already accessed.
7217 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
7218 // If it is an alloca or global variable, it is always safe to load from.
7219 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
7221 // Otherwise, be a little bit agressive by scanning the local block where we
7222 // want to check to see if the pointer is already being loaded or stored
7223 // from/to. If so, the previous load or store would have already trapped,
7224 // so there is no harm doing an extra load (also, CSE will later eliminate
7225 // the load entirely).
7226 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
7231 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7232 if (LI->getOperand(0) == V) return true;
7233 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7234 if (SI->getOperand(1) == V) return true;
7240 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
7241 Value *Op = LI.getOperand(0);
7243 // load (cast X) --> cast (load X) iff safe
7244 if (CastInst *CI = dyn_cast<CastInst>(Op))
7245 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7248 // None of the following transforms are legal for volatile loads.
7249 if (LI.isVolatile()) return 0;
7251 if (&LI.getParent()->front() != &LI) {
7252 BasicBlock::iterator BBI = &LI; --BBI;
7253 // If the instruction immediately before this is a store to the same
7254 // address, do a simple form of store->load forwarding.
7255 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
7256 if (SI->getOperand(1) == LI.getOperand(0))
7257 return ReplaceInstUsesWith(LI, SI->getOperand(0));
7258 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
7259 if (LIB->getOperand(0) == LI.getOperand(0))
7260 return ReplaceInstUsesWith(LI, LIB);
7263 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
7264 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
7265 isa<UndefValue>(GEPI->getOperand(0))) {
7266 // Insert a new store to null instruction before the load to indicate
7267 // that this code is not reachable. We do this instead of inserting
7268 // an unreachable instruction directly because we cannot modify the
7270 new StoreInst(UndefValue::get(LI.getType()),
7271 Constant::getNullValue(Op->getType()), &LI);
7272 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7275 if (Constant *C = dyn_cast<Constant>(Op)) {
7276 // load null/undef -> undef
7277 if ((C->isNullValue() || isa<UndefValue>(C))) {
7278 // Insert a new store to null instruction before the load to indicate that
7279 // this code is not reachable. We do this instead of inserting an
7280 // unreachable instruction directly because we cannot modify the CFG.
7281 new StoreInst(UndefValue::get(LI.getType()),
7282 Constant::getNullValue(Op->getType()), &LI);
7283 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7286 // Instcombine load (constant global) into the value loaded.
7287 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
7288 if (GV->isConstant() && !GV->isExternal())
7289 return ReplaceInstUsesWith(LI, GV->getInitializer());
7291 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
7292 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
7293 if (CE->getOpcode() == Instruction::GetElementPtr) {
7294 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
7295 if (GV->isConstant() && !GV->isExternal())
7297 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
7298 return ReplaceInstUsesWith(LI, V);
7299 if (CE->getOperand(0)->isNullValue()) {
7300 // Insert a new store to null instruction before the load to indicate
7301 // that this code is not reachable. We do this instead of inserting
7302 // an unreachable instruction directly because we cannot modify the
7304 new StoreInst(UndefValue::get(LI.getType()),
7305 Constant::getNullValue(Op->getType()), &LI);
7306 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
7309 } else if (CE->getOpcode() == Instruction::Cast) {
7310 if (Instruction *Res = InstCombineLoadCast(*this, LI))
7315 if (Op->hasOneUse()) {
7316 // Change select and PHI nodes to select values instead of addresses: this
7317 // helps alias analysis out a lot, allows many others simplifications, and
7318 // exposes redundancy in the code.
7320 // Note that we cannot do the transformation unless we know that the
7321 // introduced loads cannot trap! Something like this is valid as long as
7322 // the condition is always false: load (select bool %C, int* null, int* %G),
7323 // but it would not be valid if we transformed it to load from null
7326 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
7327 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
7328 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
7329 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
7330 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
7331 SI->getOperand(1)->getName()+".val"), LI);
7332 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
7333 SI->getOperand(2)->getName()+".val"), LI);
7334 return new SelectInst(SI->getCondition(), V1, V2);
7337 // load (select (cond, null, P)) -> load P
7338 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
7339 if (C->isNullValue()) {
7340 LI.setOperand(0, SI->getOperand(2));
7344 // load (select (cond, P, null)) -> load P
7345 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
7346 if (C->isNullValue()) {
7347 LI.setOperand(0, SI->getOperand(1));
7351 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
7352 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
7353 bool Safe = PN->getParent() == LI.getParent();
7355 // Scan all of the instructions between the PHI and the load to make
7356 // sure there are no instructions that might possibly alter the value
7357 // loaded from the PHI.
7359 BasicBlock::iterator I = &LI;
7360 for (--I; !isa<PHINode>(I); --I)
7361 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
7367 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
7368 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
7369 PN->getIncomingBlock(i)->getTerminator()))
7374 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
7375 InsertNewInstBefore(NewPN, *PN);
7376 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
7378 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
7379 BasicBlock *BB = PN->getIncomingBlock(i);
7380 Value *&TheLoad = LoadMap[BB];
7382 Value *InVal = PN->getIncomingValue(i);
7383 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
7384 InVal->getName()+".val"),
7385 *BB->getTerminator());
7387 NewPN->addIncoming(TheLoad, BB);
7389 return ReplaceInstUsesWith(LI, NewPN);
7396 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
7398 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
7399 User *CI = cast<User>(SI.getOperand(1));
7400 Value *CastOp = CI->getOperand(0);
7402 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7403 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7404 const Type *SrcPTy = SrcTy->getElementType();
7406 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
7407 // If the source is an array, the code below will not succeed. Check to
7408 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
7410 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
7411 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
7412 if (ASrcTy->getNumElements() != 0) {
7413 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
7414 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
7415 SrcTy = cast<PointerType>(CastOp->getType());
7416 SrcPTy = SrcTy->getElementType();
7419 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
7420 IC.getTargetData().getTypeSize(SrcPTy) ==
7421 IC.getTargetData().getTypeSize(DestPTy)) {
7423 // Okay, we are casting from one integer or pointer type to another of
7424 // the same size. Instead of casting the pointer before the store, cast
7425 // the value to be stored.
7427 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
7428 NewCast = ConstantExpr::getCast(C, SrcPTy);
7430 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
7432 SI.getOperand(0)->getName()+".c"), SI);
7434 return new StoreInst(NewCast, CastOp);
7441 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
7442 Value *Val = SI.getOperand(0);
7443 Value *Ptr = SI.getOperand(1);
7445 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
7446 EraseInstFromFunction(SI);
7451 // Do really simple DSE, to catch cases where there are several consequtive
7452 // stores to the same location, separated by a few arithmetic operations. This
7453 // situation often occurs with bitfield accesses.
7454 BasicBlock::iterator BBI = &SI;
7455 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
7459 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
7460 // Prev store isn't volatile, and stores to the same location?
7461 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
7464 EraseInstFromFunction(*PrevSI);
7470 // If this is a load, we have to stop. However, if the loaded value is from
7471 // the pointer we're loading and is producing the pointer we're storing,
7472 // then *this* store is dead (X = load P; store X -> P).
7473 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
7474 if (LI == Val && LI->getOperand(0) == Ptr) {
7475 EraseInstFromFunction(SI);
7479 // Otherwise, this is a load from some other location. Stores before it
7484 // Don't skip over loads or things that can modify memory.
7485 if (BBI->mayWriteToMemory())
7490 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
7492 // store X, null -> turns into 'unreachable' in SimplifyCFG
7493 if (isa<ConstantPointerNull>(Ptr)) {
7494 if (!isa<UndefValue>(Val)) {
7495 SI.setOperand(0, UndefValue::get(Val->getType()));
7496 if (Instruction *U = dyn_cast<Instruction>(Val))
7497 WorkList.push_back(U); // Dropped a use.
7500 return 0; // Do not modify these!
7503 // store undef, Ptr -> noop
7504 if (isa<UndefValue>(Val)) {
7505 EraseInstFromFunction(SI);
7510 // If the pointer destination is a cast, see if we can fold the cast into the
7512 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
7513 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7515 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
7516 if (CE->getOpcode() == Instruction::Cast)
7517 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
7521 // If this store is the last instruction in the basic block, and if the block
7522 // ends with an unconditional branch, try to move it to the successor block.
7524 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
7525 if (BI->isUnconditional()) {
7526 // Check to see if the successor block has exactly two incoming edges. If
7527 // so, see if the other predecessor contains a store to the same location.
7528 // if so, insert a PHI node (if needed) and move the stores down.
7529 BasicBlock *Dest = BI->getSuccessor(0);
7531 pred_iterator PI = pred_begin(Dest);
7532 BasicBlock *Other = 0;
7533 if (*PI != BI->getParent())
7536 if (PI != pred_end(Dest)) {
7537 if (*PI != BI->getParent())
7542 if (++PI != pred_end(Dest))
7545 if (Other) { // If only one other pred...
7546 BBI = Other->getTerminator();
7547 // Make sure this other block ends in an unconditional branch and that
7548 // there is an instruction before the branch.
7549 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
7550 BBI != Other->begin()) {
7552 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
7554 // If this instruction is a store to the same location.
7555 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
7556 // Okay, we know we can perform this transformation. Insert a PHI
7557 // node now if we need it.
7558 Value *MergedVal = OtherStore->getOperand(0);
7559 if (MergedVal != SI.getOperand(0)) {
7560 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
7561 PN->reserveOperandSpace(2);
7562 PN->addIncoming(SI.getOperand(0), SI.getParent());
7563 PN->addIncoming(OtherStore->getOperand(0), Other);
7564 MergedVal = InsertNewInstBefore(PN, Dest->front());
7567 // Advance to a place where it is safe to insert the new store and
7569 BBI = Dest->begin();
7570 while (isa<PHINode>(BBI)) ++BBI;
7571 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
7572 OtherStore->isVolatile()), *BBI);
7574 // Nuke the old stores.
7575 EraseInstFromFunction(SI);
7576 EraseInstFromFunction(*OtherStore);
7588 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
7589 // Change br (not X), label True, label False to: br X, label False, True
7591 BasicBlock *TrueDest;
7592 BasicBlock *FalseDest;
7593 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
7594 !isa<Constant>(X)) {
7595 // Swap Destinations and condition...
7597 BI.setSuccessor(0, FalseDest);
7598 BI.setSuccessor(1, TrueDest);
7602 // Cannonicalize setne -> seteq
7603 Instruction::BinaryOps Op; Value *Y;
7604 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
7605 TrueDest, FalseDest)))
7606 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
7607 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
7608 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
7609 std::string Name = I->getName(); I->setName("");
7610 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
7611 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
7612 // Swap Destinations and condition...
7613 BI.setCondition(NewSCC);
7614 BI.setSuccessor(0, FalseDest);
7615 BI.setSuccessor(1, TrueDest);
7616 removeFromWorkList(I);
7617 I->getParent()->getInstList().erase(I);
7618 WorkList.push_back(cast<Instruction>(NewSCC));
7625 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
7626 Value *Cond = SI.getCondition();
7627 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
7628 if (I->getOpcode() == Instruction::Add)
7629 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7630 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
7631 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
7632 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
7634 SI.setOperand(0, I->getOperand(0));
7635 WorkList.push_back(I);
7642 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
7643 /// is to leave as a vector operation.
7644 static bool CheapToScalarize(Value *V, bool isConstant) {
7645 if (isa<ConstantAggregateZero>(V))
7647 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
7648 if (isConstant) return true;
7649 // If all elts are the same, we can extract.
7650 Constant *Op0 = C->getOperand(0);
7651 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7652 if (C->getOperand(i) != Op0)
7656 Instruction *I = dyn_cast<Instruction>(V);
7657 if (!I) return false;
7659 // Insert element gets simplified to the inserted element or is deleted if
7660 // this is constant idx extract element and its a constant idx insertelt.
7661 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
7662 isa<ConstantInt>(I->getOperand(2)))
7664 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
7666 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
7667 if (BO->hasOneUse() &&
7668 (CheapToScalarize(BO->getOperand(0), isConstant) ||
7669 CheapToScalarize(BO->getOperand(1), isConstant)))
7675 /// getShuffleMask - Read and decode a shufflevector mask. It turns undef
7676 /// elements into values that are larger than the #elts in the input.
7677 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
7678 unsigned NElts = SVI->getType()->getNumElements();
7679 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
7680 return std::vector<unsigned>(NElts, 0);
7681 if (isa<UndefValue>(SVI->getOperand(2)))
7682 return std::vector<unsigned>(NElts, 2*NElts);
7684 std::vector<unsigned> Result;
7685 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
7686 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
7687 if (isa<UndefValue>(CP->getOperand(i)))
7688 Result.push_back(NElts*2); // undef -> 8
7690 Result.push_back(cast<ConstantUInt>(CP->getOperand(i))->getValue());
7694 /// FindScalarElement - Given a vector and an element number, see if the scalar
7695 /// value is already around as a register, for example if it were inserted then
7696 /// extracted from the vector.
7697 static Value *FindScalarElement(Value *V, unsigned EltNo) {
7698 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
7699 const PackedType *PTy = cast<PackedType>(V->getType());
7700 unsigned Width = PTy->getNumElements();
7701 if (EltNo >= Width) // Out of range access.
7702 return UndefValue::get(PTy->getElementType());
7704 if (isa<UndefValue>(V))
7705 return UndefValue::get(PTy->getElementType());
7706 else if (isa<ConstantAggregateZero>(V))
7707 return Constant::getNullValue(PTy->getElementType());
7708 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
7709 return CP->getOperand(EltNo);
7710 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
7711 // If this is an insert to a variable element, we don't know what it is.
7712 if (!isa<ConstantUInt>(III->getOperand(2))) return 0;
7713 unsigned IIElt = cast<ConstantUInt>(III->getOperand(2))->getValue();
7715 // If this is an insert to the element we are looking for, return the
7717 if (EltNo == IIElt) return III->getOperand(1);
7719 // Otherwise, the insertelement doesn't modify the value, recurse on its
7721 return FindScalarElement(III->getOperand(0), EltNo);
7722 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
7723 unsigned InEl = getShuffleMask(SVI)[EltNo];
7725 return FindScalarElement(SVI->getOperand(0), InEl);
7726 else if (InEl < Width*2)
7727 return FindScalarElement(SVI->getOperand(1), InEl - Width);
7729 return UndefValue::get(PTy->getElementType());
7732 // Otherwise, we don't know.
7736 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
7738 // If packed val is undef, replace extract with scalar undef.
7739 if (isa<UndefValue>(EI.getOperand(0)))
7740 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7742 // If packed val is constant 0, replace extract with scalar 0.
7743 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
7744 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
7746 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
7747 // If packed val is constant with uniform operands, replace EI
7748 // with that operand
7749 Constant *op0 = C->getOperand(0);
7750 for (unsigned i = 1; i < C->getNumOperands(); ++i)
7751 if (C->getOperand(i) != op0) {
7756 return ReplaceInstUsesWith(EI, op0);
7759 // If extracting a specified index from the vector, see if we can recursively
7760 // find a previously computed scalar that was inserted into the vector.
7761 if (ConstantUInt *IdxC = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
7762 // This instruction only demands the single element from the input vector.
7763 // If the input vector has a single use, simplify it based on this use
7765 if (EI.getOperand(0)->hasOneUse()) {
7767 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
7768 1 << IdxC->getValue(),
7770 EI.setOperand(0, V);
7775 if (Value *Elt = FindScalarElement(EI.getOperand(0), IdxC->getValue()))
7776 return ReplaceInstUsesWith(EI, Elt);
7779 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
7780 if (I->hasOneUse()) {
7781 // Push extractelement into predecessor operation if legal and
7782 // profitable to do so
7783 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
7784 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
7785 if (CheapToScalarize(BO, isConstantElt)) {
7786 ExtractElementInst *newEI0 =
7787 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
7788 EI.getName()+".lhs");
7789 ExtractElementInst *newEI1 =
7790 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
7791 EI.getName()+".rhs");
7792 InsertNewInstBefore(newEI0, EI);
7793 InsertNewInstBefore(newEI1, EI);
7794 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
7796 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7797 Value *Ptr = InsertCastBefore(I->getOperand(0),
7798 PointerType::get(EI.getType()), EI);
7799 GetElementPtrInst *GEP =
7800 new GetElementPtrInst(Ptr, EI.getOperand(1),
7801 I->getName() + ".gep");
7802 InsertNewInstBefore(GEP, EI);
7803 return new LoadInst(GEP);
7806 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
7807 // Extracting the inserted element?
7808 if (IE->getOperand(2) == EI.getOperand(1))
7809 return ReplaceInstUsesWith(EI, IE->getOperand(1));
7810 // If the inserted and extracted elements are constants, they must not
7811 // be the same value, extract from the pre-inserted value instead.
7812 if (isa<Constant>(IE->getOperand(2)) &&
7813 isa<Constant>(EI.getOperand(1))) {
7814 AddUsesToWorkList(EI);
7815 EI.setOperand(0, IE->getOperand(0));
7818 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
7819 // If this is extracting an element from a shufflevector, figure out where
7820 // it came from and extract from the appropriate input element instead.
7821 if (ConstantUInt *Elt = dyn_cast<ConstantUInt>(EI.getOperand(1))) {
7822 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getValue()];
7824 if (SrcIdx < SVI->getType()->getNumElements())
7825 Src = SVI->getOperand(0);
7826 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
7827 SrcIdx -= SVI->getType()->getNumElements();
7828 Src = SVI->getOperand(1);
7830 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
7832 return new ExtractElementInst(Src, SrcIdx);
7839 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
7840 /// elements from either LHS or RHS, return the shuffle mask and true.
7841 /// Otherwise, return false.
7842 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
7843 std::vector<Constant*> &Mask) {
7844 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
7845 "Invalid CollectSingleShuffleElements");
7846 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7848 if (isa<UndefValue>(V)) {
7849 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7851 } else if (V == LHS) {
7852 for (unsigned i = 0; i != NumElts; ++i)
7853 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7855 } else if (V == RHS) {
7856 for (unsigned i = 0; i != NumElts; ++i)
7857 Mask.push_back(ConstantUInt::get(Type::UIntTy, i+NumElts));
7859 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7860 // If this is an insert of an extract from some other vector, include it.
7861 Value *VecOp = IEI->getOperand(0);
7862 Value *ScalarOp = IEI->getOperand(1);
7863 Value *IdxOp = IEI->getOperand(2);
7865 if (!isa<ConstantInt>(IdxOp))
7867 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7869 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
7870 // Okay, we can handle this if the vector we are insertinting into is
7872 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7873 // If so, update the mask to reflect the inserted undef.
7874 Mask[InsertedIdx] = UndefValue::get(Type::UIntTy);
7877 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
7878 if (isa<ConstantInt>(EI->getOperand(1)) &&
7879 EI->getOperand(0)->getType() == V->getType()) {
7880 unsigned ExtractedIdx =
7881 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7883 // This must be extracting from either LHS or RHS.
7884 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
7885 // Okay, we can handle this if the vector we are insertinting into is
7887 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
7888 // If so, update the mask to reflect the inserted value.
7889 if (EI->getOperand(0) == LHS) {
7890 Mask[InsertedIdx & (NumElts-1)] =
7891 ConstantUInt::get(Type::UIntTy, ExtractedIdx);
7893 assert(EI->getOperand(0) == RHS);
7894 Mask[InsertedIdx & (NumElts-1)] =
7895 ConstantUInt::get(Type::UIntTy, ExtractedIdx+NumElts);
7904 // TODO: Handle shufflevector here!
7909 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
7910 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
7911 /// that computes V and the LHS value of the shuffle.
7912 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
7914 assert(isa<PackedType>(V->getType()) &&
7915 (RHS == 0 || V->getType() == RHS->getType()) &&
7916 "Invalid shuffle!");
7917 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
7919 if (isa<UndefValue>(V)) {
7920 Mask.assign(NumElts, UndefValue::get(Type::UIntTy));
7922 } else if (isa<ConstantAggregateZero>(V)) {
7923 Mask.assign(NumElts, ConstantUInt::get(Type::UIntTy, 0));
7925 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
7926 // If this is an insert of an extract from some other vector, include it.
7927 Value *VecOp = IEI->getOperand(0);
7928 Value *ScalarOp = IEI->getOperand(1);
7929 Value *IdxOp = IEI->getOperand(2);
7931 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7932 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7933 EI->getOperand(0)->getType() == V->getType()) {
7934 unsigned ExtractedIdx =
7935 cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7936 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7938 // Either the extracted from or inserted into vector must be RHSVec,
7939 // otherwise we'd end up with a shuffle of three inputs.
7940 if (EI->getOperand(0) == RHS || RHS == 0) {
7941 RHS = EI->getOperand(0);
7942 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
7943 Mask[InsertedIdx & (NumElts-1)] =
7944 ConstantUInt::get(Type::UIntTy, NumElts+ExtractedIdx);
7949 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
7950 // Everything but the extracted element is replaced with the RHS.
7951 for (unsigned i = 0; i != NumElts; ++i) {
7952 if (i != InsertedIdx)
7953 Mask[i] = ConstantUInt::get(Type::UIntTy, NumElts+i);
7958 // If this insertelement is a chain that comes from exactly these two
7959 // vectors, return the vector and the effective shuffle.
7960 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
7961 return EI->getOperand(0);
7966 // TODO: Handle shufflevector here!
7968 // Otherwise, can't do anything fancy. Return an identity vector.
7969 for (unsigned i = 0; i != NumElts; ++i)
7970 Mask.push_back(ConstantUInt::get(Type::UIntTy, i));
7974 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
7975 Value *VecOp = IE.getOperand(0);
7976 Value *ScalarOp = IE.getOperand(1);
7977 Value *IdxOp = IE.getOperand(2);
7979 // If the inserted element was extracted from some other vector, and if the
7980 // indexes are constant, try to turn this into a shufflevector operation.
7981 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
7982 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
7983 EI->getOperand(0)->getType() == IE.getType()) {
7984 unsigned NumVectorElts = IE.getType()->getNumElements();
7985 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getRawValue();
7986 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getRawValue();
7988 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
7989 return ReplaceInstUsesWith(IE, VecOp);
7991 if (InsertedIdx >= NumVectorElts) // Out of range insert.
7992 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
7994 // If we are extracting a value from a vector, then inserting it right
7995 // back into the same place, just use the input vector.
7996 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
7997 return ReplaceInstUsesWith(IE, VecOp);
7999 // We could theoretically do this for ANY input. However, doing so could
8000 // turn chains of insertelement instructions into a chain of shufflevector
8001 // instructions, and right now we do not merge shufflevectors. As such,
8002 // only do this in a situation where it is clear that there is benefit.
8003 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8004 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8005 // the values of VecOp, except then one read from EIOp0.
8006 // Build a new shuffle mask.
8007 std::vector<Constant*> Mask;
8008 if (isa<UndefValue>(VecOp))
8009 Mask.assign(NumVectorElts, UndefValue::get(Type::UIntTy));
8011 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
8012 Mask.assign(NumVectorElts, ConstantUInt::get(Type::UIntTy,
8015 Mask[InsertedIdx] = ConstantUInt::get(Type::UIntTy, ExtractedIdx);
8016 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8017 ConstantPacked::get(Mask));
8020 // If this insertelement isn't used by some other insertelement, turn it
8021 // (and any insertelements it points to), into one big shuffle.
8022 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8023 std::vector<Constant*> Mask;
8025 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8026 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8027 // We now have a shuffle of LHS, RHS, Mask.
8028 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
8037 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8038 Value *LHS = SVI.getOperand(0);
8039 Value *RHS = SVI.getOperand(1);
8040 std::vector<unsigned> Mask = getShuffleMask(&SVI);
8042 bool MadeChange = false;
8044 // Undefined shuffle mask -> undefined value.
8045 if (isa<UndefValue>(SVI.getOperand(2)))
8046 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8048 // TODO: If we have shuffle(x, undef, mask) and any elements of mask refer to
8049 // the undef, change them to undefs.
8051 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8052 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8053 if (LHS == RHS || isa<UndefValue>(LHS)) {
8054 if (isa<UndefValue>(LHS) && LHS == RHS) {
8055 // shuffle(undef,undef,mask) -> undef.
8056 return ReplaceInstUsesWith(SVI, LHS);
8059 // Remap any references to RHS to use LHS.
8060 std::vector<Constant*> Elts;
8061 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8063 Elts.push_back(UndefValue::get(Type::UIntTy));
8065 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8066 (Mask[i] < e && isa<UndefValue>(LHS)))
8067 Mask[i] = 2*e; // Turn into undef.
8069 Mask[i] &= (e-1); // Force to LHS.
8070 Elts.push_back(ConstantUInt::get(Type::UIntTy, Mask[i]));
8073 SVI.setOperand(0, SVI.getOperand(1));
8074 SVI.setOperand(1, UndefValue::get(RHS->getType()));
8075 SVI.setOperand(2, ConstantPacked::get(Elts));
8076 LHS = SVI.getOperand(0);
8077 RHS = SVI.getOperand(1);
8081 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
8082 bool isLHSID = true, isRHSID = true;
8084 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8085 if (Mask[i] >= e*2) continue; // Ignore undef values.
8086 // Is this an identity shuffle of the LHS value?
8087 isLHSID &= (Mask[i] == i);
8089 // Is this an identity shuffle of the RHS value?
8090 isRHSID &= (Mask[i]-e == i);
8093 // Eliminate identity shuffles.
8094 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8095 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
8097 // If the LHS is a shufflevector itself, see if we can combine it with this
8098 // one without producing an unusual shuffle. Here we are really conservative:
8099 // we are absolutely afraid of producing a shuffle mask not in the input
8100 // program, because the code gen may not be smart enough to turn a merged
8101 // shuffle into two specific shuffles: it may produce worse code. As such,
8102 // we only merge two shuffles if the result is one of the two input shuffle
8103 // masks. In this case, merging the shuffles just removes one instruction,
8104 // which we know is safe. This is good for things like turning:
8105 // (splat(splat)) -> splat.
8106 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8107 if (isa<UndefValue>(RHS)) {
8108 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8110 std::vector<unsigned> NewMask;
8111 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8113 NewMask.push_back(2*e);
8115 NewMask.push_back(LHSMask[Mask[i]]);
8117 // If the result mask is equal to the src shuffle or this shuffle mask, do
8119 if (NewMask == LHSMask || NewMask == Mask) {
8120 std::vector<Constant*> Elts;
8121 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8122 if (NewMask[i] >= e*2) {
8123 Elts.push_back(UndefValue::get(Type::UIntTy));
8125 Elts.push_back(ConstantUInt::get(Type::UIntTy, NewMask[i]));
8128 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8129 LHSSVI->getOperand(1),
8130 ConstantPacked::get(Elts));
8135 return MadeChange ? &SVI : 0;
8140 void InstCombiner::removeFromWorkList(Instruction *I) {
8141 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
8146 /// TryToSinkInstruction - Try to move the specified instruction from its
8147 /// current block into the beginning of DestBlock, which can only happen if it's
8148 /// safe to move the instruction past all of the instructions between it and the
8149 /// end of its block.
8150 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
8151 assert(I->hasOneUse() && "Invariants didn't hold!");
8153 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
8154 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
8156 // Do not sink alloca instructions out of the entry block.
8157 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
8160 // We can only sink load instructions if there is nothing between the load and
8161 // the end of block that could change the value.
8162 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8163 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
8165 if (Scan->mayWriteToMemory())
8169 BasicBlock::iterator InsertPos = DestBlock->begin();
8170 while (isa<PHINode>(InsertPos)) ++InsertPos;
8172 I->moveBefore(InsertPos);
8177 /// OptimizeConstantExpr - Given a constant expression and target data layout
8178 /// information, symbolically evaluation the constant expr to something simpler
8180 static Constant *OptimizeConstantExpr(ConstantExpr *CE, const TargetData *TD) {
8183 Constant *Ptr = CE->getOperand(0);
8184 if (CE->getOpcode() == Instruction::GetElementPtr && Ptr->isNullValue() &&
8185 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
8186 // If this is a constant expr gep that is effectively computing an
8187 // "offsetof", fold it into 'cast int Size to T*' instead of 'gep 0, 0, 12'
8188 bool isFoldableGEP = true;
8189 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
8190 if (!isa<ConstantInt>(CE->getOperand(i)))
8191 isFoldableGEP = false;
8192 if (isFoldableGEP) {
8193 std::vector<Value*> Ops(CE->op_begin()+1, CE->op_end());
8194 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(), Ops);
8195 Constant *C = ConstantUInt::get(Type::ULongTy, Offset);
8196 C = ConstantExpr::getCast(C, TD->getIntPtrType());
8197 return ConstantExpr::getCast(C, CE->getType());
8205 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
8206 /// all reachable code to the worklist.
8208 /// This has a couple of tricks to make the code faster and more powerful. In
8209 /// particular, we constant fold and DCE instructions as we go, to avoid adding
8210 /// them to the worklist (this significantly speeds up instcombine on code where
8211 /// many instructions are dead or constant). Additionally, if we find a branch
8212 /// whose condition is a known constant, we only visit the reachable successors.
8214 static void AddReachableCodeToWorklist(BasicBlock *BB,
8215 std::set<BasicBlock*> &Visited,
8216 std::vector<Instruction*> &WorkList,
8217 const TargetData *TD) {
8218 // We have now visited this block! If we've already been here, bail out.
8219 if (!Visited.insert(BB).second) return;
8221 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
8222 Instruction *Inst = BBI++;
8224 // DCE instruction if trivially dead.
8225 if (isInstructionTriviallyDead(Inst)) {
8227 DEBUG(std::cerr << "IC: DCE: " << *Inst);
8228 Inst->eraseFromParent();
8232 // ConstantProp instruction if trivially constant.
8233 if (Constant *C = ConstantFoldInstruction(Inst)) {
8234 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8235 C = OptimizeConstantExpr(CE, TD);
8236 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *Inst);
8237 Inst->replaceAllUsesWith(C);
8239 Inst->eraseFromParent();
8243 WorkList.push_back(Inst);
8246 // Recursively visit successors. If this is a branch or switch on a constant,
8247 // only visit the reachable successor.
8248 TerminatorInst *TI = BB->getTerminator();
8249 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
8250 if (BI->isConditional() && isa<ConstantBool>(BI->getCondition())) {
8251 bool CondVal = cast<ConstantBool>(BI->getCondition())->getValue();
8252 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
8256 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
8257 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
8258 // See if this is an explicit destination.
8259 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
8260 if (SI->getCaseValue(i) == Cond) {
8261 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
8265 // Otherwise it is the default destination.
8266 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
8271 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
8272 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
8275 bool InstCombiner::runOnFunction(Function &F) {
8276 bool Changed = false;
8277 TD = &getAnalysis<TargetData>();
8280 // Do a depth-first traversal of the function, populate the worklist with
8281 // the reachable instructions. Ignore blocks that are not reachable. Keep
8282 // track of which blocks we visit.
8283 std::set<BasicBlock*> Visited;
8284 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
8286 // Do a quick scan over the function. If we find any blocks that are
8287 // unreachable, remove any instructions inside of them. This prevents
8288 // the instcombine code from having to deal with some bad special cases.
8289 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
8290 if (!Visited.count(BB)) {
8291 Instruction *Term = BB->getTerminator();
8292 while (Term != BB->begin()) { // Remove instrs bottom-up
8293 BasicBlock::iterator I = Term; --I;
8295 DEBUG(std::cerr << "IC: DCE: " << *I);
8298 if (!I->use_empty())
8299 I->replaceAllUsesWith(UndefValue::get(I->getType()));
8300 I->eraseFromParent();
8305 while (!WorkList.empty()) {
8306 Instruction *I = WorkList.back(); // Get an instruction from the worklist
8307 WorkList.pop_back();
8309 // Check to see if we can DCE the instruction.
8310 if (isInstructionTriviallyDead(I)) {
8311 // Add operands to the worklist.
8312 if (I->getNumOperands() < 4)
8313 AddUsesToWorkList(*I);
8316 DEBUG(std::cerr << "IC: DCE: " << *I);
8318 I->eraseFromParent();
8319 removeFromWorkList(I);
8323 // Instruction isn't dead, see if we can constant propagate it.
8324 if (Constant *C = ConstantFoldInstruction(I)) {
8325 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
8326 C = OptimizeConstantExpr(CE, TD);
8327 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
8329 // Add operands to the worklist.
8330 AddUsesToWorkList(*I);
8331 ReplaceInstUsesWith(*I, C);
8334 I->eraseFromParent();
8335 removeFromWorkList(I);
8339 // See if we can trivially sink this instruction to a successor basic block.
8340 if (I->hasOneUse()) {
8341 BasicBlock *BB = I->getParent();
8342 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
8343 if (UserParent != BB) {
8344 bool UserIsSuccessor = false;
8345 // See if the user is one of our successors.
8346 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
8347 if (*SI == UserParent) {
8348 UserIsSuccessor = true;
8352 // If the user is one of our immediate successors, and if that successor
8353 // only has us as a predecessors (we'd have to split the critical edge
8354 // otherwise), we can keep going.
8355 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
8356 next(pred_begin(UserParent)) == pred_end(UserParent))
8357 // Okay, the CFG is simple enough, try to sink this instruction.
8358 Changed |= TryToSinkInstruction(I, UserParent);
8362 // Now that we have an instruction, try combining it to simplify it...
8363 if (Instruction *Result = visit(*I)) {
8365 // Should we replace the old instruction with a new one?
8367 DEBUG(std::cerr << "IC: Old = " << *I
8368 << " New = " << *Result);
8370 // Everything uses the new instruction now.
8371 I->replaceAllUsesWith(Result);
8373 // Push the new instruction and any users onto the worklist.
8374 WorkList.push_back(Result);
8375 AddUsersToWorkList(*Result);
8377 // Move the name to the new instruction first...
8378 std::string OldName = I->getName(); I->setName("");
8379 Result->setName(OldName);
8381 // Insert the new instruction into the basic block...
8382 BasicBlock *InstParent = I->getParent();
8383 BasicBlock::iterator InsertPos = I;
8385 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
8386 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
8389 InstParent->getInstList().insert(InsertPos, Result);
8391 // Make sure that we reprocess all operands now that we reduced their
8393 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8394 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8395 WorkList.push_back(OpI);
8397 // Instructions can end up on the worklist more than once. Make sure
8398 // we do not process an instruction that has been deleted.
8399 removeFromWorkList(I);
8401 // Erase the old instruction.
8402 InstParent->getInstList().erase(I);
8404 DEBUG(std::cerr << "IC: MOD = " << *I);
8406 // If the instruction was modified, it's possible that it is now dead.
8407 // if so, remove it.
8408 if (isInstructionTriviallyDead(I)) {
8409 // Make sure we process all operands now that we are reducing their
8411 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
8412 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
8413 WorkList.push_back(OpI);
8415 // Instructions may end up in the worklist more than once. Erase all
8416 // occurrences of this instruction.
8417 removeFromWorkList(I);
8418 I->eraseFromParent();
8420 WorkList.push_back(Result);
8421 AddUsersToWorkList(*Result);
8431 FunctionPass *llvm::createInstructionCombiningPass() {
8432 return new InstCombiner();