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. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All cmp 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/Analysis/ConstantFolding.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/Local.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/Debug.h"
48 #include "llvm/Support/GetElementPtrTypeIterator.h"
49 #include "llvm/Support/InstVisitor.h"
50 #include "llvm/Support/MathExtras.h"
51 #include "llvm/Support/PatternMatch.h"
52 #include "llvm/Support/Compiler.h"
53 #include "llvm/ADT/SmallVector.h"
54 #include "llvm/ADT/Statistic.h"
55 #include "llvm/ADT/STLExtras.h"
58 using namespace llvm::PatternMatch;
60 STATISTIC(NumCombined , "Number of insts combined");
61 STATISTIC(NumConstProp, "Number of constant folds");
62 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
63 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
64 STATISTIC(NumSunkInst , "Number of instructions sunk");
67 class VISIBILITY_HIDDEN InstCombiner
68 : public FunctionPass,
69 public InstVisitor<InstCombiner, Instruction*> {
70 // Worklist of all of the instructions that need to be simplified.
71 std::vector<Instruction*> WorkList;
74 /// AddUsersToWorkList - When an instruction is simplified, add all users of
75 /// the instruction to the work lists because they might get more simplified
78 void AddUsersToWorkList(Value &I) {
79 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
81 WorkList.push_back(cast<Instruction>(*UI));
84 /// AddUsesToWorkList - When an instruction is simplified, add operands to
85 /// the work lists because they might get more simplified now.
87 void AddUsesToWorkList(Instruction &I) {
88 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
89 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
90 WorkList.push_back(Op);
93 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
94 /// dead. Add all of its operands to the worklist, turning them into
95 /// undef's to reduce the number of uses of those instructions.
97 /// Return the specified operand before it is turned into an undef.
99 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
100 Value *R = I.getOperand(op);
102 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
103 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
104 WorkList.push_back(Op);
105 // Set the operand to undef to drop the use.
106 I.setOperand(i, UndefValue::get(Op->getType()));
112 // removeFromWorkList - remove all instances of I from the worklist.
113 void removeFromWorkList(Instruction *I);
115 virtual bool runOnFunction(Function &F);
117 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
118 AU.addRequired<TargetData>();
119 AU.addPreservedID(LCSSAID);
120 AU.setPreservesCFG();
123 TargetData &getTargetData() const { return *TD; }
125 // Visitation implementation - Implement instruction combining for different
126 // instruction types. The semantics are as follows:
128 // null - No change was made
129 // I - Change was made, I is still valid, I may be dead though
130 // otherwise - Change was made, replace I with returned instruction
132 Instruction *visitAdd(BinaryOperator &I);
133 Instruction *visitSub(BinaryOperator &I);
134 Instruction *visitMul(BinaryOperator &I);
135 Instruction *visitURem(BinaryOperator &I);
136 Instruction *visitSRem(BinaryOperator &I);
137 Instruction *visitFRem(BinaryOperator &I);
138 Instruction *commonRemTransforms(BinaryOperator &I);
139 Instruction *commonIRemTransforms(BinaryOperator &I);
140 Instruction *commonDivTransforms(BinaryOperator &I);
141 Instruction *commonIDivTransforms(BinaryOperator &I);
142 Instruction *visitUDiv(BinaryOperator &I);
143 Instruction *visitSDiv(BinaryOperator &I);
144 Instruction *visitFDiv(BinaryOperator &I);
145 Instruction *visitAnd(BinaryOperator &I);
146 Instruction *visitOr (BinaryOperator &I);
147 Instruction *visitXor(BinaryOperator &I);
148 Instruction *visitFCmpInst(FCmpInst &I);
149 Instruction *visitICmpInst(ICmpInst &I);
150 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
152 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
153 ICmpInst::Predicate Cond, Instruction &I);
154 Instruction *visitShiftInst(ShiftInst &I);
155 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
157 Instruction *commonCastTransforms(CastInst &CI);
158 Instruction *commonIntCastTransforms(CastInst &CI);
159 Instruction *visitTrunc(CastInst &CI);
160 Instruction *visitZExt(CastInst &CI);
161 Instruction *visitSExt(CastInst &CI);
162 Instruction *visitFPTrunc(CastInst &CI);
163 Instruction *visitFPExt(CastInst &CI);
164 Instruction *visitFPToUI(CastInst &CI);
165 Instruction *visitFPToSI(CastInst &CI);
166 Instruction *visitUIToFP(CastInst &CI);
167 Instruction *visitSIToFP(CastInst &CI);
168 Instruction *visitPtrToInt(CastInst &CI);
169 Instruction *visitIntToPtr(CastInst &CI);
170 Instruction *visitBitCast(CastInst &CI);
171 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
173 Instruction *visitSelectInst(SelectInst &CI);
174 Instruction *visitCallInst(CallInst &CI);
175 Instruction *visitInvokeInst(InvokeInst &II);
176 Instruction *visitPHINode(PHINode &PN);
177 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
178 Instruction *visitAllocationInst(AllocationInst &AI);
179 Instruction *visitFreeInst(FreeInst &FI);
180 Instruction *visitLoadInst(LoadInst &LI);
181 Instruction *visitStoreInst(StoreInst &SI);
182 Instruction *visitBranchInst(BranchInst &BI);
183 Instruction *visitSwitchInst(SwitchInst &SI);
184 Instruction *visitInsertElementInst(InsertElementInst &IE);
185 Instruction *visitExtractElementInst(ExtractElementInst &EI);
186 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
188 // visitInstruction - Specify what to return for unhandled instructions...
189 Instruction *visitInstruction(Instruction &I) { return 0; }
192 Instruction *visitCallSite(CallSite CS);
193 bool transformConstExprCastCall(CallSite CS);
196 // InsertNewInstBefore - insert an instruction New before instruction Old
197 // in the program. Add the new instruction to the worklist.
199 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
200 assert(New && New->getParent() == 0 &&
201 "New instruction already inserted into a basic block!");
202 BasicBlock *BB = Old.getParent();
203 BB->getInstList().insert(&Old, New); // Insert inst
204 WorkList.push_back(New); // Add to worklist
208 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
209 /// This also adds the cast to the worklist. Finally, this returns the
211 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
213 if (V->getType() == Ty) return V;
215 if (Constant *CV = dyn_cast<Constant>(V))
216 return ConstantExpr::getCast(opc, CV, Ty);
218 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
219 WorkList.push_back(C);
223 // ReplaceInstUsesWith - This method is to be used when an instruction is
224 // found to be dead, replacable with another preexisting expression. Here
225 // we add all uses of I to the worklist, replace all uses of I with the new
226 // value, then return I, so that the inst combiner will know that I was
229 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
230 AddUsersToWorkList(I); // Add all modified instrs to worklist
232 I.replaceAllUsesWith(V);
235 // If we are replacing the instruction with itself, this must be in a
236 // segment of unreachable code, so just clobber the instruction.
237 I.replaceAllUsesWith(UndefValue::get(I.getType()));
242 // UpdateValueUsesWith - This method is to be used when an value is
243 // found to be replacable with another preexisting expression or was
244 // updated. Here we add all uses of I to the worklist, replace all uses of
245 // I with the new value (unless the instruction was just updated), then
246 // return true, so that the inst combiner will know that I was modified.
248 bool UpdateValueUsesWith(Value *Old, Value *New) {
249 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
251 Old->replaceAllUsesWith(New);
252 if (Instruction *I = dyn_cast<Instruction>(Old))
253 WorkList.push_back(I);
254 if (Instruction *I = dyn_cast<Instruction>(New))
255 WorkList.push_back(I);
259 // EraseInstFromFunction - When dealing with an instruction that has side
260 // effects or produces a void value, we can't rely on DCE to delete the
261 // instruction. Instead, visit methods should return the value returned by
263 Instruction *EraseInstFromFunction(Instruction &I) {
264 assert(I.use_empty() && "Cannot erase instruction that is used!");
265 AddUsesToWorkList(I);
266 removeFromWorkList(&I);
268 return 0; // Don't do anything with FI
272 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
273 /// InsertBefore instruction. This is specialized a bit to avoid inserting
274 /// casts that are known to not do anything...
276 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
277 Value *V, const Type *DestTy,
278 Instruction *InsertBefore);
280 /// SimplifyCommutative - This performs a few simplifications for
281 /// commutative operators.
282 bool SimplifyCommutative(BinaryOperator &I);
284 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
285 /// most-complex to least-complex order.
286 bool SimplifyCompare(CmpInst &I);
288 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
289 uint64_t &KnownZero, uint64_t &KnownOne,
292 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
293 uint64_t &UndefElts, unsigned Depth = 0);
295 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
296 // PHI node as operand #0, see if we can fold the instruction into the PHI
297 // (which is only possible if all operands to the PHI are constants).
298 Instruction *FoldOpIntoPhi(Instruction &I);
300 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
301 // operator and they all are only used by the PHI, PHI together their
302 // inputs, and do the operation once, to the result of the PHI.
303 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
304 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
307 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
308 ConstantInt *AndRHS, BinaryOperator &TheAnd);
310 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
311 bool isSub, Instruction &I);
312 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
313 bool isSigned, bool Inside, Instruction &IB);
314 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
315 Instruction *MatchBSwap(BinaryOperator &I);
317 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
320 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
323 // getComplexity: Assign a complexity or rank value to LLVM Values...
324 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
325 static unsigned getComplexity(Value *V) {
326 if (isa<Instruction>(V)) {
327 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
331 if (isa<Argument>(V)) return 3;
332 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
335 // isOnlyUse - Return true if this instruction will be deleted if we stop using
337 static bool isOnlyUse(Value *V) {
338 return V->hasOneUse() || isa<Constant>(V);
341 // getPromotedType - Return the specified type promoted as it would be to pass
342 // though a va_arg area...
343 static const Type *getPromotedType(const Type *Ty) {
344 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
345 if (ITy->getBitWidth() < 32)
346 return Type::Int32Ty;
347 } else if (Ty == Type::FloatTy)
348 return Type::DoubleTy;
352 /// getBitCastOperand - If the specified operand is a CastInst or a constant
353 /// expression bitcast, return the operand value, otherwise return null.
354 static Value *getBitCastOperand(Value *V) {
355 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
356 return I->getOperand(0);
357 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
358 if (CE->getOpcode() == Instruction::BitCast)
359 return CE->getOperand(0);
363 /// This function is a wrapper around CastInst::isEliminableCastPair. It
364 /// simply extracts arguments and returns what that function returns.
365 /// @Determine if it is valid to eliminate a Convert pair
366 static Instruction::CastOps
367 isEliminableCastPair(
368 const CastInst *CI, ///< The first cast instruction
369 unsigned opcode, ///< The opcode of the second cast instruction
370 const Type *DstTy, ///< The target type for the second cast instruction
371 TargetData *TD ///< The target data for pointer size
374 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
375 const Type *MidTy = CI->getType(); // B from above
377 // Get the opcodes of the two Cast instructions
378 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
379 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
381 return Instruction::CastOps(
382 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
383 DstTy, TD->getIntPtrType()));
386 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
387 /// in any code being generated. It does not require codegen if V is simple
388 /// enough or if the cast can be folded into other casts.
389 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
390 const Type *Ty, TargetData *TD) {
391 if (V->getType() == Ty || isa<Constant>(V)) return false;
393 // If this is another cast that can be eliminated, it isn't codegen either.
394 if (const CastInst *CI = dyn_cast<CastInst>(V))
395 if (isEliminableCastPair(CI, opcode, Ty, TD))
400 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
401 /// InsertBefore instruction. This is specialized a bit to avoid inserting
402 /// casts that are known to not do anything...
404 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
405 Value *V, const Type *DestTy,
406 Instruction *InsertBefore) {
407 if (V->getType() == DestTy) return V;
408 if (Constant *C = dyn_cast<Constant>(V))
409 return ConstantExpr::getCast(opcode, C, DestTy);
411 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
414 // SimplifyCommutative - This performs a few simplifications for commutative
417 // 1. Order operands such that they are listed from right (least complex) to
418 // left (most complex). This puts constants before unary operators before
421 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
422 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
424 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
425 bool Changed = false;
426 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
427 Changed = !I.swapOperands();
429 if (!I.isAssociative()) return Changed;
430 Instruction::BinaryOps Opcode = I.getOpcode();
431 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
432 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
433 if (isa<Constant>(I.getOperand(1))) {
434 Constant *Folded = ConstantExpr::get(I.getOpcode(),
435 cast<Constant>(I.getOperand(1)),
436 cast<Constant>(Op->getOperand(1)));
437 I.setOperand(0, Op->getOperand(0));
438 I.setOperand(1, Folded);
440 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
441 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
442 isOnlyUse(Op) && isOnlyUse(Op1)) {
443 Constant *C1 = cast<Constant>(Op->getOperand(1));
444 Constant *C2 = cast<Constant>(Op1->getOperand(1));
446 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
447 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
448 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
451 WorkList.push_back(New);
452 I.setOperand(0, New);
453 I.setOperand(1, Folded);
460 /// SimplifyCompare - For a CmpInst this function just orders the operands
461 /// so that theyare listed from right (least complex) to left (most complex).
462 /// This puts constants before unary operators before binary operators.
463 bool InstCombiner::SimplifyCompare(CmpInst &I) {
464 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
467 // Compare instructions are not associative so there's nothing else we can do.
471 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
472 // if the LHS is a constant zero (which is the 'negate' form).
474 static inline Value *dyn_castNegVal(Value *V) {
475 if (BinaryOperator::isNeg(V))
476 return BinaryOperator::getNegArgument(V);
478 // Constants can be considered to be negated values if they can be folded.
479 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
480 return ConstantExpr::getNeg(C);
484 static inline Value *dyn_castNotVal(Value *V) {
485 if (BinaryOperator::isNot(V))
486 return BinaryOperator::getNotArgument(V);
488 // Constants can be considered to be not'ed values...
489 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
490 return ConstantExpr::getNot(C);
494 // dyn_castFoldableMul - If this value is a multiply that can be folded into
495 // other computations (because it has a constant operand), return the
496 // non-constant operand of the multiply, and set CST to point to the multiplier.
497 // Otherwise, return null.
499 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
500 if (V->hasOneUse() && V->getType()->isInteger())
501 if (Instruction *I = dyn_cast<Instruction>(V)) {
502 if (I->getOpcode() == Instruction::Mul)
503 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
504 return I->getOperand(0);
505 if (I->getOpcode() == Instruction::Shl)
506 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
507 // The multiplier is really 1 << CST.
508 Constant *One = ConstantInt::get(V->getType(), 1);
509 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
510 return I->getOperand(0);
516 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
517 /// expression, return it.
518 static User *dyn_castGetElementPtr(Value *V) {
519 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
520 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
521 if (CE->getOpcode() == Instruction::GetElementPtr)
522 return cast<User>(V);
526 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
527 static ConstantInt *AddOne(ConstantInt *C) {
528 return cast<ConstantInt>(ConstantExpr::getAdd(C,
529 ConstantInt::get(C->getType(), 1)));
531 static ConstantInt *SubOne(ConstantInt *C) {
532 return cast<ConstantInt>(ConstantExpr::getSub(C,
533 ConstantInt::get(C->getType(), 1)));
536 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
537 /// known to be either zero or one and return them in the KnownZero/KnownOne
538 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
540 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
541 uint64_t &KnownOne, unsigned Depth = 0) {
542 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
543 // we cannot optimize based on the assumption that it is zero without changing
544 // it to be an explicit zero. If we don't change it to zero, other code could
545 // optimized based on the contradictory assumption that it is non-zero.
546 // Because instcombine aggressively folds operations with undef args anyway,
547 // this won't lose us code quality.
548 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
549 // We know all of the bits for a constant!
550 KnownOne = CI->getZExtValue() & Mask;
551 KnownZero = ~KnownOne & Mask;
555 KnownZero = KnownOne = 0; // Don't know anything.
556 if (Depth == 6 || Mask == 0)
557 return; // Limit search depth.
559 uint64_t KnownZero2, KnownOne2;
560 Instruction *I = dyn_cast<Instruction>(V);
563 Mask &= cast<IntegerType>(V->getType())->getBitMask();
565 switch (I->getOpcode()) {
566 case Instruction::And:
567 // If either the LHS or the RHS are Zero, the result is zero.
568 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
570 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
571 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
572 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
574 // Output known-1 bits are only known if set in both the LHS & RHS.
575 KnownOne &= KnownOne2;
576 // Output known-0 are known to be clear if zero in either the LHS | RHS.
577 KnownZero |= KnownZero2;
579 case Instruction::Or:
580 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
582 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
583 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
584 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
586 // Output known-0 bits are only known if clear in both the LHS & RHS.
587 KnownZero &= KnownZero2;
588 // Output known-1 are known to be set if set in either the LHS | RHS.
589 KnownOne |= KnownOne2;
591 case Instruction::Xor: {
592 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
593 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
594 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
595 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
597 // Output known-0 bits are known if clear or set in both the LHS & RHS.
598 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
599 // Output known-1 are known to be set if set in only one of the LHS, RHS.
600 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
601 KnownZero = KnownZeroOut;
604 case Instruction::Select:
605 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
606 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
607 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
608 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
610 // Only known if known in both the LHS and RHS.
611 KnownOne &= KnownOne2;
612 KnownZero &= KnownZero2;
614 case Instruction::FPTrunc:
615 case Instruction::FPExt:
616 case Instruction::FPToUI:
617 case Instruction::FPToSI:
618 case Instruction::SIToFP:
619 case Instruction::PtrToInt:
620 case Instruction::UIToFP:
621 case Instruction::IntToPtr:
622 return; // Can't work with floating point or pointers
623 case Instruction::Trunc:
624 // All these have integer operands
625 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
627 case Instruction::BitCast: {
628 const Type *SrcTy = I->getOperand(0)->getType();
629 if (SrcTy->isInteger()) {
630 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
635 case Instruction::ZExt: {
636 // Compute the bits in the result that are not present in the input.
637 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
638 uint64_t NotIn = ~SrcTy->getBitMask();
639 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
641 Mask &= SrcTy->getBitMask();
642 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
643 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
644 // The top bits are known to be zero.
645 KnownZero |= NewBits;
648 case Instruction::SExt: {
649 // Compute the bits in the result that are not present in the input.
650 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
651 uint64_t NotIn = ~SrcTy->getBitMask();
652 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
654 Mask &= SrcTy->getBitMask();
655 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
656 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
658 // If the sign bit of the input is known set or clear, then we know the
659 // top bits of the result.
660 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
661 if (KnownZero & InSignBit) { // Input sign bit known zero
662 KnownZero |= NewBits;
663 KnownOne &= ~NewBits;
664 } else if (KnownOne & InSignBit) { // Input sign bit known set
666 KnownZero &= ~NewBits;
667 } else { // Input sign bit unknown
668 KnownZero &= ~NewBits;
669 KnownOne &= ~NewBits;
673 case Instruction::Shl:
674 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
675 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
676 uint64_t ShiftAmt = SA->getZExtValue();
678 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
679 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
680 KnownZero <<= ShiftAmt;
681 KnownOne <<= ShiftAmt;
682 KnownZero |= (1ULL << ShiftAmt)-1; // low bits known zero.
686 case Instruction::LShr:
687 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
688 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
689 // Compute the new bits that are at the top now.
690 uint64_t ShiftAmt = SA->getZExtValue();
691 uint64_t HighBits = (1ULL << ShiftAmt)-1;
692 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
694 // Unsigned shift right.
696 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
697 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
698 KnownZero >>= ShiftAmt;
699 KnownOne >>= ShiftAmt;
700 KnownZero |= HighBits; // high bits known zero.
704 case Instruction::AShr:
705 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
706 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
707 // Compute the new bits that are at the top now.
708 uint64_t ShiftAmt = SA->getZExtValue();
709 uint64_t HighBits = (1ULL << ShiftAmt)-1;
710 HighBits <<= I->getType()->getPrimitiveSizeInBits()-ShiftAmt;
712 // Signed shift right.
714 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
715 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
716 KnownZero >>= ShiftAmt;
717 KnownOne >>= ShiftAmt;
719 // Handle the sign bits.
720 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
721 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
723 if (KnownZero & SignBit) { // New bits are known zero.
724 KnownZero |= HighBits;
725 } else if (KnownOne & SignBit) { // New bits are known one.
726 KnownOne |= HighBits;
734 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
735 /// this predicate to simplify operations downstream. Mask is known to be zero
736 /// for bits that V cannot have.
737 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
738 uint64_t KnownZero, KnownOne;
739 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
740 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
741 return (KnownZero & Mask) == Mask;
744 /// ShrinkDemandedConstant - Check to see if the specified operand of the
745 /// specified instruction is a constant integer. If so, check to see if there
746 /// are any bits set in the constant that are not demanded. If so, shrink the
747 /// constant and return true.
748 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
750 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
751 if (!OpC) return false;
753 // If there are no bits set that aren't demanded, nothing to do.
754 if ((~Demanded & OpC->getZExtValue()) == 0)
757 // This is producing any bits that are not needed, shrink the RHS.
758 uint64_t Val = Demanded & OpC->getZExtValue();
759 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Val));
763 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
764 // set of known zero and one bits, compute the maximum and minimum values that
765 // could have the specified known zero and known one bits, returning them in
767 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
770 int64_t &Min, int64_t &Max) {
771 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
772 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
774 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
776 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
777 // bit if it is unknown.
779 Max = KnownOne|UnknownBits;
781 if (SignBit & UnknownBits) { // Sign bit is unknown
786 // Sign extend the min/max values.
787 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
788 Min = (Min << ShAmt) >> ShAmt;
789 Max = (Max << ShAmt) >> ShAmt;
792 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
793 // a set of known zero and one bits, compute the maximum and minimum values that
794 // could have the specified known zero and known one bits, returning them in
796 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
801 uint64_t TypeBits = cast<IntegerType>(Ty)->getBitMask();
802 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
804 // The minimum value is when the unknown bits are all zeros.
806 // The maximum value is when the unknown bits are all ones.
807 Max = KnownOne|UnknownBits;
811 /// SimplifyDemandedBits - Look at V. At this point, we know that only the
812 /// DemandedMask bits of the result of V are ever used downstream. If we can
813 /// use this information to simplify V, do so and return true. Otherwise,
814 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
815 /// the expression (used to simplify the caller). The KnownZero/One bits may
816 /// only be accurate for those bits in the DemandedMask.
817 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
818 uint64_t &KnownZero, uint64_t &KnownOne,
820 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
821 // We know all of the bits for a constant!
822 KnownOne = CI->getZExtValue() & DemandedMask;
823 KnownZero = ~KnownOne & DemandedMask;
827 KnownZero = KnownOne = 0;
828 if (!V->hasOneUse()) { // Other users may use these bits.
829 if (Depth != 0) { // Not at the root.
830 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
831 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
834 // If this is the root being simplified, allow it to have multiple uses,
835 // just set the DemandedMask to all bits.
836 DemandedMask = cast<IntegerType>(V->getType())->getBitMask();
837 } else if (DemandedMask == 0) { // Not demanding any bits from V.
838 if (V != UndefValue::get(V->getType()))
839 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
841 } else if (Depth == 6) { // Limit search depth.
845 Instruction *I = dyn_cast<Instruction>(V);
846 if (!I) return false; // Only analyze instructions.
848 DemandedMask &= cast<IntegerType>(V->getType())->getBitMask();
850 uint64_t KnownZero2 = 0, KnownOne2 = 0;
851 switch (I->getOpcode()) {
853 case Instruction::And:
854 // If either the LHS or the RHS are Zero, the result is zero.
855 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
856 KnownZero, KnownOne, Depth+1))
858 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
860 // If something is known zero on the RHS, the bits aren't demanded on the
862 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
863 KnownZero2, KnownOne2, Depth+1))
865 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
867 // If all of the demanded bits are known 1 on one side, return the other.
868 // These bits cannot contribute to the result of the 'and'.
869 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
870 return UpdateValueUsesWith(I, I->getOperand(0));
871 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
872 return UpdateValueUsesWith(I, I->getOperand(1));
874 // If all of the demanded bits in the inputs are known zeros, return zero.
875 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
876 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
878 // If the RHS is a constant, see if we can simplify it.
879 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
880 return UpdateValueUsesWith(I, I);
882 // Output known-1 bits are only known if set in both the LHS & RHS.
883 KnownOne &= KnownOne2;
884 // Output known-0 are known to be clear if zero in either the LHS | RHS.
885 KnownZero |= KnownZero2;
887 case Instruction::Or:
888 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
889 KnownZero, KnownOne, Depth+1))
891 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
892 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
893 KnownZero2, KnownOne2, Depth+1))
895 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
897 // If all of the demanded bits are known zero on one side, return the other.
898 // These bits cannot contribute to the result of the 'or'.
899 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
900 return UpdateValueUsesWith(I, I->getOperand(0));
901 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
902 return UpdateValueUsesWith(I, I->getOperand(1));
904 // If all of the potentially set bits on one side are known to be set on
905 // the other side, just use the 'other' side.
906 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
907 (DemandedMask & (~KnownZero)))
908 return UpdateValueUsesWith(I, I->getOperand(0));
909 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
910 (DemandedMask & (~KnownZero2)))
911 return UpdateValueUsesWith(I, I->getOperand(1));
913 // If the RHS is a constant, see if we can simplify it.
914 if (ShrinkDemandedConstant(I, 1, DemandedMask))
915 return UpdateValueUsesWith(I, I);
917 // Output known-0 bits are only known if clear in both the LHS & RHS.
918 KnownZero &= KnownZero2;
919 // Output known-1 are known to be set if set in either the LHS | RHS.
920 KnownOne |= KnownOne2;
922 case Instruction::Xor: {
923 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
924 KnownZero, KnownOne, Depth+1))
926 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
927 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
928 KnownZero2, KnownOne2, Depth+1))
930 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
932 // If all of the demanded bits are known zero on one side, return the other.
933 // These bits cannot contribute to the result of the 'xor'.
934 if ((DemandedMask & KnownZero) == DemandedMask)
935 return UpdateValueUsesWith(I, I->getOperand(0));
936 if ((DemandedMask & KnownZero2) == DemandedMask)
937 return UpdateValueUsesWith(I, I->getOperand(1));
939 // Output known-0 bits are known if clear or set in both the LHS & RHS.
940 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
941 // Output known-1 are known to be set if set in only one of the LHS, RHS.
942 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
944 // If all of the demanded bits are known to be zero on one side or the
945 // other, turn this into an *inclusive* or.
946 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
947 if ((DemandedMask & ~KnownZero & ~KnownZero2) == 0) {
949 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
951 InsertNewInstBefore(Or, *I);
952 return UpdateValueUsesWith(I, Or);
955 // If all of the demanded bits on one side are known, and all of the set
956 // bits on that side are also known to be set on the other side, turn this
957 // into an AND, as we know the bits will be cleared.
958 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
959 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
960 if ((KnownOne & KnownOne2) == KnownOne) {
961 Constant *AndC = ConstantInt::get(I->getType(),
962 ~KnownOne & DemandedMask);
964 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
965 InsertNewInstBefore(And, *I);
966 return UpdateValueUsesWith(I, And);
970 // If the RHS is a constant, see if we can simplify it.
971 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
972 if (ShrinkDemandedConstant(I, 1, DemandedMask))
973 return UpdateValueUsesWith(I, I);
975 KnownZero = KnownZeroOut;
976 KnownOne = KnownOneOut;
979 case Instruction::Select:
980 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
981 KnownZero, KnownOne, Depth+1))
983 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
984 KnownZero2, KnownOne2, Depth+1))
986 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
987 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
989 // If the operands are constants, see if we can simplify them.
990 if (ShrinkDemandedConstant(I, 1, DemandedMask))
991 return UpdateValueUsesWith(I, I);
992 if (ShrinkDemandedConstant(I, 2, DemandedMask))
993 return UpdateValueUsesWith(I, I);
995 // Only known if known in both the LHS and RHS.
996 KnownOne &= KnownOne2;
997 KnownZero &= KnownZero2;
999 case Instruction::Trunc:
1000 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1001 KnownZero, KnownOne, Depth+1))
1003 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1005 case Instruction::BitCast:
1006 if (!I->getOperand(0)->getType()->isInteger())
1009 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1010 KnownZero, KnownOne, Depth+1))
1012 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1014 case Instruction::ZExt: {
1015 // Compute the bits in the result that are not present in the input.
1016 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1017 uint64_t NotIn = ~SrcTy->getBitMask();
1018 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
1020 DemandedMask &= SrcTy->getBitMask();
1021 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1022 KnownZero, KnownOne, Depth+1))
1024 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1025 // The top bits are known to be zero.
1026 KnownZero |= NewBits;
1029 case Instruction::SExt: {
1030 // Compute the bits in the result that are not present in the input.
1031 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1032 uint64_t NotIn = ~SrcTy->getBitMask();
1033 uint64_t NewBits = cast<IntegerType>(I->getType())->getBitMask() & NotIn;
1035 // Get the sign bit for the source type
1036 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
1037 int64_t InputDemandedBits = DemandedMask & SrcTy->getBitMask();
1039 // If any of the sign extended bits are demanded, we know that the sign
1041 if (NewBits & DemandedMask)
1042 InputDemandedBits |= InSignBit;
1044 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1045 KnownZero, KnownOne, Depth+1))
1047 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1049 // If the sign bit of the input is known set or clear, then we know the
1050 // top bits of the result.
1052 // If the input sign bit is known zero, or if the NewBits are not demanded
1053 // convert this into a zero extension.
1054 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
1055 // Convert to ZExt cast
1056 CastInst *NewCast = CastInst::create(
1057 Instruction::ZExt, I->getOperand(0), I->getType(), I->getName(), I);
1058 return UpdateValueUsesWith(I, NewCast);
1059 } else if (KnownOne & InSignBit) { // Input sign bit known set
1060 KnownOne |= NewBits;
1061 KnownZero &= ~NewBits;
1062 } else { // Input sign bit unknown
1063 KnownZero &= ~NewBits;
1064 KnownOne &= ~NewBits;
1068 case Instruction::Add:
1069 // If there is a constant on the RHS, there are a variety of xformations
1071 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1072 // If null, this should be simplified elsewhere. Some of the xforms here
1073 // won't work if the RHS is zero.
1074 if (RHS->isNullValue())
1077 // Figure out what the input bits are. If the top bits of the and result
1078 // are not demanded, then the add doesn't demand them from its input
1081 // Shift the demanded mask up so that it's at the top of the uint64_t.
1082 unsigned BitWidth = I->getType()->getPrimitiveSizeInBits();
1083 unsigned NLZ = CountLeadingZeros_64(DemandedMask << (64-BitWidth));
1085 // If the top bit of the output is demanded, demand everything from the
1086 // input. Otherwise, we demand all the input bits except NLZ top bits.
1087 uint64_t InDemandedBits = ~0ULL >> (64-BitWidth+NLZ);
1089 // Find information about known zero/one bits in the input.
1090 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1091 KnownZero2, KnownOne2, Depth+1))
1094 // If the RHS of the add has bits set that can't affect the input, reduce
1096 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1097 return UpdateValueUsesWith(I, I);
1099 // Avoid excess work.
1100 if (KnownZero2 == 0 && KnownOne2 == 0)
1103 // Turn it into OR if input bits are zero.
1104 if ((KnownZero2 & RHS->getZExtValue()) == RHS->getZExtValue()) {
1106 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1108 InsertNewInstBefore(Or, *I);
1109 return UpdateValueUsesWith(I, Or);
1112 // We can say something about the output known-zero and known-one bits,
1113 // depending on potential carries from the input constant and the
1114 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1115 // bits set and the RHS constant is 0x01001, then we know we have a known
1116 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1118 // To compute this, we first compute the potential carry bits. These are
1119 // the bits which may be modified. I'm not aware of a better way to do
1121 uint64_t RHSVal = RHS->getZExtValue();
1123 bool CarryIn = false;
1124 uint64_t CarryBits = 0;
1125 uint64_t CurBit = 1;
1126 for (unsigned i = 0; i != BitWidth; ++i, CurBit <<= 1) {
1127 // Record the current carry in.
1128 if (CarryIn) CarryBits |= CurBit;
1132 // This bit has a carry out unless it is "zero + zero" or
1133 // "zero + anything" with no carry in.
1134 if ((KnownZero2 & CurBit) && ((RHSVal & CurBit) == 0)) {
1135 CarryOut = false; // 0 + 0 has no carry out, even with carry in.
1136 } else if (!CarryIn &&
1137 ((KnownZero2 & CurBit) || ((RHSVal & CurBit) == 0))) {
1138 CarryOut = false; // 0 + anything has no carry out if no carry in.
1140 // Otherwise, we have to assume we have a carry out.
1144 // This stage's carry out becomes the next stage's carry-in.
1148 // Now that we know which bits have carries, compute the known-1/0 sets.
1150 // Bits are known one if they are known zero in one operand and one in the
1151 // other, and there is no input carry.
1152 KnownOne = ((KnownZero2 & RHSVal) | (KnownOne2 & ~RHSVal)) & ~CarryBits;
1154 // Bits are known zero if they are known zero in both operands and there
1155 // is no input carry.
1156 KnownZero = KnownZero2 & ~RHSVal & ~CarryBits;
1159 case Instruction::Shl:
1160 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1161 uint64_t ShiftAmt = SA->getZExtValue();
1162 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> ShiftAmt,
1163 KnownZero, KnownOne, Depth+1))
1165 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1166 KnownZero <<= ShiftAmt;
1167 KnownOne <<= ShiftAmt;
1168 KnownZero |= (1ULL << ShiftAmt) - 1; // low bits known zero.
1171 case Instruction::LShr:
1172 // For a logical shift right
1173 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1174 unsigned ShiftAmt = SA->getZExtValue();
1176 // Compute the new bits that are at the top now.
1177 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1178 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1179 uint64_t TypeMask = cast<IntegerType>(I->getType())->getBitMask();
1180 // Unsigned shift right.
1181 if (SimplifyDemandedBits(I->getOperand(0),
1182 (DemandedMask << ShiftAmt) & TypeMask,
1183 KnownZero, KnownOne, Depth+1))
1185 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1186 KnownZero &= TypeMask;
1187 KnownOne &= TypeMask;
1188 KnownZero >>= ShiftAmt;
1189 KnownOne >>= ShiftAmt;
1190 KnownZero |= HighBits; // high bits known zero.
1193 case Instruction::AShr:
1194 // If this is an arithmetic shift right and only the low-bit is set, we can
1195 // always convert this into a logical shr, even if the shift amount is
1196 // variable. The low bit of the shift cannot be an input sign bit unless
1197 // the shift amount is >= the size of the datatype, which is undefined.
1198 if (DemandedMask == 1) {
1199 // Perform the logical shift right.
1200 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1201 I->getOperand(1), I->getName());
1202 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1203 return UpdateValueUsesWith(I, NewVal);
1206 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1207 unsigned ShiftAmt = SA->getZExtValue();
1209 // Compute the new bits that are at the top now.
1210 uint64_t HighBits = (1ULL << ShiftAmt)-1;
1211 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShiftAmt;
1212 uint64_t TypeMask = cast<IntegerType>(I->getType())->getBitMask();
1213 // Signed shift right.
1214 if (SimplifyDemandedBits(I->getOperand(0),
1215 (DemandedMask << ShiftAmt) & TypeMask,
1216 KnownZero, KnownOne, Depth+1))
1218 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1219 KnownZero &= TypeMask;
1220 KnownOne &= TypeMask;
1221 KnownZero >>= ShiftAmt;
1222 KnownOne >>= ShiftAmt;
1224 // Handle the sign bits.
1225 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
1226 SignBit >>= ShiftAmt; // Adjust to where it is now in the mask.
1228 // If the input sign bit is known to be zero, or if none of the top bits
1229 // are demanded, turn this into an unsigned shift right.
1230 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
1231 // Perform the logical shift right.
1232 Value *NewVal = new ShiftInst(Instruction::LShr, I->getOperand(0),
1234 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1235 return UpdateValueUsesWith(I, NewVal);
1236 } else if (KnownOne & SignBit) { // New bits are known one.
1237 KnownOne |= HighBits;
1243 // If the client is only demanding bits that we know, return the known
1245 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1246 return UpdateValueUsesWith(I, ConstantInt::get(I->getType(), KnownOne));
1251 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1252 /// 64 or fewer elements. DemandedElts contains the set of elements that are
1253 /// actually used by the caller. This method analyzes which elements of the
1254 /// operand are undef and returns that information in UndefElts.
1256 /// If the information about demanded elements can be used to simplify the
1257 /// operation, the operation is simplified, then the resultant value is
1258 /// returned. This returns null if no change was made.
1259 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1260 uint64_t &UndefElts,
1262 unsigned VWidth = cast<PackedType>(V->getType())->getNumElements();
1263 assert(VWidth <= 64 && "Vector too wide to analyze!");
1264 uint64_t EltMask = ~0ULL >> (64-VWidth);
1265 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1266 "Invalid DemandedElts!");
1268 if (isa<UndefValue>(V)) {
1269 // If the entire vector is undefined, just return this info.
1270 UndefElts = EltMask;
1272 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1273 UndefElts = EltMask;
1274 return UndefValue::get(V->getType());
1278 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V)) {
1279 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1280 Constant *Undef = UndefValue::get(EltTy);
1282 std::vector<Constant*> Elts;
1283 for (unsigned i = 0; i != VWidth; ++i)
1284 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1285 Elts.push_back(Undef);
1286 UndefElts |= (1ULL << i);
1287 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1288 Elts.push_back(Undef);
1289 UndefElts |= (1ULL << i);
1290 } else { // Otherwise, defined.
1291 Elts.push_back(CP->getOperand(i));
1294 // If we changed the constant, return it.
1295 Constant *NewCP = ConstantPacked::get(Elts);
1296 return NewCP != CP ? NewCP : 0;
1297 } else if (isa<ConstantAggregateZero>(V)) {
1298 // Simplify the CAZ to a ConstantPacked where the non-demanded elements are
1300 const Type *EltTy = cast<PackedType>(V->getType())->getElementType();
1301 Constant *Zero = Constant::getNullValue(EltTy);
1302 Constant *Undef = UndefValue::get(EltTy);
1303 std::vector<Constant*> Elts;
1304 for (unsigned i = 0; i != VWidth; ++i)
1305 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1306 UndefElts = DemandedElts ^ EltMask;
1307 return ConstantPacked::get(Elts);
1310 if (!V->hasOneUse()) { // Other users may use these bits.
1311 if (Depth != 0) { // Not at the root.
1312 // TODO: Just compute the UndefElts information recursively.
1316 } else if (Depth == 10) { // Limit search depth.
1320 Instruction *I = dyn_cast<Instruction>(V);
1321 if (!I) return false; // Only analyze instructions.
1323 bool MadeChange = false;
1324 uint64_t UndefElts2;
1326 switch (I->getOpcode()) {
1329 case Instruction::InsertElement: {
1330 // If this is a variable index, we don't know which element it overwrites.
1331 // demand exactly the same input as we produce.
1332 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1334 // Note that we can't propagate undef elt info, because we don't know
1335 // which elt is getting updated.
1336 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1337 UndefElts2, Depth+1);
1338 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1342 // If this is inserting an element that isn't demanded, remove this
1344 unsigned IdxNo = Idx->getZExtValue();
1345 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1346 return AddSoonDeadInstToWorklist(*I, 0);
1348 // Otherwise, the element inserted overwrites whatever was there, so the
1349 // input demanded set is simpler than the output set.
1350 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1351 DemandedElts & ~(1ULL << IdxNo),
1352 UndefElts, Depth+1);
1353 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1355 // The inserted element is defined.
1356 UndefElts |= 1ULL << IdxNo;
1360 case Instruction::And:
1361 case Instruction::Or:
1362 case Instruction::Xor:
1363 case Instruction::Add:
1364 case Instruction::Sub:
1365 case Instruction::Mul:
1366 // div/rem demand all inputs, because they don't want divide by zero.
1367 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1368 UndefElts, Depth+1);
1369 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1370 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1371 UndefElts2, Depth+1);
1372 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1374 // Output elements are undefined if both are undefined. Consider things
1375 // like undef&0. The result is known zero, not undef.
1376 UndefElts &= UndefElts2;
1379 case Instruction::Call: {
1380 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1382 switch (II->getIntrinsicID()) {
1385 // Binary vector operations that work column-wise. A dest element is a
1386 // function of the corresponding input elements from the two inputs.
1387 case Intrinsic::x86_sse_sub_ss:
1388 case Intrinsic::x86_sse_mul_ss:
1389 case Intrinsic::x86_sse_min_ss:
1390 case Intrinsic::x86_sse_max_ss:
1391 case Intrinsic::x86_sse2_sub_sd:
1392 case Intrinsic::x86_sse2_mul_sd:
1393 case Intrinsic::x86_sse2_min_sd:
1394 case Intrinsic::x86_sse2_max_sd:
1395 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1396 UndefElts, Depth+1);
1397 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1398 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1399 UndefElts2, Depth+1);
1400 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1402 // If only the low elt is demanded and this is a scalarizable intrinsic,
1403 // scalarize it now.
1404 if (DemandedElts == 1) {
1405 switch (II->getIntrinsicID()) {
1407 case Intrinsic::x86_sse_sub_ss:
1408 case Intrinsic::x86_sse_mul_ss:
1409 case Intrinsic::x86_sse2_sub_sd:
1410 case Intrinsic::x86_sse2_mul_sd:
1411 // TODO: Lower MIN/MAX/ABS/etc
1412 Value *LHS = II->getOperand(1);
1413 Value *RHS = II->getOperand(2);
1414 // Extract the element as scalars.
1415 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1416 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1418 switch (II->getIntrinsicID()) {
1419 default: assert(0 && "Case stmts out of sync!");
1420 case Intrinsic::x86_sse_sub_ss:
1421 case Intrinsic::x86_sse2_sub_sd:
1422 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1423 II->getName()), *II);
1425 case Intrinsic::x86_sse_mul_ss:
1426 case Intrinsic::x86_sse2_mul_sd:
1427 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1428 II->getName()), *II);
1433 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1435 InsertNewInstBefore(New, *II);
1436 AddSoonDeadInstToWorklist(*II, 0);
1441 // Output elements are undefined if both are undefined. Consider things
1442 // like undef&0. The result is known zero, not undef.
1443 UndefElts &= UndefElts2;
1449 return MadeChange ? I : 0;
1452 /// @returns true if the specified compare instruction is
1453 /// true when both operands are equal...
1454 /// @brief Determine if the ICmpInst returns true if both operands are equal
1455 static bool isTrueWhenEqual(ICmpInst &ICI) {
1456 ICmpInst::Predicate pred = ICI.getPredicate();
1457 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1458 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1459 pred == ICmpInst::ICMP_SLE;
1462 /// AssociativeOpt - Perform an optimization on an associative operator. This
1463 /// function is designed to check a chain of associative operators for a
1464 /// potential to apply a certain optimization. Since the optimization may be
1465 /// applicable if the expression was reassociated, this checks the chain, then
1466 /// reassociates the expression as necessary to expose the optimization
1467 /// opportunity. This makes use of a special Functor, which must define
1468 /// 'shouldApply' and 'apply' methods.
1470 template<typename Functor>
1471 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1472 unsigned Opcode = Root.getOpcode();
1473 Value *LHS = Root.getOperand(0);
1475 // Quick check, see if the immediate LHS matches...
1476 if (F.shouldApply(LHS))
1477 return F.apply(Root);
1479 // Otherwise, if the LHS is not of the same opcode as the root, return.
1480 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1481 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1482 // Should we apply this transform to the RHS?
1483 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1485 // If not to the RHS, check to see if we should apply to the LHS...
1486 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1487 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1491 // If the functor wants to apply the optimization to the RHS of LHSI,
1492 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1494 BasicBlock *BB = Root.getParent();
1496 // Now all of the instructions are in the current basic block, go ahead
1497 // and perform the reassociation.
1498 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1500 // First move the selected RHS to the LHS of the root...
1501 Root.setOperand(0, LHSI->getOperand(1));
1503 // Make what used to be the LHS of the root be the user of the root...
1504 Value *ExtraOperand = TmpLHSI->getOperand(1);
1505 if (&Root == TmpLHSI) {
1506 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1509 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1510 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1511 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1512 BasicBlock::iterator ARI = &Root; ++ARI;
1513 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1516 // Now propagate the ExtraOperand down the chain of instructions until we
1518 while (TmpLHSI != LHSI) {
1519 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1520 // Move the instruction to immediately before the chain we are
1521 // constructing to avoid breaking dominance properties.
1522 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1523 BB->getInstList().insert(ARI, NextLHSI);
1526 Value *NextOp = NextLHSI->getOperand(1);
1527 NextLHSI->setOperand(1, ExtraOperand);
1529 ExtraOperand = NextOp;
1532 // Now that the instructions are reassociated, have the functor perform
1533 // the transformation...
1534 return F.apply(Root);
1537 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1543 // AddRHS - Implements: X + X --> X << 1
1546 AddRHS(Value *rhs) : RHS(rhs) {}
1547 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1548 Instruction *apply(BinaryOperator &Add) const {
1549 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1550 ConstantInt::get(Type::Int8Ty, 1));
1554 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1556 struct AddMaskingAnd {
1558 AddMaskingAnd(Constant *c) : C2(c) {}
1559 bool shouldApply(Value *LHS) const {
1561 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1562 ConstantExpr::getAnd(C1, C2)->isNullValue();
1564 Instruction *apply(BinaryOperator &Add) const {
1565 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1569 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1571 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1572 if (Constant *SOC = dyn_cast<Constant>(SO))
1573 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1575 return IC->InsertNewInstBefore(CastInst::create(
1576 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1579 // Figure out if the constant is the left or the right argument.
1580 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1581 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1583 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1585 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1586 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1589 Value *Op0 = SO, *Op1 = ConstOperand;
1591 std::swap(Op0, Op1);
1593 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1594 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1595 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1596 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1597 SO->getName()+".cmp");
1598 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1599 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1601 assert(0 && "Unknown binary instruction type!");
1604 return IC->InsertNewInstBefore(New, I);
1607 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1608 // constant as the other operand, try to fold the binary operator into the
1609 // select arguments. This also works for Cast instructions, which obviously do
1610 // not have a second operand.
1611 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1613 // Don't modify shared select instructions
1614 if (!SI->hasOneUse()) return 0;
1615 Value *TV = SI->getOperand(1);
1616 Value *FV = SI->getOperand(2);
1618 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1619 // Bool selects with constant operands can be folded to logical ops.
1620 if (SI->getType() == Type::Int1Ty) return 0;
1622 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1623 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1625 return new SelectInst(SI->getCondition(), SelectTrueVal,
1632 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1633 /// node as operand #0, see if we can fold the instruction into the PHI (which
1634 /// is only possible if all operands to the PHI are constants).
1635 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1636 PHINode *PN = cast<PHINode>(I.getOperand(0));
1637 unsigned NumPHIValues = PN->getNumIncomingValues();
1638 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1640 // Check to see if all of the operands of the PHI are constants. If there is
1641 // one non-constant value, remember the BB it is. If there is more than one
1643 BasicBlock *NonConstBB = 0;
1644 for (unsigned i = 0; i != NumPHIValues; ++i)
1645 if (!isa<Constant>(PN->getIncomingValue(i))) {
1646 if (NonConstBB) return 0; // More than one non-const value.
1647 NonConstBB = PN->getIncomingBlock(i);
1649 // If the incoming non-constant value is in I's block, we have an infinite
1651 if (NonConstBB == I.getParent())
1655 // If there is exactly one non-constant value, we can insert a copy of the
1656 // operation in that block. However, if this is a critical edge, we would be
1657 // inserting the computation one some other paths (e.g. inside a loop). Only
1658 // do this if the pred block is unconditionally branching into the phi block.
1660 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1661 if (!BI || !BI->isUnconditional()) return 0;
1664 // Okay, we can do the transformation: create the new PHI node.
1665 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1667 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1668 InsertNewInstBefore(NewPN, *PN);
1670 // Next, add all of the operands to the PHI.
1671 if (I.getNumOperands() == 2) {
1672 Constant *C = cast<Constant>(I.getOperand(1));
1673 for (unsigned i = 0; i != NumPHIValues; ++i) {
1675 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1676 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1677 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1679 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1681 assert(PN->getIncomingBlock(i) == NonConstBB);
1682 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1683 InV = BinaryOperator::create(BO->getOpcode(),
1684 PN->getIncomingValue(i), C, "phitmp",
1685 NonConstBB->getTerminator());
1686 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1687 InV = CmpInst::create(CI->getOpcode(),
1689 PN->getIncomingValue(i), C, "phitmp",
1690 NonConstBB->getTerminator());
1691 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1692 InV = new ShiftInst(SI->getOpcode(),
1693 PN->getIncomingValue(i), C, "phitmp",
1694 NonConstBB->getTerminator());
1696 assert(0 && "Unknown binop!");
1698 WorkList.push_back(cast<Instruction>(InV));
1700 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1703 CastInst *CI = cast<CastInst>(&I);
1704 const Type *RetTy = CI->getType();
1705 for (unsigned i = 0; i != NumPHIValues; ++i) {
1707 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1708 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1710 assert(PN->getIncomingBlock(i) == NonConstBB);
1711 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1712 I.getType(), "phitmp",
1713 NonConstBB->getTerminator());
1714 WorkList.push_back(cast<Instruction>(InV));
1716 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1719 return ReplaceInstUsesWith(I, NewPN);
1722 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1723 bool Changed = SimplifyCommutative(I);
1724 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1726 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1727 // X + undef -> undef
1728 if (isa<UndefValue>(RHS))
1729 return ReplaceInstUsesWith(I, RHS);
1732 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1733 if (RHSC->isNullValue())
1734 return ReplaceInstUsesWith(I, LHS);
1735 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1736 if (CFP->isExactlyValue(-0.0))
1737 return ReplaceInstUsesWith(I, LHS);
1740 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1741 // X + (signbit) --> X ^ signbit
1742 uint64_t Val = CI->getZExtValue();
1743 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1744 return BinaryOperator::createXor(LHS, RHS);
1746 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1747 // (X & 254)+1 -> (X&254)|1
1748 uint64_t KnownZero, KnownOne;
1749 if (!isa<PackedType>(I.getType()) &&
1750 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
1751 KnownZero, KnownOne))
1755 if (isa<PHINode>(LHS))
1756 if (Instruction *NV = FoldOpIntoPhi(I))
1759 ConstantInt *XorRHS = 0;
1761 if (isa<ConstantInt>(RHSC) &&
1762 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1763 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1764 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1765 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1767 uint64_t C0080Val = 1ULL << 31;
1768 int64_t CFF80Val = -C0080Val;
1771 if (TySizeBits > Size) {
1773 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1774 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1775 if (RHSSExt == CFF80Val) {
1776 if (XorRHS->getZExtValue() == C0080Val)
1778 } else if (RHSZExt == C0080Val) {
1779 if (XorRHS->getSExtValue() == CFF80Val)
1783 // This is a sign extend if the top bits are known zero.
1784 uint64_t Mask = ~0ULL;
1785 Mask <<= 64-(TySizeBits-Size);
1786 Mask &= cast<IntegerType>(XorLHS->getType())->getBitMask();
1787 if (!MaskedValueIsZero(XorLHS, Mask))
1788 Size = 0; // Not a sign ext, but can't be any others either.
1795 } while (Size >= 8);
1798 const Type *MiddleType = 0;
1801 case 32: MiddleType = Type::Int32Ty; break;
1802 case 16: MiddleType = Type::Int16Ty; break;
1803 case 8: MiddleType = Type::Int8Ty; break;
1806 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1807 InsertNewInstBefore(NewTrunc, I);
1808 return new SExtInst(NewTrunc, I.getType());
1814 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
1815 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1817 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1818 if (RHSI->getOpcode() == Instruction::Sub)
1819 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1820 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1822 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1823 if (LHSI->getOpcode() == Instruction::Sub)
1824 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1825 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1830 if (Value *V = dyn_castNegVal(LHS))
1831 return BinaryOperator::createSub(RHS, V);
1834 if (!isa<Constant>(RHS))
1835 if (Value *V = dyn_castNegVal(RHS))
1836 return BinaryOperator::createSub(LHS, V);
1840 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1841 if (X == RHS) // X*C + X --> X * (C+1)
1842 return BinaryOperator::createMul(RHS, AddOne(C2));
1844 // X*C1 + X*C2 --> X * (C1+C2)
1846 if (X == dyn_castFoldableMul(RHS, C1))
1847 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1850 // X + X*C --> X * (C+1)
1851 if (dyn_castFoldableMul(RHS, C2) == LHS)
1852 return BinaryOperator::createMul(LHS, AddOne(C2));
1854 // X + ~X --> -1 since ~X = -X-1
1855 if (dyn_castNotVal(LHS) == RHS ||
1856 dyn_castNotVal(RHS) == LHS)
1857 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
1860 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1861 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1862 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
1865 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1867 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1868 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1869 return BinaryOperator::createSub(C, X);
1872 // (X & FF00) + xx00 -> (X+xx00) & FF00
1873 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1874 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1875 if (Anded == CRHS) {
1876 // See if all bits from the first bit set in the Add RHS up are included
1877 // in the mask. First, get the rightmost bit.
1878 uint64_t AddRHSV = CRHS->getZExtValue();
1880 // Form a mask of all bits from the lowest bit added through the top.
1881 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1882 AddRHSHighBits &= C2->getType()->getBitMask();
1884 // See if the and mask includes all of these bits.
1885 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getZExtValue();
1887 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1888 // Okay, the xform is safe. Insert the new add pronto.
1889 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1890 LHS->getName()), I);
1891 return BinaryOperator::createAnd(NewAdd, C2);
1896 // Try to fold constant add into select arguments.
1897 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1898 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1902 // add (cast *A to intptrtype) B ->
1903 // cast (GEP (cast *A to sbyte*) B) ->
1906 CastInst *CI = dyn_cast<CastInst>(LHS);
1909 CI = dyn_cast<CastInst>(RHS);
1912 if (CI && CI->getType()->isSized() &&
1913 (CI->getType()->getPrimitiveSizeInBits() ==
1914 TD->getIntPtrType()->getPrimitiveSizeInBits())
1915 && isa<PointerType>(CI->getOperand(0)->getType())) {
1916 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
1917 PointerType::get(Type::Int8Ty), I);
1918 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
1919 return new PtrToIntInst(I2, CI->getType());
1923 return Changed ? &I : 0;
1926 // isSignBit - Return true if the value represented by the constant only has the
1927 // highest order bit set.
1928 static bool isSignBit(ConstantInt *CI) {
1929 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1930 return (CI->getZExtValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1933 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1934 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1936 if (Op0 == Op1) // sub X, X -> 0
1937 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1939 // If this is a 'B = x-(-A)', change to B = x+A...
1940 if (Value *V = dyn_castNegVal(Op1))
1941 return BinaryOperator::createAdd(Op0, V);
1943 if (isa<UndefValue>(Op0))
1944 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1945 if (isa<UndefValue>(Op1))
1946 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1948 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1949 // Replace (-1 - A) with (~A)...
1950 if (C->isAllOnesValue())
1951 return BinaryOperator::createNot(Op1);
1953 // C - ~X == X + (1+C)
1955 if (match(Op1, m_Not(m_Value(X))))
1956 return BinaryOperator::createAdd(X,
1957 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1958 // -(X >>u 31) -> (X >>s 31)
1959 // -(X >>s 31) -> (X >>u 31)
1960 if (C->isNullValue()) {
1961 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op1))
1962 if (SI->getOpcode() == Instruction::LShr) {
1963 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1964 // Check to see if we are shifting out everything but the sign bit.
1965 if (CU->getZExtValue() ==
1966 SI->getType()->getPrimitiveSizeInBits()-1) {
1967 // Ok, the transformation is safe. Insert AShr.
1968 return new ShiftInst(Instruction::AShr, SI->getOperand(0), CU,
1973 else if (SI->getOpcode() == Instruction::AShr) {
1974 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
1975 // Check to see if we are shifting out everything but the sign bit.
1976 if (CU->getZExtValue() ==
1977 SI->getType()->getPrimitiveSizeInBits()-1) {
1978 // Ok, the transformation is safe. Insert LShr.
1979 return new ShiftInst(Instruction::LShr, SI->getOperand(0), CU,
1986 // Try to fold constant sub into select arguments.
1987 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1988 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1991 if (isa<PHINode>(Op0))
1992 if (Instruction *NV = FoldOpIntoPhi(I))
1996 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1997 if (Op1I->getOpcode() == Instruction::Add &&
1998 !Op0->getType()->isFPOrFPVector()) {
1999 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2000 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2001 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2002 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2003 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2004 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2005 // C1-(X+C2) --> (C1-C2)-X
2006 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
2007 Op1I->getOperand(0));
2011 if (Op1I->hasOneUse()) {
2012 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2013 // is not used by anyone else...
2015 if (Op1I->getOpcode() == Instruction::Sub &&
2016 !Op1I->getType()->isFPOrFPVector()) {
2017 // Swap the two operands of the subexpr...
2018 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2019 Op1I->setOperand(0, IIOp1);
2020 Op1I->setOperand(1, IIOp0);
2022 // Create the new top level add instruction...
2023 return BinaryOperator::createAdd(Op0, Op1);
2026 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2028 if (Op1I->getOpcode() == Instruction::And &&
2029 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2030 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2033 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2034 return BinaryOperator::createAnd(Op0, NewNot);
2037 // 0 - (X sdiv C) -> (X sdiv -C)
2038 if (Op1I->getOpcode() == Instruction::SDiv)
2039 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2040 if (CSI->isNullValue())
2041 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2042 return BinaryOperator::createSDiv(Op1I->getOperand(0),
2043 ConstantExpr::getNeg(DivRHS));
2045 // X - X*C --> X * (1-C)
2046 ConstantInt *C2 = 0;
2047 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2049 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
2050 return BinaryOperator::createMul(Op0, CP1);
2055 if (!Op0->getType()->isFPOrFPVector())
2056 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2057 if (Op0I->getOpcode() == Instruction::Add) {
2058 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2059 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2060 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2061 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2062 } else if (Op0I->getOpcode() == Instruction::Sub) {
2063 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2064 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2068 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2069 if (X == Op1) { // X*C - X --> X * (C-1)
2070 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
2071 return BinaryOperator::createMul(Op1, CP1);
2074 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2075 if (X == dyn_castFoldableMul(Op1, C2))
2076 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
2081 /// isSignBitCheck - Given an exploded icmp instruction, return true if it
2082 /// really just returns true if the most significant (sign) bit is set.
2083 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2085 case ICmpInst::ICMP_SLT:
2086 // True if LHS s< RHS and RHS == 0
2087 return RHS->isNullValue();
2088 case ICmpInst::ICMP_SLE:
2089 // True if LHS s<= RHS and RHS == -1
2090 return RHS->isAllOnesValue();
2091 case ICmpInst::ICMP_UGE:
2092 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2093 return RHS->getZExtValue() == (1ULL <<
2094 (RHS->getType()->getPrimitiveSizeInBits()-1));
2095 case ICmpInst::ICMP_UGT:
2096 // True if LHS u> RHS and RHS == high-bit-mask - 1
2097 return RHS->getZExtValue() ==
2098 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
2104 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2105 bool Changed = SimplifyCommutative(I);
2106 Value *Op0 = I.getOperand(0);
2108 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2109 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2111 // Simplify mul instructions with a constant RHS...
2112 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2113 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2115 // ((X << C1)*C2) == (X * (C2 << C1))
2116 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
2117 if (SI->getOpcode() == Instruction::Shl)
2118 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2119 return BinaryOperator::createMul(SI->getOperand(0),
2120 ConstantExpr::getShl(CI, ShOp));
2122 if (CI->isNullValue())
2123 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2124 if (CI->equalsInt(1)) // X * 1 == X
2125 return ReplaceInstUsesWith(I, Op0);
2126 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2127 return BinaryOperator::createNeg(Op0, I.getName());
2129 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getZExtValue();
2130 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
2131 uint64_t C = Log2_64(Val);
2132 return new ShiftInst(Instruction::Shl, Op0,
2133 ConstantInt::get(Type::Int8Ty, C));
2135 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2136 if (Op1F->isNullValue())
2137 return ReplaceInstUsesWith(I, Op1);
2139 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2140 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2141 if (Op1F->getValue() == 1.0)
2142 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2145 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2146 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2147 isa<ConstantInt>(Op0I->getOperand(1))) {
2148 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2149 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2151 InsertNewInstBefore(Add, I);
2152 Value *C1C2 = ConstantExpr::getMul(Op1,
2153 cast<Constant>(Op0I->getOperand(1)));
2154 return BinaryOperator::createAdd(Add, C1C2);
2158 // Try to fold constant mul into select arguments.
2159 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2160 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2163 if (isa<PHINode>(Op0))
2164 if (Instruction *NV = FoldOpIntoPhi(I))
2168 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2169 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2170 return BinaryOperator::createMul(Op0v, Op1v);
2172 // If one of the operands of the multiply is a cast from a boolean value, then
2173 // we know the bool is either zero or one, so this is a 'masking' multiply.
2174 // See if we can simplify things based on how the boolean was originally
2176 CastInst *BoolCast = 0;
2177 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2178 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2181 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2182 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2185 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2186 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2187 const Type *SCOpTy = SCIOp0->getType();
2189 // If the icmp is true iff the sign bit of X is set, then convert this
2190 // multiply into a shift/and combination.
2191 if (isa<ConstantInt>(SCIOp1) &&
2192 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
2193 // Shift the X value right to turn it into "all signbits".
2194 Constant *Amt = ConstantInt::get(Type::Int8Ty,
2195 SCOpTy->getPrimitiveSizeInBits()-1);
2197 InsertNewInstBefore(new ShiftInst(Instruction::AShr, SCIOp0, Amt,
2198 BoolCast->getOperand(0)->getName()+
2201 // If the multiply type is not the same as the source type, sign extend
2202 // or truncate to the multiply type.
2203 if (I.getType() != V->getType()) {
2204 unsigned SrcBits = V->getType()->getPrimitiveSizeInBits();
2205 unsigned DstBits = I.getType()->getPrimitiveSizeInBits();
2206 Instruction::CastOps opcode =
2207 (SrcBits == DstBits ? Instruction::BitCast :
2208 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2209 V = InsertCastBefore(opcode, V, I.getType(), I);
2212 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2213 return BinaryOperator::createAnd(V, OtherOp);
2218 return Changed ? &I : 0;
2221 /// This function implements the transforms on div instructions that work
2222 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2223 /// used by the visitors to those instructions.
2224 /// @brief Transforms common to all three div instructions
2225 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2226 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2229 if (isa<UndefValue>(Op0))
2230 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2232 // X / undef -> undef
2233 if (isa<UndefValue>(Op1))
2234 return ReplaceInstUsesWith(I, Op1);
2236 // Handle cases involving: div X, (select Cond, Y, Z)
2237 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2238 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
2239 // same basic block, then we replace the select with Y, and the condition
2240 // of the select with false (if the cond value is in the same BB). If the
2241 // select has uses other than the div, this allows them to be simplified
2242 // also. Note that div X, Y is just as good as div X, 0 (undef)
2243 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2244 if (ST->isNullValue()) {
2245 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2246 if (CondI && CondI->getParent() == I.getParent())
2247 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2248 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2249 I.setOperand(1, SI->getOperand(2));
2251 UpdateValueUsesWith(SI, SI->getOperand(2));
2255 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2256 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2257 if (ST->isNullValue()) {
2258 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2259 if (CondI && CondI->getParent() == I.getParent())
2260 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2261 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2262 I.setOperand(1, SI->getOperand(1));
2264 UpdateValueUsesWith(SI, SI->getOperand(1));
2272 /// This function implements the transforms common to both integer division
2273 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2274 /// division instructions.
2275 /// @brief Common integer divide transforms
2276 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2277 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2279 if (Instruction *Common = commonDivTransforms(I))
2282 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2284 if (RHS->equalsInt(1))
2285 return ReplaceInstUsesWith(I, Op0);
2287 // (X / C1) / C2 -> X / (C1*C2)
2288 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2289 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2290 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2291 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2292 ConstantExpr::getMul(RHS, LHSRHS));
2295 if (!RHS->isNullValue()) { // avoid X udiv 0
2296 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2297 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2299 if (isa<PHINode>(Op0))
2300 if (Instruction *NV = FoldOpIntoPhi(I))
2305 // 0 / X == 0, we don't need to preserve faults!
2306 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2307 if (LHS->equalsInt(0))
2308 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2313 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2314 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2316 // Handle the integer div common cases
2317 if (Instruction *Common = commonIDivTransforms(I))
2320 // X udiv C^2 -> X >> C
2321 // Check to see if this is an unsigned division with an exact power of 2,
2322 // if so, convert to a right shift.
2323 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2324 if (uint64_t Val = C->getZExtValue()) // Don't break X / 0
2325 if (isPowerOf2_64(Val)) {
2326 uint64_t ShiftAmt = Log2_64(Val);
2327 return new ShiftInst(Instruction::LShr, Op0,
2328 ConstantInt::get(Type::Int8Ty, ShiftAmt));
2332 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2333 if (ShiftInst *RHSI = dyn_cast<ShiftInst>(I.getOperand(1))) {
2334 if (RHSI->getOpcode() == Instruction::Shl &&
2335 isa<ConstantInt>(RHSI->getOperand(0))) {
2336 uint64_t C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2337 if (isPowerOf2_64(C1)) {
2338 Value *N = RHSI->getOperand(1);
2339 const Type *NTy = N->getType();
2340 if (uint64_t C2 = Log2_64(C1)) {
2341 Constant *C2V = ConstantInt::get(NTy, C2);
2342 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2344 return new ShiftInst(Instruction::LShr, Op0, N);
2349 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2350 // where C1&C2 are powers of two.
2351 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2352 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2353 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2)))
2354 if (!STO->isNullValue() && !STO->isNullValue()) {
2355 uint64_t TVA = STO->getZExtValue(), FVA = SFO->getZExtValue();
2356 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
2357 // Compute the shift amounts
2358 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
2359 // Construct the "on true" case of the select
2360 Constant *TC = ConstantInt::get(Type::Int8Ty, TSA);
2362 new ShiftInst(Instruction::LShr, Op0, TC, SI->getName()+".t");
2363 TSI = InsertNewInstBefore(TSI, I);
2365 // Construct the "on false" case of the select
2366 Constant *FC = ConstantInt::get(Type::Int8Ty, FSA);
2368 new ShiftInst(Instruction::LShr, Op0, FC, SI->getName()+".f");
2369 FSI = InsertNewInstBefore(FSI, I);
2371 // construct the select instruction and return it.
2372 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2379 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2380 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2382 // Handle the integer div common cases
2383 if (Instruction *Common = commonIDivTransforms(I))
2386 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2388 if (RHS->isAllOnesValue())
2389 return BinaryOperator::createNeg(Op0);
2392 if (Value *LHSNeg = dyn_castNegVal(Op0))
2393 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2396 // If the sign bits of both operands are zero (i.e. we can prove they are
2397 // unsigned inputs), turn this into a udiv.
2398 if (I.getType()->isInteger()) {
2399 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2400 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2401 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2408 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2409 return commonDivTransforms(I);
2412 /// GetFactor - If we can prove that the specified value is at least a multiple
2413 /// of some factor, return that factor.
2414 static Constant *GetFactor(Value *V) {
2415 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2418 // Unless we can be tricky, we know this is a multiple of 1.
2419 Constant *Result = ConstantInt::get(V->getType(), 1);
2421 Instruction *I = dyn_cast<Instruction>(V);
2422 if (!I) return Result;
2424 if (I->getOpcode() == Instruction::Mul) {
2425 // Handle multiplies by a constant, etc.
2426 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2427 GetFactor(I->getOperand(1)));
2428 } else if (I->getOpcode() == Instruction::Shl) {
2429 // (X<<C) -> X * (1 << C)
2430 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2431 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2432 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2434 } else if (I->getOpcode() == Instruction::And) {
2435 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2436 // X & 0xFFF0 is known to be a multiple of 16.
2437 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
2438 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2439 return ConstantExpr::getShl(Result,
2440 ConstantInt::get(Type::Int8Ty, Zeros));
2442 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2443 // Only handle int->int casts.
2444 if (!CI->isIntegerCast())
2446 Value *Op = CI->getOperand(0);
2447 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2452 /// This function implements the transforms on rem instructions that work
2453 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2454 /// is used by the visitors to those instructions.
2455 /// @brief Transforms common to all three rem instructions
2456 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2457 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2459 // 0 % X == 0, we don't need to preserve faults!
2460 if (Constant *LHS = dyn_cast<Constant>(Op0))
2461 if (LHS->isNullValue())
2462 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2464 if (isa<UndefValue>(Op0)) // undef % X -> 0
2465 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2466 if (isa<UndefValue>(Op1))
2467 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2469 // Handle cases involving: rem X, (select Cond, Y, Z)
2470 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2471 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2472 // the same basic block, then we replace the select with Y, and the
2473 // condition of the select with false (if the cond value is in the same
2474 // BB). If the select has uses other than the div, this allows them to be
2476 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2477 if (ST->isNullValue()) {
2478 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2479 if (CondI && CondI->getParent() == I.getParent())
2480 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2481 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2482 I.setOperand(1, SI->getOperand(2));
2484 UpdateValueUsesWith(SI, SI->getOperand(2));
2487 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2488 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2489 if (ST->isNullValue()) {
2490 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2491 if (CondI && CondI->getParent() == I.getParent())
2492 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2493 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2494 I.setOperand(1, SI->getOperand(1));
2496 UpdateValueUsesWith(SI, SI->getOperand(1));
2504 /// This function implements the transforms common to both integer remainder
2505 /// instructions (urem and srem). It is called by the visitors to those integer
2506 /// remainder instructions.
2507 /// @brief Common integer remainder transforms
2508 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2509 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2511 if (Instruction *common = commonRemTransforms(I))
2514 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2515 // X % 0 == undef, we don't need to preserve faults!
2516 if (RHS->equalsInt(0))
2517 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2519 if (RHS->equalsInt(1)) // X % 1 == 0
2520 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2522 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2523 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2524 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2526 } else if (isa<PHINode>(Op0I)) {
2527 if (Instruction *NV = FoldOpIntoPhi(I))
2530 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2531 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2532 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2539 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2540 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2542 if (Instruction *common = commonIRemTransforms(I))
2545 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2546 // X urem C^2 -> X and C
2547 // Check to see if this is an unsigned remainder with an exact power of 2,
2548 // if so, convert to a bitwise and.
2549 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2550 if (isPowerOf2_64(C->getZExtValue()))
2551 return BinaryOperator::createAnd(Op0, SubOne(C));
2554 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2555 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2556 if (RHSI->getOpcode() == Instruction::Shl &&
2557 isa<ConstantInt>(RHSI->getOperand(0))) {
2558 unsigned C1 = cast<ConstantInt>(RHSI->getOperand(0))->getZExtValue();
2559 if (isPowerOf2_64(C1)) {
2560 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2561 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2563 return BinaryOperator::createAnd(Op0, Add);
2568 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2569 // where C1&C2 are powers of two.
2570 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2571 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2572 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2573 // STO == 0 and SFO == 0 handled above.
2574 if (isPowerOf2_64(STO->getZExtValue()) &&
2575 isPowerOf2_64(SFO->getZExtValue())) {
2576 Value *TrueAnd = InsertNewInstBefore(
2577 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2578 Value *FalseAnd = InsertNewInstBefore(
2579 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2580 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2588 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2589 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2591 if (Instruction *common = commonIRemTransforms(I))
2594 if (Value *RHSNeg = dyn_castNegVal(Op1))
2595 if (!isa<ConstantInt>(RHSNeg) ||
2596 cast<ConstantInt>(RHSNeg)->getSExtValue() > 0) {
2598 AddUsesToWorkList(I);
2599 I.setOperand(1, RHSNeg);
2603 // If the top bits of both operands are zero (i.e. we can prove they are
2604 // unsigned inputs), turn this into a urem.
2605 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
2606 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2607 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2608 return BinaryOperator::createURem(Op0, Op1, I.getName());
2614 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2615 return commonRemTransforms(I);
2618 // isMaxValueMinusOne - return true if this is Max-1
2619 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2621 // Calculate 0111111111..11111
2622 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2623 int64_t Val = INT64_MAX; // All ones
2624 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
2625 return C->getSExtValue() == Val-1;
2627 return C->getZExtValue() == C->getType()->getBitMask()-1;
2630 // isMinValuePlusOne - return true if this is Min+1
2631 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2633 // Calculate 1111111111000000000000
2634 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2635 int64_t Val = -1; // All ones
2636 Val <<= TypeBits-1; // Shift over to the right spot
2637 return C->getSExtValue() == Val+1;
2639 return C->getZExtValue() == 1; // unsigned
2642 // isOneBitSet - Return true if there is exactly one bit set in the specified
2644 static bool isOneBitSet(const ConstantInt *CI) {
2645 uint64_t V = CI->getZExtValue();
2646 return V && (V & (V-1)) == 0;
2649 #if 0 // Currently unused
2650 // isLowOnes - Return true if the constant is of the form 0+1+.
2651 static bool isLowOnes(const ConstantInt *CI) {
2652 uint64_t V = CI->getZExtValue();
2654 // There won't be bits set in parts that the type doesn't contain.
2655 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2657 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2658 return U && V && (U & V) == 0;
2662 // isHighOnes - Return true if the constant is of the form 1+0+.
2663 // This is the same as lowones(~X).
2664 static bool isHighOnes(const ConstantInt *CI) {
2665 uint64_t V = ~CI->getZExtValue();
2666 if (~V == 0) return false; // 0's does not match "1+"
2668 // There won't be bits set in parts that the type doesn't contain.
2669 V &= ConstantInt::getAllOnesValue(CI->getType())->getZExtValue();
2671 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2672 return U && V && (U & V) == 0;
2675 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
2676 /// are carefully arranged to allow folding of expressions such as:
2678 /// (A < B) | (A > B) --> (A != B)
2680 /// Note that this is only valid if the first and second predicates have the
2681 /// same sign. Is illegal to do: (A u< B) | (A s> B)
2683 /// Three bits are used to represent the condition, as follows:
2688 /// <=> Value Definition
2689 /// 000 0 Always false
2696 /// 111 7 Always true
2698 static unsigned getICmpCode(const ICmpInst *ICI) {
2699 switch (ICI->getPredicate()) {
2701 case ICmpInst::ICMP_UGT: return 1; // 001
2702 case ICmpInst::ICMP_SGT: return 1; // 001
2703 case ICmpInst::ICMP_EQ: return 2; // 010
2704 case ICmpInst::ICMP_UGE: return 3; // 011
2705 case ICmpInst::ICMP_SGE: return 3; // 011
2706 case ICmpInst::ICMP_ULT: return 4; // 100
2707 case ICmpInst::ICMP_SLT: return 4; // 100
2708 case ICmpInst::ICMP_NE: return 5; // 101
2709 case ICmpInst::ICMP_ULE: return 6; // 110
2710 case ICmpInst::ICMP_SLE: return 6; // 110
2713 assert(0 && "Invalid ICmp predicate!");
2718 /// getICmpValue - This is the complement of getICmpCode, which turns an
2719 /// opcode and two operands into either a constant true or false, or a brand
2720 /// new /// ICmp instruction. The sign is passed in to determine which kind
2721 /// of predicate to use in new icmp instructions.
2722 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2724 default: assert(0 && "Illegal ICmp code!");
2725 case 0: return ConstantInt::getFalse();
2728 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2730 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2731 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2734 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2736 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2739 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2741 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2742 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2745 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2747 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2748 case 7: return ConstantInt::getTrue();
2752 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2753 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2754 (ICmpInst::isSignedPredicate(p1) &&
2755 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2756 (ICmpInst::isSignedPredicate(p2) &&
2757 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2761 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2762 struct FoldICmpLogical {
2765 ICmpInst::Predicate pred;
2766 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2767 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2768 pred(ICI->getPredicate()) {}
2769 bool shouldApply(Value *V) const {
2770 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2771 if (PredicatesFoldable(pred, ICI->getPredicate()))
2772 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2773 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
2776 Instruction *apply(Instruction &Log) const {
2777 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2778 if (ICI->getOperand(0) != LHS) {
2779 assert(ICI->getOperand(1) == LHS);
2780 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
2783 unsigned LHSCode = getICmpCode(ICI);
2784 unsigned RHSCode = getICmpCode(cast<ICmpInst>(Log.getOperand(1)));
2786 switch (Log.getOpcode()) {
2787 case Instruction::And: Code = LHSCode & RHSCode; break;
2788 case Instruction::Or: Code = LHSCode | RHSCode; break;
2789 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2790 default: assert(0 && "Illegal logical opcode!"); return 0;
2793 Value *RV = getICmpValue(ICmpInst::isSignedPredicate(pred), Code, LHS, RHS);
2794 if (Instruction *I = dyn_cast<Instruction>(RV))
2796 // Otherwise, it's a constant boolean value...
2797 return IC.ReplaceInstUsesWith(Log, RV);
2800 } // end anonymous namespace
2802 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2803 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2804 // guaranteed to be either a shift instruction or a binary operator.
2805 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2807 ConstantInt *AndRHS,
2808 BinaryOperator &TheAnd) {
2809 Value *X = Op->getOperand(0);
2810 Constant *Together = 0;
2811 if (!isa<ShiftInst>(Op))
2812 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2814 switch (Op->getOpcode()) {
2815 case Instruction::Xor:
2816 if (Op->hasOneUse()) {
2817 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2818 std::string OpName = Op->getName(); Op->setName("");
2819 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2820 InsertNewInstBefore(And, TheAnd);
2821 return BinaryOperator::createXor(And, Together);
2824 case Instruction::Or:
2825 if (Together == AndRHS) // (X | C) & C --> C
2826 return ReplaceInstUsesWith(TheAnd, AndRHS);
2828 if (Op->hasOneUse() && Together != OpRHS) {
2829 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2830 std::string Op0Name = Op->getName(); Op->setName("");
2831 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2832 InsertNewInstBefore(Or, TheAnd);
2833 return BinaryOperator::createAnd(Or, AndRHS);
2836 case Instruction::Add:
2837 if (Op->hasOneUse()) {
2838 // Adding a one to a single bit bit-field should be turned into an XOR
2839 // of the bit. First thing to check is to see if this AND is with a
2840 // single bit constant.
2841 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getZExtValue();
2843 // Clear bits that are not part of the constant.
2844 AndRHSV &= AndRHS->getType()->getBitMask();
2846 // If there is only one bit set...
2847 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2848 // Ok, at this point, we know that we are masking the result of the
2849 // ADD down to exactly one bit. If the constant we are adding has
2850 // no bits set below this bit, then we can eliminate the ADD.
2851 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getZExtValue();
2853 // Check to see if any bits below the one bit set in AndRHSV are set.
2854 if ((AddRHS & (AndRHSV-1)) == 0) {
2855 // If not, the only thing that can effect the output of the AND is
2856 // the bit specified by AndRHSV. If that bit is set, the effect of
2857 // the XOR is to toggle the bit. If it is clear, then the ADD has
2859 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2860 TheAnd.setOperand(0, X);
2863 std::string Name = Op->getName(); Op->setName("");
2864 // Pull the XOR out of the AND.
2865 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2866 InsertNewInstBefore(NewAnd, TheAnd);
2867 return BinaryOperator::createXor(NewAnd, AndRHS);
2874 case Instruction::Shl: {
2875 // We know that the AND will not produce any of the bits shifted in, so if
2876 // the anded constant includes them, clear them now!
2878 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2879 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2880 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2882 if (CI == ShlMask) { // Masking out bits that the shift already masks
2883 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2884 } else if (CI != AndRHS) { // Reducing bits set in and.
2885 TheAnd.setOperand(1, CI);
2890 case Instruction::LShr:
2892 // We know that the AND will not produce any of the bits shifted in, so if
2893 // the anded constant includes them, clear them now! This only applies to
2894 // unsigned shifts, because a signed shr may bring in set bits!
2896 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2897 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2898 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2900 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2901 return ReplaceInstUsesWith(TheAnd, Op);
2902 } else if (CI != AndRHS) {
2903 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2908 case Instruction::AShr:
2910 // See if this is shifting in some sign extension, then masking it out
2912 if (Op->hasOneUse()) {
2913 Constant *AllOne = ConstantInt::getAllOnesValue(AndRHS->getType());
2914 Constant *ShrMask = ConstantExpr::getLShr(AllOne, OpRHS);
2915 Constant *C = ConstantExpr::getAnd(AndRHS, ShrMask);
2916 if (C == AndRHS) { // Masking out bits shifted in.
2917 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
2918 // Make the argument unsigned.
2919 Value *ShVal = Op->getOperand(0);
2920 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::LShr, ShVal,
2921 OpRHS, Op->getName()), TheAnd);
2922 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
2931 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2932 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2933 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
2934 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
2935 /// insert new instructions.
2936 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2937 bool isSigned, bool Inside,
2939 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
2940 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
2941 "Lo is not <= Hi in range emission code!");
2944 if (Lo == Hi) // Trivially false.
2945 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
2947 // V >= Min && V < Hi --> V < Hi
2948 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
2949 ICmpInst::Predicate pred = (isSigned ?
2950 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
2951 return new ICmpInst(pred, V, Hi);
2954 // Emit V-Lo <u Hi-Lo
2955 Constant *NegLo = ConstantExpr::getNeg(Lo);
2956 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
2957 InsertNewInstBefore(Add, IB);
2958 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
2959 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
2962 if (Lo == Hi) // Trivially true.
2963 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
2965 // V < Min || V >= Hi ->'V > Hi-1'
2966 Hi = SubOne(cast<ConstantInt>(Hi));
2967 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
2968 ICmpInst::Predicate pred = (isSigned ?
2969 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
2970 return new ICmpInst(pred, V, Hi);
2973 // Emit V-Lo > Hi-1-Lo
2974 Constant *NegLo = ConstantExpr::getNeg(Lo);
2975 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
2976 InsertNewInstBefore(Add, IB);
2977 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
2978 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
2981 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2982 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
2983 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2984 // not, since all 1s are not contiguous.
2985 static bool isRunOfOnes(ConstantInt *Val, unsigned &MB, unsigned &ME) {
2986 uint64_t V = Val->getZExtValue();
2987 if (!isShiftedMask_64(V)) return false;
2989 // look for the first zero bit after the run of ones
2990 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2991 // look for the first non-zero bit
2992 ME = 64-CountLeadingZeros_64(V);
2998 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2999 /// where isSub determines whether the operator is a sub. If we can fold one of
3000 /// the following xforms:
3002 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3003 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3004 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3006 /// return (A +/- B).
3008 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3009 ConstantInt *Mask, bool isSub,
3011 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3012 if (!LHSI || LHSI->getNumOperands() != 2 ||
3013 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3015 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3017 switch (LHSI->getOpcode()) {
3019 case Instruction::And:
3020 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3021 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3022 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0)
3025 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3026 // part, we don't need any explicit masks to take them out of A. If that
3027 // is all N is, ignore it.
3029 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3030 uint64_t Mask = cast<IntegerType>(RHS->getType())->getBitMask();
3032 if (MaskedValueIsZero(RHS, Mask))
3037 case Instruction::Or:
3038 case Instruction::Xor:
3039 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3040 if ((Mask->getZExtValue() & Mask->getZExtValue()+1) == 0 &&
3041 ConstantExpr::getAnd(N, Mask)->isNullValue())
3048 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3050 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3051 return InsertNewInstBefore(New, I);
3054 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3055 bool Changed = SimplifyCommutative(I);
3056 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3058 if (isa<UndefValue>(Op1)) // X & undef -> 0
3059 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3063 return ReplaceInstUsesWith(I, Op1);
3065 // See if we can simplify any instructions used by the instruction whose sole
3066 // purpose is to compute bits we don't care about.
3067 uint64_t KnownZero, KnownOne;
3068 if (!isa<PackedType>(I.getType())) {
3069 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
3070 KnownZero, KnownOne))
3073 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Op1)) {
3074 if (CP->isAllOnesValue())
3075 return ReplaceInstUsesWith(I, I.getOperand(0));
3079 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3080 uint64_t AndRHSMask = AndRHS->getZExtValue();
3081 uint64_t TypeMask = cast<IntegerType>(Op0->getType())->getBitMask();
3082 uint64_t NotAndRHS = AndRHSMask^TypeMask;
3084 // Optimize a variety of ((val OP C1) & C2) combinations...
3085 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
3086 Instruction *Op0I = cast<Instruction>(Op0);
3087 Value *Op0LHS = Op0I->getOperand(0);
3088 Value *Op0RHS = Op0I->getOperand(1);
3089 switch (Op0I->getOpcode()) {
3090 case Instruction::Xor:
3091 case Instruction::Or:
3092 // If the mask is only needed on one incoming arm, push it up.
3093 if (Op0I->hasOneUse()) {
3094 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3095 // Not masking anything out for the LHS, move to RHS.
3096 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3097 Op0RHS->getName()+".masked");
3098 InsertNewInstBefore(NewRHS, I);
3099 return BinaryOperator::create(
3100 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3102 if (!isa<Constant>(Op0RHS) &&
3103 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3104 // Not masking anything out for the RHS, move to LHS.
3105 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3106 Op0LHS->getName()+".masked");
3107 InsertNewInstBefore(NewLHS, I);
3108 return BinaryOperator::create(
3109 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3114 case Instruction::Add:
3115 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3116 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3117 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3118 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3119 return BinaryOperator::createAnd(V, AndRHS);
3120 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3121 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
3124 case Instruction::Sub:
3125 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3126 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3127 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3128 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3129 return BinaryOperator::createAnd(V, AndRHS);
3133 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3134 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3136 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3137 // If this is an integer truncation or change from signed-to-unsigned, and
3138 // if the source is an and/or with immediate, transform it. This
3139 // frequently occurs for bitfield accesses.
3140 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3141 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3142 CastOp->getNumOperands() == 2)
3143 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3144 if (CastOp->getOpcode() == Instruction::And) {
3145 // Change: and (cast (and X, C1) to T), C2
3146 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3147 // This will fold the two constants together, which may allow
3148 // other simplifications.
3149 Instruction *NewCast = CastInst::createTruncOrBitCast(
3150 CastOp->getOperand(0), I.getType(),
3151 CastOp->getName()+".shrunk");
3152 NewCast = InsertNewInstBefore(NewCast, I);
3153 // trunc_or_bitcast(C1)&C2
3154 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3155 C3 = ConstantExpr::getAnd(C3, AndRHS);
3156 return BinaryOperator::createAnd(NewCast, C3);
3157 } else if (CastOp->getOpcode() == Instruction::Or) {
3158 // Change: and (cast (or X, C1) to T), C2
3159 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3160 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3161 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3162 return ReplaceInstUsesWith(I, AndRHS);
3167 // Try to fold constant and into select arguments.
3168 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3169 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3171 if (isa<PHINode>(Op0))
3172 if (Instruction *NV = FoldOpIntoPhi(I))
3176 Value *Op0NotVal = dyn_castNotVal(Op0);
3177 Value *Op1NotVal = dyn_castNotVal(Op1);
3179 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3180 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3182 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3183 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3184 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3185 I.getName()+".demorgan");
3186 InsertNewInstBefore(Or, I);
3187 return BinaryOperator::createNot(Or);
3191 Value *A = 0, *B = 0;
3192 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3193 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3194 return ReplaceInstUsesWith(I, Op1);
3195 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3196 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3197 return ReplaceInstUsesWith(I, Op0);
3199 if (Op0->hasOneUse() &&
3200 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3201 if (A == Op1) { // (A^B)&A -> A&(A^B)
3202 I.swapOperands(); // Simplify below
3203 std::swap(Op0, Op1);
3204 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3205 cast<BinaryOperator>(Op0)->swapOperands();
3206 I.swapOperands(); // Simplify below
3207 std::swap(Op0, Op1);
3210 if (Op1->hasOneUse() &&
3211 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3212 if (B == Op0) { // B&(A^B) -> B&(B^A)
3213 cast<BinaryOperator>(Op1)->swapOperands();
3216 if (A == Op0) { // A&(A^B) -> A & ~B
3217 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3218 InsertNewInstBefore(NotB, I);
3219 return BinaryOperator::createAnd(A, NotB);
3224 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3225 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3226 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3229 Value *LHSVal, *RHSVal;
3230 ConstantInt *LHSCst, *RHSCst;
3231 ICmpInst::Predicate LHSCC, RHSCC;
3232 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3233 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3234 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3235 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3236 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3237 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3238 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3239 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3240 // Ensure that the larger constant is on the RHS.
3241 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3242 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3243 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3244 ICmpInst *LHS = cast<ICmpInst>(Op0);
3245 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3246 std::swap(LHS, RHS);
3247 std::swap(LHSCst, RHSCst);
3248 std::swap(LHSCC, RHSCC);
3251 // At this point, we know we have have two icmp instructions
3252 // comparing a value against two constants and and'ing the result
3253 // together. Because of the above check, we know that we only have
3254 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3255 // (from the FoldICmpLogical check above), that the two constants
3256 // are not equal and that the larger constant is on the RHS
3257 assert(LHSCst != RHSCst && "Compares not folded above?");
3260 default: assert(0 && "Unknown integer condition code!");
3261 case ICmpInst::ICMP_EQ:
3263 default: assert(0 && "Unknown integer condition code!");
3264 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3265 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3266 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3267 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3268 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3269 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3270 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3271 return ReplaceInstUsesWith(I, LHS);
3273 case ICmpInst::ICMP_NE:
3275 default: assert(0 && "Unknown integer condition code!");
3276 case ICmpInst::ICMP_ULT:
3277 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3278 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3279 break; // (X != 13 & X u< 15) -> no change
3280 case ICmpInst::ICMP_SLT:
3281 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3282 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3283 break; // (X != 13 & X s< 15) -> no change
3284 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3285 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3286 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3287 return ReplaceInstUsesWith(I, RHS);
3288 case ICmpInst::ICMP_NE:
3289 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3290 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3291 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3292 LHSVal->getName()+".off");
3293 InsertNewInstBefore(Add, I);
3294 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3295 ConstantInt::get(Add->getType(), 1));
3297 break; // (X != 13 & X != 15) -> no change
3300 case ICmpInst::ICMP_ULT:
3302 default: assert(0 && "Unknown integer condition code!");
3303 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3304 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3305 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3306 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3308 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3309 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3310 return ReplaceInstUsesWith(I, LHS);
3311 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3315 case ICmpInst::ICMP_SLT:
3317 default: assert(0 && "Unknown integer condition code!");
3318 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3319 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3320 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3321 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3323 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3324 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3325 return ReplaceInstUsesWith(I, LHS);
3326 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3330 case ICmpInst::ICMP_UGT:
3332 default: assert(0 && "Unknown integer condition code!");
3333 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3334 return ReplaceInstUsesWith(I, LHS);
3335 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3336 return ReplaceInstUsesWith(I, RHS);
3337 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3339 case ICmpInst::ICMP_NE:
3340 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3341 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3342 break; // (X u> 13 & X != 15) -> no change
3343 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3344 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3346 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3350 case ICmpInst::ICMP_SGT:
3352 default: assert(0 && "Unknown integer condition code!");
3353 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3354 return ReplaceInstUsesWith(I, LHS);
3355 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3356 return ReplaceInstUsesWith(I, RHS);
3357 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3359 case ICmpInst::ICMP_NE:
3360 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3361 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3362 break; // (X s> 13 & X != 15) -> no change
3363 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3364 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3366 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3374 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3375 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3376 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3377 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3378 const Type *SrcTy = Op0C->getOperand(0)->getType();
3379 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3380 // Only do this if the casts both really cause code to be generated.
3381 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3383 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3385 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3386 Op1C->getOperand(0),
3388 InsertNewInstBefore(NewOp, I);
3389 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3393 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3394 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3395 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3396 if (SI0->getOpcode() == SI1->getOpcode() &&
3397 SI0->getOperand(1) == SI1->getOperand(1) &&
3398 (SI0->hasOneUse() || SI1->hasOneUse())) {
3399 Instruction *NewOp =
3400 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3402 SI0->getName()), I);
3403 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3407 return Changed ? &I : 0;
3410 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3411 /// in the result. If it does, and if the specified byte hasn't been filled in
3412 /// yet, fill it in and return false.
3413 static bool CollectBSwapParts(Value *V, std::vector<Value*> &ByteValues) {
3414 Instruction *I = dyn_cast<Instruction>(V);
3415 if (I == 0) return true;
3417 // If this is an or instruction, it is an inner node of the bswap.
3418 if (I->getOpcode() == Instruction::Or)
3419 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3420 CollectBSwapParts(I->getOperand(1), ByteValues);
3422 // If this is a shift by a constant int, and it is "24", then its operand
3423 // defines a byte. We only handle unsigned types here.
3424 if (isa<ShiftInst>(I) && isa<ConstantInt>(I->getOperand(1))) {
3425 // Not shifting the entire input by N-1 bytes?
3426 if (cast<ConstantInt>(I->getOperand(1))->getZExtValue() !=
3427 8*(ByteValues.size()-1))
3431 if (I->getOpcode() == Instruction::Shl) {
3432 // X << 24 defines the top byte with the lowest of the input bytes.
3433 DestNo = ByteValues.size()-1;
3435 // X >>u 24 defines the low byte with the highest of the input bytes.
3439 // If the destination byte value is already defined, the values are or'd
3440 // together, which isn't a bswap (unless it's an or of the same bits).
3441 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3443 ByteValues[DestNo] = I->getOperand(0);
3447 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3449 Value *Shift = 0, *ShiftLHS = 0;
3450 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3451 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3452 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3454 Instruction *SI = cast<Instruction>(Shift);
3456 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3457 if (ShiftAmt->getZExtValue() & 7 ||
3458 ShiftAmt->getZExtValue() > 8*ByteValues.size())
3461 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3463 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3464 if (AndAmt->getZExtValue() == uint64_t(0xFF) << 8*DestByte)
3466 // Unknown mask for bswap.
3467 if (DestByte == ByteValues.size()) return true;
3469 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3471 if (SI->getOpcode() == Instruction::Shl)
3472 SrcByte = DestByte - ShiftBytes;
3474 SrcByte = DestByte + ShiftBytes;
3476 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3477 if (SrcByte != ByteValues.size()-DestByte-1)
3480 // If the destination byte value is already defined, the values are or'd
3481 // together, which isn't a bswap (unless it's an or of the same bits).
3482 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3484 ByteValues[DestByte] = SI->getOperand(0);
3488 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3489 /// If so, insert the new bswap intrinsic and return it.
3490 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3491 // We can only handle bswap of unsigned integers, and cannot bswap one byte.
3492 if (I.getType() == Type::Int8Ty)
3495 /// ByteValues - For each byte of the result, we keep track of which value
3496 /// defines each byte.
3497 std::vector<Value*> ByteValues;
3498 ByteValues.resize(TD->getTypeSize(I.getType()));
3500 // Try to find all the pieces corresponding to the bswap.
3501 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3502 CollectBSwapParts(I.getOperand(1), ByteValues))
3505 // Check to see if all of the bytes come from the same value.
3506 Value *V = ByteValues[0];
3507 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3509 // Check to make sure that all of the bytes come from the same value.
3510 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3511 if (ByteValues[i] != V)
3514 // If they do then *success* we can turn this into a bswap. Figure out what
3515 // bswap to make it into.
3516 Module *M = I.getParent()->getParent()->getParent();
3517 const char *FnName = 0;
3518 if (I.getType() == Type::Int16Ty)
3519 FnName = "llvm.bswap.i16";
3520 else if (I.getType() == Type::Int32Ty)
3521 FnName = "llvm.bswap.i32";
3522 else if (I.getType() == Type::Int64Ty)
3523 FnName = "llvm.bswap.i64";
3525 assert(0 && "Unknown integer type!");
3526 Constant *F = M->getOrInsertFunction(FnName, I.getType(), I.getType(), NULL);
3527 return new CallInst(F, V);
3531 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3532 bool Changed = SimplifyCommutative(I);
3533 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3535 if (isa<UndefValue>(Op1))
3536 return ReplaceInstUsesWith(I, // X | undef -> -1
3537 ConstantInt::getAllOnesValue(I.getType()));
3541 return ReplaceInstUsesWith(I, Op0);
3543 // See if we can simplify any instructions used by the instruction whose sole
3544 // purpose is to compute bits we don't care about.
3545 uint64_t KnownZero, KnownOne;
3546 if (!isa<PackedType>(I.getType()) &&
3547 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
3548 KnownZero, KnownOne))
3552 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3553 ConstantInt *C1 = 0; Value *X = 0;
3554 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3555 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3556 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
3558 InsertNewInstBefore(Or, I);
3559 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
3562 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3563 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3564 std::string Op0Name = Op0->getName(); Op0->setName("");
3565 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
3566 InsertNewInstBefore(Or, I);
3567 return BinaryOperator::createXor(Or,
3568 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
3571 // Try to fold constant and into select arguments.
3572 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3573 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3575 if (isa<PHINode>(Op0))
3576 if (Instruction *NV = FoldOpIntoPhi(I))
3580 Value *A = 0, *B = 0;
3581 ConstantInt *C1 = 0, *C2 = 0;
3583 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3584 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3585 return ReplaceInstUsesWith(I, Op1);
3586 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3587 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3588 return ReplaceInstUsesWith(I, Op0);
3590 // (A | B) | C and A | (B | C) -> bswap if possible.
3591 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
3592 if (match(Op0, m_Or(m_Value(), m_Value())) ||
3593 match(Op1, m_Or(m_Value(), m_Value())) ||
3594 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3595 match(Op1, m_Shift(m_Value(), m_Value())))) {
3596 if (Instruction *BSwap = MatchBSwap(I))
3600 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3601 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3602 MaskedValueIsZero(Op1, C1->getZExtValue())) {
3603 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
3605 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3608 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3609 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3610 MaskedValueIsZero(Op0, C1->getZExtValue())) {
3611 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
3613 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
3616 // (A & C1)|(B & C2)
3617 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
3618 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
3620 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
3621 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
3624 // If we have: ((V + N) & C1) | (V & C2)
3625 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3626 // replace with V+N.
3627 if (C1 == ConstantExpr::getNot(C2)) {
3628 Value *V1 = 0, *V2 = 0;
3629 if ((C2->getZExtValue() & (C2->getZExtValue()+1)) == 0 && // C2 == 0+1+
3630 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3631 // Add commutes, try both ways.
3632 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
3633 return ReplaceInstUsesWith(I, A);
3634 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
3635 return ReplaceInstUsesWith(I, A);
3637 // Or commutes, try both ways.
3638 if ((C1->getZExtValue() & (C1->getZExtValue()+1)) == 0 &&
3639 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3640 // Add commutes, try both ways.
3641 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
3642 return ReplaceInstUsesWith(I, B);
3643 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
3644 return ReplaceInstUsesWith(I, B);
3649 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3650 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
3651 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
3652 if (SI0->getOpcode() == SI1->getOpcode() &&
3653 SI0->getOperand(1) == SI1->getOperand(1) &&
3654 (SI0->hasOneUse() || SI1->hasOneUse())) {
3655 Instruction *NewOp =
3656 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3658 SI0->getName()), I);
3659 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
3663 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3664 if (A == Op1) // ~A | A == -1
3665 return ReplaceInstUsesWith(I,
3666 ConstantInt::getAllOnesValue(I.getType()));
3670 // Note, A is still live here!
3671 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3673 return ReplaceInstUsesWith(I,
3674 ConstantInt::getAllOnesValue(I.getType()));
3676 // (~A | ~B) == (~(A & B)) - De Morgan's Law
3677 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3678 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3679 I.getName()+".demorgan"), I);
3680 return BinaryOperator::createNot(And);
3684 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3685 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3686 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3689 Value *LHSVal, *RHSVal;
3690 ConstantInt *LHSCst, *RHSCst;
3691 ICmpInst::Predicate LHSCC, RHSCC;
3692 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3693 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3694 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3695 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3696 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3697 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3698 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3699 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3700 // Ensure that the larger constant is on the RHS.
3701 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3702 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3703 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3704 ICmpInst *LHS = cast<ICmpInst>(Op0);
3705 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3706 std::swap(LHS, RHS);
3707 std::swap(LHSCst, RHSCst);
3708 std::swap(LHSCC, RHSCC);
3711 // At this point, we know we have have two icmp instructions
3712 // comparing a value against two constants and or'ing the result
3713 // together. Because of the above check, we know that we only have
3714 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3715 // FoldICmpLogical check above), that the two constants are not
3717 assert(LHSCst != RHSCst && "Compares not folded above?");
3720 default: assert(0 && "Unknown integer condition code!");
3721 case ICmpInst::ICMP_EQ:
3723 default: assert(0 && "Unknown integer condition code!");
3724 case ICmpInst::ICMP_EQ:
3725 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3726 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3727 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3728 LHSVal->getName()+".off");
3729 InsertNewInstBefore(Add, I);
3730 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
3731 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
3733 break; // (X == 13 | X == 15) -> no change
3734 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3735 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
3737 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3738 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3739 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
3740 return ReplaceInstUsesWith(I, RHS);
3743 case ICmpInst::ICMP_NE:
3745 default: assert(0 && "Unknown integer condition code!");
3746 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3747 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3748 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
3749 return ReplaceInstUsesWith(I, LHS);
3750 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3751 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3752 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
3753 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3756 case ICmpInst::ICMP_ULT:
3758 default: assert(0 && "Unknown integer condition code!");
3759 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
3761 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3762 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3764 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3766 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3767 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
3768 return ReplaceInstUsesWith(I, RHS);
3769 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3773 case ICmpInst::ICMP_SLT:
3775 default: assert(0 && "Unknown integer condition code!");
3776 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3778 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3779 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
3781 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
3783 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
3784 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
3785 return ReplaceInstUsesWith(I, RHS);
3786 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
3790 case ICmpInst::ICMP_UGT:
3792 default: assert(0 && "Unknown integer condition code!");
3793 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
3794 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
3795 return ReplaceInstUsesWith(I, LHS);
3796 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
3798 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
3799 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
3800 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3801 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
3805 case ICmpInst::ICMP_SGT:
3807 default: assert(0 && "Unknown integer condition code!");
3808 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
3809 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
3810 return ReplaceInstUsesWith(I, LHS);
3811 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
3813 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
3814 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
3815 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3816 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
3824 // fold (or (cast A), (cast B)) -> (cast (or A, B))
3825 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3826 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3827 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
3828 const Type *SrcTy = Op0C->getOperand(0)->getType();
3829 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3830 // Only do this if the casts both really cause code to be generated.
3831 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3833 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3835 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
3836 Op1C->getOperand(0),
3838 InsertNewInstBefore(NewOp, I);
3839 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3844 return Changed ? &I : 0;
3847 // XorSelf - Implements: X ^ X --> 0
3850 XorSelf(Value *rhs) : RHS(rhs) {}
3851 bool shouldApply(Value *LHS) const { return LHS == RHS; }
3852 Instruction *apply(BinaryOperator &Xor) const {
3858 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
3859 bool Changed = SimplifyCommutative(I);
3860 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3862 if (isa<UndefValue>(Op1))
3863 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
3865 // xor X, X = 0, even if X is nested in a sequence of Xor's.
3866 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
3867 assert(Result == &I && "AssociativeOpt didn't work?");
3868 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3871 // See if we can simplify any instructions used by the instruction whose sole
3872 // purpose is to compute bits we don't care about.
3873 uint64_t KnownZero, KnownOne;
3874 if (!isa<PackedType>(I.getType()) &&
3875 SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
3876 KnownZero, KnownOne))
3879 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3880 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
3881 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
3882 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
3883 return new ICmpInst(ICI->getInversePredicate(),
3884 ICI->getOperand(0), ICI->getOperand(1));
3886 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3887 // ~(c-X) == X-c-1 == X+(-c-1)
3888 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
3889 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
3890 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
3891 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
3892 ConstantInt::get(I.getType(), 1));
3893 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
3896 // ~(~X & Y) --> (X | ~Y)
3897 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
3898 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
3899 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
3901 BinaryOperator::createNot(Op0I->getOperand(1),
3902 Op0I->getOperand(1)->getName()+".not");
3903 InsertNewInstBefore(NotY, I);
3904 return BinaryOperator::createOr(Op0NotVal, NotY);
3908 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3909 if (Op0I->getOpcode() == Instruction::Add) {
3910 // ~(X-c) --> (-c-1)-X
3911 if (RHS->isAllOnesValue()) {
3912 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
3913 return BinaryOperator::createSub(
3914 ConstantExpr::getSub(NegOp0CI,
3915 ConstantInt::get(I.getType(), 1)),
3916 Op0I->getOperand(0));
3918 } else if (Op0I->getOpcode() == Instruction::Or) {
3919 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
3920 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
3921 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
3922 // Anything in both C1 and C2 is known to be zero, remove it from
3924 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
3925 NewRHS = ConstantExpr::getAnd(NewRHS,
3926 ConstantExpr::getNot(CommonBits));
3927 WorkList.push_back(Op0I);
3928 I.setOperand(0, Op0I->getOperand(0));
3929 I.setOperand(1, NewRHS);
3935 // Try to fold constant and into select arguments.
3936 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3937 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3939 if (isa<PHINode>(Op0))
3940 if (Instruction *NV = FoldOpIntoPhi(I))
3944 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
3946 return ReplaceInstUsesWith(I,
3947 ConstantInt::getAllOnesValue(I.getType()));
3949 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
3951 return ReplaceInstUsesWith(I,
3952 ConstantInt::getAllOnesValue(I.getType()));
3954 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
3955 if (Op1I->getOpcode() == Instruction::Or) {
3956 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
3957 Op1I->swapOperands();
3959 std::swap(Op0, Op1);
3960 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
3961 I.swapOperands(); // Simplified below.
3962 std::swap(Op0, Op1);
3964 } else if (Op1I->getOpcode() == Instruction::Xor) {
3965 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
3966 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
3967 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
3968 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
3969 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
3970 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
3971 Op1I->swapOperands();
3972 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
3973 I.swapOperands(); // Simplified below.
3974 std::swap(Op0, Op1);
3978 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3979 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
3980 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
3981 Op0I->swapOperands();
3982 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
3983 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3984 InsertNewInstBefore(NotB, I);
3985 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
3987 } else if (Op0I->getOpcode() == Instruction::Xor) {
3988 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3989 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3990 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3991 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3992 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3993 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3994 Op0I->swapOperands();
3995 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3996 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
3997 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3998 InsertNewInstBefore(N, I);
3999 return BinaryOperator::createAnd(N, Op1);
4003 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4004 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4005 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4008 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4009 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4010 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4011 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4012 const Type *SrcTy = Op0C->getOperand(0)->getType();
4013 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4014 // Only do this if the casts both really cause code to be generated.
4015 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4017 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4019 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4020 Op1C->getOperand(0),
4022 InsertNewInstBefore(NewOp, I);
4023 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4027 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4028 if (ShiftInst *SI1 = dyn_cast<ShiftInst>(Op1)) {
4029 if (ShiftInst *SI0 = dyn_cast<ShiftInst>(Op0))
4030 if (SI0->getOpcode() == SI1->getOpcode() &&
4031 SI0->getOperand(1) == SI1->getOperand(1) &&
4032 (SI0->hasOneUse() || SI1->hasOneUse())) {
4033 Instruction *NewOp =
4034 InsertNewInstBefore(BinaryOperator::createXor(SI0->getOperand(0),
4036 SI0->getName()), I);
4037 return new ShiftInst(SI1->getOpcode(), NewOp, SI1->getOperand(1));
4041 return Changed ? &I : 0;
4044 static bool isPositive(ConstantInt *C) {
4045 return C->getSExtValue() >= 0;
4048 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4049 /// overflowed for this type.
4050 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4052 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
4054 return cast<ConstantInt>(Result)->getZExtValue() <
4055 cast<ConstantInt>(In1)->getZExtValue();
4058 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4059 /// code necessary to compute the offset from the base pointer (without adding
4060 /// in the base pointer). Return the result as a signed integer of intptr size.
4061 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4062 TargetData &TD = IC.getTargetData();
4063 gep_type_iterator GTI = gep_type_begin(GEP);
4064 const Type *IntPtrTy = TD.getIntPtrType();
4065 Value *Result = Constant::getNullValue(IntPtrTy);
4067 // Build a mask for high order bits.
4068 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
4070 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4071 Value *Op = GEP->getOperand(i);
4072 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
4073 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4074 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4075 if (!OpC->isNullValue()) {
4076 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4077 Scale = ConstantExpr::getMul(OpC, Scale);
4078 if (Constant *RC = dyn_cast<Constant>(Result))
4079 Result = ConstantExpr::getAdd(RC, Scale);
4081 // Emit an add instruction.
4082 Result = IC.InsertNewInstBefore(
4083 BinaryOperator::createAdd(Result, Scale,
4084 GEP->getName()+".offs"), I);
4088 // Convert to correct type.
4089 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
4090 Op->getName()+".c"), I);
4092 // We'll let instcombine(mul) convert this to a shl if possible.
4093 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4094 GEP->getName()+".idx"), I);
4096 // Emit an add instruction.
4097 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4098 GEP->getName()+".offs"), I);
4104 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4105 /// else. At this point we know that the GEP is on the LHS of the comparison.
4106 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4107 ICmpInst::Predicate Cond,
4109 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4111 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4112 if (isa<PointerType>(CI->getOperand(0)->getType()))
4113 RHS = CI->getOperand(0);
4115 Value *PtrBase = GEPLHS->getOperand(0);
4116 if (PtrBase == RHS) {
4117 // As an optimization, we don't actually have to compute the actual value of
4118 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4119 // each index is zero or not.
4120 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4121 Instruction *InVal = 0;
4122 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4123 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4125 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4126 if (isa<UndefValue>(C)) // undef index -> undef.
4127 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4128 if (C->isNullValue())
4130 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4131 EmitIt = false; // This is indexing into a zero sized array?
4132 } else if (isa<ConstantInt>(C))
4133 return ReplaceInstUsesWith(I, // No comparison is needed here.
4134 ConstantInt::get(Type::Int1Ty,
4135 Cond == ICmpInst::ICMP_NE));
4140 new ICmpInst(Cond, GEPLHS->getOperand(i),
4141 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4145 InVal = InsertNewInstBefore(InVal, I);
4146 InsertNewInstBefore(Comp, I);
4147 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
4148 InVal = BinaryOperator::createOr(InVal, Comp);
4149 else // True if all are equal
4150 InVal = BinaryOperator::createAnd(InVal, Comp);
4158 // No comparison is needed here, all indexes = 0
4159 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4160 Cond == ICmpInst::ICMP_EQ));
4163 // Only lower this if the icmp is the only user of the GEP or if we expect
4164 // the result to fold to a constant!
4165 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4166 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4167 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4168 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4169 Constant::getNullValue(Offset->getType()));
4171 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4172 // If the base pointers are different, but the indices are the same, just
4173 // compare the base pointer.
4174 if (PtrBase != GEPRHS->getOperand(0)) {
4175 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4176 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4177 GEPRHS->getOperand(0)->getType();
4179 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4180 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4181 IndicesTheSame = false;
4185 // If all indices are the same, just compare the base pointers.
4187 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4188 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4190 // Otherwise, the base pointers are different and the indices are
4191 // different, bail out.
4195 // If one of the GEPs has all zero indices, recurse.
4196 bool AllZeros = true;
4197 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4198 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4199 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4204 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4205 ICmpInst::getSwappedPredicate(Cond), I);
4207 // If the other GEP has all zero indices, recurse.
4209 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4210 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4211 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4216 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4218 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4219 // If the GEPs only differ by one index, compare it.
4220 unsigned NumDifferences = 0; // Keep track of # differences.
4221 unsigned DiffOperand = 0; // The operand that differs.
4222 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4223 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4224 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4225 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4226 // Irreconcilable differences.
4230 if (NumDifferences++) break;
4235 if (NumDifferences == 0) // SAME GEP?
4236 return ReplaceInstUsesWith(I, // No comparison is needed here.
4237 ConstantInt::get(Type::Int1Ty,
4238 Cond == ICmpInst::ICMP_EQ));
4239 else if (NumDifferences == 1) {
4240 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4241 Value *RHSV = GEPRHS->getOperand(DiffOperand);
4242 // Make sure we do a signed comparison here.
4243 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4247 // Only lower this if the icmp is the only user of the GEP or if we expect
4248 // the result to fold to a constant!
4249 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4250 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4251 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4252 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4253 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4254 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4260 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4261 bool Changed = SimplifyCompare(I);
4262 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4264 // Fold trivial predicates.
4265 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4266 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4267 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4268 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4270 // Simplify 'fcmp pred X, X'
4272 switch (I.getPredicate()) {
4273 default: assert(0 && "Unknown predicate!");
4274 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4275 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4276 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4277 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4278 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4279 case FCmpInst::FCMP_OLT: // True if ordered and less than
4280 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4281 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4283 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4284 case FCmpInst::FCMP_ULT: // True if unordered or less than
4285 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4286 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4287 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4288 I.setPredicate(FCmpInst::FCMP_UNO);
4289 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4292 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4293 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4294 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4295 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4296 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4297 I.setPredicate(FCmpInst::FCMP_ORD);
4298 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4303 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
4304 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4306 // Handle fcmp with constant RHS
4307 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4308 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4309 switch (LHSI->getOpcode()) {
4310 case Instruction::PHI:
4311 if (Instruction *NV = FoldOpIntoPhi(I))
4314 case Instruction::Select:
4315 // If either operand of the select is a constant, we can fold the
4316 // comparison into the select arms, which will cause one to be
4317 // constant folded and the select turned into a bitwise or.
4318 Value *Op1 = 0, *Op2 = 0;
4319 if (LHSI->hasOneUse()) {
4320 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4321 // Fold the known value into the constant operand.
4322 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4323 // Insert a new FCmp of the other select operand.
4324 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4325 LHSI->getOperand(2), RHSC,
4327 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4328 // Fold the known value into the constant operand.
4329 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4330 // Insert a new FCmp of the other select operand.
4331 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4332 LHSI->getOperand(1), RHSC,
4338 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4343 return Changed ? &I : 0;
4346 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4347 bool Changed = SimplifyCompare(I);
4348 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4349 const Type *Ty = Op0->getType();
4353 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4354 isTrueWhenEqual(I)));
4356 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
4357 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4359 // icmp of GlobalValues can never equal each other as long as they aren't
4360 // external weak linkage type.
4361 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4362 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4363 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
4364 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4365 !isTrueWhenEqual(I)));
4367 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4368 // addresses never equal each other! We already know that Op0 != Op1.
4369 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4370 isa<ConstantPointerNull>(Op0)) &&
4371 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4372 isa<ConstantPointerNull>(Op1)))
4373 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4374 !isTrueWhenEqual(I)));
4376 // icmp's with boolean values can always be turned into bitwise operations
4377 if (Ty == Type::Int1Ty) {
4378 switch (I.getPredicate()) {
4379 default: assert(0 && "Invalid icmp instruction!");
4380 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
4381 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4382 InsertNewInstBefore(Xor, I);
4383 return BinaryOperator::createNot(Xor);
4385 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
4386 return BinaryOperator::createXor(Op0, Op1);
4388 case ICmpInst::ICMP_UGT:
4389 case ICmpInst::ICMP_SGT:
4390 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
4392 case ICmpInst::ICMP_ULT:
4393 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
4394 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4395 InsertNewInstBefore(Not, I);
4396 return BinaryOperator::createAnd(Not, Op1);
4398 case ICmpInst::ICMP_UGE:
4399 case ICmpInst::ICMP_SGE:
4400 std::swap(Op0, Op1); // Change icmp ge -> icmp le
4402 case ICmpInst::ICMP_ULE:
4403 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
4404 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4405 InsertNewInstBefore(Not, I);
4406 return BinaryOperator::createOr(Not, Op1);
4411 // See if we are doing a comparison between a constant and an instruction that
4412 // can be folded into the comparison.
4413 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4414 switch (I.getPredicate()) {
4416 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4417 if (CI->isMinValue(false))
4418 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4419 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4420 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4421 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4422 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4425 case ICmpInst::ICMP_SLT:
4426 if (CI->isMinValue(true)) // A <s MIN -> FALSE
4427 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4428 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4429 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4430 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4431 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4434 case ICmpInst::ICMP_UGT:
4435 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
4436 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4437 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4438 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4439 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4440 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4443 case ICmpInst::ICMP_SGT:
4444 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
4445 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4446 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4447 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4448 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4449 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4452 case ICmpInst::ICMP_ULE:
4453 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
4454 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4455 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4456 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4457 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4458 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4461 case ICmpInst::ICMP_SLE:
4462 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
4463 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4464 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4465 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4466 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4467 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4470 case ICmpInst::ICMP_UGE:
4471 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
4472 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4473 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4474 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4475 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4476 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4479 case ICmpInst::ICMP_SGE:
4480 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
4481 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4482 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4483 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4484 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4485 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4489 // If we still have a icmp le or icmp ge instruction, turn it into the
4490 // appropriate icmp lt or icmp gt instruction. Since the border cases have
4491 // already been handled above, this requires little checking.
4493 if (I.getPredicate() == ICmpInst::ICMP_ULE)
4494 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4495 if (I.getPredicate() == ICmpInst::ICMP_SLE)
4496 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4497 if (I.getPredicate() == ICmpInst::ICMP_UGE)
4498 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4499 if (I.getPredicate() == ICmpInst::ICMP_SGE)
4500 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4502 // See if we can fold the comparison based on bits known to be zero or one
4504 uint64_t KnownZero, KnownOne;
4505 if (SimplifyDemandedBits(Op0, cast<IntegerType>(Ty)->getBitMask(),
4506 KnownZero, KnownOne, 0))
4509 // Given the known and unknown bits, compute a range that the LHS could be
4511 if (KnownOne | KnownZero) {
4512 // Compute the Min, Max and RHS values based on the known bits. For the
4513 // EQ and NE we use unsigned values.
4514 uint64_t UMin = 0, UMax = 0, URHSVal = 0;
4515 int64_t SMin = 0, SMax = 0, SRHSVal = 0;
4516 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4517 SRHSVal = CI->getSExtValue();
4518 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, SMin,
4521 URHSVal = CI->getZExtValue();
4522 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, UMin,
4525 switch (I.getPredicate()) { // LE/GE have been folded already.
4526 default: assert(0 && "Unknown icmp opcode!");
4527 case ICmpInst::ICMP_EQ:
4528 if (UMax < URHSVal || UMin > URHSVal)
4529 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4531 case ICmpInst::ICMP_NE:
4532 if (UMax < URHSVal || UMin > URHSVal)
4533 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4535 case ICmpInst::ICMP_ULT:
4537 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4539 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4541 case ICmpInst::ICMP_UGT:
4543 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4545 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4547 case ICmpInst::ICMP_SLT:
4549 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4551 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4553 case ICmpInst::ICMP_SGT:
4555 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4557 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4562 // Since the RHS is a ConstantInt (CI), if the left hand side is an
4563 // instruction, see if that instruction also has constants so that the
4564 // instruction can be folded into the icmp
4565 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4566 switch (LHSI->getOpcode()) {
4567 case Instruction::And:
4568 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
4569 LHSI->getOperand(0)->hasOneUse()) {
4570 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
4572 // If the LHS is an AND of a truncating cast, we can widen the
4573 // and/compare to be the input width without changing the value
4574 // produced, eliminating a cast.
4575 if (CastInst *Cast = dyn_cast<CastInst>(LHSI->getOperand(0))) {
4576 // We can do this transformation if either the AND constant does not
4577 // have its sign bit set or if it is an equality comparison.
4578 // Extending a relational comparison when we're checking the sign
4579 // bit would not work.
4580 if (Cast->hasOneUse() && isa<TruncInst>(Cast) &&
4582 (AndCST->getZExtValue() == (uint64_t)AndCST->getSExtValue()) &&
4583 (CI->getZExtValue() == (uint64_t)CI->getSExtValue()))) {
4584 ConstantInt *NewCST;
4586 NewCST = ConstantInt::get(Cast->getOperand(0)->getType(),
4587 AndCST->getZExtValue());
4588 NewCI = ConstantInt::get(Cast->getOperand(0)->getType(),
4589 CI->getZExtValue());
4590 Instruction *NewAnd =
4591 BinaryOperator::createAnd(Cast->getOperand(0), NewCST,
4593 InsertNewInstBefore(NewAnd, I);
4594 return new ICmpInst(I.getPredicate(), NewAnd, NewCI);
4598 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
4599 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
4600 // happens a LOT in code produced by the C front-end, for bitfield
4602 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
4604 // Check to see if there is a noop-cast between the shift and the and.
4606 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
4607 if (CI->getOpcode() == Instruction::BitCast)
4608 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
4612 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
4613 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
4614 const Type *AndTy = AndCST->getType(); // Type of the and.
4616 // We can fold this as long as we can't shift unknown bits
4617 // into the mask. This can only happen with signed shift
4618 // rights, as they sign-extend.
4620 bool CanFold = Shift->isLogicalShift();
4622 // To test for the bad case of the signed shr, see if any
4623 // of the bits shifted in could be tested after the mask.
4624 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getZExtValue();
4625 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
4627 Constant *OShAmt = ConstantInt::get(Type::Int8Ty, ShAmtVal);
4629 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
4631 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
4637 if (Shift->getOpcode() == Instruction::Shl)
4638 NewCst = ConstantExpr::getLShr(CI, ShAmt);
4640 NewCst = ConstantExpr::getShl(CI, ShAmt);
4642 // Check to see if we are shifting out any of the bits being
4644 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
4645 // If we shifted bits out, the fold is not going to work out.
4646 // As a special case, check to see if this means that the
4647 // result is always true or false now.
4648 if (I.getPredicate() == ICmpInst::ICMP_EQ)
4649 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4650 if (I.getPredicate() == ICmpInst::ICMP_NE)
4651 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4653 I.setOperand(1, NewCst);
4654 Constant *NewAndCST;
4655 if (Shift->getOpcode() == Instruction::Shl)
4656 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
4658 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
4659 LHSI->setOperand(1, NewAndCST);
4660 LHSI->setOperand(0, Shift->getOperand(0));
4661 WorkList.push_back(Shift); // Shift is dead.
4662 AddUsesToWorkList(I);
4668 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
4669 // preferable because it allows the C<<Y expression to be hoisted out
4670 // of a loop if Y is invariant and X is not.
4671 if (Shift && Shift->hasOneUse() && CI->isNullValue() &&
4672 I.isEquality() && !Shift->isArithmeticShift() &&
4673 isa<Instruction>(Shift->getOperand(0))) {
4676 if (Shift->getOpcode() == Instruction::LShr) {
4677 NS = new ShiftInst(Instruction::Shl, AndCST, Shift->getOperand(1),
4680 // Insert a logical shift.
4681 NS = new ShiftInst(Instruction::LShr, AndCST,
4682 Shift->getOperand(1), "tmp");
4684 InsertNewInstBefore(cast<Instruction>(NS), I);
4686 // Compute X & (C << Y).
4687 Instruction *NewAnd = BinaryOperator::createAnd(
4688 Shift->getOperand(0), NS, LHSI->getName());
4689 InsertNewInstBefore(NewAnd, I);
4691 I.setOperand(0, NewAnd);
4697 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
4698 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4699 if (I.isEquality()) {
4700 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4702 // Check that the shift amount is in range. If not, don't perform
4703 // undefined shifts. When the shift is visited it will be
4705 if (ShAmt->getZExtValue() >= TypeBits)
4708 // If we are comparing against bits always shifted out, the
4709 // comparison cannot succeed.
4711 ConstantExpr::getShl(ConstantExpr::getLShr(CI, ShAmt), ShAmt);
4712 if (Comp != CI) {// Comparing against a bit that we know is zero.
4713 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4714 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
4715 return ReplaceInstUsesWith(I, Cst);
4718 if (LHSI->hasOneUse()) {
4719 // Otherwise strength reduce the shift into an and.
4720 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4721 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
4722 Constant *Mask = ConstantInt::get(CI->getType(), Val);
4725 BinaryOperator::createAnd(LHSI->getOperand(0),
4726 Mask, LHSI->getName()+".mask");
4727 Value *And = InsertNewInstBefore(AndI, I);
4728 return new ICmpInst(I.getPredicate(), And,
4729 ConstantExpr::getLShr(CI, ShAmt));
4735 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
4736 case Instruction::AShr:
4737 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4738 if (I.isEquality()) {
4739 // Check that the shift amount is in range. If not, don't perform
4740 // undefined shifts. When the shift is visited it will be
4742 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
4743 if (ShAmt->getZExtValue() >= TypeBits)
4746 // If we are comparing against bits always shifted out, the
4747 // comparison cannot succeed.
4749 if (LHSI->getOpcode() == Instruction::LShr)
4750 Comp = ConstantExpr::getLShr(ConstantExpr::getShl(CI, ShAmt),
4753 Comp = ConstantExpr::getAShr(ConstantExpr::getShl(CI, ShAmt),
4756 if (Comp != CI) {// Comparing against a bit that we know is zero.
4757 bool IsICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4758 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
4759 return ReplaceInstUsesWith(I, Cst);
4762 if (LHSI->hasOneUse() || CI->isNullValue()) {
4763 unsigned ShAmtVal = (unsigned)ShAmt->getZExtValue();
4765 // Otherwise strength reduce the shift into an and.
4766 uint64_t Val = ~0ULL; // All ones.
4767 Val <<= ShAmtVal; // Shift over to the right spot.
4768 Val &= ~0ULL >> (64-TypeBits);
4769 Constant *Mask = ConstantInt::get(CI->getType(), Val);
4772 BinaryOperator::createAnd(LHSI->getOperand(0),
4773 Mask, LHSI->getName()+".mask");
4774 Value *And = InsertNewInstBefore(AndI, I);
4775 return new ICmpInst(I.getPredicate(), And,
4776 ConstantExpr::getShl(CI, ShAmt));
4782 case Instruction::SDiv:
4783 case Instruction::UDiv:
4784 // Fold: icmp pred ([us]div X, C1), C2 -> range test
4785 // Fold this div into the comparison, producing a range check.
4786 // Determine, based on the divide type, what the range is being
4787 // checked. If there is an overflow on the low or high side, remember
4788 // it, otherwise compute the range [low, hi) bounding the new value.
4789 // See: InsertRangeTest above for the kinds of replacements possible.
4790 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
4791 // FIXME: If the operand types don't match the type of the divide
4792 // then don't attempt this transform. The code below doesn't have the
4793 // logic to deal with a signed divide and an unsigned compare (and
4794 // vice versa). This is because (x /s C1) <s C2 produces different
4795 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
4796 // (x /u C1) <u C2. Simply casting the operands and result won't
4797 // work. :( The if statement below tests that condition and bails
4799 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
4800 if (!I.isEquality() && DivIsSigned != I.isSignedPredicate())
4803 // Initialize the variables that will indicate the nature of the
4805 bool LoOverflow = false, HiOverflow = false;
4806 ConstantInt *LoBound = 0, *HiBound = 0;
4808 // Compute Prod = CI * DivRHS. We are essentially solving an equation
4809 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
4810 // C2 (CI). By solving for X we can turn this into a range check
4811 // instead of computing a divide.
4813 cast<ConstantInt>(ConstantExpr::getMul(CI, DivRHS));
4815 // Determine if the product overflows by seeing if the product is
4816 // not equal to the divide. Make sure we do the same kind of divide
4817 // as in the LHS instruction that we're folding.
4818 bool ProdOV = !DivRHS->isNullValue() &&
4819 (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
4820 ConstantExpr::getUDiv(Prod, DivRHS)) != CI;
4822 // Get the ICmp opcode
4823 ICmpInst::Predicate predicate = I.getPredicate();
4825 if (DivRHS->isNullValue()) {
4826 // Don't hack on divide by zeros!
4827 } else if (!DivIsSigned) { // udiv
4829 LoOverflow = ProdOV;
4830 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
4831 } else if (isPositive(DivRHS)) { // Divisor is > 0.
4832 if (CI->isNullValue()) { // (X / pos) op 0
4834 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
4836 } else if (isPositive(CI)) { // (X / pos) op pos
4838 LoOverflow = ProdOV;
4839 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
4840 } else { // (X / pos) op neg
4841 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
4842 LoOverflow = AddWithOverflow(LoBound, Prod,
4843 cast<ConstantInt>(DivRHSH));
4845 HiOverflow = ProdOV;
4847 } else { // Divisor is < 0.
4848 if (CI->isNullValue()) { // (X / neg) op 0
4849 LoBound = AddOne(DivRHS);
4850 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
4851 if (HiBound == DivRHS)
4852 LoBound = 0; // - INTMIN = INTMIN
4853 } else if (isPositive(CI)) { // (X / neg) op pos
4854 HiOverflow = LoOverflow = ProdOV;
4856 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
4857 HiBound = AddOne(Prod);
4858 } else { // (X / neg) op neg
4860 LoOverflow = HiOverflow = ProdOV;
4861 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
4864 // Dividing by a negate swaps the condition.
4865 predicate = ICmpInst::getSwappedPredicate(predicate);
4869 Value *X = LHSI->getOperand(0);
4870 switch (predicate) {
4871 default: assert(0 && "Unhandled icmp opcode!");
4872 case ICmpInst::ICMP_EQ:
4873 if (LoOverflow && HiOverflow)
4874 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4875 else if (HiOverflow)
4876 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4877 ICmpInst::ICMP_UGE, X, LoBound);
4878 else if (LoOverflow)
4879 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4880 ICmpInst::ICMP_ULT, X, HiBound);
4882 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4884 case ICmpInst::ICMP_NE:
4885 if (LoOverflow && HiOverflow)
4886 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4887 else if (HiOverflow)
4888 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
4889 ICmpInst::ICMP_ULT, X, LoBound);
4890 else if (LoOverflow)
4891 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
4892 ICmpInst::ICMP_UGE, X, HiBound);
4894 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
4896 case ICmpInst::ICMP_ULT:
4897 case ICmpInst::ICMP_SLT:
4899 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4900 return new ICmpInst(predicate, X, LoBound);
4901 case ICmpInst::ICMP_UGT:
4902 case ICmpInst::ICMP_SGT:
4904 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4905 if (predicate == ICmpInst::ICMP_UGT)
4906 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
4908 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
4915 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
4916 if (I.isEquality()) {
4917 bool isICMP_NE = I.getPredicate() == ICmpInst::ICMP_NE;
4919 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
4920 // the second operand is a constant, simplify a bit.
4921 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
4922 switch (BO->getOpcode()) {
4923 case Instruction::SRem:
4924 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
4925 if (CI->isNullValue() && isa<ConstantInt>(BO->getOperand(1)) &&
4927 int64_t V = cast<ConstantInt>(BO->getOperand(1))->getSExtValue();
4928 if (V > 1 && isPowerOf2_64(V)) {
4929 Value *NewRem = InsertNewInstBefore(BinaryOperator::createURem(
4930 BO->getOperand(0), BO->getOperand(1), BO->getName()), I);
4931 return new ICmpInst(I.getPredicate(), NewRem,
4932 Constant::getNullValue(BO->getType()));
4936 case Instruction::Add:
4937 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
4938 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4939 if (BO->hasOneUse())
4940 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4941 ConstantExpr::getSub(CI, BOp1C));
4942 } else if (CI->isNullValue()) {
4943 // Replace ((add A, B) != 0) with (A != -B) if A or B is
4944 // efficiently invertible, or if the add has just this one use.
4945 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
4947 if (Value *NegVal = dyn_castNegVal(BOp1))
4948 return new ICmpInst(I.getPredicate(), BOp0, NegVal);
4949 else if (Value *NegVal = dyn_castNegVal(BOp0))
4950 return new ICmpInst(I.getPredicate(), NegVal, BOp1);
4951 else if (BO->hasOneUse()) {
4952 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
4954 InsertNewInstBefore(Neg, I);
4955 return new ICmpInst(I.getPredicate(), BOp0, Neg);
4959 case Instruction::Xor:
4960 // For the xor case, we can xor two constants together, eliminating
4961 // the explicit xor.
4962 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
4963 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4964 ConstantExpr::getXor(CI, BOC));
4967 case Instruction::Sub:
4968 // Replace (([sub|xor] A, B) != 0) with (A != B)
4969 if (CI->isNullValue())
4970 return new ICmpInst(I.getPredicate(), BO->getOperand(0),
4974 case Instruction::Or:
4975 // If bits are being or'd in that are not present in the constant we
4976 // are comparing against, then the comparison could never succeed!
4977 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
4978 Constant *NotCI = ConstantExpr::getNot(CI);
4979 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
4980 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4985 case Instruction::And:
4986 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
4987 // If bits are being compared against that are and'd out, then the
4988 // comparison can never succeed!
4989 if (!ConstantExpr::getAnd(CI,
4990 ConstantExpr::getNot(BOC))->isNullValue())
4991 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4994 // If we have ((X & C) == C), turn it into ((X & C) != 0).
4995 if (CI == BOC && isOneBitSet(CI))
4996 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
4997 ICmpInst::ICMP_NE, Op0,
4998 Constant::getNullValue(CI->getType()));
5000 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5001 if (isSignBit(BOC)) {
5002 Value *X = BO->getOperand(0);
5003 Constant *Zero = Constant::getNullValue(X->getType());
5004 ICmpInst::Predicate pred = isICMP_NE ?
5005 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5006 return new ICmpInst(pred, X, Zero);
5009 // ((X & ~7) == 0) --> X < 8
5010 if (CI->isNullValue() && isHighOnes(BOC)) {
5011 Value *X = BO->getOperand(0);
5012 Constant *NegX = ConstantExpr::getNeg(BOC);
5013 ICmpInst::Predicate pred = isICMP_NE ?
5014 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5015 return new ICmpInst(pred, X, NegX);
5021 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Op0)) {
5022 // Handle set{eq|ne} <intrinsic>, intcst.
5023 switch (II->getIntrinsicID()) {
5025 case Intrinsic::bswap_i16:
5026 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5027 WorkList.push_back(II); // Dead?
5028 I.setOperand(0, II->getOperand(1));
5029 I.setOperand(1, ConstantInt::get(Type::Int16Ty,
5030 ByteSwap_16(CI->getZExtValue())));
5032 case Intrinsic::bswap_i32:
5033 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5034 WorkList.push_back(II); // Dead?
5035 I.setOperand(0, II->getOperand(1));
5036 I.setOperand(1, ConstantInt::get(Type::Int32Ty,
5037 ByteSwap_32(CI->getZExtValue())));
5039 case Intrinsic::bswap_i64:
5040 // icmp eq (bswap(x)), c -> icmp eq (x,bswap(c))
5041 WorkList.push_back(II); // Dead?
5042 I.setOperand(0, II->getOperand(1));
5043 I.setOperand(1, ConstantInt::get(Type::Int64Ty,
5044 ByteSwap_64(CI->getZExtValue())));
5048 } else { // Not a ICMP_EQ/ICMP_NE
5049 // If the LHS is a cast from an integral value of the same size, then
5050 // since we know the RHS is a constant, try to simlify.
5051 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
5052 Value *CastOp = Cast->getOperand(0);
5053 const Type *SrcTy = CastOp->getType();
5054 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
5055 if (SrcTy->isInteger() &&
5056 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5057 // If this is an unsigned comparison, try to make the comparison use
5058 // smaller constant values.
5059 switch (I.getPredicate()) {
5061 case ICmpInst::ICMP_ULT: { // X u< 128 => X s> -1
5062 ConstantInt *CUI = cast<ConstantInt>(CI);
5063 if (CUI->getZExtValue() == 1ULL << (SrcTySize-1))
5064 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5065 ConstantInt::get(SrcTy, -1));
5068 case ICmpInst::ICMP_UGT: { // X u> 127 => X s< 0
5069 ConstantInt *CUI = cast<ConstantInt>(CI);
5070 if (CUI->getZExtValue() == (1ULL << (SrcTySize-1))-1)
5071 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5072 Constant::getNullValue(SrcTy));
5082 // Handle icmp with constant RHS
5083 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5084 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5085 switch (LHSI->getOpcode()) {
5086 case Instruction::GetElementPtr:
5087 if (RHSC->isNullValue()) {
5088 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5089 bool isAllZeros = true;
5090 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5091 if (!isa<Constant>(LHSI->getOperand(i)) ||
5092 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5097 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5098 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5102 case Instruction::PHI:
5103 if (Instruction *NV = FoldOpIntoPhi(I))
5106 case Instruction::Select:
5107 // If either operand of the select is a constant, we can fold the
5108 // comparison into the select arms, which will cause one to be
5109 // constant folded and the select turned into a bitwise or.
5110 Value *Op1 = 0, *Op2 = 0;
5111 if (LHSI->hasOneUse()) {
5112 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5113 // Fold the known value into the constant operand.
5114 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5115 // Insert a new ICmp of the other select operand.
5116 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5117 LHSI->getOperand(2), RHSC,
5119 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5120 // Fold the known value into the constant operand.
5121 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5122 // Insert a new ICmp of the other select operand.
5123 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5124 LHSI->getOperand(1), RHSC,
5130 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5135 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5136 if (User *GEP = dyn_castGetElementPtr(Op0))
5137 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5139 if (User *GEP = dyn_castGetElementPtr(Op1))
5140 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5141 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5144 // Test to see if the operands of the icmp are casted versions of other
5145 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5147 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5148 if (isa<PointerType>(Op0->getType()) &&
5149 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
5150 // We keep moving the cast from the left operand over to the right
5151 // operand, where it can often be eliminated completely.
5152 Op0 = CI->getOperand(0);
5154 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5155 // so eliminate it as well.
5156 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5157 Op1 = CI2->getOperand(0);
5159 // If Op1 is a constant, we can fold the cast into the constant.
5160 if (Op0->getType() != Op1->getType())
5161 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5162 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5164 // Otherwise, cast the RHS right before the icmp
5165 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
5167 return new ICmpInst(I.getPredicate(), Op0, Op1);
5171 if (isa<CastInst>(Op0)) {
5172 // Handle the special case of: icmp (cast bool to X), <cst>
5173 // This comes up when you have code like
5176 // For generality, we handle any zero-extension of any operand comparison
5177 // with a constant or another cast from the same type.
5178 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5179 if (Instruction *R = visitICmpInstWithCastAndCast(I))
5183 if (I.isEquality()) {
5184 Value *A, *B, *C, *D;
5185 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5186 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5187 Value *OtherVal = A == Op1 ? B : A;
5188 return new ICmpInst(I.getPredicate(), OtherVal,
5189 Constant::getNullValue(A->getType()));
5192 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5193 // A^c1 == C^c2 --> A == C^(c1^c2)
5194 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5195 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5196 if (Op1->hasOneUse()) {
5197 Constant *NC = ConstantExpr::getXor(C1, C2);
5198 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5199 return new ICmpInst(I.getPredicate(), A,
5200 InsertNewInstBefore(Xor, I));
5203 // A^B == A^D -> B == D
5204 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5205 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5206 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5207 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5211 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5212 (A == Op0 || B == Op0)) {
5213 // A == (A^B) -> B == 0
5214 Value *OtherVal = A == Op0 ? B : A;
5215 return new ICmpInst(I.getPredicate(), OtherVal,
5216 Constant::getNullValue(A->getType()));
5218 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5219 // (A-B) == A -> B == 0
5220 return new ICmpInst(I.getPredicate(), B,
5221 Constant::getNullValue(B->getType()));
5223 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5224 // A == (A-B) -> B == 0
5225 return new ICmpInst(I.getPredicate(), B,
5226 Constant::getNullValue(B->getType()));
5229 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5230 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5231 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5232 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5233 Value *X = 0, *Y = 0, *Z = 0;
5236 X = B; Y = D; Z = A;
5237 } else if (A == D) {
5238 X = B; Y = C; Z = A;
5239 } else if (B == C) {
5240 X = A; Y = D; Z = B;
5241 } else if (B == D) {
5242 X = A; Y = C; Z = B;
5245 if (X) { // Build (X^Y) & Z
5246 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5247 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5248 I.setOperand(0, Op1);
5249 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5254 return Changed ? &I : 0;
5257 // visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5258 // We only handle extending casts so far.
5260 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5261 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5262 Value *LHSCIOp = LHSCI->getOperand(0);
5263 const Type *SrcTy = LHSCIOp->getType();
5264 const Type *DestTy = LHSCI->getType();
5267 // We only handle extension cast instructions, so far. Enforce this.
5268 if (LHSCI->getOpcode() != Instruction::ZExt &&
5269 LHSCI->getOpcode() != Instruction::SExt)
5272 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5273 bool isSignedCmp = ICI.isSignedPredicate();
5275 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5276 // Not an extension from the same type?
5277 RHSCIOp = CI->getOperand(0);
5278 if (RHSCIOp->getType() != LHSCIOp->getType())
5281 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5282 // and the other is a zext), then we can't handle this.
5283 if (CI->getOpcode() != LHSCI->getOpcode())
5286 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5287 // then we can't handle this.
5288 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5291 // Okay, just insert a compare of the reduced operands now!
5292 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5295 // If we aren't dealing with a constant on the RHS, exit early
5296 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5300 // Compute the constant that would happen if we truncated to SrcTy then
5301 // reextended to DestTy.
5302 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5303 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5305 // If the re-extended constant didn't change...
5307 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5308 // For example, we might have:
5309 // %A = sext short %X to uint
5310 // %B = icmp ugt uint %A, 1330
5311 // It is incorrect to transform this into
5312 // %B = icmp ugt short %X, 1330
5313 // because %A may have negative value.
5315 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5316 // OR operation is EQ/NE.
5317 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5318 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5323 // The re-extended constant changed so the constant cannot be represented
5324 // in the shorter type. Consequently, we cannot emit a simple comparison.
5326 // First, handle some easy cases. We know the result cannot be equal at this
5327 // point so handle the ICI.isEquality() cases
5328 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5329 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5330 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5331 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5333 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5334 // should have been folded away previously and not enter in here.
5337 // We're performing a signed comparison.
5338 if (cast<ConstantInt>(CI)->getSExtValue() < 0)
5339 Result = ConstantInt::getFalse(); // X < (small) --> false
5341 Result = ConstantInt::getTrue(); // X < (large) --> true
5343 // We're performing an unsigned comparison.
5345 // We're performing an unsigned comp with a sign extended value.
5346 // This is true if the input is >= 0. [aka >s -1]
5347 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5348 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5349 NegOne, ICI.getName()), ICI);
5351 // Unsigned extend & unsigned compare -> always true.
5352 Result = ConstantInt::getTrue();
5356 // Finally, return the value computed.
5357 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5358 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5359 return ReplaceInstUsesWith(ICI, Result);
5361 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5362 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5363 "ICmp should be folded!");
5364 if (Constant *CI = dyn_cast<Constant>(Result))
5365 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5367 return BinaryOperator::createNot(Result);
5371 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
5372 assert(I.getOperand(1)->getType() == Type::Int8Ty);
5373 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5375 // shl X, 0 == X and shr X, 0 == X
5376 // shl 0, X == 0 and shr 0, X == 0
5377 if (Op1 == Constant::getNullValue(Type::Int8Ty) ||
5378 Op0 == Constant::getNullValue(Op0->getType()))
5379 return ReplaceInstUsesWith(I, Op0);
5381 if (isa<UndefValue>(Op0)) {
5382 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
5383 return ReplaceInstUsesWith(I, Op0);
5384 else // undef << X -> 0, undef >>u X -> 0
5385 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5387 if (isa<UndefValue>(Op1)) {
5388 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5389 return ReplaceInstUsesWith(I, Op0);
5390 else // X << undef, X >>u undef -> 0
5391 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5394 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5395 if (I.getOpcode() == Instruction::AShr)
5396 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5397 if (CSI->isAllOnesValue())
5398 return ReplaceInstUsesWith(I, CSI);
5400 // Try to fold constant and into select arguments.
5401 if (isa<Constant>(Op0))
5402 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5403 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5406 // See if we can turn a signed shr into an unsigned shr.
5407 if (I.isArithmeticShift()) {
5408 if (MaskedValueIsZero(Op0,
5409 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
5410 return new ShiftInst(Instruction::LShr, Op0, Op1, I.getName());
5414 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5415 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5420 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5422 bool isLeftShift = I.getOpcode() == Instruction::Shl;
5423 bool isSignedShift = I.getOpcode() == Instruction::AShr;
5424 bool isUnsignedShift = !isSignedShift;
5426 // See if we can simplify any instructions used by the instruction whose sole
5427 // purpose is to compute bits we don't care about.
5428 uint64_t KnownZero, KnownOne;
5429 if (SimplifyDemandedBits(&I, cast<IntegerType>(I.getType())->getBitMask(),
5430 KnownZero, KnownOne))
5433 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5434 // of a signed value.
5436 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5437 if (Op1->getZExtValue() >= TypeBits) {
5438 if (isUnsignedShift || isLeftShift)
5439 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5441 I.setOperand(1, ConstantInt::get(Type::Int8Ty, TypeBits-1));
5446 // ((X*C1) << C2) == (X * (C1 << C2))
5447 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5448 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5449 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5450 return BinaryOperator::createMul(BO->getOperand(0),
5451 ConstantExpr::getShl(BOOp, Op1));
5453 // Try to fold constant and into select arguments.
5454 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5455 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5457 if (isa<PHINode>(Op0))
5458 if (Instruction *NV = FoldOpIntoPhi(I))
5461 if (Op0->hasOneUse()) {
5462 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5463 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5466 switch (Op0BO->getOpcode()) {
5468 case Instruction::Add:
5469 case Instruction::And:
5470 case Instruction::Or:
5471 case Instruction::Xor:
5472 // These operators commute.
5473 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
5474 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5475 match(Op0BO->getOperand(1),
5476 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5477 Instruction *YS = new ShiftInst(Instruction::Shl,
5478 Op0BO->getOperand(0), Op1,
5480 InsertNewInstBefore(YS, I); // (Y << C)
5482 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5483 Op0BO->getOperand(1)->getName());
5484 InsertNewInstBefore(X, I); // (X + (Y << C))
5485 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5486 C2 = ConstantExpr::getShl(C2, Op1);
5487 return BinaryOperator::createAnd(X, C2);
5490 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5491 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5492 match(Op0BO->getOperand(1),
5493 m_And(m_Shr(m_Value(V1), m_Value(V2)),
5494 m_ConstantInt(CC))) && V2 == Op1 &&
5495 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
5496 Instruction *YS = new ShiftInst(Instruction::Shl,
5497 Op0BO->getOperand(0), Op1,
5499 InsertNewInstBefore(YS, I); // (Y << C)
5501 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5502 V1->getName()+".mask");
5503 InsertNewInstBefore(XM, I); // X & (CC << C)
5505 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5509 case Instruction::Sub:
5510 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5511 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5512 match(Op0BO->getOperand(0),
5513 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5514 Instruction *YS = new ShiftInst(Instruction::Shl,
5515 Op0BO->getOperand(1), Op1,
5517 InsertNewInstBefore(YS, I); // (Y << C)
5519 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5520 Op0BO->getOperand(0)->getName());
5521 InsertNewInstBefore(X, I); // (X + (Y << C))
5522 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
5523 C2 = ConstantExpr::getShl(C2, Op1);
5524 return BinaryOperator::createAnd(X, C2);
5527 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
5528 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5529 match(Op0BO->getOperand(0),
5530 m_And(m_Shr(m_Value(V1), m_Value(V2)),
5531 m_ConstantInt(CC))) && V2 == Op1 &&
5532 cast<BinaryOperator>(Op0BO->getOperand(0))
5533 ->getOperand(0)->hasOneUse()) {
5534 Instruction *YS = new ShiftInst(Instruction::Shl,
5535 Op0BO->getOperand(1), Op1,
5537 InsertNewInstBefore(YS, I); // (Y << C)
5539 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5540 V1->getName()+".mask");
5541 InsertNewInstBefore(XM, I); // X & (CC << C)
5543 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5550 // If the operand is an bitwise operator with a constant RHS, and the
5551 // shift is the only use, we can pull it out of the shift.
5552 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5553 bool isValid = true; // Valid only for And, Or, Xor
5554 bool highBitSet = false; // Transform if high bit of constant set?
5556 switch (Op0BO->getOpcode()) {
5557 default: isValid = false; break; // Do not perform transform!
5558 case Instruction::Add:
5559 isValid = isLeftShift;
5561 case Instruction::Or:
5562 case Instruction::Xor:
5565 case Instruction::And:
5570 // If this is a signed shift right, and the high bit is modified
5571 // by the logical operation, do not perform the transformation.
5572 // The highBitSet boolean indicates the value of the high bit of
5573 // the constant which would cause it to be modified for this
5576 if (isValid && !isLeftShift && isSignedShift) {
5577 uint64_t Val = Op0C->getZExtValue();
5578 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
5582 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5584 Instruction *NewShift =
5585 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
5588 InsertNewInstBefore(NewShift, I);
5590 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5597 // Find out if this is a shift of a shift by a constant.
5598 ShiftInst *ShiftOp = 0;
5599 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
5601 else if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5602 // If this is a noop-integer cast of a shift instruction, use the shift.
5603 if (isa<ShiftInst>(CI->getOperand(0))) {
5604 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
5608 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5609 // Find the operands and properties of the input shift. Note that the
5610 // signedness of the input shift may differ from the current shift if there
5611 // is a noop cast between the two.
5612 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
5613 bool isShiftOfSignedShift = ShiftOp->getOpcode() == Instruction::AShr;
5614 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
5616 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5618 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getZExtValue();
5619 unsigned ShiftAmt2 = (unsigned)Op1->getZExtValue();
5621 // Check for (A << c1) << c2 and (A >> c1) >> c2.
5622 if (isLeftShift == isShiftOfLeftShift) {
5623 // Do not fold these shifts if the first one is signed and the second one
5624 // is unsigned and this is a right shift. Further, don't do any folding
5626 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
5629 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5630 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
5631 Amt = Op0->getType()->getPrimitiveSizeInBits();
5633 Value *Op = ShiftOp->getOperand(0);
5634 ShiftInst *ShiftResult = new ShiftInst(I.getOpcode(), Op,
5635 ConstantInt::get(Type::Int8Ty, Amt));
5636 if (I.getType() == ShiftResult->getType())
5638 InsertNewInstBefore(ShiftResult, I);
5639 return CastInst::create(Instruction::BitCast, ShiftResult, I.getType());
5642 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
5643 // signed types, we can only support the (A >> c1) << c2 configuration,
5644 // because it can not turn an arbitrary bit of A into a sign bit.
5645 if (isUnsignedShift || isLeftShift) {
5646 // Calculate bitmask for what gets shifted off the edge.
5647 Constant *C = ConstantInt::getAllOnesValue(I.getType());
5649 C = ConstantExpr::getShl(C, ShiftAmt1C);
5651 C = ConstantExpr::getLShr(C, ShiftAmt1C);
5653 Value *Op = ShiftOp->getOperand(0);
5656 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
5657 InsertNewInstBefore(Mask, I);
5659 // Figure out what flavor of shift we should use...
5660 if (ShiftAmt1 == ShiftAmt2) {
5661 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
5662 } else if (ShiftAmt1 < ShiftAmt2) {
5663 return new ShiftInst(I.getOpcode(), Mask,
5664 ConstantInt::get(Type::Int8Ty, ShiftAmt2-ShiftAmt1));
5665 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
5666 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
5667 return new ShiftInst(Instruction::LShr, Mask,
5668 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5670 return new ShiftInst(ShiftOp->getOpcode(), Mask,
5671 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5674 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
5675 Instruction *Shift =
5676 new ShiftInst(ShiftOp->getOpcode(), Mask,
5677 ConstantInt::get(Type::Int8Ty, ShiftAmt1-ShiftAmt2));
5678 InsertNewInstBefore(Shift, I);
5680 C = ConstantInt::getAllOnesValue(Shift->getType());
5681 C = ConstantExpr::getShl(C, Op1);
5682 return BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
5685 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
5686 // this case, C1 == C2 and C1 is 8, 16, or 32.
5687 if (ShiftAmt1 == ShiftAmt2) {
5688 const Type *SExtType = 0;
5689 switch (Op0->getType()->getPrimitiveSizeInBits() - ShiftAmt1) {
5690 case 8 : SExtType = Type::Int8Ty; break;
5691 case 16: SExtType = Type::Int16Ty; break;
5692 case 32: SExtType = Type::Int32Ty; break;
5696 Instruction *NewTrunc =
5697 new TruncInst(ShiftOp->getOperand(0), SExtType, "sext");
5698 InsertNewInstBefore(NewTrunc, I);
5699 return new SExtInst(NewTrunc, I.getType());
5708 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
5709 /// expression. If so, decompose it, returning some value X, such that Val is
5712 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
5714 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
5715 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
5716 Offset = CI->getZExtValue();
5718 return ConstantInt::get(Type::Int32Ty, 0);
5719 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
5720 if (I->getNumOperands() == 2) {
5721 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
5722 if (I->getOpcode() == Instruction::Shl) {
5723 // This is a value scaled by '1 << the shift amt'.
5724 Scale = 1U << CUI->getZExtValue();
5726 return I->getOperand(0);
5727 } else if (I->getOpcode() == Instruction::Mul) {
5728 // This value is scaled by 'CUI'.
5729 Scale = CUI->getZExtValue();
5731 return I->getOperand(0);
5732 } else if (I->getOpcode() == Instruction::Add) {
5733 // We have X+C. Check to see if we really have (X*C2)+C1,
5734 // where C1 is divisible by C2.
5737 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
5738 Offset += CUI->getZExtValue();
5739 if (SubScale > 1 && (Offset % SubScale == 0)) {
5748 // Otherwise, we can't look past this.
5755 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
5756 /// try to eliminate the cast by moving the type information into the alloc.
5757 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
5758 AllocationInst &AI) {
5759 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
5760 if (!PTy) return 0; // Not casting the allocation to a pointer type.
5762 // Remove any uses of AI that are dead.
5763 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
5764 std::vector<Instruction*> DeadUsers;
5765 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
5766 Instruction *User = cast<Instruction>(*UI++);
5767 if (isInstructionTriviallyDead(User)) {
5768 while (UI != E && *UI == User)
5769 ++UI; // If this instruction uses AI more than once, don't break UI.
5771 // Add operands to the worklist.
5772 AddUsesToWorkList(*User);
5774 DOUT << "IC: DCE: " << *User;
5776 User->eraseFromParent();
5777 removeFromWorkList(User);
5781 // Get the type really allocated and the type casted to.
5782 const Type *AllocElTy = AI.getAllocatedType();
5783 const Type *CastElTy = PTy->getElementType();
5784 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
5786 unsigned AllocElTyAlign = TD->getTypeAlignmentABI(AllocElTy);
5787 unsigned CastElTyAlign = TD->getTypeAlignmentABI(CastElTy);
5788 if (CastElTyAlign < AllocElTyAlign) return 0;
5790 // If the allocation has multiple uses, only promote it if we are strictly
5791 // increasing the alignment of the resultant allocation. If we keep it the
5792 // same, we open the door to infinite loops of various kinds.
5793 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
5795 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
5796 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
5797 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
5799 // See if we can satisfy the modulus by pulling a scale out of the array
5801 unsigned ArraySizeScale, ArrayOffset;
5802 Value *NumElements = // See if the array size is a decomposable linear expr.
5803 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
5805 // If we can now satisfy the modulus, by using a non-1 scale, we really can
5807 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
5808 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
5810 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
5815 // If the allocation size is constant, form a constant mul expression
5816 Amt = ConstantInt::get(Type::Int32Ty, Scale);
5817 if (isa<ConstantInt>(NumElements))
5818 Amt = ConstantExpr::getMul(
5819 cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
5820 // otherwise multiply the amount and the number of elements
5821 else if (Scale != 1) {
5822 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
5823 Amt = InsertNewInstBefore(Tmp, AI);
5827 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
5828 Value *Off = ConstantInt::get(Type::Int32Ty, Offset);
5829 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
5830 Amt = InsertNewInstBefore(Tmp, AI);
5833 std::string Name = AI.getName(); AI.setName("");
5834 AllocationInst *New;
5835 if (isa<MallocInst>(AI))
5836 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
5838 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
5839 InsertNewInstBefore(New, AI);
5841 // If the allocation has multiple uses, insert a cast and change all things
5842 // that used it to use the new cast. This will also hack on CI, but it will
5844 if (!AI.hasOneUse()) {
5845 AddUsesToWorkList(AI);
5846 // New is the allocation instruction, pointer typed. AI is the original
5847 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
5848 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
5849 InsertNewInstBefore(NewCast, AI);
5850 AI.replaceAllUsesWith(NewCast);
5852 return ReplaceInstUsesWith(CI, New);
5855 /// CanEvaluateInDifferentType - Return true if we can take the specified value
5856 /// and return it without inserting any new casts. This is used by code that
5857 /// tries to decide whether promoting or shrinking integer operations to wider
5858 /// or smaller types will allow us to eliminate a truncate or extend.
5859 static bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
5860 int &NumCastsRemoved) {
5861 if (isa<Constant>(V)) return true;
5863 Instruction *I = dyn_cast<Instruction>(V);
5864 if (!I || !I->hasOneUse()) return false;
5866 switch (I->getOpcode()) {
5867 case Instruction::And:
5868 case Instruction::Or:
5869 case Instruction::Xor:
5870 // These operators can all arbitrarily be extended or truncated.
5871 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
5872 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
5873 case Instruction::AShr:
5874 case Instruction::LShr:
5875 case Instruction::Shl:
5876 // If this is just a bitcast changing the sign of the operation, we can
5877 // convert if the operand can be converted.
5878 if (V->getType()->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
5879 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved);
5881 case Instruction::Trunc:
5882 case Instruction::ZExt:
5883 case Instruction::SExt:
5884 case Instruction::BitCast:
5885 // If this is a cast from the destination type, we can trivially eliminate
5886 // it, and this will remove a cast overall.
5887 if (I->getOperand(0)->getType() == Ty) {
5888 // If the first operand is itself a cast, and is eliminable, do not count
5889 // this as an eliminable cast. We would prefer to eliminate those two
5891 if (isa<CastInst>(I->getOperand(0)))
5899 // TODO: Can handle more cases here.
5906 /// EvaluateInDifferentType - Given an expression that
5907 /// CanEvaluateInDifferentType returns true for, actually insert the code to
5908 /// evaluate the expression.
5909 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
5911 if (Constant *C = dyn_cast<Constant>(V))
5912 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
5914 // Otherwise, it must be an instruction.
5915 Instruction *I = cast<Instruction>(V);
5916 Instruction *Res = 0;
5917 switch (I->getOpcode()) {
5918 case Instruction::And:
5919 case Instruction::Or:
5920 case Instruction::Xor: {
5921 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5922 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
5923 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
5924 LHS, RHS, I->getName());
5927 case Instruction::AShr:
5928 case Instruction::LShr:
5929 case Instruction::Shl: {
5930 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
5931 Res = new ShiftInst((Instruction::OtherOps)I->getOpcode(), LHS,
5932 I->getOperand(1), I->getName());
5935 case Instruction::Trunc:
5936 case Instruction::ZExt:
5937 case Instruction::SExt:
5938 case Instruction::BitCast:
5939 // If the source type of the cast is the type we're trying for then we can
5940 // just return the source. There's no need to insert it because its not new.
5941 if (I->getOperand(0)->getType() == Ty)
5942 return I->getOperand(0);
5944 // Some other kind of cast, which shouldn't happen, so just ..
5947 // TODO: Can handle more cases here.
5948 assert(0 && "Unreachable!");
5952 return InsertNewInstBefore(Res, *I);
5955 /// @brief Implement the transforms common to all CastInst visitors.
5956 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
5957 Value *Src = CI.getOperand(0);
5959 // Casting undef to anything results in undef so might as just replace it and
5960 // get rid of the cast.
5961 if (isa<UndefValue>(Src)) // cast undef -> undef
5962 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
5964 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
5965 // eliminate it now.
5966 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
5967 if (Instruction::CastOps opc =
5968 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
5969 // The first cast (CSrc) is eliminable so we need to fix up or replace
5970 // the second cast (CI). CSrc will then have a good chance of being dead.
5971 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
5975 // If casting the result of a getelementptr instruction with no offset, turn
5976 // this into a cast of the original pointer!
5978 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
5979 bool AllZeroOperands = true;
5980 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
5981 if (!isa<Constant>(GEP->getOperand(i)) ||
5982 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
5983 AllZeroOperands = false;
5986 if (AllZeroOperands) {
5987 // Changing the cast operand is usually not a good idea but it is safe
5988 // here because the pointer operand is being replaced with another
5989 // pointer operand so the opcode doesn't need to change.
5990 CI.setOperand(0, GEP->getOperand(0));
5995 // If we are casting a malloc or alloca to a pointer to a type of the same
5996 // size, rewrite the allocation instruction to allocate the "right" type.
5997 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
5998 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6001 // If we are casting a select then fold the cast into the select
6002 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6003 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6006 // If we are casting a PHI then fold the cast into the PHI
6007 if (isa<PHINode>(Src))
6008 if (Instruction *NV = FoldOpIntoPhi(CI))
6014 /// Only the TRUNC, ZEXT, SEXT, and BITCONVERT can have both operands as
6015 /// integers. This function implements the common transforms for all those
6017 /// @brief Implement the transforms common to CastInst with integer operands
6018 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6019 if (Instruction *Result = commonCastTransforms(CI))
6022 Value *Src = CI.getOperand(0);
6023 const Type *SrcTy = Src->getType();
6024 const Type *DestTy = CI.getType();
6025 unsigned SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6026 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
6028 // See if we can simplify any instructions used by the LHS whose sole
6029 // purpose is to compute bits we don't care about.
6030 uint64_t KnownZero = 0, KnownOne = 0;
6031 if (SimplifyDemandedBits(&CI, cast<IntegerType>(DestTy)->getBitMask(),
6032 KnownZero, KnownOne))
6035 // If the source isn't an instruction or has more than one use then we
6036 // can't do anything more.
6037 Instruction *SrcI = dyn_cast<Instruction>(Src);
6038 if (!SrcI || !Src->hasOneUse())
6041 // Attempt to propagate the cast into the instruction.
6042 int NumCastsRemoved = 0;
6043 if (CanEvaluateInDifferentType(SrcI, DestTy, NumCastsRemoved)) {
6044 // If this cast is a truncate, evaluting in a different type always
6045 // eliminates the cast, so it is always a win. If this is a noop-cast
6046 // this just removes a noop cast which isn't pointful, but simplifies
6047 // the code. If this is a zero-extension, we need to do an AND to
6048 // maintain the clear top-part of the computation, so we require that
6049 // the input have eliminated at least one cast. If this is a sign
6050 // extension, we insert two new casts (to do the extension) so we
6051 // require that two casts have been eliminated.
6052 bool DoXForm = CI.isNoopCast(TD->getIntPtrType());
6054 switch (CI.getOpcode()) {
6055 case Instruction::Trunc:
6058 case Instruction::ZExt:
6059 DoXForm = NumCastsRemoved >= 1;
6061 case Instruction::SExt:
6062 DoXForm = NumCastsRemoved >= 2;
6064 case Instruction::BitCast:
6068 // All the others use floating point so we shouldn't actually
6069 // get here because of the check above.
6070 assert(!"Unknown cast type .. unreachable");
6076 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6077 CI.getOpcode() == Instruction::SExt);
6078 assert(Res->getType() == DestTy);
6079 switch (CI.getOpcode()) {
6080 default: assert(0 && "Unknown cast type!");
6081 case Instruction::Trunc:
6082 case Instruction::BitCast:
6083 // Just replace this cast with the result.
6084 return ReplaceInstUsesWith(CI, Res);
6085 case Instruction::ZExt: {
6086 // We need to emit an AND to clear the high bits.
6087 assert(SrcBitSize < DestBitSize && "Not a zext?");
6089 ConstantInt::get(Type::Int64Ty, (1ULL << SrcBitSize)-1);
6090 if (DestBitSize < 64)
6091 C = ConstantExpr::getTrunc(C, DestTy);
6092 return BinaryOperator::createAnd(Res, C);
6094 case Instruction::SExt:
6095 // We need to emit a cast to truncate, then a cast to sext.
6096 return CastInst::create(Instruction::SExt,
6097 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6103 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6104 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6106 switch (SrcI->getOpcode()) {
6107 case Instruction::Add:
6108 case Instruction::Mul:
6109 case Instruction::And:
6110 case Instruction::Or:
6111 case Instruction::Xor:
6112 // If we are discarding information, or just changing the sign,
6114 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6115 // Don't insert two casts if they cannot be eliminated. We allow
6116 // two casts to be inserted if the sizes are the same. This could
6117 // only be converting signedness, which is a noop.
6118 if (DestBitSize == SrcBitSize ||
6119 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6120 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6121 Instruction::CastOps opcode = CI.getOpcode();
6122 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6123 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6124 return BinaryOperator::create(
6125 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6129 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6130 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6131 SrcI->getOpcode() == Instruction::Xor &&
6132 Op1 == ConstantInt::getTrue() &&
6133 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6134 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6135 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6138 case Instruction::SDiv:
6139 case Instruction::UDiv:
6140 case Instruction::SRem:
6141 case Instruction::URem:
6142 // If we are just changing the sign, rewrite.
6143 if (DestBitSize == SrcBitSize) {
6144 // Don't insert two casts if they cannot be eliminated. We allow
6145 // two casts to be inserted if the sizes are the same. This could
6146 // only be converting signedness, which is a noop.
6147 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6148 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6149 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6151 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6153 return BinaryOperator::create(
6154 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6159 case Instruction::Shl:
6160 // Allow changing the sign of the source operand. Do not allow
6161 // changing the size of the shift, UNLESS the shift amount is a
6162 // constant. We must not change variable sized shifts to a smaller
6163 // size, because it is undefined to shift more bits out than exist
6165 if (DestBitSize == SrcBitSize ||
6166 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6167 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6168 Instruction::BitCast : Instruction::Trunc);
6169 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6170 return new ShiftInst(Instruction::Shl, Op0c, Op1);
6173 case Instruction::AShr:
6174 // If this is a signed shr, and if all bits shifted in are about to be
6175 // truncated off, turn it into an unsigned shr to allow greater
6177 if (DestBitSize < SrcBitSize &&
6178 isa<ConstantInt>(Op1)) {
6179 unsigned ShiftAmt = cast<ConstantInt>(Op1)->getZExtValue();
6180 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6181 // Insert the new logical shift right.
6182 return new ShiftInst(Instruction::LShr, Op0, Op1);
6187 case Instruction::ICmp:
6188 // If we are just checking for a icmp eq of a single bit and casting it
6189 // to an integer, then shift the bit to the appropriate place and then
6190 // cast to integer to avoid the comparison.
6191 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
6192 uint64_t Op1CV = Op1C->getZExtValue();
6193 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
6194 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6195 // cast (X == 1) to int --> X iff X has only the low bit set.
6196 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
6197 // cast (X != 0) to int --> X iff X has only the low bit set.
6198 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
6199 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
6200 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
6201 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
6202 // If Op1C some other power of two, convert:
6203 uint64_t KnownZero, KnownOne;
6204 uint64_t TypeMask = Op1C->getType()->getBitMask();
6205 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
6207 // This only works for EQ and NE
6208 ICmpInst::Predicate pred = cast<ICmpInst>(SrcI)->getPredicate();
6209 if (pred != ICmpInst::ICMP_NE && pred != ICmpInst::ICMP_EQ)
6212 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly 1 possible 1?
6213 bool isNE = pred == ICmpInst::ICMP_NE;
6214 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
6215 // (X&4) == 2 --> false
6216 // (X&4) != 2 --> true
6217 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
6218 Res = ConstantExpr::getZExt(Res, CI.getType());
6219 return ReplaceInstUsesWith(CI, Res);
6222 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
6225 // Perform a logical shr by shiftamt.
6226 // Insert the shift to put the result in the low bit.
6227 In = InsertNewInstBefore(
6228 new ShiftInst(Instruction::LShr, In,
6229 ConstantInt::get(Type::Int8Ty, ShiftAmt),
6230 In->getName()+".lobit"), CI);
6233 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6234 Constant *One = ConstantInt::get(In->getType(), 1);
6235 In = BinaryOperator::createXor(In, One, "tmp");
6236 InsertNewInstBefore(cast<Instruction>(In), CI);
6239 if (CI.getType() == In->getType())
6240 return ReplaceInstUsesWith(CI, In);
6242 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6251 Instruction *InstCombiner::visitTrunc(CastInst &CI) {
6252 if (Instruction *Result = commonIntCastTransforms(CI))
6255 Value *Src = CI.getOperand(0);
6256 const Type *Ty = CI.getType();
6257 unsigned DestBitWidth = Ty->getPrimitiveSizeInBits();
6259 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6260 switch (SrcI->getOpcode()) {
6262 case Instruction::LShr:
6263 // We can shrink lshr to something smaller if we know the bits shifted in
6264 // are already zeros.
6265 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6266 unsigned ShAmt = ShAmtV->getZExtValue();
6268 // Get a mask for the bits shifting in.
6269 uint64_t Mask = (~0ULL >> (64-ShAmt)) << DestBitWidth;
6270 Value* SrcIOp0 = SrcI->getOperand(0);
6271 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6272 if (ShAmt >= DestBitWidth) // All zeros.
6273 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6275 // Okay, we can shrink this. Truncate the input, then return a new
6277 Value *V = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6278 return new ShiftInst(Instruction::LShr, V, SrcI->getOperand(1));
6280 } else { // This is a variable shr.
6282 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6283 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6284 // loop-invariant and CSE'd.
6285 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
6286 Value *One = ConstantInt::get(SrcI->getType(), 1);
6288 Value *V = InsertNewInstBefore(new ShiftInst(Instruction::Shl, One,
6289 SrcI->getOperand(1),
6291 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6292 SrcI->getOperand(0),
6294 Value *Zero = Constant::getNullValue(V->getType());
6295 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
6305 Instruction *InstCombiner::visitZExt(CastInst &CI) {
6306 // If one of the common conversion will work ..
6307 if (Instruction *Result = commonIntCastTransforms(CI))
6310 Value *Src = CI.getOperand(0);
6312 // If this is a cast of a cast
6313 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
6314 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6315 // types and if the sizes are just right we can convert this into a logical
6316 // 'and' which will be much cheaper than the pair of casts.
6317 if (isa<TruncInst>(CSrc)) {
6318 // Get the sizes of the types involved
6319 Value *A = CSrc->getOperand(0);
6320 unsigned SrcSize = A->getType()->getPrimitiveSizeInBits();
6321 unsigned MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6322 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
6323 // If we're actually extending zero bits and the trunc is a no-op
6324 if (MidSize < DstSize && SrcSize == DstSize) {
6325 // Replace both of the casts with an And of the type mask.
6326 uint64_t AndValue = cast<IntegerType>(CSrc->getType())->getBitMask();
6327 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
6329 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6330 // Unfortunately, if the type changed, we need to cast it back.
6331 if (And->getType() != CI.getType()) {
6332 And->setName(CSrc->getName()+".mask");
6333 InsertNewInstBefore(And, CI);
6334 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
6344 Instruction *InstCombiner::visitSExt(CastInst &CI) {
6345 return commonIntCastTransforms(CI);
6348 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6349 return commonCastTransforms(CI);
6352 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6353 return commonCastTransforms(CI);
6356 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
6357 return commonCastTransforms(CI);
6360 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
6361 return commonCastTransforms(CI);
6364 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6365 return commonCastTransforms(CI);
6368 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6369 return commonCastTransforms(CI);
6372 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
6373 return commonCastTransforms(CI);
6376 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6377 return commonCastTransforms(CI);
6380 Instruction *InstCombiner::visitBitCast(CastInst &CI) {
6382 // If the operands are integer typed then apply the integer transforms,
6383 // otherwise just apply the common ones.
6384 Value *Src = CI.getOperand(0);
6385 const Type *SrcTy = Src->getType();
6386 const Type *DestTy = CI.getType();
6388 if (SrcTy->isInteger() && DestTy->isInteger()) {
6389 if (Instruction *Result = commonIntCastTransforms(CI))
6392 if (Instruction *Result = commonCastTransforms(CI))
6397 // Get rid of casts from one type to the same type. These are useless and can
6398 // be replaced by the operand.
6399 if (DestTy == Src->getType())
6400 return ReplaceInstUsesWith(CI, Src);
6402 // If the source and destination are pointers, and this cast is equivalent to
6403 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6404 // This can enhance SROA and other transforms that want type-safe pointers.
6405 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6406 if (const PointerType *SrcPTy = dyn_cast<PointerType>(SrcTy)) {
6407 const Type *DstElTy = DstPTy->getElementType();
6408 const Type *SrcElTy = SrcPTy->getElementType();
6410 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
6411 unsigned NumZeros = 0;
6412 while (SrcElTy != DstElTy &&
6413 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6414 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6415 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
6419 // If we found a path from the src to dest, create the getelementptr now.
6420 if (SrcElTy == DstElTy) {
6421 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6422 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
6427 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6428 if (SVI->hasOneUse()) {
6429 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6430 // a bitconvert to a vector with the same # elts.
6431 if (isa<PackedType>(DestTy) &&
6432 cast<PackedType>(DestTy)->getNumElements() ==
6433 SVI->getType()->getNumElements()) {
6435 // If either of the operands is a cast from CI.getType(), then
6436 // evaluating the shuffle in the casted destination's type will allow
6437 // us to eliminate at least one cast.
6438 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6439 Tmp->getOperand(0)->getType() == DestTy) ||
6440 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6441 Tmp->getOperand(0)->getType() == DestTy)) {
6442 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6443 SVI->getOperand(0), DestTy, &CI);
6444 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6445 SVI->getOperand(1), DestTy, &CI);
6446 // Return a new shuffle vector. Use the same element ID's, as we
6447 // know the vector types match #elts.
6448 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
6456 /// GetSelectFoldableOperands - We want to turn code that looks like this:
6458 /// %D = select %cond, %C, %A
6460 /// %C = select %cond, %B, 0
6463 /// Assuming that the specified instruction is an operand to the select, return
6464 /// a bitmask indicating which operands of this instruction are foldable if they
6465 /// equal the other incoming value of the select.
6467 static unsigned GetSelectFoldableOperands(Instruction *I) {
6468 switch (I->getOpcode()) {
6469 case Instruction::Add:
6470 case Instruction::Mul:
6471 case Instruction::And:
6472 case Instruction::Or:
6473 case Instruction::Xor:
6474 return 3; // Can fold through either operand.
6475 case Instruction::Sub: // Can only fold on the amount subtracted.
6476 case Instruction::Shl: // Can only fold on the shift amount.
6477 case Instruction::LShr:
6478 case Instruction::AShr:
6481 return 0; // Cannot fold
6485 /// GetSelectFoldableConstant - For the same transformation as the previous
6486 /// function, return the identity constant that goes into the select.
6487 static Constant *GetSelectFoldableConstant(Instruction *I) {
6488 switch (I->getOpcode()) {
6489 default: assert(0 && "This cannot happen!"); abort();
6490 case Instruction::Add:
6491 case Instruction::Sub:
6492 case Instruction::Or:
6493 case Instruction::Xor:
6494 return Constant::getNullValue(I->getType());
6495 case Instruction::Shl:
6496 case Instruction::LShr:
6497 case Instruction::AShr:
6498 return Constant::getNullValue(Type::Int8Ty);
6499 case Instruction::And:
6500 return ConstantInt::getAllOnesValue(I->getType());
6501 case Instruction::Mul:
6502 return ConstantInt::get(I->getType(), 1);
6506 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6507 /// have the same opcode and only one use each. Try to simplify this.
6508 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6510 if (TI->getNumOperands() == 1) {
6511 // If this is a non-volatile load or a cast from the same type,
6514 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6517 return 0; // unknown unary op.
6520 // Fold this by inserting a select from the input values.
6521 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6522 FI->getOperand(0), SI.getName()+".v");
6523 InsertNewInstBefore(NewSI, SI);
6524 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6528 // Only handle binary, compare and shift operators here.
6529 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
6532 // Figure out if the operations have any operands in common.
6533 Value *MatchOp, *OtherOpT, *OtherOpF;
6535 if (TI->getOperand(0) == FI->getOperand(0)) {
6536 MatchOp = TI->getOperand(0);
6537 OtherOpT = TI->getOperand(1);
6538 OtherOpF = FI->getOperand(1);
6539 MatchIsOpZero = true;
6540 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6541 MatchOp = TI->getOperand(1);
6542 OtherOpT = TI->getOperand(0);
6543 OtherOpF = FI->getOperand(0);
6544 MatchIsOpZero = false;
6545 } else if (!TI->isCommutative()) {
6547 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6548 MatchOp = TI->getOperand(0);
6549 OtherOpT = TI->getOperand(1);
6550 OtherOpF = FI->getOperand(0);
6551 MatchIsOpZero = true;
6552 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6553 MatchOp = TI->getOperand(1);
6554 OtherOpT = TI->getOperand(0);
6555 OtherOpF = FI->getOperand(1);
6556 MatchIsOpZero = true;
6561 // If we reach here, they do have operations in common.
6562 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6563 OtherOpF, SI.getName()+".v");
6564 InsertNewInstBefore(NewSI, SI);
6566 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6568 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6570 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6573 assert(isa<ShiftInst>(TI) && "Should only have Shift here");
6575 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
6577 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
6580 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
6581 Value *CondVal = SI.getCondition();
6582 Value *TrueVal = SI.getTrueValue();
6583 Value *FalseVal = SI.getFalseValue();
6585 // select true, X, Y -> X
6586 // select false, X, Y -> Y
6587 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
6588 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
6590 // select C, X, X -> X
6591 if (TrueVal == FalseVal)
6592 return ReplaceInstUsesWith(SI, TrueVal);
6594 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
6595 return ReplaceInstUsesWith(SI, FalseVal);
6596 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
6597 return ReplaceInstUsesWith(SI, TrueVal);
6598 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
6599 if (isa<Constant>(TrueVal))
6600 return ReplaceInstUsesWith(SI, TrueVal);
6602 return ReplaceInstUsesWith(SI, FalseVal);
6605 if (SI.getType() == Type::Int1Ty) {
6606 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
6607 if (C->getZExtValue()) {
6608 // Change: A = select B, true, C --> A = or B, C
6609 return BinaryOperator::createOr(CondVal, FalseVal);
6611 // Change: A = select B, false, C --> A = and !B, C
6613 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6614 "not."+CondVal->getName()), SI);
6615 return BinaryOperator::createAnd(NotCond, FalseVal);
6617 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
6618 if (C->getZExtValue() == false) {
6619 // Change: A = select B, C, false --> A = and B, C
6620 return BinaryOperator::createAnd(CondVal, TrueVal);
6622 // Change: A = select B, C, true --> A = or !B, C
6624 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6625 "not."+CondVal->getName()), SI);
6626 return BinaryOperator::createOr(NotCond, TrueVal);
6631 // Selecting between two integer constants?
6632 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
6633 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
6634 // select C, 1, 0 -> cast C to int
6635 if (FalseValC->isNullValue() && TrueValC->getZExtValue() == 1) {
6636 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
6637 } else if (TrueValC->isNullValue() && FalseValC->getZExtValue() == 1) {
6638 // select C, 0, 1 -> cast !C to int
6640 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
6641 "not."+CondVal->getName()), SI);
6642 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
6645 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
6647 // (x <s 0) ? -1 : 0 -> ashr x, 31
6648 // (x >u 2147483647) ? -1 : 0 -> ashr x, 31
6649 if (TrueValC->isAllOnesValue() && FalseValC->isNullValue())
6650 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
6651 bool CanXForm = false;
6652 if (IC->isSignedPredicate())
6653 CanXForm = CmpCst->isNullValue() &&
6654 IC->getPredicate() == ICmpInst::ICMP_SLT;
6656 unsigned Bits = CmpCst->getType()->getPrimitiveSizeInBits();
6657 CanXForm = (CmpCst->getZExtValue() == ~0ULL >> (64-Bits+1)) &&
6658 IC->getPredicate() == ICmpInst::ICMP_UGT;
6662 // The comparison constant and the result are not neccessarily the
6663 // same width. Make an all-ones value by inserting a AShr.
6664 Value *X = IC->getOperand(0);
6665 unsigned Bits = X->getType()->getPrimitiveSizeInBits();
6666 Constant *ShAmt = ConstantInt::get(Type::Int8Ty, Bits-1);
6667 Instruction *SRA = new ShiftInst(Instruction::AShr, X,
6669 InsertNewInstBefore(SRA, SI);
6671 // Finally, convert to the type of the select RHS. We figure out
6672 // if this requires a SExt, Trunc or BitCast based on the sizes.
6673 Instruction::CastOps opc = Instruction::BitCast;
6674 unsigned SRASize = SRA->getType()->getPrimitiveSizeInBits();
6675 unsigned SISize = SI.getType()->getPrimitiveSizeInBits();
6676 if (SRASize < SISize)
6677 opc = Instruction::SExt;
6678 else if (SRASize > SISize)
6679 opc = Instruction::Trunc;
6680 return CastInst::create(opc, SRA, SI.getType());
6685 // If one of the constants is zero (we know they can't both be) and we
6686 // have a fcmp instruction with zero, and we have an 'and' with the
6687 // non-constant value, eliminate this whole mess. This corresponds to
6688 // cases like this: ((X & 27) ? 27 : 0)
6689 if (TrueValC->isNullValue() || FalseValC->isNullValue())
6690 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
6691 cast<Constant>(IC->getOperand(1))->isNullValue())
6692 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
6693 if (ICA->getOpcode() == Instruction::And &&
6694 isa<ConstantInt>(ICA->getOperand(1)) &&
6695 (ICA->getOperand(1) == TrueValC ||
6696 ICA->getOperand(1) == FalseValC) &&
6697 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
6698 // Okay, now we know that everything is set up, we just don't
6699 // know whether we have a icmp_ne or icmp_eq and whether the
6700 // true or false val is the zero.
6701 bool ShouldNotVal = !TrueValC->isNullValue();
6702 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
6705 V = InsertNewInstBefore(BinaryOperator::create(
6706 Instruction::Xor, V, ICA->getOperand(1)), SI);
6707 return ReplaceInstUsesWith(SI, V);
6712 // See if we are selecting two values based on a comparison of the two values.
6713 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
6714 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
6715 // Transform (X == Y) ? X : Y -> Y
6716 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6717 return ReplaceInstUsesWith(SI, FalseVal);
6718 // Transform (X != Y) ? X : Y -> X
6719 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6720 return ReplaceInstUsesWith(SI, TrueVal);
6721 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6723 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
6724 // Transform (X == Y) ? Y : X -> X
6725 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
6726 return ReplaceInstUsesWith(SI, FalseVal);
6727 // Transform (X != Y) ? Y : X -> Y
6728 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
6729 return ReplaceInstUsesWith(SI, TrueVal);
6730 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6734 // See if we are selecting two values based on a comparison of the two values.
6735 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
6736 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
6737 // Transform (X == Y) ? X : Y -> Y
6738 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6739 return ReplaceInstUsesWith(SI, FalseVal);
6740 // Transform (X != Y) ? X : Y -> X
6741 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6742 return ReplaceInstUsesWith(SI, TrueVal);
6743 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6745 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
6746 // Transform (X == Y) ? Y : X -> X
6747 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
6748 return ReplaceInstUsesWith(SI, FalseVal);
6749 // Transform (X != Y) ? Y : X -> Y
6750 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
6751 return ReplaceInstUsesWith(SI, TrueVal);
6752 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
6756 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
6757 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
6758 if (TI->hasOneUse() && FI->hasOneUse()) {
6759 Instruction *AddOp = 0, *SubOp = 0;
6761 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
6762 if (TI->getOpcode() == FI->getOpcode())
6763 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
6766 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
6767 // even legal for FP.
6768 if (TI->getOpcode() == Instruction::Sub &&
6769 FI->getOpcode() == Instruction::Add) {
6770 AddOp = FI; SubOp = TI;
6771 } else if (FI->getOpcode() == Instruction::Sub &&
6772 TI->getOpcode() == Instruction::Add) {
6773 AddOp = TI; SubOp = FI;
6777 Value *OtherAddOp = 0;
6778 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
6779 OtherAddOp = AddOp->getOperand(1);
6780 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
6781 OtherAddOp = AddOp->getOperand(0);
6785 // So at this point we know we have (Y -> OtherAddOp):
6786 // select C, (add X, Y), (sub X, Z)
6787 Value *NegVal; // Compute -Z
6788 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
6789 NegVal = ConstantExpr::getNeg(C);
6791 NegVal = InsertNewInstBefore(
6792 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
6795 Value *NewTrueOp = OtherAddOp;
6796 Value *NewFalseOp = NegVal;
6798 std::swap(NewTrueOp, NewFalseOp);
6799 Instruction *NewSel =
6800 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
6802 NewSel = InsertNewInstBefore(NewSel, SI);
6803 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
6808 // See if we can fold the select into one of our operands.
6809 if (SI.getType()->isInteger()) {
6810 // See the comment above GetSelectFoldableOperands for a description of the
6811 // transformation we are doing here.
6812 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
6813 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
6814 !isa<Constant>(FalseVal))
6815 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
6816 unsigned OpToFold = 0;
6817 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
6819 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
6824 Constant *C = GetSelectFoldableConstant(TVI);
6825 std::string Name = TVI->getName(); TVI->setName("");
6826 Instruction *NewSel =
6827 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
6829 InsertNewInstBefore(NewSel, SI);
6830 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
6831 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
6832 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
6833 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
6835 assert(0 && "Unknown instruction!!");
6840 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
6841 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
6842 !isa<Constant>(TrueVal))
6843 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
6844 unsigned OpToFold = 0;
6845 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
6847 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
6852 Constant *C = GetSelectFoldableConstant(FVI);
6853 std::string Name = FVI->getName(); FVI->setName("");
6854 Instruction *NewSel =
6855 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
6857 InsertNewInstBefore(NewSel, SI);
6858 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
6859 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
6860 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
6861 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
6863 assert(0 && "Unknown instruction!!");
6869 if (BinaryOperator::isNot(CondVal)) {
6870 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
6871 SI.setOperand(1, FalseVal);
6872 SI.setOperand(2, TrueVal);
6879 /// GetKnownAlignment - If the specified pointer has an alignment that we can
6880 /// determine, return it, otherwise return 0.
6881 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
6882 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
6883 unsigned Align = GV->getAlignment();
6884 if (Align == 0 && TD)
6885 Align = TD->getTypeAlignmentPref(GV->getType()->getElementType());
6887 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
6888 unsigned Align = AI->getAlignment();
6889 if (Align == 0 && TD) {
6890 if (isa<AllocaInst>(AI))
6891 Align = TD->getTypeAlignmentPref(AI->getType()->getElementType());
6892 else if (isa<MallocInst>(AI)) {
6893 // Malloc returns maximally aligned memory.
6894 Align = TD->getTypeAlignmentABI(AI->getType()->getElementType());
6897 (unsigned)TD->getTypeAlignmentABI(Type::DoubleTy));
6900 (unsigned)TD->getTypeAlignmentABI(Type::Int64Ty));
6904 } else if (isa<BitCastInst>(V) ||
6905 (isa<ConstantExpr>(V) &&
6906 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
6907 User *CI = cast<User>(V);
6908 if (isa<PointerType>(CI->getOperand(0)->getType()))
6909 return GetKnownAlignment(CI->getOperand(0), TD);
6911 } else if (isa<GetElementPtrInst>(V) ||
6912 (isa<ConstantExpr>(V) &&
6913 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
6914 User *GEPI = cast<User>(V);
6915 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
6916 if (BaseAlignment == 0) return 0;
6918 // If all indexes are zero, it is just the alignment of the base pointer.
6919 bool AllZeroOperands = true;
6920 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
6921 if (!isa<Constant>(GEPI->getOperand(i)) ||
6922 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
6923 AllZeroOperands = false;
6926 if (AllZeroOperands)
6927 return BaseAlignment;
6929 // Otherwise, if the base alignment is >= the alignment we expect for the
6930 // base pointer type, then we know that the resultant pointer is aligned at
6931 // least as much as its type requires.
6934 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
6935 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
6936 if (TD->getTypeAlignmentABI(PtrTy->getElementType())
6938 const Type *GEPTy = GEPI->getType();
6939 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
6940 return TD->getTypeAlignmentABI(GEPPtrTy->getElementType());
6948 /// visitCallInst - CallInst simplification. This mostly only handles folding
6949 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
6950 /// the heavy lifting.
6952 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
6953 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
6954 if (!II) return visitCallSite(&CI);
6956 // Intrinsics cannot occur in an invoke, so handle them here instead of in
6958 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
6959 bool Changed = false;
6961 // memmove/cpy/set of zero bytes is a noop.
6962 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
6963 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
6965 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
6966 if (CI->getZExtValue() == 1) {
6967 // Replace the instruction with just byte operations. We would
6968 // transform other cases to loads/stores, but we don't know if
6969 // alignment is sufficient.
6973 // If we have a memmove and the source operation is a constant global,
6974 // then the source and dest pointers can't alias, so we can change this
6975 // into a call to memcpy.
6976 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
6977 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
6978 if (GVSrc->isConstant()) {
6979 Module *M = CI.getParent()->getParent()->getParent();
6981 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
6983 Name = "llvm.memcpy.i32";
6985 Name = "llvm.memcpy.i64";
6986 Constant *MemCpy = M->getOrInsertFunction(Name,
6987 CI.getCalledFunction()->getFunctionType());
6988 CI.setOperand(0, MemCpy);
6993 // If we can determine a pointer alignment that is bigger than currently
6994 // set, update the alignment.
6995 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
6996 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
6997 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
6998 unsigned Align = std::min(Alignment1, Alignment2);
6999 if (MI->getAlignment()->getZExtValue() < Align) {
7000 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
7003 } else if (isa<MemSetInst>(MI)) {
7004 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
7005 if (MI->getAlignment()->getZExtValue() < Alignment) {
7006 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
7011 if (Changed) return II;
7013 switch (II->getIntrinsicID()) {
7015 case Intrinsic::ppc_altivec_lvx:
7016 case Intrinsic::ppc_altivec_lvxl:
7017 case Intrinsic::x86_sse_loadu_ps:
7018 case Intrinsic::x86_sse2_loadu_pd:
7019 case Intrinsic::x86_sse2_loadu_dq:
7020 // Turn PPC lvx -> load if the pointer is known aligned.
7021 // Turn X86 loadups -> load if the pointer is known aligned.
7022 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7023 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7024 PointerType::get(II->getType()), CI);
7025 return new LoadInst(Ptr);
7028 case Intrinsic::ppc_altivec_stvx:
7029 case Intrinsic::ppc_altivec_stvxl:
7030 // Turn stvx -> store if the pointer is known aligned.
7031 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
7032 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
7033 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7035 return new StoreInst(II->getOperand(1), Ptr);
7038 case Intrinsic::x86_sse_storeu_ps:
7039 case Intrinsic::x86_sse2_storeu_pd:
7040 case Intrinsic::x86_sse2_storeu_dq:
7041 case Intrinsic::x86_sse2_storel_dq:
7042 // Turn X86 storeu -> store if the pointer is known aligned.
7043 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7044 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
7045 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7047 return new StoreInst(II->getOperand(2), Ptr);
7051 case Intrinsic::x86_sse_cvttss2si: {
7052 // These intrinsics only demands the 0th element of its input vector. If
7053 // we can simplify the input based on that, do so now.
7055 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7057 II->setOperand(1, V);
7063 case Intrinsic::ppc_altivec_vperm:
7064 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7065 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
7066 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7068 // Check that all of the elements are integer constants or undefs.
7069 bool AllEltsOk = true;
7070 for (unsigned i = 0; i != 16; ++i) {
7071 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7072 !isa<UndefValue>(Mask->getOperand(i))) {
7079 // Cast the input vectors to byte vectors.
7080 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7081 II->getOperand(1), Mask->getType(), CI);
7082 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7083 II->getOperand(2), Mask->getType(), CI);
7084 Value *Result = UndefValue::get(Op0->getType());
7086 // Only extract each element once.
7087 Value *ExtractedElts[32];
7088 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7090 for (unsigned i = 0; i != 16; ++i) {
7091 if (isa<UndefValue>(Mask->getOperand(i)))
7093 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
7094 Idx &= 31; // Match the hardware behavior.
7096 if (ExtractedElts[Idx] == 0) {
7098 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
7099 InsertNewInstBefore(Elt, CI);
7100 ExtractedElts[Idx] = Elt;
7103 // Insert this value into the result vector.
7104 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
7105 InsertNewInstBefore(cast<Instruction>(Result), CI);
7107 return CastInst::create(Instruction::BitCast, Result, CI.getType());
7112 case Intrinsic::stackrestore: {
7113 // If the save is right next to the restore, remove the restore. This can
7114 // happen when variable allocas are DCE'd.
7115 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7116 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7117 BasicBlock::iterator BI = SS;
7119 return EraseInstFromFunction(CI);
7123 // If the stack restore is in a return/unwind block and if there are no
7124 // allocas or calls between the restore and the return, nuke the restore.
7125 TerminatorInst *TI = II->getParent()->getTerminator();
7126 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7127 BasicBlock::iterator BI = II;
7128 bool CannotRemove = false;
7129 for (++BI; &*BI != TI; ++BI) {
7130 if (isa<AllocaInst>(BI) ||
7131 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7132 CannotRemove = true;
7137 return EraseInstFromFunction(CI);
7144 return visitCallSite(II);
7147 // InvokeInst simplification
7149 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
7150 return visitCallSite(&II);
7153 // visitCallSite - Improvements for call and invoke instructions.
7155 Instruction *InstCombiner::visitCallSite(CallSite CS) {
7156 bool Changed = false;
7158 // If the callee is a constexpr cast of a function, attempt to move the cast
7159 // to the arguments of the call/invoke.
7160 if (transformConstExprCastCall(CS)) return 0;
7162 Value *Callee = CS.getCalledValue();
7164 if (Function *CalleeF = dyn_cast<Function>(Callee))
7165 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7166 Instruction *OldCall = CS.getInstruction();
7167 // If the call and callee calling conventions don't match, this call must
7168 // be unreachable, as the call is undefined.
7169 new StoreInst(ConstantInt::getTrue(),
7170 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
7171 if (!OldCall->use_empty())
7172 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7173 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7174 return EraseInstFromFunction(*OldCall);
7178 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7179 // This instruction is not reachable, just remove it. We insert a store to
7180 // undef so that we know that this code is not reachable, despite the fact
7181 // that we can't modify the CFG here.
7182 new StoreInst(ConstantInt::getTrue(),
7183 UndefValue::get(PointerType::get(Type::Int1Ty)),
7184 CS.getInstruction());
7186 if (!CS.getInstruction()->use_empty())
7187 CS.getInstruction()->
7188 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7190 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7191 // Don't break the CFG, insert a dummy cond branch.
7192 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
7193 ConstantInt::getTrue(), II);
7195 return EraseInstFromFunction(*CS.getInstruction());
7198 const PointerType *PTy = cast<PointerType>(Callee->getType());
7199 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7200 if (FTy->isVarArg()) {
7201 // See if we can optimize any arguments passed through the varargs area of
7203 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7204 E = CS.arg_end(); I != E; ++I)
7205 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7206 // If this cast does not effect the value passed through the varargs
7207 // area, we can eliminate the use of the cast.
7208 Value *Op = CI->getOperand(0);
7209 if (CI->isLosslessCast()) {
7216 return Changed ? CS.getInstruction() : 0;
7219 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
7220 // attempt to move the cast to the arguments of the call/invoke.
7222 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7223 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7224 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
7225 if (CE->getOpcode() != Instruction::BitCast ||
7226 !isa<Function>(CE->getOperand(0)))
7228 Function *Callee = cast<Function>(CE->getOperand(0));
7229 Instruction *Caller = CS.getInstruction();
7231 // Okay, this is a cast from a function to a different type. Unless doing so
7232 // would cause a type conversion of one of our arguments, change this call to
7233 // be a direct call with arguments casted to the appropriate types.
7235 const FunctionType *FT = Callee->getFunctionType();
7236 const Type *OldRetTy = Caller->getType();
7238 // Check to see if we are changing the return type...
7239 if (OldRetTy != FT->getReturnType()) {
7240 if (Callee->isDeclaration() && !Caller->use_empty() &&
7241 OldRetTy != FT->getReturnType() &&
7242 // Conversion is ok if changing from pointer to int of same size.
7243 !(isa<PointerType>(FT->getReturnType()) &&
7244 TD->getIntPtrType() == OldRetTy))
7245 return false; // Cannot transform this return value.
7247 // If the callsite is an invoke instruction, and the return value is used by
7248 // a PHI node in a successor, we cannot change the return type of the call
7249 // because there is no place to put the cast instruction (without breaking
7250 // the critical edge). Bail out in this case.
7251 if (!Caller->use_empty())
7252 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7253 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7255 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7256 if (PN->getParent() == II->getNormalDest() ||
7257 PN->getParent() == II->getUnwindDest())
7261 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7262 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
7264 CallSite::arg_iterator AI = CS.arg_begin();
7265 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7266 const Type *ParamTy = FT->getParamType(i);
7267 const Type *ActTy = (*AI)->getType();
7268 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
7269 //Either we can cast directly, or we can upconvert the argument
7270 bool isConvertible = ActTy == ParamTy ||
7271 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
7272 (ParamTy->isInteger() && ActTy->isInteger() &&
7273 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7274 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7275 && c->getSExtValue() > 0);
7276 if (Callee->isDeclaration() && !isConvertible) return false;
7279 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7280 Callee->isDeclaration())
7281 return false; // Do not delete arguments unless we have a function body...
7283 // Okay, we decided that this is a safe thing to do: go ahead and start
7284 // inserting cast instructions as necessary...
7285 std::vector<Value*> Args;
7286 Args.reserve(NumActualArgs);
7288 AI = CS.arg_begin();
7289 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7290 const Type *ParamTy = FT->getParamType(i);
7291 if ((*AI)->getType() == ParamTy) {
7292 Args.push_back(*AI);
7294 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
7295 false, ParamTy, false);
7296 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
7297 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
7301 // If the function takes more arguments than the call was taking, add them
7303 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7304 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7306 // If we are removing arguments to the function, emit an obnoxious warning...
7307 if (FT->getNumParams() < NumActualArgs)
7308 if (!FT->isVarArg()) {
7309 cerr << "WARNING: While resolving call to function '"
7310 << Callee->getName() << "' arguments were dropped!\n";
7312 // Add all of the arguments in their promoted form to the arg list...
7313 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7314 const Type *PTy = getPromotedType((*AI)->getType());
7315 if (PTy != (*AI)->getType()) {
7316 // Must promote to pass through va_arg area!
7317 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7319 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
7320 InsertNewInstBefore(Cast, *Caller);
7321 Args.push_back(Cast);
7323 Args.push_back(*AI);
7328 if (FT->getReturnType() == Type::VoidTy)
7329 Caller->setName(""); // Void type should not have a name...
7332 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7333 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
7334 Args, Caller->getName(), Caller);
7335 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
7337 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
7338 if (cast<CallInst>(Caller)->isTailCall())
7339 cast<CallInst>(NC)->setTailCall();
7340 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
7343 // Insert a cast of the return type as necessary...
7345 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7346 if (NV->getType() != Type::VoidTy) {
7347 const Type *CallerTy = Caller->getType();
7348 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7350 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
7352 // If this is an invoke instruction, we should insert it after the first
7353 // non-phi, instruction in the normal successor block.
7354 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7355 BasicBlock::iterator I = II->getNormalDest()->begin();
7356 while (isa<PHINode>(I)) ++I;
7357 InsertNewInstBefore(NC, *I);
7359 // Otherwise, it's a call, just insert cast right after the call instr
7360 InsertNewInstBefore(NC, *Caller);
7362 AddUsersToWorkList(*Caller);
7364 NV = UndefValue::get(Caller->getType());
7368 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7369 Caller->replaceAllUsesWith(NV);
7370 Caller->getParent()->getInstList().erase(Caller);
7371 removeFromWorkList(Caller);
7375 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7376 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7377 /// and a single binop.
7378 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7379 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7380 assert(isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7381 isa<GetElementPtrInst>(FirstInst) || isa<CmpInst>(FirstInst));
7382 unsigned Opc = FirstInst->getOpcode();
7383 Value *LHSVal = FirstInst->getOperand(0);
7384 Value *RHSVal = FirstInst->getOperand(1);
7386 const Type *LHSType = LHSVal->getType();
7387 const Type *RHSType = RHSVal->getType();
7389 // Scan to see if all operands are the same opcode, all have one use, and all
7390 // kill their operands (i.e. the operands have one use).
7391 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
7392 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
7393 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7394 // Verify type of the LHS matches so we don't fold cmp's of different
7395 // types or GEP's with different index types.
7396 I->getOperand(0)->getType() != LHSType ||
7397 I->getOperand(1)->getType() != RHSType)
7400 // If they are CmpInst instructions, check their predicates
7401 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7402 if (cast<CmpInst>(I)->getPredicate() !=
7403 cast<CmpInst>(FirstInst)->getPredicate())
7406 // Keep track of which operand needs a phi node.
7407 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7408 if (I->getOperand(1) != RHSVal) RHSVal = 0;
7411 // Otherwise, this is safe to transform, determine if it is profitable.
7413 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7414 // Indexes are often folded into load/store instructions, so we don't want to
7415 // hide them behind a phi.
7416 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7419 Value *InLHS = FirstInst->getOperand(0);
7420 Value *InRHS = FirstInst->getOperand(1);
7421 PHINode *NewLHS = 0, *NewRHS = 0;
7423 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7424 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7425 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
7426 InsertNewInstBefore(NewLHS, PN);
7431 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7432 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7433 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
7434 InsertNewInstBefore(NewRHS, PN);
7438 // Add all operands to the new PHIs.
7439 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7441 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7442 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7445 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7446 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7450 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7451 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7452 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7453 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7455 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FirstInst))
7456 return new ShiftInst(SI->getOpcode(), LHSVal, RHSVal);
7458 assert(isa<GetElementPtrInst>(FirstInst));
7459 return new GetElementPtrInst(LHSVal, RHSVal);
7463 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7464 /// of the block that defines it. This means that it must be obvious the value
7465 /// of the load is not changed from the point of the load to the end of the
7467 static bool isSafeToSinkLoad(LoadInst *L) {
7468 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7470 for (++BBI; BBI != E; ++BBI)
7471 if (BBI->mayWriteToMemory())
7477 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7478 // operator and they all are only used by the PHI, PHI together their
7479 // inputs, and do the operation once, to the result of the PHI.
7480 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7481 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7483 // Scan the instruction, looking for input operations that can be folded away.
7484 // If all input operands to the phi are the same instruction (e.g. a cast from
7485 // the same type or "+42") we can pull the operation through the PHI, reducing
7486 // code size and simplifying code.
7487 Constant *ConstantOp = 0;
7488 const Type *CastSrcTy = 0;
7489 bool isVolatile = false;
7490 if (isa<CastInst>(FirstInst)) {
7491 CastSrcTy = FirstInst->getOperand(0)->getType();
7492 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst) ||
7493 isa<CmpInst>(FirstInst)) {
7494 // Can fold binop, compare or shift here if the RHS is a constant,
7495 // otherwise call FoldPHIArgBinOpIntoPHI.
7496 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
7497 if (ConstantOp == 0)
7498 return FoldPHIArgBinOpIntoPHI(PN);
7499 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7500 isVolatile = LI->isVolatile();
7501 // We can't sink the load if the loaded value could be modified between the
7502 // load and the PHI.
7503 if (LI->getParent() != PN.getIncomingBlock(0) ||
7504 !isSafeToSinkLoad(LI))
7506 } else if (isa<GetElementPtrInst>(FirstInst)) {
7507 if (FirstInst->getNumOperands() == 2)
7508 return FoldPHIArgBinOpIntoPHI(PN);
7509 // Can't handle general GEPs yet.
7512 return 0; // Cannot fold this operation.
7515 // Check to see if all arguments are the same operation.
7516 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7517 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7518 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7519 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
7522 if (I->getOperand(0)->getType() != CastSrcTy)
7523 return 0; // Cast operation must match.
7524 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7525 // We can't sink the load if the loaded value could be modified between
7526 // the load and the PHI.
7527 if (LI->isVolatile() != isVolatile ||
7528 LI->getParent() != PN.getIncomingBlock(i) ||
7529 !isSafeToSinkLoad(LI))
7531 } else if (I->getOperand(1) != ConstantOp) {
7536 // Okay, they are all the same operation. Create a new PHI node of the
7537 // correct type, and PHI together all of the LHS's of the instructions.
7538 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7539 PN.getName()+".in");
7540 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
7542 Value *InVal = FirstInst->getOperand(0);
7543 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7545 // Add all operands to the new PHI.
7546 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7547 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7548 if (NewInVal != InVal)
7550 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
7555 // The new PHI unions all of the same values together. This is really
7556 // common, so we handle it intelligently here for compile-time speed.
7560 InsertNewInstBefore(NewPN, PN);
7564 // Insert and return the new operation.
7565 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
7566 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
7567 else if (isa<LoadInst>(FirstInst))
7568 return new LoadInst(PhiVal, "", isVolatile);
7569 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7570 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
7571 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7572 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
7573 PhiVal, ConstantOp);
7575 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
7576 PhiVal, ConstantOp);
7579 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
7581 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
7582 if (PN->use_empty()) return true;
7583 if (!PN->hasOneUse()) return false;
7585 // Remember this node, and if we find the cycle, return.
7586 if (!PotentiallyDeadPHIs.insert(PN).second)
7589 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
7590 return DeadPHICycle(PU, PotentiallyDeadPHIs);
7595 // PHINode simplification
7597 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
7598 // If LCSSA is around, don't mess with Phi nodes
7599 if (mustPreserveAnalysisID(LCSSAID)) return 0;
7601 if (Value *V = PN.hasConstantValue())
7602 return ReplaceInstUsesWith(PN, V);
7604 // If all PHI operands are the same operation, pull them through the PHI,
7605 // reducing code size.
7606 if (isa<Instruction>(PN.getIncomingValue(0)) &&
7607 PN.getIncomingValue(0)->hasOneUse())
7608 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
7611 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
7612 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
7613 // PHI)... break the cycle.
7614 if (PN.hasOneUse()) {
7615 Instruction *PHIUser = cast<Instruction>(PN.use_back());
7616 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
7617 std::set<PHINode*> PotentiallyDeadPHIs;
7618 PotentiallyDeadPHIs.insert(&PN);
7619 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
7620 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7623 // If this phi has a single use, and if that use just computes a value for
7624 // the next iteration of a loop, delete the phi. This occurs with unused
7625 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
7626 // common case here is good because the only other things that catch this
7627 // are induction variable analysis (sometimes) and ADCE, which is only run
7629 if (PHIUser->hasOneUse() &&
7630 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
7631 PHIUser->use_back() == &PN) {
7632 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
7639 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
7640 Instruction *InsertPoint,
7642 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
7643 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
7644 // We must cast correctly to the pointer type. Ensure that we
7645 // sign extend the integer value if it is smaller as this is
7646 // used for address computation.
7647 Instruction::CastOps opcode =
7648 (VTySize < PtrSize ? Instruction::SExt :
7649 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
7650 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
7654 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
7655 Value *PtrOp = GEP.getOperand(0);
7656 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
7657 // If so, eliminate the noop.
7658 if (GEP.getNumOperands() == 1)
7659 return ReplaceInstUsesWith(GEP, PtrOp);
7661 if (isa<UndefValue>(GEP.getOperand(0)))
7662 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
7664 bool HasZeroPointerIndex = false;
7665 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
7666 HasZeroPointerIndex = C->isNullValue();
7668 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
7669 return ReplaceInstUsesWith(GEP, PtrOp);
7671 // Eliminate unneeded casts for indices.
7672 bool MadeChange = false;
7673 gep_type_iterator GTI = gep_type_begin(GEP);
7674 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
7675 if (isa<SequentialType>(*GTI)) {
7676 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
7677 if (CI->getOpcode() == Instruction::ZExt ||
7678 CI->getOpcode() == Instruction::SExt) {
7679 const Type *SrcTy = CI->getOperand(0)->getType();
7680 // We can eliminate a cast from i32 to i64 iff the target
7681 // is a 32-bit pointer target.
7682 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
7684 GEP.setOperand(i, CI->getOperand(0));
7688 // If we are using a wider index than needed for this platform, shrink it
7689 // to what we need. If the incoming value needs a cast instruction,
7690 // insert it. This explicit cast can make subsequent optimizations more
7692 Value *Op = GEP.getOperand(i);
7693 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
7694 if (Constant *C = dyn_cast<Constant>(Op)) {
7695 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
7698 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
7700 GEP.setOperand(i, Op);
7704 if (MadeChange) return &GEP;
7706 // Combine Indices - If the source pointer to this getelementptr instruction
7707 // is a getelementptr instruction, combine the indices of the two
7708 // getelementptr instructions into a single instruction.
7710 std::vector<Value*> SrcGEPOperands;
7711 if (User *Src = dyn_castGetElementPtr(PtrOp))
7712 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
7714 if (!SrcGEPOperands.empty()) {
7715 // Note that if our source is a gep chain itself that we wait for that
7716 // chain to be resolved before we perform this transformation. This
7717 // avoids us creating a TON of code in some cases.
7719 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
7720 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
7721 return 0; // Wait until our source is folded to completion.
7723 std::vector<Value *> Indices;
7725 // Find out whether the last index in the source GEP is a sequential idx.
7726 bool EndsWithSequential = false;
7727 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
7728 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
7729 EndsWithSequential = !isa<StructType>(*I);
7731 // Can we combine the two pointer arithmetics offsets?
7732 if (EndsWithSequential) {
7733 // Replace: gep (gep %P, long B), long A, ...
7734 // With: T = long A+B; gep %P, T, ...
7736 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
7737 if (SO1 == Constant::getNullValue(SO1->getType())) {
7739 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
7742 // If they aren't the same type, convert both to an integer of the
7743 // target's pointer size.
7744 if (SO1->getType() != GO1->getType()) {
7745 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
7746 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
7747 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
7748 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
7750 unsigned PS = TD->getPointerSize();
7751 if (TD->getTypeSize(SO1->getType()) == PS) {
7752 // Convert GO1 to SO1's type.
7753 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
7755 } else if (TD->getTypeSize(GO1->getType()) == PS) {
7756 // Convert SO1 to GO1's type.
7757 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
7759 const Type *PT = TD->getIntPtrType();
7760 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
7761 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
7765 if (isa<Constant>(SO1) && isa<Constant>(GO1))
7766 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
7768 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
7769 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
7773 // Recycle the GEP we already have if possible.
7774 if (SrcGEPOperands.size() == 2) {
7775 GEP.setOperand(0, SrcGEPOperands[0]);
7776 GEP.setOperand(1, Sum);
7779 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7780 SrcGEPOperands.end()-1);
7781 Indices.push_back(Sum);
7782 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
7784 } else if (isa<Constant>(*GEP.idx_begin()) &&
7785 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
7786 SrcGEPOperands.size() != 1) {
7787 // Otherwise we can do the fold if the first index of the GEP is a zero
7788 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
7789 SrcGEPOperands.end());
7790 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
7793 if (!Indices.empty())
7794 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
7796 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
7797 // GEP of global variable. If all of the indices for this GEP are
7798 // constants, we can promote this to a constexpr instead of an instruction.
7800 // Scan for nonconstants...
7801 SmallVector<Constant*, 8> Indices;
7802 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
7803 for (; I != E && isa<Constant>(*I); ++I)
7804 Indices.push_back(cast<Constant>(*I));
7806 if (I == E) { // If they are all constants...
7807 Constant *CE = ConstantExpr::getGetElementPtr(GV,
7808 &Indices[0],Indices.size());
7810 // Replace all uses of the GEP with the new constexpr...
7811 return ReplaceInstUsesWith(GEP, CE);
7813 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
7814 if (!isa<PointerType>(X->getType())) {
7815 // Not interesting. Source pointer must be a cast from pointer.
7816 } else if (HasZeroPointerIndex) {
7817 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
7818 // into : GEP [10 x ubyte]* X, long 0, ...
7820 // This occurs when the program declares an array extern like "int X[];"
7822 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
7823 const PointerType *XTy = cast<PointerType>(X->getType());
7824 if (const ArrayType *XATy =
7825 dyn_cast<ArrayType>(XTy->getElementType()))
7826 if (const ArrayType *CATy =
7827 dyn_cast<ArrayType>(CPTy->getElementType()))
7828 if (CATy->getElementType() == XATy->getElementType()) {
7829 // At this point, we know that the cast source type is a pointer
7830 // to an array of the same type as the destination pointer
7831 // array. Because the array type is never stepped over (there
7832 // is a leading zero) we can fold the cast into this GEP.
7833 GEP.setOperand(0, X);
7836 } else if (GEP.getNumOperands() == 2) {
7837 // Transform things like:
7838 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
7839 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
7840 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
7841 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
7842 if (isa<ArrayType>(SrcElTy) &&
7843 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
7844 TD->getTypeSize(ResElTy)) {
7845 Value *V = InsertNewInstBefore(
7846 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
7847 GEP.getOperand(1), GEP.getName()), GEP);
7848 // V and GEP are both pointer types --> BitCast
7849 return new BitCastInst(V, GEP.getType());
7852 // Transform things like:
7853 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
7854 // (where tmp = 8*tmp2) into:
7855 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
7857 if (isa<ArrayType>(SrcElTy) &&
7858 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
7859 uint64_t ArrayEltSize =
7860 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
7862 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
7863 // allow either a mul, shift, or constant here.
7865 ConstantInt *Scale = 0;
7866 if (ArrayEltSize == 1) {
7867 NewIdx = GEP.getOperand(1);
7868 Scale = ConstantInt::get(NewIdx->getType(), 1);
7869 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
7870 NewIdx = ConstantInt::get(CI->getType(), 1);
7872 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
7873 if (Inst->getOpcode() == Instruction::Shl &&
7874 isa<ConstantInt>(Inst->getOperand(1))) {
7876 cast<ConstantInt>(Inst->getOperand(1))->getZExtValue();
7877 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmt);
7878 NewIdx = Inst->getOperand(0);
7879 } else if (Inst->getOpcode() == Instruction::Mul &&
7880 isa<ConstantInt>(Inst->getOperand(1))) {
7881 Scale = cast<ConstantInt>(Inst->getOperand(1));
7882 NewIdx = Inst->getOperand(0);
7886 // If the index will be to exactly the right offset with the scale taken
7887 // out, perform the transformation.
7888 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
7889 if (isa<ConstantInt>(Scale))
7890 Scale = ConstantInt::get(Scale->getType(),
7891 Scale->getZExtValue() / ArrayEltSize);
7892 if (Scale->getZExtValue() != 1) {
7893 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
7895 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
7896 NewIdx = InsertNewInstBefore(Sc, GEP);
7899 // Insert the new GEP instruction.
7900 Instruction *NewGEP =
7901 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
7902 NewIdx, GEP.getName());
7903 NewGEP = InsertNewInstBefore(NewGEP, GEP);
7904 // The NewGEP must be pointer typed, so must the old one -> BitCast
7905 return new BitCastInst(NewGEP, GEP.getType());
7914 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
7915 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
7916 if (AI.isArrayAllocation()) // Check C != 1
7917 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
7919 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
7920 AllocationInst *New = 0;
7922 // Create and insert the replacement instruction...
7923 if (isa<MallocInst>(AI))
7924 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
7926 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
7927 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
7930 InsertNewInstBefore(New, AI);
7932 // Scan to the end of the allocation instructions, to skip over a block of
7933 // allocas if possible...
7935 BasicBlock::iterator It = New;
7936 while (isa<AllocationInst>(*It)) ++It;
7938 // Now that I is pointing to the first non-allocation-inst in the block,
7939 // insert our getelementptr instruction...
7941 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
7942 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
7943 New->getName()+".sub", It);
7945 // Now make everything use the getelementptr instead of the original
7947 return ReplaceInstUsesWith(AI, V);
7948 } else if (isa<UndefValue>(AI.getArraySize())) {
7949 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7952 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
7953 // Note that we only do this for alloca's, because malloc should allocate and
7954 // return a unique pointer, even for a zero byte allocation.
7955 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
7956 TD->getTypeSize(AI.getAllocatedType()) == 0)
7957 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
7962 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
7963 Value *Op = FI.getOperand(0);
7965 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
7966 if (CastInst *CI = dyn_cast<CastInst>(Op))
7967 if (isa<PointerType>(CI->getOperand(0)->getType())) {
7968 FI.setOperand(0, CI->getOperand(0));
7972 // free undef -> unreachable.
7973 if (isa<UndefValue>(Op)) {
7974 // Insert a new store to null because we cannot modify the CFG here.
7975 new StoreInst(ConstantInt::getTrue(),
7976 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
7977 return EraseInstFromFunction(FI);
7980 // If we have 'free null' delete the instruction. This can happen in stl code
7981 // when lots of inlining happens.
7982 if (isa<ConstantPointerNull>(Op))
7983 return EraseInstFromFunction(FI);
7989 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
7990 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
7991 User *CI = cast<User>(LI.getOperand(0));
7992 Value *CastOp = CI->getOperand(0);
7994 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
7995 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
7996 const Type *SrcPTy = SrcTy->getElementType();
7998 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
7999 isa<PackedType>(DestPTy)) {
8000 // If the source is an array, the code below will not succeed. Check to
8001 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8003 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8004 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8005 if (ASrcTy->getNumElements() != 0) {
8007 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8008 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
8009 SrcTy = cast<PointerType>(CastOp->getType());
8010 SrcPTy = SrcTy->getElementType();
8013 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
8014 isa<PackedType>(SrcPTy)) &&
8015 // Do not allow turning this into a load of an integer, which is then
8016 // casted to a pointer, this pessimizes pointer analysis a lot.
8017 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
8018 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8019 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
8021 // Okay, we are casting from one integer or pointer type to another of
8022 // the same size. Instead of casting the pointer before the load, cast
8023 // the result of the loaded value.
8024 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8026 LI.isVolatile()),LI);
8027 // Now cast the result of the load.
8028 return new BitCastInst(NewLoad, LI.getType());
8035 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
8036 /// from this value cannot trap. If it is not obviously safe to load from the
8037 /// specified pointer, we do a quick local scan of the basic block containing
8038 /// ScanFrom, to determine if the address is already accessed.
8039 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8040 // If it is an alloca or global variable, it is always safe to load from.
8041 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8043 // Otherwise, be a little bit agressive by scanning the local block where we
8044 // want to check to see if the pointer is already being loaded or stored
8045 // from/to. If so, the previous load or store would have already trapped,
8046 // so there is no harm doing an extra load (also, CSE will later eliminate
8047 // the load entirely).
8048 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8053 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8054 if (LI->getOperand(0) == V) return true;
8055 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8056 if (SI->getOperand(1) == V) return true;
8062 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8063 Value *Op = LI.getOperand(0);
8065 // load (cast X) --> cast (load X) iff safe
8066 if (isa<CastInst>(Op))
8067 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8070 // None of the following transforms are legal for volatile loads.
8071 if (LI.isVolatile()) return 0;
8073 if (&LI.getParent()->front() != &LI) {
8074 BasicBlock::iterator BBI = &LI; --BBI;
8075 // If the instruction immediately before this is a store to the same
8076 // address, do a simple form of store->load forwarding.
8077 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8078 if (SI->getOperand(1) == LI.getOperand(0))
8079 return ReplaceInstUsesWith(LI, SI->getOperand(0));
8080 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8081 if (LIB->getOperand(0) == LI.getOperand(0))
8082 return ReplaceInstUsesWith(LI, LIB);
8085 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8086 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8087 isa<UndefValue>(GEPI->getOperand(0))) {
8088 // Insert a new store to null instruction before the load to indicate
8089 // that this code is not reachable. We do this instead of inserting
8090 // an unreachable instruction directly because we cannot modify the
8092 new StoreInst(UndefValue::get(LI.getType()),
8093 Constant::getNullValue(Op->getType()), &LI);
8094 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8097 if (Constant *C = dyn_cast<Constant>(Op)) {
8098 // load null/undef -> undef
8099 if ((C->isNullValue() || isa<UndefValue>(C))) {
8100 // Insert a new store to null instruction before the load to indicate that
8101 // this code is not reachable. We do this instead of inserting an
8102 // unreachable instruction directly because we cannot modify the CFG.
8103 new StoreInst(UndefValue::get(LI.getType()),
8104 Constant::getNullValue(Op->getType()), &LI);
8105 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8108 // Instcombine load (constant global) into the value loaded.
8109 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8110 if (GV->isConstant() && !GV->isDeclaration())
8111 return ReplaceInstUsesWith(LI, GV->getInitializer());
8113 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8114 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8115 if (CE->getOpcode() == Instruction::GetElementPtr) {
8116 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8117 if (GV->isConstant() && !GV->isDeclaration())
8119 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
8120 return ReplaceInstUsesWith(LI, V);
8121 if (CE->getOperand(0)->isNullValue()) {
8122 // Insert a new store to null instruction before the load to indicate
8123 // that this code is not reachable. We do this instead of inserting
8124 // an unreachable instruction directly because we cannot modify the
8126 new StoreInst(UndefValue::get(LI.getType()),
8127 Constant::getNullValue(Op->getType()), &LI);
8128 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8131 } else if (CE->isCast()) {
8132 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8137 if (Op->hasOneUse()) {
8138 // Change select and PHI nodes to select values instead of addresses: this
8139 // helps alias analysis out a lot, allows many others simplifications, and
8140 // exposes redundancy in the code.
8142 // Note that we cannot do the transformation unless we know that the
8143 // introduced loads cannot trap! Something like this is valid as long as
8144 // the condition is always false: load (select bool %C, int* null, int* %G),
8145 // but it would not be valid if we transformed it to load from null
8148 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8149 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
8150 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8151 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
8152 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
8153 SI->getOperand(1)->getName()+".val"), LI);
8154 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
8155 SI->getOperand(2)->getName()+".val"), LI);
8156 return new SelectInst(SI->getCondition(), V1, V2);
8159 // load (select (cond, null, P)) -> load P
8160 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8161 if (C->isNullValue()) {
8162 LI.setOperand(0, SI->getOperand(2));
8166 // load (select (cond, P, null)) -> load P
8167 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8168 if (C->isNullValue()) {
8169 LI.setOperand(0, SI->getOperand(1));
8177 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
8179 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8180 User *CI = cast<User>(SI.getOperand(1));
8181 Value *CastOp = CI->getOperand(0);
8183 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8184 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8185 const Type *SrcPTy = SrcTy->getElementType();
8187 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
8188 // If the source is an array, the code below will not succeed. Check to
8189 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8191 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8192 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8193 if (ASrcTy->getNumElements() != 0) {
8195 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8196 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
8197 SrcTy = cast<PointerType>(CastOp->getType());
8198 SrcPTy = SrcTy->getElementType();
8201 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8202 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8203 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
8205 // Okay, we are casting from one integer or pointer type to another of
8206 // the same size. Instead of casting the pointer before
8207 // the store, cast the value to be stored.
8209 Value *SIOp0 = SI.getOperand(0);
8210 Instruction::CastOps opcode = Instruction::BitCast;
8211 const Type* CastSrcTy = SIOp0->getType();
8212 const Type* CastDstTy = SrcPTy;
8213 if (isa<PointerType>(CastDstTy)) {
8214 if (CastSrcTy->isInteger())
8215 opcode = Instruction::IntToPtr;
8216 } else if (isa<IntegerType>(CastDstTy)) {
8217 if (isa<PointerType>(SIOp0->getType()))
8218 opcode = Instruction::PtrToInt;
8220 if (Constant *C = dyn_cast<Constant>(SIOp0))
8221 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
8223 NewCast = IC.InsertNewInstBefore(
8224 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
8226 return new StoreInst(NewCast, CastOp);
8233 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8234 Value *Val = SI.getOperand(0);
8235 Value *Ptr = SI.getOperand(1);
8237 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
8238 EraseInstFromFunction(SI);
8243 // If the RHS is an alloca with a single use, zapify the store, making the
8245 if (Ptr->hasOneUse()) {
8246 if (isa<AllocaInst>(Ptr)) {
8247 EraseInstFromFunction(SI);
8252 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8253 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8254 GEP->getOperand(0)->hasOneUse()) {
8255 EraseInstFromFunction(SI);
8261 // Do really simple DSE, to catch cases where there are several consequtive
8262 // stores to the same location, separated by a few arithmetic operations. This
8263 // situation often occurs with bitfield accesses.
8264 BasicBlock::iterator BBI = &SI;
8265 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8269 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8270 // Prev store isn't volatile, and stores to the same location?
8271 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8274 EraseInstFromFunction(*PrevSI);
8280 // If this is a load, we have to stop. However, if the loaded value is from
8281 // the pointer we're loading and is producing the pointer we're storing,
8282 // then *this* store is dead (X = load P; store X -> P).
8283 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8284 if (LI == Val && LI->getOperand(0) == Ptr) {
8285 EraseInstFromFunction(SI);
8289 // Otherwise, this is a load from some other location. Stores before it
8294 // Don't skip over loads or things that can modify memory.
8295 if (BBI->mayWriteToMemory())
8300 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
8302 // store X, null -> turns into 'unreachable' in SimplifyCFG
8303 if (isa<ConstantPointerNull>(Ptr)) {
8304 if (!isa<UndefValue>(Val)) {
8305 SI.setOperand(0, UndefValue::get(Val->getType()));
8306 if (Instruction *U = dyn_cast<Instruction>(Val))
8307 WorkList.push_back(U); // Dropped a use.
8310 return 0; // Do not modify these!
8313 // store undef, Ptr -> noop
8314 if (isa<UndefValue>(Val)) {
8315 EraseInstFromFunction(SI);
8320 // If the pointer destination is a cast, see if we can fold the cast into the
8322 if (isa<CastInst>(Ptr))
8323 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8325 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
8327 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8331 // If this store is the last instruction in the basic block, and if the block
8332 // ends with an unconditional branch, try to move it to the successor block.
8334 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8335 if (BI->isUnconditional()) {
8336 // Check to see if the successor block has exactly two incoming edges. If
8337 // so, see if the other predecessor contains a store to the same location.
8338 // if so, insert a PHI node (if needed) and move the stores down.
8339 BasicBlock *Dest = BI->getSuccessor(0);
8341 pred_iterator PI = pred_begin(Dest);
8342 BasicBlock *Other = 0;
8343 if (*PI != BI->getParent())
8346 if (PI != pred_end(Dest)) {
8347 if (*PI != BI->getParent())
8352 if (++PI != pred_end(Dest))
8355 if (Other) { // If only one other pred...
8356 BBI = Other->getTerminator();
8357 // Make sure this other block ends in an unconditional branch and that
8358 // there is an instruction before the branch.
8359 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
8360 BBI != Other->begin()) {
8362 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
8364 // If this instruction is a store to the same location.
8365 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
8366 // Okay, we know we can perform this transformation. Insert a PHI
8367 // node now if we need it.
8368 Value *MergedVal = OtherStore->getOperand(0);
8369 if (MergedVal != SI.getOperand(0)) {
8370 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8371 PN->reserveOperandSpace(2);
8372 PN->addIncoming(SI.getOperand(0), SI.getParent());
8373 PN->addIncoming(OtherStore->getOperand(0), Other);
8374 MergedVal = InsertNewInstBefore(PN, Dest->front());
8377 // Advance to a place where it is safe to insert the new store and
8379 BBI = Dest->begin();
8380 while (isa<PHINode>(BBI)) ++BBI;
8381 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8382 OtherStore->isVolatile()), *BBI);
8384 // Nuke the old stores.
8385 EraseInstFromFunction(SI);
8386 EraseInstFromFunction(*OtherStore);
8398 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8399 // Change br (not X), label True, label False to: br X, label False, True
8401 BasicBlock *TrueDest;
8402 BasicBlock *FalseDest;
8403 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8404 !isa<Constant>(X)) {
8405 // Swap Destinations and condition...
8407 BI.setSuccessor(0, FalseDest);
8408 BI.setSuccessor(1, TrueDest);
8412 // Cannonicalize fcmp_one -> fcmp_oeq
8413 FCmpInst::Predicate FPred; Value *Y;
8414 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8415 TrueDest, FalseDest)))
8416 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8417 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8418 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
8419 std::string Name = I->getName(); I->setName("");
8420 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8421 Value *NewSCC = new FCmpInst(NewPred, X, Y, Name, I);
8422 // Swap Destinations and condition...
8423 BI.setCondition(NewSCC);
8424 BI.setSuccessor(0, FalseDest);
8425 BI.setSuccessor(1, TrueDest);
8426 removeFromWorkList(I);
8427 I->getParent()->getInstList().erase(I);
8428 WorkList.push_back(cast<Instruction>(NewSCC));
8432 // Cannonicalize icmp_ne -> icmp_eq
8433 ICmpInst::Predicate IPred;
8434 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8435 TrueDest, FalseDest)))
8436 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8437 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8438 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8439 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8440 std::string Name = I->getName(); I->setName("");
8441 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8442 Value *NewSCC = new ICmpInst(NewPred, X, Y, Name, I);
8443 // Swap Destinations and condition...
8444 BI.setCondition(NewSCC);
8445 BI.setSuccessor(0, FalseDest);
8446 BI.setSuccessor(1, TrueDest);
8447 removeFromWorkList(I);
8448 I->getParent()->getInstList().erase(I);
8449 WorkList.push_back(cast<Instruction>(NewSCC));
8456 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8457 Value *Cond = SI.getCondition();
8458 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
8459 if (I->getOpcode() == Instruction::Add)
8460 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8461 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
8462 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
8463 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
8465 SI.setOperand(0, I->getOperand(0));
8466 WorkList.push_back(I);
8473 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
8474 /// is to leave as a vector operation.
8475 static bool CheapToScalarize(Value *V, bool isConstant) {
8476 if (isa<ConstantAggregateZero>(V))
8478 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
8479 if (isConstant) return true;
8480 // If all elts are the same, we can extract.
8481 Constant *Op0 = C->getOperand(0);
8482 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8483 if (C->getOperand(i) != Op0)
8487 Instruction *I = dyn_cast<Instruction>(V);
8488 if (!I) return false;
8490 // Insert element gets simplified to the inserted element or is deleted if
8491 // this is constant idx extract element and its a constant idx insertelt.
8492 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
8493 isa<ConstantInt>(I->getOperand(2)))
8495 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
8497 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
8498 if (BO->hasOneUse() &&
8499 (CheapToScalarize(BO->getOperand(0), isConstant) ||
8500 CheapToScalarize(BO->getOperand(1), isConstant)))
8502 if (CmpInst *CI = dyn_cast<CmpInst>(I))
8503 if (CI->hasOneUse() &&
8504 (CheapToScalarize(CI->getOperand(0), isConstant) ||
8505 CheapToScalarize(CI->getOperand(1), isConstant)))
8511 /// getShuffleMask - Read and decode a shufflevector mask. It turns undef
8512 /// elements into values that are larger than the #elts in the input.
8513 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
8514 unsigned NElts = SVI->getType()->getNumElements();
8515 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
8516 return std::vector<unsigned>(NElts, 0);
8517 if (isa<UndefValue>(SVI->getOperand(2)))
8518 return std::vector<unsigned>(NElts, 2*NElts);
8520 std::vector<unsigned> Result;
8521 const ConstantPacked *CP = cast<ConstantPacked>(SVI->getOperand(2));
8522 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
8523 if (isa<UndefValue>(CP->getOperand(i)))
8524 Result.push_back(NElts*2); // undef -> 8
8526 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
8530 /// FindScalarElement - Given a vector and an element number, see if the scalar
8531 /// value is already around as a register, for example if it were inserted then
8532 /// extracted from the vector.
8533 static Value *FindScalarElement(Value *V, unsigned EltNo) {
8534 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
8535 const PackedType *PTy = cast<PackedType>(V->getType());
8536 unsigned Width = PTy->getNumElements();
8537 if (EltNo >= Width) // Out of range access.
8538 return UndefValue::get(PTy->getElementType());
8540 if (isa<UndefValue>(V))
8541 return UndefValue::get(PTy->getElementType());
8542 else if (isa<ConstantAggregateZero>(V))
8543 return Constant::getNullValue(PTy->getElementType());
8544 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
8545 return CP->getOperand(EltNo);
8546 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
8547 // If this is an insert to a variable element, we don't know what it is.
8548 if (!isa<ConstantInt>(III->getOperand(2)))
8550 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
8552 // If this is an insert to the element we are looking for, return the
8555 return III->getOperand(1);
8557 // Otherwise, the insertelement doesn't modify the value, recurse on its
8559 return FindScalarElement(III->getOperand(0), EltNo);
8560 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
8561 unsigned InEl = getShuffleMask(SVI)[EltNo];
8563 return FindScalarElement(SVI->getOperand(0), InEl);
8564 else if (InEl < Width*2)
8565 return FindScalarElement(SVI->getOperand(1), InEl - Width);
8567 return UndefValue::get(PTy->getElementType());
8570 // Otherwise, we don't know.
8574 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
8576 // If packed val is undef, replace extract with scalar undef.
8577 if (isa<UndefValue>(EI.getOperand(0)))
8578 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8580 // If packed val is constant 0, replace extract with scalar 0.
8581 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
8582 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
8584 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
8585 // If packed val is constant with uniform operands, replace EI
8586 // with that operand
8587 Constant *op0 = C->getOperand(0);
8588 for (unsigned i = 1; i < C->getNumOperands(); ++i)
8589 if (C->getOperand(i) != op0) {
8594 return ReplaceInstUsesWith(EI, op0);
8597 // If extracting a specified index from the vector, see if we can recursively
8598 // find a previously computed scalar that was inserted into the vector.
8599 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8600 // This instruction only demands the single element from the input vector.
8601 // If the input vector has a single use, simplify it based on this use
8603 uint64_t IndexVal = IdxC->getZExtValue();
8604 if (EI.getOperand(0)->hasOneUse()) {
8606 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
8609 EI.setOperand(0, V);
8614 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
8615 return ReplaceInstUsesWith(EI, Elt);
8618 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
8619 if (I->hasOneUse()) {
8620 // Push extractelement into predecessor operation if legal and
8621 // profitable to do so
8622 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
8623 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
8624 if (CheapToScalarize(BO, isConstantElt)) {
8625 ExtractElementInst *newEI0 =
8626 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
8627 EI.getName()+".lhs");
8628 ExtractElementInst *newEI1 =
8629 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
8630 EI.getName()+".rhs");
8631 InsertNewInstBefore(newEI0, EI);
8632 InsertNewInstBefore(newEI1, EI);
8633 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
8635 } else if (isa<LoadInst>(I)) {
8636 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
8637 PointerType::get(EI.getType()), EI);
8638 GetElementPtrInst *GEP =
8639 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
8640 InsertNewInstBefore(GEP, EI);
8641 return new LoadInst(GEP);
8644 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
8645 // Extracting the inserted element?
8646 if (IE->getOperand(2) == EI.getOperand(1))
8647 return ReplaceInstUsesWith(EI, IE->getOperand(1));
8648 // If the inserted and extracted elements are constants, they must not
8649 // be the same value, extract from the pre-inserted value instead.
8650 if (isa<Constant>(IE->getOperand(2)) &&
8651 isa<Constant>(EI.getOperand(1))) {
8652 AddUsesToWorkList(EI);
8653 EI.setOperand(0, IE->getOperand(0));
8656 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
8657 // If this is extracting an element from a shufflevector, figure out where
8658 // it came from and extract from the appropriate input element instead.
8659 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
8660 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
8662 if (SrcIdx < SVI->getType()->getNumElements())
8663 Src = SVI->getOperand(0);
8664 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
8665 SrcIdx -= SVI->getType()->getNumElements();
8666 Src = SVI->getOperand(1);
8668 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
8670 return new ExtractElementInst(Src, SrcIdx);
8677 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
8678 /// elements from either LHS or RHS, return the shuffle mask and true.
8679 /// Otherwise, return false.
8680 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
8681 std::vector<Constant*> &Mask) {
8682 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
8683 "Invalid CollectSingleShuffleElements");
8684 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8686 if (isa<UndefValue>(V)) {
8687 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8689 } else if (V == LHS) {
8690 for (unsigned i = 0; i != NumElts; ++i)
8691 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8693 } else if (V == RHS) {
8694 for (unsigned i = 0; i != NumElts; ++i)
8695 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
8697 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8698 // If this is an insert of an extract from some other vector, include it.
8699 Value *VecOp = IEI->getOperand(0);
8700 Value *ScalarOp = IEI->getOperand(1);
8701 Value *IdxOp = IEI->getOperand(2);
8703 if (!isa<ConstantInt>(IdxOp))
8705 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8707 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
8708 // Okay, we can handle this if the vector we are insertinting into is
8710 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8711 // If so, update the mask to reflect the inserted undef.
8712 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
8715 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
8716 if (isa<ConstantInt>(EI->getOperand(1)) &&
8717 EI->getOperand(0)->getType() == V->getType()) {
8718 unsigned ExtractedIdx =
8719 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8721 // This must be extracting from either LHS or RHS.
8722 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
8723 // Okay, we can handle this if the vector we are insertinting into is
8725 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
8726 // If so, update the mask to reflect the inserted value.
8727 if (EI->getOperand(0) == LHS) {
8728 Mask[InsertedIdx & (NumElts-1)] =
8729 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8731 assert(EI->getOperand(0) == RHS);
8732 Mask[InsertedIdx & (NumElts-1)] =
8733 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
8742 // TODO: Handle shufflevector here!
8747 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
8748 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
8749 /// that computes V and the LHS value of the shuffle.
8750 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
8752 assert(isa<PackedType>(V->getType()) &&
8753 (RHS == 0 || V->getType() == RHS->getType()) &&
8754 "Invalid shuffle!");
8755 unsigned NumElts = cast<PackedType>(V->getType())->getNumElements();
8757 if (isa<UndefValue>(V)) {
8758 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
8760 } else if (isa<ConstantAggregateZero>(V)) {
8761 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
8763 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
8764 // If this is an insert of an extract from some other vector, include it.
8765 Value *VecOp = IEI->getOperand(0);
8766 Value *ScalarOp = IEI->getOperand(1);
8767 Value *IdxOp = IEI->getOperand(2);
8769 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8770 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8771 EI->getOperand(0)->getType() == V->getType()) {
8772 unsigned ExtractedIdx =
8773 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8774 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8776 // Either the extracted from or inserted into vector must be RHSVec,
8777 // otherwise we'd end up with a shuffle of three inputs.
8778 if (EI->getOperand(0) == RHS || RHS == 0) {
8779 RHS = EI->getOperand(0);
8780 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
8781 Mask[InsertedIdx & (NumElts-1)] =
8782 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
8787 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
8788 // Everything but the extracted element is replaced with the RHS.
8789 for (unsigned i = 0; i != NumElts; ++i) {
8790 if (i != InsertedIdx)
8791 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
8796 // If this insertelement is a chain that comes from exactly these two
8797 // vectors, return the vector and the effective shuffle.
8798 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
8799 return EI->getOperand(0);
8804 // TODO: Handle shufflevector here!
8806 // Otherwise, can't do anything fancy. Return an identity vector.
8807 for (unsigned i = 0; i != NumElts; ++i)
8808 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
8812 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
8813 Value *VecOp = IE.getOperand(0);
8814 Value *ScalarOp = IE.getOperand(1);
8815 Value *IdxOp = IE.getOperand(2);
8817 // If the inserted element was extracted from some other vector, and if the
8818 // indexes are constant, try to turn this into a shufflevector operation.
8819 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
8820 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
8821 EI->getOperand(0)->getType() == IE.getType()) {
8822 unsigned NumVectorElts = IE.getType()->getNumElements();
8823 unsigned ExtractedIdx=cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
8824 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
8826 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
8827 return ReplaceInstUsesWith(IE, VecOp);
8829 if (InsertedIdx >= NumVectorElts) // Out of range insert.
8830 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
8832 // If we are extracting a value from a vector, then inserting it right
8833 // back into the same place, just use the input vector.
8834 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
8835 return ReplaceInstUsesWith(IE, VecOp);
8837 // We could theoretically do this for ANY input. However, doing so could
8838 // turn chains of insertelement instructions into a chain of shufflevector
8839 // instructions, and right now we do not merge shufflevectors. As such,
8840 // only do this in a situation where it is clear that there is benefit.
8841 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
8842 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
8843 // the values of VecOp, except then one read from EIOp0.
8844 // Build a new shuffle mask.
8845 std::vector<Constant*> Mask;
8846 if (isa<UndefValue>(VecOp))
8847 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
8849 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
8850 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
8853 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
8854 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
8855 ConstantPacked::get(Mask));
8858 // If this insertelement isn't used by some other insertelement, turn it
8859 // (and any insertelements it points to), into one big shuffle.
8860 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
8861 std::vector<Constant*> Mask;
8863 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
8864 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
8865 // We now have a shuffle of LHS, RHS, Mask.
8866 return new ShuffleVectorInst(LHS, RHS, ConstantPacked::get(Mask));
8875 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
8876 Value *LHS = SVI.getOperand(0);
8877 Value *RHS = SVI.getOperand(1);
8878 std::vector<unsigned> Mask = getShuffleMask(&SVI);
8880 bool MadeChange = false;
8882 // Undefined shuffle mask -> undefined value.
8883 if (isa<UndefValue>(SVI.getOperand(2)))
8884 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
8886 // If we have shuffle(x, undef, mask) and any elements of mask refer to
8887 // the undef, change them to undefs.
8888 if (isa<UndefValue>(SVI.getOperand(1))) {
8889 // Scan to see if there are any references to the RHS. If so, replace them
8890 // with undef element refs and set MadeChange to true.
8891 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8892 if (Mask[i] >= e && Mask[i] != 2*e) {
8899 // Remap any references to RHS to use LHS.
8900 std::vector<Constant*> Elts;
8901 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8903 Elts.push_back(UndefValue::get(Type::Int32Ty));
8905 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8907 SVI.setOperand(2, ConstantPacked::get(Elts));
8911 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
8912 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
8913 if (LHS == RHS || isa<UndefValue>(LHS)) {
8914 if (isa<UndefValue>(LHS) && LHS == RHS) {
8915 // shuffle(undef,undef,mask) -> undef.
8916 return ReplaceInstUsesWith(SVI, LHS);
8919 // Remap any references to RHS to use LHS.
8920 std::vector<Constant*> Elts;
8921 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8923 Elts.push_back(UndefValue::get(Type::Int32Ty));
8925 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
8926 (Mask[i] < e && isa<UndefValue>(LHS)))
8927 Mask[i] = 2*e; // Turn into undef.
8929 Mask[i] &= (e-1); // Force to LHS.
8930 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
8933 SVI.setOperand(0, SVI.getOperand(1));
8934 SVI.setOperand(1, UndefValue::get(RHS->getType()));
8935 SVI.setOperand(2, ConstantPacked::get(Elts));
8936 LHS = SVI.getOperand(0);
8937 RHS = SVI.getOperand(1);
8941 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
8942 bool isLHSID = true, isRHSID = true;
8944 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
8945 if (Mask[i] >= e*2) continue; // Ignore undef values.
8946 // Is this an identity shuffle of the LHS value?
8947 isLHSID &= (Mask[i] == i);
8949 // Is this an identity shuffle of the RHS value?
8950 isRHSID &= (Mask[i]-e == i);
8953 // Eliminate identity shuffles.
8954 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
8955 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
8957 // If the LHS is a shufflevector itself, see if we can combine it with this
8958 // one without producing an unusual shuffle. Here we are really conservative:
8959 // we are absolutely afraid of producing a shuffle mask not in the input
8960 // program, because the code gen may not be smart enough to turn a merged
8961 // shuffle into two specific shuffles: it may produce worse code. As such,
8962 // we only merge two shuffles if the result is one of the two input shuffle
8963 // masks. In this case, merging the shuffles just removes one instruction,
8964 // which we know is safe. This is good for things like turning:
8965 // (splat(splat)) -> splat.
8966 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
8967 if (isa<UndefValue>(RHS)) {
8968 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
8970 std::vector<unsigned> NewMask;
8971 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
8973 NewMask.push_back(2*e);
8975 NewMask.push_back(LHSMask[Mask[i]]);
8977 // If the result mask is equal to the src shuffle or this shuffle mask, do
8979 if (NewMask == LHSMask || NewMask == Mask) {
8980 std::vector<Constant*> Elts;
8981 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
8982 if (NewMask[i] >= e*2) {
8983 Elts.push_back(UndefValue::get(Type::Int32Ty));
8985 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
8988 return new ShuffleVectorInst(LHSSVI->getOperand(0),
8989 LHSSVI->getOperand(1),
8990 ConstantPacked::get(Elts));
8995 return MadeChange ? &SVI : 0;
9000 void InstCombiner::removeFromWorkList(Instruction *I) {
9001 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
9006 /// TryToSinkInstruction - Try to move the specified instruction from its
9007 /// current block into the beginning of DestBlock, which can only happen if it's
9008 /// safe to move the instruction past all of the instructions between it and the
9009 /// end of its block.
9010 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9011 assert(I->hasOneUse() && "Invariants didn't hold!");
9013 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9014 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
9016 // Do not sink alloca instructions out of the entry block.
9017 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
9020 // We can only sink load instructions if there is nothing between the load and
9021 // the end of block that could change the value.
9022 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9023 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9025 if (Scan->mayWriteToMemory())
9029 BasicBlock::iterator InsertPos = DestBlock->begin();
9030 while (isa<PHINode>(InsertPos)) ++InsertPos;
9032 I->moveBefore(InsertPos);
9038 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9039 /// all reachable code to the worklist.
9041 /// This has a couple of tricks to make the code faster and more powerful. In
9042 /// particular, we constant fold and DCE instructions as we go, to avoid adding
9043 /// them to the worklist (this significantly speeds up instcombine on code where
9044 /// many instructions are dead or constant). Additionally, if we find a branch
9045 /// whose condition is a known constant, we only visit the reachable successors.
9047 static void AddReachableCodeToWorklist(BasicBlock *BB,
9048 std::set<BasicBlock*> &Visited,
9049 std::vector<Instruction*> &WorkList,
9050 const TargetData *TD) {
9051 // We have now visited this block! If we've already been here, bail out.
9052 if (!Visited.insert(BB).second) return;
9054 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9055 Instruction *Inst = BBI++;
9057 // DCE instruction if trivially dead.
9058 if (isInstructionTriviallyDead(Inst)) {
9060 DOUT << "IC: DCE: " << *Inst;
9061 Inst->eraseFromParent();
9065 // ConstantProp instruction if trivially constant.
9066 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
9067 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9068 Inst->replaceAllUsesWith(C);
9070 Inst->eraseFromParent();
9074 WorkList.push_back(Inst);
9077 // Recursively visit successors. If this is a branch or switch on a constant,
9078 // only visit the reachable successor.
9079 TerminatorInst *TI = BB->getTerminator();
9080 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9081 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9082 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9083 AddReachableCodeToWorklist(BI->getSuccessor(!CondVal), Visited, WorkList,
9087 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9088 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9089 // See if this is an explicit destination.
9090 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9091 if (SI->getCaseValue(i) == Cond) {
9092 AddReachableCodeToWorklist(SI->getSuccessor(i), Visited, WorkList,TD);
9096 // Otherwise it is the default destination.
9097 AddReachableCodeToWorklist(SI->getSuccessor(0), Visited, WorkList, TD);
9102 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9103 AddReachableCodeToWorklist(TI->getSuccessor(i), Visited, WorkList, TD);
9106 bool InstCombiner::runOnFunction(Function &F) {
9107 bool Changed = false;
9108 TD = &getAnalysis<TargetData>();
9111 // Do a depth-first traversal of the function, populate the worklist with
9112 // the reachable instructions. Ignore blocks that are not reachable. Keep
9113 // track of which blocks we visit.
9114 std::set<BasicBlock*> Visited;
9115 AddReachableCodeToWorklist(F.begin(), Visited, WorkList, TD);
9117 // Do a quick scan over the function. If we find any blocks that are
9118 // unreachable, remove any instructions inside of them. This prevents
9119 // the instcombine code from having to deal with some bad special cases.
9120 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9121 if (!Visited.count(BB)) {
9122 Instruction *Term = BB->getTerminator();
9123 while (Term != BB->begin()) { // Remove instrs bottom-up
9124 BasicBlock::iterator I = Term; --I;
9126 DOUT << "IC: DCE: " << *I;
9129 if (!I->use_empty())
9130 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9131 I->eraseFromParent();
9136 while (!WorkList.empty()) {
9137 Instruction *I = WorkList.back(); // Get an instruction from the worklist
9138 WorkList.pop_back();
9140 // Check to see if we can DCE the instruction.
9141 if (isInstructionTriviallyDead(I)) {
9142 // Add operands to the worklist.
9143 if (I->getNumOperands() < 4)
9144 AddUsesToWorkList(*I);
9147 DOUT << "IC: DCE: " << *I;
9149 I->eraseFromParent();
9150 removeFromWorkList(I);
9154 // Instruction isn't dead, see if we can constant propagate it.
9155 if (Constant *C = ConstantFoldInstruction(I, TD)) {
9156 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
9158 // Add operands to the worklist.
9159 AddUsesToWorkList(*I);
9160 ReplaceInstUsesWith(*I, C);
9163 I->eraseFromParent();
9164 removeFromWorkList(I);
9168 // See if we can trivially sink this instruction to a successor basic block.
9169 if (I->hasOneUse()) {
9170 BasicBlock *BB = I->getParent();
9171 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9172 if (UserParent != BB) {
9173 bool UserIsSuccessor = false;
9174 // See if the user is one of our successors.
9175 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9176 if (*SI == UserParent) {
9177 UserIsSuccessor = true;
9181 // If the user is one of our immediate successors, and if that successor
9182 // only has us as a predecessors (we'd have to split the critical edge
9183 // otherwise), we can keep going.
9184 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9185 next(pred_begin(UserParent)) == pred_end(UserParent))
9186 // Okay, the CFG is simple enough, try to sink this instruction.
9187 Changed |= TryToSinkInstruction(I, UserParent);
9191 // Now that we have an instruction, try combining it to simplify it...
9192 if (Instruction *Result = visit(*I)) {
9194 // Should we replace the old instruction with a new one?
9196 DOUT << "IC: Old = " << *I
9197 << " New = " << *Result;
9199 // Everything uses the new instruction now.
9200 I->replaceAllUsesWith(Result);
9202 // Push the new instruction and any users onto the worklist.
9203 WorkList.push_back(Result);
9204 AddUsersToWorkList(*Result);
9206 // Move the name to the new instruction first...
9207 std::string OldName = I->getName(); I->setName("");
9208 Result->setName(OldName);
9210 // Insert the new instruction into the basic block...
9211 BasicBlock *InstParent = I->getParent();
9212 BasicBlock::iterator InsertPos = I;
9214 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9215 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9218 InstParent->getInstList().insert(InsertPos, Result);
9220 // Make sure that we reprocess all operands now that we reduced their
9222 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9223 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9224 WorkList.push_back(OpI);
9226 // Instructions can end up on the worklist more than once. Make sure
9227 // we do not process an instruction that has been deleted.
9228 removeFromWorkList(I);
9230 // Erase the old instruction.
9231 InstParent->getInstList().erase(I);
9233 DOUT << "IC: MOD = " << *I;
9235 // If the instruction was modified, it's possible that it is now dead.
9236 // if so, remove it.
9237 if (isInstructionTriviallyDead(I)) {
9238 // Make sure we process all operands now that we are reducing their
9240 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
9241 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
9242 WorkList.push_back(OpI);
9244 // Instructions may end up in the worklist more than once. Erase all
9245 // occurrences of this instruction.
9246 removeFromWorkList(I);
9247 I->eraseFromParent();
9249 WorkList.push_back(Result);
9250 AddUsersToWorkList(*Result);
9260 FunctionPass *llvm::createInstructionCombiningPass() {
9261 return new InstCombiner();