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/DenseMap.h"
54 #include "llvm/ADT/SmallVector.h"
55 #include "llvm/ADT/SmallPtrSet.h"
56 #include "llvm/ADT/Statistic.h"
57 #include "llvm/ADT/STLExtras.h"
61 using namespace llvm::PatternMatch;
63 STATISTIC(NumCombined , "Number of insts combined");
64 STATISTIC(NumConstProp, "Number of constant folds");
65 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
66 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
67 STATISTIC(NumSunkInst , "Number of instructions sunk");
70 class VISIBILITY_HIDDEN InstCombiner
71 : public FunctionPass,
72 public InstVisitor<InstCombiner, Instruction*> {
73 // Worklist of all of the instructions that need to be simplified.
74 std::vector<Instruction*> Worklist;
75 DenseMap<Instruction*, unsigned> WorklistMap;
77 bool MustPreserveLCSSA;
79 /// AddToWorkList - Add the specified instruction to the worklist if it
80 /// isn't already in it.
81 void AddToWorkList(Instruction *I) {
82 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
83 Worklist.push_back(I);
86 // RemoveFromWorkList - remove I from the worklist if it exists.
87 void RemoveFromWorkList(Instruction *I) {
88 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
89 if (It == WorklistMap.end()) return; // Not in worklist.
91 // Don't bother moving everything down, just null out the slot.
92 Worklist[It->second] = 0;
94 WorklistMap.erase(It);
97 Instruction *RemoveOneFromWorkList() {
98 Instruction *I = Worklist.back();
100 WorklistMap.erase(I);
105 /// AddUsersToWorkList - When an instruction is simplified, add all users of
106 /// the instruction to the work lists because they might get more simplified
109 void AddUsersToWorkList(Value &I) {
110 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
112 AddToWorkList(cast<Instruction>(*UI));
115 /// AddUsesToWorkList - When an instruction is simplified, add operands to
116 /// the work lists because they might get more simplified now.
118 void AddUsesToWorkList(Instruction &I) {
119 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
120 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
124 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
125 /// dead. Add all of its operands to the worklist, turning them into
126 /// undef's to reduce the number of uses of those instructions.
128 /// Return the specified operand before it is turned into an undef.
130 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
131 Value *R = I.getOperand(op);
133 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
134 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
136 // Set the operand to undef to drop the use.
137 I.setOperand(i, UndefValue::get(Op->getType()));
144 virtual bool runOnFunction(Function &F);
146 bool DoOneIteration(Function &F, unsigned ItNum);
148 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
149 AU.addRequired<TargetData>();
150 AU.addPreservedID(LCSSAID);
151 AU.setPreservesCFG();
154 TargetData &getTargetData() const { return *TD; }
156 // Visitation implementation - Implement instruction combining for different
157 // instruction types. The semantics are as follows:
159 // null - No change was made
160 // I - Change was made, I is still valid, I may be dead though
161 // otherwise - Change was made, replace I with returned instruction
163 Instruction *visitAdd(BinaryOperator &I);
164 Instruction *visitSub(BinaryOperator &I);
165 Instruction *visitMul(BinaryOperator &I);
166 Instruction *visitURem(BinaryOperator &I);
167 Instruction *visitSRem(BinaryOperator &I);
168 Instruction *visitFRem(BinaryOperator &I);
169 Instruction *commonRemTransforms(BinaryOperator &I);
170 Instruction *commonIRemTransforms(BinaryOperator &I);
171 Instruction *commonDivTransforms(BinaryOperator &I);
172 Instruction *commonIDivTransforms(BinaryOperator &I);
173 Instruction *visitUDiv(BinaryOperator &I);
174 Instruction *visitSDiv(BinaryOperator &I);
175 Instruction *visitFDiv(BinaryOperator &I);
176 Instruction *visitAnd(BinaryOperator &I);
177 Instruction *visitOr (BinaryOperator &I);
178 Instruction *visitXor(BinaryOperator &I);
179 Instruction *visitShl(BinaryOperator &I);
180 Instruction *visitAShr(BinaryOperator &I);
181 Instruction *visitLShr(BinaryOperator &I);
182 Instruction *commonShiftTransforms(BinaryOperator &I);
183 Instruction *visitFCmpInst(FCmpInst &I);
184 Instruction *visitICmpInst(ICmpInst &I);
185 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
186 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
190 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
191 ICmpInst::Predicate Cond, Instruction &I);
192 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
194 Instruction *commonCastTransforms(CastInst &CI);
195 Instruction *commonIntCastTransforms(CastInst &CI);
196 Instruction *commonPointerCastTransforms(CastInst &CI);
197 Instruction *visitTrunc(TruncInst &CI);
198 Instruction *visitZExt(ZExtInst &CI);
199 Instruction *visitSExt(SExtInst &CI);
200 Instruction *visitFPTrunc(CastInst &CI);
201 Instruction *visitFPExt(CastInst &CI);
202 Instruction *visitFPToUI(CastInst &CI);
203 Instruction *visitFPToSI(CastInst &CI);
204 Instruction *visitUIToFP(CastInst &CI);
205 Instruction *visitSIToFP(CastInst &CI);
206 Instruction *visitPtrToInt(CastInst &CI);
207 Instruction *visitIntToPtr(CastInst &CI);
208 Instruction *visitBitCast(BitCastInst &CI);
209 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
211 Instruction *visitSelectInst(SelectInst &CI);
212 Instruction *visitCallInst(CallInst &CI);
213 Instruction *visitInvokeInst(InvokeInst &II);
214 Instruction *visitPHINode(PHINode &PN);
215 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
216 Instruction *visitAllocationInst(AllocationInst &AI);
217 Instruction *visitFreeInst(FreeInst &FI);
218 Instruction *visitLoadInst(LoadInst &LI);
219 Instruction *visitStoreInst(StoreInst &SI);
220 Instruction *visitBranchInst(BranchInst &BI);
221 Instruction *visitSwitchInst(SwitchInst &SI);
222 Instruction *visitInsertElementInst(InsertElementInst &IE);
223 Instruction *visitExtractElementInst(ExtractElementInst &EI);
224 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
226 // visitInstruction - Specify what to return for unhandled instructions...
227 Instruction *visitInstruction(Instruction &I) { return 0; }
230 Instruction *visitCallSite(CallSite CS);
231 bool transformConstExprCastCall(CallSite CS);
234 // InsertNewInstBefore - insert an instruction New before instruction Old
235 // in the program. Add the new instruction to the worklist.
237 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
238 assert(New && New->getParent() == 0 &&
239 "New instruction already inserted into a basic block!");
240 BasicBlock *BB = Old.getParent();
241 BB->getInstList().insert(&Old, New); // Insert inst
246 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
247 /// This also adds the cast to the worklist. Finally, this returns the
249 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
251 if (V->getType() == Ty) return V;
253 if (Constant *CV = dyn_cast<Constant>(V))
254 return ConstantExpr::getCast(opc, CV, Ty);
256 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
261 // ReplaceInstUsesWith - This method is to be used when an instruction is
262 // found to be dead, replacable with another preexisting expression. Here
263 // we add all uses of I to the worklist, replace all uses of I with the new
264 // value, then return I, so that the inst combiner will know that I was
267 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
268 AddUsersToWorkList(I); // Add all modified instrs to worklist
270 I.replaceAllUsesWith(V);
273 // If we are replacing the instruction with itself, this must be in a
274 // segment of unreachable code, so just clobber the instruction.
275 I.replaceAllUsesWith(UndefValue::get(I.getType()));
280 // UpdateValueUsesWith - This method is to be used when an value is
281 // found to be replacable with another preexisting expression or was
282 // updated. Here we add all uses of I to the worklist, replace all uses of
283 // I with the new value (unless the instruction was just updated), then
284 // return true, so that the inst combiner will know that I was modified.
286 bool UpdateValueUsesWith(Value *Old, Value *New) {
287 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
289 Old->replaceAllUsesWith(New);
290 if (Instruction *I = dyn_cast<Instruction>(Old))
292 if (Instruction *I = dyn_cast<Instruction>(New))
297 // EraseInstFromFunction - When dealing with an instruction that has side
298 // effects or produces a void value, we can't rely on DCE to delete the
299 // instruction. Instead, visit methods should return the value returned by
301 Instruction *EraseInstFromFunction(Instruction &I) {
302 assert(I.use_empty() && "Cannot erase instruction that is used!");
303 AddUsesToWorkList(I);
304 RemoveFromWorkList(&I);
306 return 0; // Don't do anything with FI
310 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
311 /// InsertBefore instruction. This is specialized a bit to avoid inserting
312 /// casts that are known to not do anything...
314 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
315 Value *V, const Type *DestTy,
316 Instruction *InsertBefore);
318 /// SimplifyCommutative - This performs a few simplifications for
319 /// commutative operators.
320 bool SimplifyCommutative(BinaryOperator &I);
322 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
323 /// most-complex to least-complex order.
324 bool SimplifyCompare(CmpInst &I);
326 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
327 /// on the demanded bits.
328 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
329 APInt& KnownZero, APInt& KnownOne,
332 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
333 uint64_t &UndefElts, unsigned Depth = 0);
335 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
336 // PHI node as operand #0, see if we can fold the instruction into the PHI
337 // (which is only possible if all operands to the PHI are constants).
338 Instruction *FoldOpIntoPhi(Instruction &I);
340 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
341 // operator and they all are only used by the PHI, PHI together their
342 // inputs, and do the operation once, to the result of the PHI.
343 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
344 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
347 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
348 ConstantInt *AndRHS, BinaryOperator &TheAnd);
350 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
351 bool isSub, Instruction &I);
352 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
353 bool isSigned, bool Inside, Instruction &IB);
354 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
355 Instruction *MatchBSwap(BinaryOperator &I);
356 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
358 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
361 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
364 // getComplexity: Assign a complexity or rank value to LLVM Values...
365 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
366 static unsigned getComplexity(Value *V) {
367 if (isa<Instruction>(V)) {
368 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
372 if (isa<Argument>(V)) return 3;
373 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
376 // isOnlyUse - Return true if this instruction will be deleted if we stop using
378 static bool isOnlyUse(Value *V) {
379 return V->hasOneUse() || isa<Constant>(V);
382 // getPromotedType - Return the specified type promoted as it would be to pass
383 // though a va_arg area...
384 static const Type *getPromotedType(const Type *Ty) {
385 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
386 if (ITy->getBitWidth() < 32)
387 return Type::Int32Ty;
388 } else if (Ty == Type::FloatTy)
389 return Type::DoubleTy;
393 /// getBitCastOperand - If the specified operand is a CastInst or a constant
394 /// expression bitcast, return the operand value, otherwise return null.
395 static Value *getBitCastOperand(Value *V) {
396 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
397 return I->getOperand(0);
398 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
399 if (CE->getOpcode() == Instruction::BitCast)
400 return CE->getOperand(0);
404 /// This function is a wrapper around CastInst::isEliminableCastPair. It
405 /// simply extracts arguments and returns what that function returns.
406 static Instruction::CastOps
407 isEliminableCastPair(
408 const CastInst *CI, ///< The first cast instruction
409 unsigned opcode, ///< The opcode of the second cast instruction
410 const Type *DstTy, ///< The target type for the second cast instruction
411 TargetData *TD ///< The target data for pointer size
414 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
415 const Type *MidTy = CI->getType(); // B from above
417 // Get the opcodes of the two Cast instructions
418 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
419 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
421 return Instruction::CastOps(
422 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
423 DstTy, TD->getIntPtrType()));
426 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
427 /// in any code being generated. It does not require codegen if V is simple
428 /// enough or if the cast can be folded into other casts.
429 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
430 const Type *Ty, TargetData *TD) {
431 if (V->getType() == Ty || isa<Constant>(V)) return false;
433 // If this is another cast that can be eliminated, it isn't codegen either.
434 if (const CastInst *CI = dyn_cast<CastInst>(V))
435 if (isEliminableCastPair(CI, opcode, Ty, TD))
440 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
441 /// InsertBefore instruction. This is specialized a bit to avoid inserting
442 /// casts that are known to not do anything...
444 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
445 Value *V, const Type *DestTy,
446 Instruction *InsertBefore) {
447 if (V->getType() == DestTy) return V;
448 if (Constant *C = dyn_cast<Constant>(V))
449 return ConstantExpr::getCast(opcode, C, DestTy);
451 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
454 // SimplifyCommutative - This performs a few simplifications for commutative
457 // 1. Order operands such that they are listed from right (least complex) to
458 // left (most complex). This puts constants before unary operators before
461 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
462 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
464 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
465 bool Changed = false;
466 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
467 Changed = !I.swapOperands();
469 if (!I.isAssociative()) return Changed;
470 Instruction::BinaryOps Opcode = I.getOpcode();
471 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
472 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
473 if (isa<Constant>(I.getOperand(1))) {
474 Constant *Folded = ConstantExpr::get(I.getOpcode(),
475 cast<Constant>(I.getOperand(1)),
476 cast<Constant>(Op->getOperand(1)));
477 I.setOperand(0, Op->getOperand(0));
478 I.setOperand(1, Folded);
480 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
481 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
482 isOnlyUse(Op) && isOnlyUse(Op1)) {
483 Constant *C1 = cast<Constant>(Op->getOperand(1));
484 Constant *C2 = cast<Constant>(Op1->getOperand(1));
486 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
487 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
488 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
492 I.setOperand(0, New);
493 I.setOperand(1, Folded);
500 /// SimplifyCompare - For a CmpInst this function just orders the operands
501 /// so that theyare listed from right (least complex) to left (most complex).
502 /// This puts constants before unary operators before binary operators.
503 bool InstCombiner::SimplifyCompare(CmpInst &I) {
504 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
507 // Compare instructions are not associative so there's nothing else we can do.
511 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
512 // if the LHS is a constant zero (which is the 'negate' form).
514 static inline Value *dyn_castNegVal(Value *V) {
515 if (BinaryOperator::isNeg(V))
516 return BinaryOperator::getNegArgument(V);
518 // Constants can be considered to be negated values if they can be folded.
519 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
520 return ConstantExpr::getNeg(C);
524 static inline Value *dyn_castNotVal(Value *V) {
525 if (BinaryOperator::isNot(V))
526 return BinaryOperator::getNotArgument(V);
528 // Constants can be considered to be not'ed values...
529 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
530 return ConstantInt::get(~C->getValue());
534 // dyn_castFoldableMul - If this value is a multiply that can be folded into
535 // other computations (because it has a constant operand), return the
536 // non-constant operand of the multiply, and set CST to point to the multiplier.
537 // Otherwise, return null.
539 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
540 if (V->hasOneUse() && V->getType()->isInteger())
541 if (Instruction *I = dyn_cast<Instruction>(V)) {
542 if (I->getOpcode() == Instruction::Mul)
543 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
544 return I->getOperand(0);
545 if (I->getOpcode() == Instruction::Shl)
546 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
547 // The multiplier is really 1 << CST.
548 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
549 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
550 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
551 return I->getOperand(0);
557 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
558 /// expression, return it.
559 static User *dyn_castGetElementPtr(Value *V) {
560 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
561 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
562 if (CE->getOpcode() == Instruction::GetElementPtr)
563 return cast<User>(V);
567 /// AddOne - Add one to a ConstantInt
568 static ConstantInt *AddOne(ConstantInt *C) {
569 APInt Val(C->getValue());
570 return ConstantInt::get(++Val);
572 /// SubOne - Subtract one from a ConstantInt
573 static ConstantInt *SubOne(ConstantInt *C) {
574 APInt Val(C->getValue());
575 return ConstantInt::get(--Val);
577 /// Add - Add two ConstantInts together
578 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
579 return ConstantInt::get(C1->getValue() + C2->getValue());
581 /// And - Bitwise AND two ConstantInts together
582 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
583 return ConstantInt::get(C1->getValue() & C2->getValue());
585 /// Subtract - Subtract one ConstantInt from another
586 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
587 return ConstantInt::get(C1->getValue() - C2->getValue());
589 /// Multiply - Multiply two ConstantInts together
590 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
591 return ConstantInt::get(C1->getValue() * C2->getValue());
594 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
595 /// known to be either zero or one and return them in the KnownZero/KnownOne
596 /// bit sets. This code only analyzes bits in Mask, in order to short-circuit
598 /// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
599 /// we cannot optimize based on the assumption that it is zero without changing
600 /// it to be an explicit zero. If we don't change it to zero, other code could
601 /// optimized based on the contradictory assumption that it is non-zero.
602 /// Because instcombine aggressively folds operations with undef args anyway,
603 /// this won't lose us code quality.
604 static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
605 APInt& KnownOne, unsigned Depth = 0) {
606 assert(V && "No Value?");
607 assert(Depth <= 6 && "Limit Search Depth");
608 uint32_t BitWidth = Mask.getBitWidth();
609 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
610 KnownZero.getBitWidth() == BitWidth &&
611 KnownOne.getBitWidth() == BitWidth &&
612 "V, Mask, KnownOne and KnownZero should have same BitWidth");
613 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
614 // We know all of the bits for a constant!
615 KnownOne = CI->getValue() & Mask;
616 KnownZero = ~KnownOne & Mask;
620 if (Depth == 6 || Mask == 0)
621 return; // Limit search depth.
623 Instruction *I = dyn_cast<Instruction>(V);
626 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
627 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
629 switch (I->getOpcode()) {
630 case Instruction::And: {
631 // If either the LHS or the RHS are Zero, the result is zero.
632 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
633 APInt Mask2(Mask & ~KnownZero);
634 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
635 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
636 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
638 // Output known-1 bits are only known if set in both the LHS & RHS.
639 KnownOne &= KnownOne2;
640 // Output known-0 are known to be clear if zero in either the LHS | RHS.
641 KnownZero |= KnownZero2;
644 case Instruction::Or: {
645 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
646 APInt Mask2(Mask & ~KnownOne);
647 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
648 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
649 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
651 // Output known-0 bits are only known if clear in both the LHS & RHS.
652 KnownZero &= KnownZero2;
653 // Output known-1 are known to be set if set in either the LHS | RHS.
654 KnownOne |= KnownOne2;
657 case Instruction::Xor: {
658 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
659 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
660 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
661 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
663 // Output known-0 bits are known if clear or set in both the LHS & RHS.
664 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
665 // Output known-1 are known to be set if set in only one of the LHS, RHS.
666 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
667 KnownZero = KnownZeroOut;
670 case Instruction::Select:
671 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
672 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
673 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
674 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
676 // Only known if known in both the LHS and RHS.
677 KnownOne &= KnownOne2;
678 KnownZero &= KnownZero2;
680 case Instruction::FPTrunc:
681 case Instruction::FPExt:
682 case Instruction::FPToUI:
683 case Instruction::FPToSI:
684 case Instruction::SIToFP:
685 case Instruction::PtrToInt:
686 case Instruction::UIToFP:
687 case Instruction::IntToPtr:
688 return; // Can't work with floating point or pointers
689 case Instruction::Trunc: {
690 // All these have integer operands
691 uint32_t SrcBitWidth =
692 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
694 MaskIn.zext(SrcBitWidth);
695 KnownZero.zext(SrcBitWidth);
696 KnownOne.zext(SrcBitWidth);
697 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
698 KnownZero.trunc(BitWidth);
699 KnownOne.trunc(BitWidth);
702 case Instruction::BitCast: {
703 const Type *SrcTy = I->getOperand(0)->getType();
704 if (SrcTy->isInteger()) {
705 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
710 case Instruction::ZExt: {
711 // Compute the bits in the result that are not present in the input.
712 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
713 uint32_t SrcBitWidth = SrcTy->getBitWidth();
716 MaskIn.trunc(SrcBitWidth);
717 KnownZero.trunc(SrcBitWidth);
718 KnownOne.trunc(SrcBitWidth);
719 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
720 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
721 // The top bits are known to be zero.
722 KnownZero.zext(BitWidth);
723 KnownOne.zext(BitWidth);
724 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
727 case Instruction::SExt: {
728 // Compute the bits in the result that are not present in the input.
729 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
730 uint32_t SrcBitWidth = SrcTy->getBitWidth();
733 MaskIn.trunc(SrcBitWidth);
734 KnownZero.trunc(SrcBitWidth);
735 KnownOne.trunc(SrcBitWidth);
736 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
737 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
738 KnownZero.zext(BitWidth);
739 KnownOne.zext(BitWidth);
741 // If the sign bit of the input is known set or clear, then we know the
742 // top bits of the result.
743 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
744 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
745 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
746 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
749 case Instruction::Shl:
750 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
751 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
752 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
753 APInt Mask2(Mask.lshr(ShiftAmt));
754 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
755 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
756 KnownZero <<= ShiftAmt;
757 KnownOne <<= ShiftAmt;
758 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
762 case Instruction::LShr:
763 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
764 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
765 // Compute the new bits that are at the top now.
766 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
768 // Unsigned shift right.
769 APInt Mask2(Mask.shl(ShiftAmt));
770 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
771 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
772 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
773 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
774 // high bits known zero.
775 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
779 case Instruction::AShr:
780 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
781 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
782 // Compute the new bits that are at the top now.
783 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
785 // Signed shift right.
786 APInt Mask2(Mask.shl(ShiftAmt));
787 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
788 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
789 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
790 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
792 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
793 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
794 KnownZero |= HighBits;
795 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
796 KnownOne |= HighBits;
803 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
804 /// this predicate to simplify operations downstream. Mask is known to be zero
805 /// for bits that V cannot have.
806 static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
807 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
808 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
809 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
810 return (KnownZero & Mask) == Mask;
813 /// ShrinkDemandedConstant - Check to see if the specified operand of the
814 /// specified instruction is a constant integer. If so, check to see if there
815 /// are any bits set in the constant that are not demanded. If so, shrink the
816 /// constant and return true.
817 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
819 assert(I && "No instruction?");
820 assert(OpNo < I->getNumOperands() && "Operand index too large");
822 // If the operand is not a constant integer, nothing to do.
823 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
824 if (!OpC) return false;
826 // If there are no bits set that aren't demanded, nothing to do.
827 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
828 if ((~Demanded & OpC->getValue()) == 0)
831 // This instruction is producing bits that are not demanded. Shrink the RHS.
832 Demanded &= OpC->getValue();
833 I->setOperand(OpNo, ConstantInt::get(Demanded));
837 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
838 // set of known zero and one bits, compute the maximum and minimum values that
839 // could have the specified known zero and known one bits, returning them in
841 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
842 const APInt& KnownZero,
843 const APInt& KnownOne,
844 APInt& Min, APInt& Max) {
845 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
846 assert(KnownZero.getBitWidth() == BitWidth &&
847 KnownOne.getBitWidth() == BitWidth &&
848 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
849 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
850 APInt UnknownBits = ~(KnownZero|KnownOne);
852 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
853 // bit if it is unknown.
855 Max = KnownOne|UnknownBits;
857 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
859 Max.clear(BitWidth-1);
863 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
864 // a set of known zero and one bits, compute the maximum and minimum values that
865 // could have the specified known zero and known one bits, returning them in
867 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
868 const APInt& KnownZero,
869 const APInt& KnownOne,
872 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
873 assert(KnownZero.getBitWidth() == BitWidth &&
874 KnownOne.getBitWidth() == BitWidth &&
875 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
876 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
877 APInt UnknownBits = ~(KnownZero|KnownOne);
879 // The minimum value is when the unknown bits are all zeros.
881 // The maximum value is when the unknown bits are all ones.
882 Max = KnownOne|UnknownBits;
885 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
886 /// value based on the demanded bits. When this function is called, it is known
887 /// that only the bits set in DemandedMask of the result of V are ever used
888 /// downstream. Consequently, depending on the mask and V, it may be possible
889 /// to replace V with a constant or one of its operands. In such cases, this
890 /// function does the replacement and returns true. In all other cases, it
891 /// returns false after analyzing the expression and setting KnownOne and known
892 /// to be one in the expression. KnownZero contains all the bits that are known
893 /// to be zero in the expression. These are provided to potentially allow the
894 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
895 /// the expression. KnownOne and KnownZero always follow the invariant that
896 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
897 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
898 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
899 /// and KnownOne must all be the same.
900 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
901 APInt& KnownZero, APInt& KnownOne,
903 assert(V != 0 && "Null pointer of Value???");
904 assert(Depth <= 6 && "Limit Search Depth");
905 uint32_t BitWidth = DemandedMask.getBitWidth();
906 const IntegerType *VTy = cast<IntegerType>(V->getType());
907 assert(VTy->getBitWidth() == BitWidth &&
908 KnownZero.getBitWidth() == BitWidth &&
909 KnownOne.getBitWidth() == BitWidth &&
910 "Value *V, DemandedMask, KnownZero and KnownOne \
911 must have same BitWidth");
912 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
913 // We know all of the bits for a constant!
914 KnownOne = CI->getValue() & DemandedMask;
915 KnownZero = ~KnownOne & DemandedMask;
921 if (!V->hasOneUse()) { // Other users may use these bits.
922 if (Depth != 0) { // Not at the root.
923 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
924 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
927 // If this is the root being simplified, allow it to have multiple uses,
928 // just set the DemandedMask to all bits.
929 DemandedMask = APInt::getAllOnesValue(BitWidth);
930 } else if (DemandedMask == 0) { // Not demanding any bits from V.
931 if (V != UndefValue::get(VTy))
932 return UpdateValueUsesWith(V, UndefValue::get(VTy));
934 } else if (Depth == 6) { // Limit search depth.
938 Instruction *I = dyn_cast<Instruction>(V);
939 if (!I) return false; // Only analyze instructions.
941 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
942 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
943 switch (I->getOpcode()) {
945 case Instruction::And:
946 // If either the LHS or the RHS are Zero, the result is zero.
947 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
948 RHSKnownZero, RHSKnownOne, Depth+1))
950 assert((RHSKnownZero & RHSKnownOne) == 0 &&
951 "Bits known to be one AND zero?");
953 // If something is known zero on the RHS, the bits aren't demanded on the
955 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
956 LHSKnownZero, LHSKnownOne, Depth+1))
958 assert((LHSKnownZero & LHSKnownOne) == 0 &&
959 "Bits known to be one AND zero?");
961 // If all of the demanded bits are known 1 on one side, return the other.
962 // These bits cannot contribute to the result of the 'and'.
963 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
964 (DemandedMask & ~LHSKnownZero))
965 return UpdateValueUsesWith(I, I->getOperand(0));
966 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
967 (DemandedMask & ~RHSKnownZero))
968 return UpdateValueUsesWith(I, I->getOperand(1));
970 // If all of the demanded bits in the inputs are known zeros, return zero.
971 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
972 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
974 // If the RHS is a constant, see if we can simplify it.
975 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
976 return UpdateValueUsesWith(I, I);
978 // Output known-1 bits are only known if set in both the LHS & RHS.
979 RHSKnownOne &= LHSKnownOne;
980 // Output known-0 are known to be clear if zero in either the LHS | RHS.
981 RHSKnownZero |= LHSKnownZero;
983 case Instruction::Or:
984 // If either the LHS or the RHS are One, the result is One.
985 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
986 RHSKnownZero, RHSKnownOne, Depth+1))
988 assert((RHSKnownZero & RHSKnownOne) == 0 &&
989 "Bits known to be one AND zero?");
990 // If something is known one on the RHS, the bits aren't demanded on the
992 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
993 LHSKnownZero, LHSKnownOne, Depth+1))
995 assert((LHSKnownZero & LHSKnownOne) == 0 &&
996 "Bits known to be one AND zero?");
998 // If all of the demanded bits are known zero on one side, return the other.
999 // These bits cannot contribute to the result of the 'or'.
1000 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1001 (DemandedMask & ~LHSKnownOne))
1002 return UpdateValueUsesWith(I, I->getOperand(0));
1003 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1004 (DemandedMask & ~RHSKnownOne))
1005 return UpdateValueUsesWith(I, I->getOperand(1));
1007 // If all of the potentially set bits on one side are known to be set on
1008 // the other side, just use the 'other' side.
1009 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1010 (DemandedMask & (~RHSKnownZero)))
1011 return UpdateValueUsesWith(I, I->getOperand(0));
1012 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1013 (DemandedMask & (~LHSKnownZero)))
1014 return UpdateValueUsesWith(I, I->getOperand(1));
1016 // If the RHS is a constant, see if we can simplify it.
1017 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1018 return UpdateValueUsesWith(I, I);
1020 // Output known-0 bits are only known if clear in both the LHS & RHS.
1021 RHSKnownZero &= LHSKnownZero;
1022 // Output known-1 are known to be set if set in either the LHS | RHS.
1023 RHSKnownOne |= LHSKnownOne;
1025 case Instruction::Xor: {
1026 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1027 RHSKnownZero, RHSKnownOne, Depth+1))
1029 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1030 "Bits known to be one AND zero?");
1031 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1032 LHSKnownZero, LHSKnownOne, Depth+1))
1034 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1035 "Bits known to be one AND zero?");
1037 // If all of the demanded bits are known zero on one side, return the other.
1038 // These bits cannot contribute to the result of the 'xor'.
1039 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1040 return UpdateValueUsesWith(I, I->getOperand(0));
1041 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1042 return UpdateValueUsesWith(I, I->getOperand(1));
1044 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1045 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1046 (RHSKnownOne & LHSKnownOne);
1047 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1048 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1049 (RHSKnownOne & LHSKnownZero);
1051 // If all of the demanded bits are known to be zero on one side or the
1052 // other, turn this into an *inclusive* or.
1053 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1054 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1056 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1058 InsertNewInstBefore(Or, *I);
1059 return UpdateValueUsesWith(I, Or);
1062 // If all of the demanded bits on one side are known, and all of the set
1063 // bits on that side are also known to be set on the other side, turn this
1064 // into an AND, as we know the bits will be cleared.
1065 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1066 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1068 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1069 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1071 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1072 InsertNewInstBefore(And, *I);
1073 return UpdateValueUsesWith(I, And);
1077 // If the RHS is a constant, see if we can simplify it.
1078 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1079 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1080 return UpdateValueUsesWith(I, I);
1082 RHSKnownZero = KnownZeroOut;
1083 RHSKnownOne = KnownOneOut;
1086 case Instruction::Select:
1087 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1088 RHSKnownZero, RHSKnownOne, Depth+1))
1090 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1091 LHSKnownZero, LHSKnownOne, Depth+1))
1093 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1094 "Bits known to be one AND zero?");
1095 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1096 "Bits known to be one AND zero?");
1098 // If the operands are constants, see if we can simplify them.
1099 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1100 return UpdateValueUsesWith(I, I);
1101 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1102 return UpdateValueUsesWith(I, I);
1104 // Only known if known in both the LHS and RHS.
1105 RHSKnownOne &= LHSKnownOne;
1106 RHSKnownZero &= LHSKnownZero;
1108 case Instruction::Trunc: {
1110 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1111 DemandedMask.zext(truncBf);
1112 RHSKnownZero.zext(truncBf);
1113 RHSKnownOne.zext(truncBf);
1114 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1115 RHSKnownZero, RHSKnownOne, Depth+1))
1117 DemandedMask.trunc(BitWidth);
1118 RHSKnownZero.trunc(BitWidth);
1119 RHSKnownOne.trunc(BitWidth);
1120 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1121 "Bits known to be one AND zero?");
1124 case Instruction::BitCast:
1125 if (!I->getOperand(0)->getType()->isInteger())
1128 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1129 RHSKnownZero, RHSKnownOne, Depth+1))
1131 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1132 "Bits known to be one AND zero?");
1134 case Instruction::ZExt: {
1135 // Compute the bits in the result that are not present in the input.
1136 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1137 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1139 DemandedMask.trunc(SrcBitWidth);
1140 RHSKnownZero.trunc(SrcBitWidth);
1141 RHSKnownOne.trunc(SrcBitWidth);
1142 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1143 RHSKnownZero, RHSKnownOne, Depth+1))
1145 DemandedMask.zext(BitWidth);
1146 RHSKnownZero.zext(BitWidth);
1147 RHSKnownOne.zext(BitWidth);
1148 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1149 "Bits known to be one AND zero?");
1150 // The top bits are known to be zero.
1151 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1154 case Instruction::SExt: {
1155 // Compute the bits in the result that are not present in the input.
1156 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1157 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1159 APInt InputDemandedBits = DemandedMask &
1160 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1162 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1163 // If any of the sign extended bits are demanded, we know that the sign
1165 if ((NewBits & DemandedMask) != 0)
1166 InputDemandedBits.set(SrcBitWidth-1);
1168 InputDemandedBits.trunc(SrcBitWidth);
1169 RHSKnownZero.trunc(SrcBitWidth);
1170 RHSKnownOne.trunc(SrcBitWidth);
1171 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1172 RHSKnownZero, RHSKnownOne, Depth+1))
1174 InputDemandedBits.zext(BitWidth);
1175 RHSKnownZero.zext(BitWidth);
1176 RHSKnownOne.zext(BitWidth);
1177 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1178 "Bits known to be one AND zero?");
1180 // If the sign bit of the input is known set or clear, then we know the
1181 // top bits of the result.
1183 // If the input sign bit is known zero, or if the NewBits are not demanded
1184 // convert this into a zero extension.
1185 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1187 // Convert to ZExt cast
1188 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1189 return UpdateValueUsesWith(I, NewCast);
1190 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1191 RHSKnownOne |= NewBits;
1195 case Instruction::Add: {
1196 // Figure out what the input bits are. If the top bits of the and result
1197 // are not demanded, then the add doesn't demand them from its input
1199 uint32_t NLZ = DemandedMask.countLeadingZeros();
1201 // If there is a constant on the RHS, there are a variety of xformations
1203 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1204 // If null, this should be simplified elsewhere. Some of the xforms here
1205 // won't work if the RHS is zero.
1209 // If the top bit of the output is demanded, demand everything from the
1210 // input. Otherwise, we demand all the input bits except NLZ top bits.
1211 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1213 // Find information about known zero/one bits in the input.
1214 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1215 LHSKnownZero, LHSKnownOne, Depth+1))
1218 // If the RHS of the add has bits set that can't affect the input, reduce
1220 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1221 return UpdateValueUsesWith(I, I);
1223 // Avoid excess work.
1224 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1227 // Turn it into OR if input bits are zero.
1228 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1230 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1232 InsertNewInstBefore(Or, *I);
1233 return UpdateValueUsesWith(I, Or);
1236 // We can say something about the output known-zero and known-one bits,
1237 // depending on potential carries from the input constant and the
1238 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1239 // bits set and the RHS constant is 0x01001, then we know we have a known
1240 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1242 // To compute this, we first compute the potential carry bits. These are
1243 // the bits which may be modified. I'm not aware of a better way to do
1245 const APInt& RHSVal = RHS->getValue();
1246 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1248 // Now that we know which bits have carries, compute the known-1/0 sets.
1250 // Bits are known one if they are known zero in one operand and one in the
1251 // other, and there is no input carry.
1252 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1253 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1255 // Bits are known zero if they are known zero in both operands and there
1256 // is no input carry.
1257 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1259 // If the high-bits of this ADD are not demanded, then it does not demand
1260 // the high bits of its LHS or RHS.
1261 if (DemandedMask[BitWidth-1] == 0) {
1262 // Right fill the mask of bits for this ADD to demand the most
1263 // significant bit and all those below it.
1264 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1265 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1266 LHSKnownZero, LHSKnownOne, Depth+1))
1268 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1269 LHSKnownZero, LHSKnownOne, Depth+1))
1275 case Instruction::Sub:
1276 // If the high-bits of this SUB are not demanded, then it does not demand
1277 // the high bits of its LHS or RHS.
1278 if (DemandedMask[BitWidth-1] == 0) {
1279 // Right fill the mask of bits for this SUB to demand the most
1280 // significant bit and all those below it.
1281 uint32_t NLZ = DemandedMask.countLeadingZeros();
1282 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1283 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1284 LHSKnownZero, LHSKnownOne, Depth+1))
1286 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1287 LHSKnownZero, LHSKnownOne, Depth+1))
1291 case Instruction::Shl:
1292 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1293 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1294 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1295 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1296 RHSKnownZero, RHSKnownOne, Depth+1))
1298 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1299 "Bits known to be one AND zero?");
1300 RHSKnownZero <<= ShiftAmt;
1301 RHSKnownOne <<= ShiftAmt;
1302 // low bits known zero.
1304 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1307 case Instruction::LShr:
1308 // For a logical shift right
1309 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1310 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1312 // Unsigned shift right.
1313 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1314 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1315 RHSKnownZero, RHSKnownOne, Depth+1))
1317 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1318 "Bits known to be one AND zero?");
1319 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1320 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1322 // Compute the new bits that are at the top now.
1323 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1324 RHSKnownZero |= HighBits; // high bits known zero.
1328 case Instruction::AShr:
1329 // If this is an arithmetic shift right and only the low-bit is set, we can
1330 // always convert this into a logical shr, even if the shift amount is
1331 // variable. The low bit of the shift cannot be an input sign bit unless
1332 // the shift amount is >= the size of the datatype, which is undefined.
1333 if (DemandedMask == 1) {
1334 // Perform the logical shift right.
1335 Value *NewVal = BinaryOperator::createLShr(
1336 I->getOperand(0), I->getOperand(1), I->getName());
1337 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1338 return UpdateValueUsesWith(I, NewVal);
1341 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1342 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1344 // Signed shift right.
1345 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1346 if (SimplifyDemandedBits(I->getOperand(0),
1348 RHSKnownZero, RHSKnownOne, Depth+1))
1350 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1351 "Bits known to be one AND zero?");
1352 // Compute the new bits that are at the top now.
1353 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1354 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1355 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1357 // Handle the sign bits.
1358 APInt SignBit(APInt::getSignBit(BitWidth));
1359 // Adjust to where it is now in the mask.
1360 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1362 // If the input sign bit is known to be zero, or if none of the top bits
1363 // are demanded, turn this into an unsigned shift right.
1364 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
1365 (HighBits & ~DemandedMask) == HighBits) {
1366 // Perform the logical shift right.
1367 Value *NewVal = BinaryOperator::createLShr(
1368 I->getOperand(0), SA, I->getName());
1369 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1370 return UpdateValueUsesWith(I, NewVal);
1371 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1372 RHSKnownOne |= HighBits;
1378 // If the client is only demanding bits that we know, return the known
1380 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1381 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1386 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1387 /// 64 or fewer elements. DemandedElts contains the set of elements that are
1388 /// actually used by the caller. This method analyzes which elements of the
1389 /// operand are undef and returns that information in UndefElts.
1391 /// If the information about demanded elements can be used to simplify the
1392 /// operation, the operation is simplified, then the resultant value is
1393 /// returned. This returns null if no change was made.
1394 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1395 uint64_t &UndefElts,
1397 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1398 assert(VWidth <= 64 && "Vector too wide to analyze!");
1399 uint64_t EltMask = ~0ULL >> (64-VWidth);
1400 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1401 "Invalid DemandedElts!");
1403 if (isa<UndefValue>(V)) {
1404 // If the entire vector is undefined, just return this info.
1405 UndefElts = EltMask;
1407 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1408 UndefElts = EltMask;
1409 return UndefValue::get(V->getType());
1413 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1414 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1415 Constant *Undef = UndefValue::get(EltTy);
1417 std::vector<Constant*> Elts;
1418 for (unsigned i = 0; i != VWidth; ++i)
1419 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1420 Elts.push_back(Undef);
1421 UndefElts |= (1ULL << i);
1422 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1423 Elts.push_back(Undef);
1424 UndefElts |= (1ULL << i);
1425 } else { // Otherwise, defined.
1426 Elts.push_back(CP->getOperand(i));
1429 // If we changed the constant, return it.
1430 Constant *NewCP = ConstantVector::get(Elts);
1431 return NewCP != CP ? NewCP : 0;
1432 } else if (isa<ConstantAggregateZero>(V)) {
1433 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1435 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1436 Constant *Zero = Constant::getNullValue(EltTy);
1437 Constant *Undef = UndefValue::get(EltTy);
1438 std::vector<Constant*> Elts;
1439 for (unsigned i = 0; i != VWidth; ++i)
1440 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1441 UndefElts = DemandedElts ^ EltMask;
1442 return ConstantVector::get(Elts);
1445 if (!V->hasOneUse()) { // Other users may use these bits.
1446 if (Depth != 0) { // Not at the root.
1447 // TODO: Just compute the UndefElts information recursively.
1451 } else if (Depth == 10) { // Limit search depth.
1455 Instruction *I = dyn_cast<Instruction>(V);
1456 if (!I) return false; // Only analyze instructions.
1458 bool MadeChange = false;
1459 uint64_t UndefElts2;
1461 switch (I->getOpcode()) {
1464 case Instruction::InsertElement: {
1465 // If this is a variable index, we don't know which element it overwrites.
1466 // demand exactly the same input as we produce.
1467 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1469 // Note that we can't propagate undef elt info, because we don't know
1470 // which elt is getting updated.
1471 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1472 UndefElts2, Depth+1);
1473 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1477 // If this is inserting an element that isn't demanded, remove this
1479 unsigned IdxNo = Idx->getZExtValue();
1480 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1481 return AddSoonDeadInstToWorklist(*I, 0);
1483 // Otherwise, the element inserted overwrites whatever was there, so the
1484 // input demanded set is simpler than the output set.
1485 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1486 DemandedElts & ~(1ULL << IdxNo),
1487 UndefElts, Depth+1);
1488 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1490 // The inserted element is defined.
1491 UndefElts |= 1ULL << IdxNo;
1494 case Instruction::BitCast: {
1495 // Packed->packed casts only.
1496 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1498 unsigned InVWidth = VTy->getNumElements();
1499 uint64_t InputDemandedElts = 0;
1502 if (VWidth == InVWidth) {
1503 // If we are converting from <4x i32> -> <4 x f32>, we demand the same
1504 // elements as are demanded of us.
1506 InputDemandedElts = DemandedElts;
1507 } else if (VWidth > InVWidth) {
1511 // If there are more elements in the result than there are in the source,
1512 // then an input element is live if any of the corresponding output
1513 // elements are live.
1514 Ratio = VWidth/InVWidth;
1515 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1516 if (DemandedElts & (1ULL << OutIdx))
1517 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1523 // If there are more elements in the source than there are in the result,
1524 // then an input element is live if the corresponding output element is
1526 Ratio = InVWidth/VWidth;
1527 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1528 if (DemandedElts & (1ULL << InIdx/Ratio))
1529 InputDemandedElts |= 1ULL << InIdx;
1532 // div/rem demand all inputs, because they don't want divide by zero.
1533 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1534 UndefElts2, Depth+1);
1536 I->setOperand(0, TmpV);
1540 UndefElts = UndefElts2;
1541 if (VWidth > InVWidth) {
1542 assert(0 && "Unimp");
1543 // If there are more elements in the result than there are in the source,
1544 // then an output element is undef if the corresponding input element is
1546 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1547 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1548 UndefElts |= 1ULL << OutIdx;
1549 } else if (VWidth < InVWidth) {
1550 assert(0 && "Unimp");
1551 // If there are more elements in the source than there are in the result,
1552 // then a result element is undef if all of the corresponding input
1553 // elements are undef.
1554 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1555 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1556 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1557 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1561 case Instruction::And:
1562 case Instruction::Or:
1563 case Instruction::Xor:
1564 case Instruction::Add:
1565 case Instruction::Sub:
1566 case Instruction::Mul:
1567 // div/rem demand all inputs, because they don't want divide by zero.
1568 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1569 UndefElts, Depth+1);
1570 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1571 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1572 UndefElts2, Depth+1);
1573 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1575 // Output elements are undefined if both are undefined. Consider things
1576 // like undef&0. The result is known zero, not undef.
1577 UndefElts &= UndefElts2;
1580 case Instruction::Call: {
1581 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1583 switch (II->getIntrinsicID()) {
1586 // Binary vector operations that work column-wise. A dest element is a
1587 // function of the corresponding input elements from the two inputs.
1588 case Intrinsic::x86_sse_sub_ss:
1589 case Intrinsic::x86_sse_mul_ss:
1590 case Intrinsic::x86_sse_min_ss:
1591 case Intrinsic::x86_sse_max_ss:
1592 case Intrinsic::x86_sse2_sub_sd:
1593 case Intrinsic::x86_sse2_mul_sd:
1594 case Intrinsic::x86_sse2_min_sd:
1595 case Intrinsic::x86_sse2_max_sd:
1596 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1597 UndefElts, Depth+1);
1598 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1599 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1600 UndefElts2, Depth+1);
1601 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1603 // If only the low elt is demanded and this is a scalarizable intrinsic,
1604 // scalarize it now.
1605 if (DemandedElts == 1) {
1606 switch (II->getIntrinsicID()) {
1608 case Intrinsic::x86_sse_sub_ss:
1609 case Intrinsic::x86_sse_mul_ss:
1610 case Intrinsic::x86_sse2_sub_sd:
1611 case Intrinsic::x86_sse2_mul_sd:
1612 // TODO: Lower MIN/MAX/ABS/etc
1613 Value *LHS = II->getOperand(1);
1614 Value *RHS = II->getOperand(2);
1615 // Extract the element as scalars.
1616 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1617 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1619 switch (II->getIntrinsicID()) {
1620 default: assert(0 && "Case stmts out of sync!");
1621 case Intrinsic::x86_sse_sub_ss:
1622 case Intrinsic::x86_sse2_sub_sd:
1623 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1624 II->getName()), *II);
1626 case Intrinsic::x86_sse_mul_ss:
1627 case Intrinsic::x86_sse2_mul_sd:
1628 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1629 II->getName()), *II);
1634 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1636 InsertNewInstBefore(New, *II);
1637 AddSoonDeadInstToWorklist(*II, 0);
1642 // Output elements are undefined if both are undefined. Consider things
1643 // like undef&0. The result is known zero, not undef.
1644 UndefElts &= UndefElts2;
1650 return MadeChange ? I : 0;
1653 /// @returns true if the specified compare instruction is
1654 /// true when both operands are equal...
1655 /// @brief Determine if the ICmpInst returns true if both operands are equal
1656 static bool isTrueWhenEqual(ICmpInst &ICI) {
1657 ICmpInst::Predicate pred = ICI.getPredicate();
1658 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1659 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1660 pred == ICmpInst::ICMP_SLE;
1663 /// AssociativeOpt - Perform an optimization on an associative operator. This
1664 /// function is designed to check a chain of associative operators for a
1665 /// potential to apply a certain optimization. Since the optimization may be
1666 /// applicable if the expression was reassociated, this checks the chain, then
1667 /// reassociates the expression as necessary to expose the optimization
1668 /// opportunity. This makes use of a special Functor, which must define
1669 /// 'shouldApply' and 'apply' methods.
1671 template<typename Functor>
1672 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1673 unsigned Opcode = Root.getOpcode();
1674 Value *LHS = Root.getOperand(0);
1676 // Quick check, see if the immediate LHS matches...
1677 if (F.shouldApply(LHS))
1678 return F.apply(Root);
1680 // Otherwise, if the LHS is not of the same opcode as the root, return.
1681 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1682 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1683 // Should we apply this transform to the RHS?
1684 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1686 // If not to the RHS, check to see if we should apply to the LHS...
1687 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1688 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1692 // If the functor wants to apply the optimization to the RHS of LHSI,
1693 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1695 BasicBlock *BB = Root.getParent();
1697 // Now all of the instructions are in the current basic block, go ahead
1698 // and perform the reassociation.
1699 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1701 // First move the selected RHS to the LHS of the root...
1702 Root.setOperand(0, LHSI->getOperand(1));
1704 // Make what used to be the LHS of the root be the user of the root...
1705 Value *ExtraOperand = TmpLHSI->getOperand(1);
1706 if (&Root == TmpLHSI) {
1707 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1710 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1711 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1712 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1713 BasicBlock::iterator ARI = &Root; ++ARI;
1714 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1717 // Now propagate the ExtraOperand down the chain of instructions until we
1719 while (TmpLHSI != LHSI) {
1720 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1721 // Move the instruction to immediately before the chain we are
1722 // constructing to avoid breaking dominance properties.
1723 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1724 BB->getInstList().insert(ARI, NextLHSI);
1727 Value *NextOp = NextLHSI->getOperand(1);
1728 NextLHSI->setOperand(1, ExtraOperand);
1730 ExtraOperand = NextOp;
1733 // Now that the instructions are reassociated, have the functor perform
1734 // the transformation...
1735 return F.apply(Root);
1738 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1744 // AddRHS - Implements: X + X --> X << 1
1747 AddRHS(Value *rhs) : RHS(rhs) {}
1748 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1749 Instruction *apply(BinaryOperator &Add) const {
1750 return BinaryOperator::createShl(Add.getOperand(0),
1751 ConstantInt::get(Add.getType(), 1));
1755 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1757 struct AddMaskingAnd {
1759 AddMaskingAnd(Constant *c) : C2(c) {}
1760 bool shouldApply(Value *LHS) const {
1762 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1763 ConstantExpr::getAnd(C1, C2)->isNullValue();
1765 Instruction *apply(BinaryOperator &Add) const {
1766 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1770 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1772 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1773 if (Constant *SOC = dyn_cast<Constant>(SO))
1774 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1776 return IC->InsertNewInstBefore(CastInst::create(
1777 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1780 // Figure out if the constant is the left or the right argument.
1781 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1782 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1784 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1786 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1787 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1790 Value *Op0 = SO, *Op1 = ConstOperand;
1792 std::swap(Op0, Op1);
1794 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1795 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1796 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1797 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1798 SO->getName()+".cmp");
1800 assert(0 && "Unknown binary instruction type!");
1803 return IC->InsertNewInstBefore(New, I);
1806 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1807 // constant as the other operand, try to fold the binary operator into the
1808 // select arguments. This also works for Cast instructions, which obviously do
1809 // not have a second operand.
1810 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1812 // Don't modify shared select instructions
1813 if (!SI->hasOneUse()) return 0;
1814 Value *TV = SI->getOperand(1);
1815 Value *FV = SI->getOperand(2);
1817 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1818 // Bool selects with constant operands can be folded to logical ops.
1819 if (SI->getType() == Type::Int1Ty) return 0;
1821 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1822 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1824 return new SelectInst(SI->getCondition(), SelectTrueVal,
1831 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1832 /// node as operand #0, see if we can fold the instruction into the PHI (which
1833 /// is only possible if all operands to the PHI are constants).
1834 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1835 PHINode *PN = cast<PHINode>(I.getOperand(0));
1836 unsigned NumPHIValues = PN->getNumIncomingValues();
1837 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1839 // Check to see if all of the operands of the PHI are constants. If there is
1840 // one non-constant value, remember the BB it is. If there is more than one
1841 // or if *it* is a PHI, bail out.
1842 BasicBlock *NonConstBB = 0;
1843 for (unsigned i = 0; i != NumPHIValues; ++i)
1844 if (!isa<Constant>(PN->getIncomingValue(i))) {
1845 if (NonConstBB) return 0; // More than one non-const value.
1846 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1847 NonConstBB = PN->getIncomingBlock(i);
1849 // If the incoming non-constant value is in I's block, we have an infinite
1851 if (NonConstBB == I.getParent())
1855 // If there is exactly one non-constant value, we can insert a copy of the
1856 // operation in that block. However, if this is a critical edge, we would be
1857 // inserting the computation one some other paths (e.g. inside a loop). Only
1858 // do this if the pred block is unconditionally branching into the phi block.
1860 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1861 if (!BI || !BI->isUnconditional()) return 0;
1864 // Okay, we can do the transformation: create the new PHI node.
1865 PHINode *NewPN = new PHINode(I.getType(), "");
1866 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1867 InsertNewInstBefore(NewPN, *PN);
1868 NewPN->takeName(PN);
1870 // Next, add all of the operands to the PHI.
1871 if (I.getNumOperands() == 2) {
1872 Constant *C = cast<Constant>(I.getOperand(1));
1873 for (unsigned i = 0; i != NumPHIValues; ++i) {
1875 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1876 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1877 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1879 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1881 assert(PN->getIncomingBlock(i) == NonConstBB);
1882 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1883 InV = BinaryOperator::create(BO->getOpcode(),
1884 PN->getIncomingValue(i), C, "phitmp",
1885 NonConstBB->getTerminator());
1886 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1887 InV = CmpInst::create(CI->getOpcode(),
1889 PN->getIncomingValue(i), C, "phitmp",
1890 NonConstBB->getTerminator());
1892 assert(0 && "Unknown binop!");
1894 AddToWorkList(cast<Instruction>(InV));
1896 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1899 CastInst *CI = cast<CastInst>(&I);
1900 const Type *RetTy = CI->getType();
1901 for (unsigned i = 0; i != NumPHIValues; ++i) {
1903 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1904 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1906 assert(PN->getIncomingBlock(i) == NonConstBB);
1907 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1908 I.getType(), "phitmp",
1909 NonConstBB->getTerminator());
1910 AddToWorkList(cast<Instruction>(InV));
1912 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1915 return ReplaceInstUsesWith(I, NewPN);
1918 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1919 bool Changed = SimplifyCommutative(I);
1920 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1922 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1923 // X + undef -> undef
1924 if (isa<UndefValue>(RHS))
1925 return ReplaceInstUsesWith(I, RHS);
1928 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1929 if (RHSC->isNullValue())
1930 return ReplaceInstUsesWith(I, LHS);
1931 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1932 if (CFP->isExactlyValue(-0.0))
1933 return ReplaceInstUsesWith(I, LHS);
1936 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1937 // X + (signbit) --> X ^ signbit
1938 const APInt& Val = CI->getValue();
1939 uint32_t BitWidth = Val.getBitWidth();
1940 if (Val == APInt::getSignBit(BitWidth))
1941 return BinaryOperator::createXor(LHS, RHS);
1943 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1944 // (X & 254)+1 -> (X&254)|1
1945 if (!isa<VectorType>(I.getType())) {
1946 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1947 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1948 KnownZero, KnownOne))
1953 if (isa<PHINode>(LHS))
1954 if (Instruction *NV = FoldOpIntoPhi(I))
1957 ConstantInt *XorRHS = 0;
1959 if (isa<ConstantInt>(RHSC) &&
1960 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1961 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
1962 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
1964 uint32_t Size = TySizeBits / 2;
1965 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1966 APInt CFF80Val(-C0080Val);
1968 if (TySizeBits > Size) {
1969 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1970 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1971 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1972 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
1973 // This is a sign extend if the top bits are known zero.
1974 if (!MaskedValueIsZero(XorLHS,
1975 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
1976 Size = 0; // Not a sign ext, but can't be any others either.
1981 C0080Val = APIntOps::lshr(C0080Val, Size);
1982 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1983 } while (Size >= 1);
1985 // FIXME: This shouldn't be necessary. When the backends can handle types
1986 // with funny bit widths then this whole cascade of if statements should
1987 // be removed. It is just here to get the size of the "middle" type back
1988 // up to something that the back ends can handle.
1989 const Type *MiddleType = 0;
1992 case 32: MiddleType = Type::Int32Ty; break;
1993 case 16: MiddleType = Type::Int16Ty; break;
1994 case 8: MiddleType = Type::Int8Ty; break;
1997 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1998 InsertNewInstBefore(NewTrunc, I);
1999 return new SExtInst(NewTrunc, I.getType(), I.getName());
2005 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2006 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2008 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2009 if (RHSI->getOpcode() == Instruction::Sub)
2010 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2011 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2013 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2014 if (LHSI->getOpcode() == Instruction::Sub)
2015 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2016 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2021 if (Value *V = dyn_castNegVal(LHS))
2022 return BinaryOperator::createSub(RHS, V);
2025 if (!isa<Constant>(RHS))
2026 if (Value *V = dyn_castNegVal(RHS))
2027 return BinaryOperator::createSub(LHS, V);
2031 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2032 if (X == RHS) // X*C + X --> X * (C+1)
2033 return BinaryOperator::createMul(RHS, AddOne(C2));
2035 // X*C1 + X*C2 --> X * (C1+C2)
2037 if (X == dyn_castFoldableMul(RHS, C1))
2038 return BinaryOperator::createMul(X, Add(C1, C2));
2041 // X + X*C --> X * (C+1)
2042 if (dyn_castFoldableMul(RHS, C2) == LHS)
2043 return BinaryOperator::createMul(LHS, AddOne(C2));
2045 // X + ~X --> -1 since ~X = -X-1
2046 if (dyn_castNotVal(LHS) == RHS ||
2047 dyn_castNotVal(RHS) == LHS)
2048 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
2051 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2052 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2053 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2056 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2058 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2059 return BinaryOperator::createSub(SubOne(CRHS), X);
2061 // (X & FF00) + xx00 -> (X+xx00) & FF00
2062 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2063 Constant *Anded = And(CRHS, C2);
2064 if (Anded == CRHS) {
2065 // See if all bits from the first bit set in the Add RHS up are included
2066 // in the mask. First, get the rightmost bit.
2067 const APInt& AddRHSV = CRHS->getValue();
2069 // Form a mask of all bits from the lowest bit added through the top.
2070 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2072 // See if the and mask includes all of these bits.
2073 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2075 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2076 // Okay, the xform is safe. Insert the new add pronto.
2077 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2078 LHS->getName()), I);
2079 return BinaryOperator::createAnd(NewAdd, C2);
2084 // Try to fold constant add into select arguments.
2085 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2086 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2090 // add (cast *A to intptrtype) B ->
2091 // cast (GEP (cast *A to sbyte*) B) ->
2094 CastInst *CI = dyn_cast<CastInst>(LHS);
2097 CI = dyn_cast<CastInst>(RHS);
2100 if (CI && CI->getType()->isSized() &&
2101 (CI->getType()->getPrimitiveSizeInBits() ==
2102 TD->getIntPtrType()->getPrimitiveSizeInBits())
2103 && isa<PointerType>(CI->getOperand(0)->getType())) {
2104 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
2105 PointerType::get(Type::Int8Ty), I);
2106 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
2107 return new PtrToIntInst(I2, CI->getType());
2111 return Changed ? &I : 0;
2114 // isSignBit - Return true if the value represented by the constant only has the
2115 // highest order bit set.
2116 static bool isSignBit(ConstantInt *CI) {
2117 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2118 return CI->getValue() == APInt::getSignBit(NumBits);
2121 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2122 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2124 if (Op0 == Op1) // sub X, X -> 0
2125 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2127 // If this is a 'B = x-(-A)', change to B = x+A...
2128 if (Value *V = dyn_castNegVal(Op1))
2129 return BinaryOperator::createAdd(Op0, V);
2131 if (isa<UndefValue>(Op0))
2132 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2133 if (isa<UndefValue>(Op1))
2134 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2136 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2137 // Replace (-1 - A) with (~A)...
2138 if (C->isAllOnesValue())
2139 return BinaryOperator::createNot(Op1);
2141 // C - ~X == X + (1+C)
2143 if (match(Op1, m_Not(m_Value(X))))
2144 return BinaryOperator::createAdd(X, AddOne(C));
2146 // -(X >>u 31) -> (X >>s 31)
2147 // -(X >>s 31) -> (X >>u 31)
2149 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
2150 if (SI->getOpcode() == Instruction::LShr) {
2151 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2152 // Check to see if we are shifting out everything but the sign bit.
2153 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2154 SI->getType()->getPrimitiveSizeInBits()-1) {
2155 // Ok, the transformation is safe. Insert AShr.
2156 return BinaryOperator::create(Instruction::AShr,
2157 SI->getOperand(0), CU, SI->getName());
2161 else if (SI->getOpcode() == Instruction::AShr) {
2162 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2163 // Check to see if we are shifting out everything but the sign bit.
2164 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2165 SI->getType()->getPrimitiveSizeInBits()-1) {
2166 // Ok, the transformation is safe. Insert LShr.
2167 return BinaryOperator::createLShr(
2168 SI->getOperand(0), CU, SI->getName());
2174 // Try to fold constant sub into select arguments.
2175 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2176 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2179 if (isa<PHINode>(Op0))
2180 if (Instruction *NV = FoldOpIntoPhi(I))
2184 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2185 if (Op1I->getOpcode() == Instruction::Add &&
2186 !Op0->getType()->isFPOrFPVector()) {
2187 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2188 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2189 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2190 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2191 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2192 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2193 // C1-(X+C2) --> (C1-C2)-X
2194 return BinaryOperator::createSub(Subtract(CI1, CI2),
2195 Op1I->getOperand(0));
2199 if (Op1I->hasOneUse()) {
2200 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2201 // is not used by anyone else...
2203 if (Op1I->getOpcode() == Instruction::Sub &&
2204 !Op1I->getType()->isFPOrFPVector()) {
2205 // Swap the two operands of the subexpr...
2206 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2207 Op1I->setOperand(0, IIOp1);
2208 Op1I->setOperand(1, IIOp0);
2210 // Create the new top level add instruction...
2211 return BinaryOperator::createAdd(Op0, Op1);
2214 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2216 if (Op1I->getOpcode() == Instruction::And &&
2217 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2218 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2221 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2222 return BinaryOperator::createAnd(Op0, NewNot);
2225 // 0 - (X sdiv C) -> (X sdiv -C)
2226 if (Op1I->getOpcode() == Instruction::SDiv)
2227 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2229 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2230 return BinaryOperator::createSDiv(Op1I->getOperand(0),
2231 ConstantExpr::getNeg(DivRHS));
2233 // X - X*C --> X * (1-C)
2234 ConstantInt *C2 = 0;
2235 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2236 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2237 return BinaryOperator::createMul(Op0, CP1);
2242 if (!Op0->getType()->isFPOrFPVector())
2243 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2244 if (Op0I->getOpcode() == Instruction::Add) {
2245 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2246 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2247 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2248 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2249 } else if (Op0I->getOpcode() == Instruction::Sub) {
2250 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2251 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2255 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2256 if (X == Op1) // X*C - X --> X * (C-1)
2257 return BinaryOperator::createMul(Op1, SubOne(C1));
2259 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2260 if (X == dyn_castFoldableMul(Op1, C2))
2261 return BinaryOperator::createMul(Op1, Subtract(C1, C2));
2266 /// isSignBitCheck - Given an exploded icmp instruction, return true if it
2267 /// really just returns true if the most significant (sign) bit is set.
2268 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS) {
2270 case ICmpInst::ICMP_SLT:
2271 // True if LHS s< RHS and RHS == 0
2272 return RHS->isZero();
2273 case ICmpInst::ICMP_SLE:
2274 // True if LHS s<= RHS and RHS == -1
2275 return RHS->isAllOnesValue();
2276 case ICmpInst::ICMP_UGE:
2277 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2278 return RHS->getValue() ==
2279 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
2280 case ICmpInst::ICMP_UGT:
2281 // True if LHS u> RHS and RHS == high-bit-mask - 1
2282 return RHS->getValue() ==
2283 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2289 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2290 bool Changed = SimplifyCommutative(I);
2291 Value *Op0 = I.getOperand(0);
2293 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2294 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2296 // Simplify mul instructions with a constant RHS...
2297 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2298 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2300 // ((X << C1)*C2) == (X * (C2 << C1))
2301 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2302 if (SI->getOpcode() == Instruction::Shl)
2303 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2304 return BinaryOperator::createMul(SI->getOperand(0),
2305 ConstantExpr::getShl(CI, ShOp));
2308 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2309 if (CI->equalsInt(1)) // X * 1 == X
2310 return ReplaceInstUsesWith(I, Op0);
2311 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2312 return BinaryOperator::createNeg(Op0, I.getName());
2314 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2315 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2316 return BinaryOperator::createShl(Op0,
2317 ConstantInt::get(Op0->getType(), Val.logBase2()));
2319 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2320 if (Op1F->isNullValue())
2321 return ReplaceInstUsesWith(I, Op1);
2323 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2324 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2325 if (Op1F->getValue() == 1.0)
2326 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2329 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2330 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2331 isa<ConstantInt>(Op0I->getOperand(1))) {
2332 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2333 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2335 InsertNewInstBefore(Add, I);
2336 Value *C1C2 = ConstantExpr::getMul(Op1,
2337 cast<Constant>(Op0I->getOperand(1)));
2338 return BinaryOperator::createAdd(Add, C1C2);
2342 // Try to fold constant mul into select arguments.
2343 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2344 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2347 if (isa<PHINode>(Op0))
2348 if (Instruction *NV = FoldOpIntoPhi(I))
2352 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2353 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2354 return BinaryOperator::createMul(Op0v, Op1v);
2356 // If one of the operands of the multiply is a cast from a boolean value, then
2357 // we know the bool is either zero or one, so this is a 'masking' multiply.
2358 // See if we can simplify things based on how the boolean was originally
2360 CastInst *BoolCast = 0;
2361 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2362 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2365 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2366 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2369 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2370 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2371 const Type *SCOpTy = SCIOp0->getType();
2373 // If the icmp is true iff the sign bit of X is set, then convert this
2374 // multiply into a shift/and combination.
2375 if (isa<ConstantInt>(SCIOp1) &&
2376 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1))) {
2377 // Shift the X value right to turn it into "all signbits".
2378 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2379 SCOpTy->getPrimitiveSizeInBits()-1);
2381 InsertNewInstBefore(
2382 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
2383 BoolCast->getOperand(0)->getName()+
2386 // If the multiply type is not the same as the source type, sign extend
2387 // or truncate to the multiply type.
2388 if (I.getType() != V->getType()) {
2389 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2390 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2391 Instruction::CastOps opcode =
2392 (SrcBits == DstBits ? Instruction::BitCast :
2393 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2394 V = InsertCastBefore(opcode, V, I.getType(), I);
2397 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2398 return BinaryOperator::createAnd(V, OtherOp);
2403 return Changed ? &I : 0;
2406 /// This function implements the transforms on div instructions that work
2407 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2408 /// used by the visitors to those instructions.
2409 /// @brief Transforms common to all three div instructions
2410 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2411 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2414 if (isa<UndefValue>(Op0))
2415 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2417 // X / undef -> undef
2418 if (isa<UndefValue>(Op1))
2419 return ReplaceInstUsesWith(I, Op1);
2421 // Handle cases involving: div X, (select Cond, Y, Z)
2422 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2423 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
2424 // same basic block, then we replace the select with Y, and the condition
2425 // of the select with false (if the cond value is in the same BB). If the
2426 // select has uses other than the div, this allows them to be simplified
2427 // also. Note that div X, Y is just as good as div X, 0 (undef)
2428 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2429 if (ST->isNullValue()) {
2430 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2431 if (CondI && CondI->getParent() == I.getParent())
2432 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2433 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2434 I.setOperand(1, SI->getOperand(2));
2436 UpdateValueUsesWith(SI, SI->getOperand(2));
2440 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2441 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2442 if (ST->isNullValue()) {
2443 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2444 if (CondI && CondI->getParent() == I.getParent())
2445 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2446 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2447 I.setOperand(1, SI->getOperand(1));
2449 UpdateValueUsesWith(SI, SI->getOperand(1));
2457 /// This function implements the transforms common to both integer division
2458 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2459 /// division instructions.
2460 /// @brief Common integer divide transforms
2461 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2462 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2464 if (Instruction *Common = commonDivTransforms(I))
2467 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2469 if (RHS->equalsInt(1))
2470 return ReplaceInstUsesWith(I, Op0);
2472 // (X / C1) / C2 -> X / (C1*C2)
2473 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2474 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2475 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2476 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2477 Multiply(RHS, LHSRHS));
2480 if (!RHS->isZero()) { // avoid X udiv 0
2481 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2482 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2484 if (isa<PHINode>(Op0))
2485 if (Instruction *NV = FoldOpIntoPhi(I))
2490 // 0 / X == 0, we don't need to preserve faults!
2491 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2492 if (LHS->equalsInt(0))
2493 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2498 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2499 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2501 // Handle the integer div common cases
2502 if (Instruction *Common = commonIDivTransforms(I))
2505 // X udiv C^2 -> X >> C
2506 // Check to see if this is an unsigned division with an exact power of 2,
2507 // if so, convert to a right shift.
2508 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2509 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
2510 return BinaryOperator::createLShr(Op0,
2511 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2514 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2515 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2516 if (RHSI->getOpcode() == Instruction::Shl &&
2517 isa<ConstantInt>(RHSI->getOperand(0))) {
2518 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2519 if (C1.isPowerOf2()) {
2520 Value *N = RHSI->getOperand(1);
2521 const Type *NTy = N->getType();
2522 if (uint32_t C2 = C1.logBase2()) {
2523 Constant *C2V = ConstantInt::get(NTy, C2);
2524 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2526 return BinaryOperator::createLShr(Op0, N);
2531 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2532 // where C1&C2 are powers of two.
2533 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2534 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2535 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2536 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2537 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2538 // Compute the shift amounts
2539 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2540 // Construct the "on true" case of the select
2541 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2542 Instruction *TSI = BinaryOperator::createLShr(
2543 Op0, TC, SI->getName()+".t");
2544 TSI = InsertNewInstBefore(TSI, I);
2546 // Construct the "on false" case of the select
2547 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2548 Instruction *FSI = BinaryOperator::createLShr(
2549 Op0, FC, SI->getName()+".f");
2550 FSI = InsertNewInstBefore(FSI, I);
2552 // construct the select instruction and return it.
2553 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2559 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2560 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2562 // Handle the integer div common cases
2563 if (Instruction *Common = commonIDivTransforms(I))
2566 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2568 if (RHS->isAllOnesValue())
2569 return BinaryOperator::createNeg(Op0);
2572 if (Value *LHSNeg = dyn_castNegVal(Op0))
2573 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2576 // If the sign bits of both operands are zero (i.e. we can prove they are
2577 // unsigned inputs), turn this into a udiv.
2578 if (I.getType()->isInteger()) {
2579 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2580 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2581 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2588 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2589 return commonDivTransforms(I);
2592 /// GetFactor - If we can prove that the specified value is at least a multiple
2593 /// of some factor, return that factor.
2594 static Constant *GetFactor(Value *V) {
2595 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2598 // Unless we can be tricky, we know this is a multiple of 1.
2599 Constant *Result = ConstantInt::get(V->getType(), 1);
2601 Instruction *I = dyn_cast<Instruction>(V);
2602 if (!I) return Result;
2604 if (I->getOpcode() == Instruction::Mul) {
2605 // Handle multiplies by a constant, etc.
2606 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2607 GetFactor(I->getOperand(1)));
2608 } else if (I->getOpcode() == Instruction::Shl) {
2609 // (X<<C) -> X * (1 << C)
2610 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2611 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2612 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2614 } else if (I->getOpcode() == Instruction::And) {
2615 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2616 // X & 0xFFF0 is known to be a multiple of 16.
2617 uint32_t Zeros = RHS->getValue().countTrailingZeros();
2618 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2619 return ConstantExpr::getShl(Result,
2620 ConstantInt::get(Result->getType(), Zeros));
2622 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2623 // Only handle int->int casts.
2624 if (!CI->isIntegerCast())
2626 Value *Op = CI->getOperand(0);
2627 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2632 /// This function implements the transforms on rem instructions that work
2633 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2634 /// is used by the visitors to those instructions.
2635 /// @brief Transforms common to all three rem instructions
2636 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2637 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2639 // 0 % X == 0, we don't need to preserve faults!
2640 if (Constant *LHS = dyn_cast<Constant>(Op0))
2641 if (LHS->isNullValue())
2642 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2644 if (isa<UndefValue>(Op0)) // undef % X -> 0
2645 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2646 if (isa<UndefValue>(Op1))
2647 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2649 // Handle cases involving: rem X, (select Cond, Y, Z)
2650 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2651 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2652 // the same basic block, then we replace the select with Y, and the
2653 // condition of the select with false (if the cond value is in the same
2654 // BB). If the select has uses other than the div, this allows them to be
2656 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2657 if (ST->isNullValue()) {
2658 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2659 if (CondI && CondI->getParent() == I.getParent())
2660 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2661 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2662 I.setOperand(1, SI->getOperand(2));
2664 UpdateValueUsesWith(SI, SI->getOperand(2));
2667 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2668 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2669 if (ST->isNullValue()) {
2670 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2671 if (CondI && CondI->getParent() == I.getParent())
2672 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2673 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2674 I.setOperand(1, SI->getOperand(1));
2676 UpdateValueUsesWith(SI, SI->getOperand(1));
2684 /// This function implements the transforms common to both integer remainder
2685 /// instructions (urem and srem). It is called by the visitors to those integer
2686 /// remainder instructions.
2687 /// @brief Common integer remainder transforms
2688 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2689 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2691 if (Instruction *common = commonRemTransforms(I))
2694 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2695 // X % 0 == undef, we don't need to preserve faults!
2696 if (RHS->equalsInt(0))
2697 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2699 if (RHS->equalsInt(1)) // X % 1 == 0
2700 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2702 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2703 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2704 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2706 } else if (isa<PHINode>(Op0I)) {
2707 if (Instruction *NV = FoldOpIntoPhi(I))
2710 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2711 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2712 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2719 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2720 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2722 if (Instruction *common = commonIRemTransforms(I))
2725 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2726 // X urem C^2 -> X and C
2727 // Check to see if this is an unsigned remainder with an exact power of 2,
2728 // if so, convert to a bitwise and.
2729 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2730 if (C->getValue().isPowerOf2())
2731 return BinaryOperator::createAnd(Op0, SubOne(C));
2734 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2735 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2736 if (RHSI->getOpcode() == Instruction::Shl &&
2737 isa<ConstantInt>(RHSI->getOperand(0))) {
2738 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2739 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2740 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2742 return BinaryOperator::createAnd(Op0, Add);
2747 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2748 // where C1&C2 are powers of two.
2749 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2750 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2751 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2752 // STO == 0 and SFO == 0 handled above.
2753 if ((STO->getValue().isPowerOf2()) &&
2754 (SFO->getValue().isPowerOf2())) {
2755 Value *TrueAnd = InsertNewInstBefore(
2756 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2757 Value *FalseAnd = InsertNewInstBefore(
2758 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2759 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2767 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2768 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2770 if (Instruction *common = commonIRemTransforms(I))
2773 if (Value *RHSNeg = dyn_castNegVal(Op1))
2774 if (!isa<ConstantInt>(RHSNeg) ||
2775 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2777 AddUsesToWorkList(I);
2778 I.setOperand(1, RHSNeg);
2782 // If the top bits of both operands are zero (i.e. we can prove they are
2783 // unsigned inputs), turn this into a urem.
2784 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2785 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2786 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2787 return BinaryOperator::createURem(Op0, Op1, I.getName());
2793 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2794 return commonRemTransforms(I);
2797 // isMaxValueMinusOne - return true if this is Max-1
2798 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2799 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2801 // Calculate 0111111111..11111
2802 APInt Val(APInt::getSignedMaxValue(TypeBits));
2803 return C->getValue() == Val-1;
2805 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2808 // isMinValuePlusOne - return true if this is Min+1
2809 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2811 // Calculate 1111111111000000000000
2812 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2813 APInt Val(APInt::getSignedMinValue(TypeBits));
2814 return C->getValue() == Val+1;
2816 return C->getValue() == 1; // unsigned
2819 // isOneBitSet - Return true if there is exactly one bit set in the specified
2821 static bool isOneBitSet(const ConstantInt *CI) {
2822 return CI->getValue().isPowerOf2();
2825 // isHighOnes - Return true if the constant is of the form 1+0+.
2826 // This is the same as lowones(~X).
2827 static bool isHighOnes(const ConstantInt *CI) {
2828 return (~CI->getValue() + 1).isPowerOf2();
2831 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
2832 /// are carefully arranged to allow folding of expressions such as:
2834 /// (A < B) | (A > B) --> (A != B)
2836 /// Note that this is only valid if the first and second predicates have the
2837 /// same sign. Is illegal to do: (A u< B) | (A s> B)
2839 /// Three bits are used to represent the condition, as follows:
2844 /// <=> Value Definition
2845 /// 000 0 Always false
2852 /// 111 7 Always true
2854 static unsigned getICmpCode(const ICmpInst *ICI) {
2855 switch (ICI->getPredicate()) {
2857 case ICmpInst::ICMP_UGT: return 1; // 001
2858 case ICmpInst::ICMP_SGT: return 1; // 001
2859 case ICmpInst::ICMP_EQ: return 2; // 010
2860 case ICmpInst::ICMP_UGE: return 3; // 011
2861 case ICmpInst::ICMP_SGE: return 3; // 011
2862 case ICmpInst::ICMP_ULT: return 4; // 100
2863 case ICmpInst::ICMP_SLT: return 4; // 100
2864 case ICmpInst::ICMP_NE: return 5; // 101
2865 case ICmpInst::ICMP_ULE: return 6; // 110
2866 case ICmpInst::ICMP_SLE: return 6; // 110
2869 assert(0 && "Invalid ICmp predicate!");
2874 /// getICmpValue - This is the complement of getICmpCode, which turns an
2875 /// opcode and two operands into either a constant true or false, or a brand
2876 /// new /// ICmp instruction. The sign is passed in to determine which kind
2877 /// of predicate to use in new icmp instructions.
2878 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2880 default: assert(0 && "Illegal ICmp code!");
2881 case 0: return ConstantInt::getFalse();
2884 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2886 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2887 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2890 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2892 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2895 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2897 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2898 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2901 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2903 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2904 case 7: return ConstantInt::getTrue();
2908 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2909 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2910 (ICmpInst::isSignedPredicate(p1) &&
2911 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2912 (ICmpInst::isSignedPredicate(p2) &&
2913 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2917 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2918 struct FoldICmpLogical {
2921 ICmpInst::Predicate pred;
2922 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2923 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2924 pred(ICI->getPredicate()) {}
2925 bool shouldApply(Value *V) const {
2926 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2927 if (PredicatesFoldable(pred, ICI->getPredicate()))
2928 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2929 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
2932 Instruction *apply(Instruction &Log) const {
2933 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2934 if (ICI->getOperand(0) != LHS) {
2935 assert(ICI->getOperand(1) == LHS);
2936 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
2939 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
2940 unsigned LHSCode = getICmpCode(ICI);
2941 unsigned RHSCode = getICmpCode(RHSICI);
2943 switch (Log.getOpcode()) {
2944 case Instruction::And: Code = LHSCode & RHSCode; break;
2945 case Instruction::Or: Code = LHSCode | RHSCode; break;
2946 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2947 default: assert(0 && "Illegal logical opcode!"); return 0;
2950 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
2951 ICmpInst::isSignedPredicate(ICI->getPredicate());
2953 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
2954 if (Instruction *I = dyn_cast<Instruction>(RV))
2956 // Otherwise, it's a constant boolean value...
2957 return IC.ReplaceInstUsesWith(Log, RV);
2960 } // end anonymous namespace
2962 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2963 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2964 // guaranteed to be a binary operator.
2965 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2967 ConstantInt *AndRHS,
2968 BinaryOperator &TheAnd) {
2969 Value *X = Op->getOperand(0);
2970 Constant *Together = 0;
2972 Together = And(AndRHS, OpRHS);
2974 switch (Op->getOpcode()) {
2975 case Instruction::Xor:
2976 if (Op->hasOneUse()) {
2977 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2978 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
2979 InsertNewInstBefore(And, TheAnd);
2981 return BinaryOperator::createXor(And, Together);
2984 case Instruction::Or:
2985 if (Together == AndRHS) // (X | C) & C --> C
2986 return ReplaceInstUsesWith(TheAnd, AndRHS);
2988 if (Op->hasOneUse() && Together != OpRHS) {
2989 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2990 Instruction *Or = BinaryOperator::createOr(X, Together);
2991 InsertNewInstBefore(Or, TheAnd);
2993 return BinaryOperator::createAnd(Or, AndRHS);
2996 case Instruction::Add:
2997 if (Op->hasOneUse()) {
2998 // Adding a one to a single bit bit-field should be turned into an XOR
2999 // of the bit. First thing to check is to see if this AND is with a
3000 // single bit constant.
3001 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3003 // If there is only one bit set...
3004 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3005 // Ok, at this point, we know that we are masking the result of the
3006 // ADD down to exactly one bit. If the constant we are adding has
3007 // no bits set below this bit, then we can eliminate the ADD.
3008 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3010 // Check to see if any bits below the one bit set in AndRHSV are set.
3011 if ((AddRHS & (AndRHSV-1)) == 0) {
3012 // If not, the only thing that can effect the output of the AND is
3013 // the bit specified by AndRHSV. If that bit is set, the effect of
3014 // the XOR is to toggle the bit. If it is clear, then the ADD has
3016 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3017 TheAnd.setOperand(0, X);
3020 // Pull the XOR out of the AND.
3021 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
3022 InsertNewInstBefore(NewAnd, TheAnd);
3023 NewAnd->takeName(Op);
3024 return BinaryOperator::createXor(NewAnd, AndRHS);
3031 case Instruction::Shl: {
3032 // We know that the AND will not produce any of the bits shifted in, so if
3033 // the anded constant includes them, clear them now!
3035 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3036 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3037 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3038 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3040 if (CI->getValue() == ShlMask) {
3041 // Masking out bits that the shift already masks
3042 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3043 } else if (CI != AndRHS) { // Reducing bits set in and.
3044 TheAnd.setOperand(1, CI);
3049 case Instruction::LShr:
3051 // We know that the AND will not produce any of the bits shifted in, so if
3052 // the anded constant includes them, clear them now! This only applies to
3053 // unsigned shifts, because a signed shr may bring in set bits!
3055 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3056 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3057 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3058 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3060 if (CI->getValue() == ShrMask) {
3061 // Masking out bits that the shift already masks.
3062 return ReplaceInstUsesWith(TheAnd, Op);
3063 } else if (CI != AndRHS) {
3064 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3069 case Instruction::AShr:
3071 // See if this is shifting in some sign extension, then masking it out
3073 if (Op->hasOneUse()) {
3074 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3075 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3076 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3077 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3078 if (C == AndRHS) { // Masking out bits shifted in.
3079 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3080 // Make the argument unsigned.
3081 Value *ShVal = Op->getOperand(0);
3082 ShVal = InsertNewInstBefore(
3083 BinaryOperator::createLShr(ShVal, OpRHS,
3084 Op->getName()), TheAnd);
3085 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
3094 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3095 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3096 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3097 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3098 /// insert new instructions.
3099 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3100 bool isSigned, bool Inside,
3102 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3103 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3104 "Lo is not <= Hi in range emission code!");
3107 if (Lo == Hi) // Trivially false.
3108 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3110 // V >= Min && V < Hi --> V < Hi
3111 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3112 ICmpInst::Predicate pred = (isSigned ?
3113 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3114 return new ICmpInst(pred, V, Hi);
3117 // Emit V-Lo <u Hi-Lo
3118 Constant *NegLo = ConstantExpr::getNeg(Lo);
3119 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3120 InsertNewInstBefore(Add, IB);
3121 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3122 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3125 if (Lo == Hi) // Trivially true.
3126 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3128 // V < Min || V >= Hi -> V > Hi-1
3129 Hi = SubOne(cast<ConstantInt>(Hi));
3130 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3131 ICmpInst::Predicate pred = (isSigned ?
3132 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3133 return new ICmpInst(pred, V, Hi);
3136 // Emit V-Lo >u Hi-1-Lo
3137 // Note that Hi has already had one subtracted from it, above.
3138 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3139 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3140 InsertNewInstBefore(Add, IB);
3141 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3142 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3145 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3146 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3147 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3148 // not, since all 1s are not contiguous.
3149 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3150 const APInt& V = Val->getValue();
3151 uint32_t BitWidth = Val->getType()->getBitWidth();
3152 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3154 // look for the first zero bit after the run of ones
3155 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3156 // look for the first non-zero bit
3157 ME = V.getActiveBits();
3161 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3162 /// where isSub determines whether the operator is a sub. If we can fold one of
3163 /// the following xforms:
3165 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3166 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3167 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3169 /// return (A +/- B).
3171 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3172 ConstantInt *Mask, bool isSub,
3174 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3175 if (!LHSI || LHSI->getNumOperands() != 2 ||
3176 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3178 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3180 switch (LHSI->getOpcode()) {
3182 case Instruction::And:
3183 if (And(N, Mask) == Mask) {
3184 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3185 if ((Mask->getValue().countLeadingZeros() +
3186 Mask->getValue().countPopulation()) ==
3187 Mask->getValue().getBitWidth())
3190 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3191 // part, we don't need any explicit masks to take them out of A. If that
3192 // is all N is, ignore it.
3193 uint32_t MB = 0, ME = 0;
3194 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3195 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3196 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3197 if (MaskedValueIsZero(RHS, Mask))
3202 case Instruction::Or:
3203 case Instruction::Xor:
3204 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3205 if ((Mask->getValue().countLeadingZeros() +
3206 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3207 && And(N, Mask)->isZero())
3214 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3216 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3217 return InsertNewInstBefore(New, I);
3220 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3221 bool Changed = SimplifyCommutative(I);
3222 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3224 if (isa<UndefValue>(Op1)) // X & undef -> 0
3225 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3229 return ReplaceInstUsesWith(I, Op1);
3231 // See if we can simplify any instructions used by the instruction whose sole
3232 // purpose is to compute bits we don't care about.
3233 if (!isa<VectorType>(I.getType())) {
3234 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3235 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3236 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3237 KnownZero, KnownOne))
3240 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3241 if (CP->isAllOnesValue())
3242 return ReplaceInstUsesWith(I, I.getOperand(0));
3246 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3247 const APInt& AndRHSMask = AndRHS->getValue();
3248 APInt NotAndRHS(~AndRHSMask);
3250 // Optimize a variety of ((val OP C1) & C2) combinations...
3251 if (isa<BinaryOperator>(Op0)) {
3252 Instruction *Op0I = cast<Instruction>(Op0);
3253 Value *Op0LHS = Op0I->getOperand(0);
3254 Value *Op0RHS = Op0I->getOperand(1);
3255 switch (Op0I->getOpcode()) {
3256 case Instruction::Xor:
3257 case Instruction::Or:
3258 // If the mask is only needed on one incoming arm, push it up.
3259 if (Op0I->hasOneUse()) {
3260 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3261 // Not masking anything out for the LHS, move to RHS.
3262 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3263 Op0RHS->getName()+".masked");
3264 InsertNewInstBefore(NewRHS, I);
3265 return BinaryOperator::create(
3266 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3268 if (!isa<Constant>(Op0RHS) &&
3269 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3270 // Not masking anything out for the RHS, move to LHS.
3271 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3272 Op0LHS->getName()+".masked");
3273 InsertNewInstBefore(NewLHS, I);
3274 return BinaryOperator::create(
3275 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3280 case Instruction::Add:
3281 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3282 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3283 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3284 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3285 return BinaryOperator::createAnd(V, AndRHS);
3286 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3287 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
3290 case Instruction::Sub:
3291 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3292 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3293 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3294 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3295 return BinaryOperator::createAnd(V, AndRHS);
3299 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3300 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3302 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3303 // If this is an integer truncation or change from signed-to-unsigned, and
3304 // if the source is an and/or with immediate, transform it. This
3305 // frequently occurs for bitfield accesses.
3306 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3307 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3308 CastOp->getNumOperands() == 2)
3309 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3310 if (CastOp->getOpcode() == Instruction::And) {
3311 // Change: and (cast (and X, C1) to T), C2
3312 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3313 // This will fold the two constants together, which may allow
3314 // other simplifications.
3315 Instruction *NewCast = CastInst::createTruncOrBitCast(
3316 CastOp->getOperand(0), I.getType(),
3317 CastOp->getName()+".shrunk");
3318 NewCast = InsertNewInstBefore(NewCast, I);
3319 // trunc_or_bitcast(C1)&C2
3320 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3321 C3 = ConstantExpr::getAnd(C3, AndRHS);
3322 return BinaryOperator::createAnd(NewCast, C3);
3323 } else if (CastOp->getOpcode() == Instruction::Or) {
3324 // Change: and (cast (or X, C1) to T), C2
3325 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3326 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3327 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3328 return ReplaceInstUsesWith(I, AndRHS);
3333 // Try to fold constant and into select arguments.
3334 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3335 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3337 if (isa<PHINode>(Op0))
3338 if (Instruction *NV = FoldOpIntoPhi(I))
3342 Value *Op0NotVal = dyn_castNotVal(Op0);
3343 Value *Op1NotVal = dyn_castNotVal(Op1);
3345 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3346 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3348 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3349 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3350 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3351 I.getName()+".demorgan");
3352 InsertNewInstBefore(Or, I);
3353 return BinaryOperator::createNot(Or);
3357 Value *A = 0, *B = 0;
3358 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
3359 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3360 return ReplaceInstUsesWith(I, Op1);
3361 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
3362 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3363 return ReplaceInstUsesWith(I, Op0);
3365 if (Op0->hasOneUse() &&
3366 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3367 if (A == Op1) { // (A^B)&A -> A&(A^B)
3368 I.swapOperands(); // Simplify below
3369 std::swap(Op0, Op1);
3370 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3371 cast<BinaryOperator>(Op0)->swapOperands();
3372 I.swapOperands(); // Simplify below
3373 std::swap(Op0, Op1);
3376 if (Op1->hasOneUse() &&
3377 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3378 if (B == Op0) { // B&(A^B) -> B&(B^A)
3379 cast<BinaryOperator>(Op1)->swapOperands();
3382 if (A == Op0) { // A&(A^B) -> A & ~B
3383 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3384 InsertNewInstBefore(NotB, I);
3385 return BinaryOperator::createAnd(A, NotB);
3390 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3391 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3392 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3395 Value *LHSVal, *RHSVal;
3396 ConstantInt *LHSCst, *RHSCst;
3397 ICmpInst::Predicate LHSCC, RHSCC;
3398 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3399 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3400 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3401 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3402 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3403 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3404 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3405 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3406 // Ensure that the larger constant is on the RHS.
3407 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3408 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3409 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3410 ICmpInst *LHS = cast<ICmpInst>(Op0);
3411 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3412 std::swap(LHS, RHS);
3413 std::swap(LHSCst, RHSCst);
3414 std::swap(LHSCC, RHSCC);
3417 // At this point, we know we have have two icmp instructions
3418 // comparing a value against two constants and and'ing the result
3419 // together. Because of the above check, we know that we only have
3420 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3421 // (from the FoldICmpLogical check above), that the two constants
3422 // are not equal and that the larger constant is on the RHS
3423 assert(LHSCst != RHSCst && "Compares not folded above?");
3426 default: assert(0 && "Unknown integer condition code!");
3427 case ICmpInst::ICMP_EQ:
3429 default: assert(0 && "Unknown integer condition code!");
3430 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3431 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3432 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3433 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3434 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3435 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3436 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3437 return ReplaceInstUsesWith(I, LHS);
3439 case ICmpInst::ICMP_NE:
3441 default: assert(0 && "Unknown integer condition code!");
3442 case ICmpInst::ICMP_ULT:
3443 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3444 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3445 break; // (X != 13 & X u< 15) -> no change
3446 case ICmpInst::ICMP_SLT:
3447 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3448 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3449 break; // (X != 13 & X s< 15) -> no change
3450 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3451 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3452 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3453 return ReplaceInstUsesWith(I, RHS);
3454 case ICmpInst::ICMP_NE:
3455 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3456 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3457 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3458 LHSVal->getName()+".off");
3459 InsertNewInstBefore(Add, I);
3460 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3461 ConstantInt::get(Add->getType(), 1));
3463 break; // (X != 13 & X != 15) -> no change
3466 case ICmpInst::ICMP_ULT:
3468 default: assert(0 && "Unknown integer condition code!");
3469 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3470 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3471 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3472 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3474 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3475 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3476 return ReplaceInstUsesWith(I, LHS);
3477 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3481 case ICmpInst::ICMP_SLT:
3483 default: assert(0 && "Unknown integer condition code!");
3484 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3485 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3486 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3487 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3489 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3490 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3491 return ReplaceInstUsesWith(I, LHS);
3492 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3496 case ICmpInst::ICMP_UGT:
3498 default: assert(0 && "Unknown integer condition code!");
3499 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3500 return ReplaceInstUsesWith(I, LHS);
3501 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3502 return ReplaceInstUsesWith(I, RHS);
3503 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3505 case ICmpInst::ICMP_NE:
3506 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3507 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3508 break; // (X u> 13 & X != 15) -> no change
3509 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3510 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3512 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3516 case ICmpInst::ICMP_SGT:
3518 default: assert(0 && "Unknown integer condition code!");
3519 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3520 return ReplaceInstUsesWith(I, LHS);
3521 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3522 return ReplaceInstUsesWith(I, RHS);
3523 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3525 case ICmpInst::ICMP_NE:
3526 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3527 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3528 break; // (X s> 13 & X != 15) -> no change
3529 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3530 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3532 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3540 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3541 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3542 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3543 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3544 const Type *SrcTy = Op0C->getOperand(0)->getType();
3545 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3546 // Only do this if the casts both really cause code to be generated.
3547 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3549 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3551 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3552 Op1C->getOperand(0),
3554 InsertNewInstBefore(NewOp, I);
3555 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3559 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3560 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3561 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3562 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
3563 SI0->getOperand(1) == SI1->getOperand(1) &&
3564 (SI0->hasOneUse() || SI1->hasOneUse())) {
3565 Instruction *NewOp =
3566 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3568 SI0->getName()), I);
3569 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3570 SI1->getOperand(1));
3574 return Changed ? &I : 0;
3577 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3578 /// in the result. If it does, and if the specified byte hasn't been filled in
3579 /// yet, fill it in and return false.
3580 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3581 Instruction *I = dyn_cast<Instruction>(V);
3582 if (I == 0) return true;
3584 // If this is an or instruction, it is an inner node of the bswap.
3585 if (I->getOpcode() == Instruction::Or)
3586 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3587 CollectBSwapParts(I->getOperand(1), ByteValues);
3589 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3590 // If this is a shift by a constant int, and it is "24", then its operand
3591 // defines a byte. We only handle unsigned types here.
3592 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3593 // Not shifting the entire input by N-1 bytes?
3594 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3595 8*(ByteValues.size()-1))
3599 if (I->getOpcode() == Instruction::Shl) {
3600 // X << 24 defines the top byte with the lowest of the input bytes.
3601 DestNo = ByteValues.size()-1;
3603 // X >>u 24 defines the low byte with the highest of the input bytes.
3607 // If the destination byte value is already defined, the values are or'd
3608 // together, which isn't a bswap (unless it's an or of the same bits).
3609 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3611 ByteValues[DestNo] = I->getOperand(0);
3615 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3617 Value *Shift = 0, *ShiftLHS = 0;
3618 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3619 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3620 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3622 Instruction *SI = cast<Instruction>(Shift);
3624 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3625 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3626 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3629 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3631 if (AndAmt->getValue().getActiveBits() > 64)
3633 uint64_t AndAmtVal = AndAmt->getZExtValue();
3634 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3635 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3637 // Unknown mask for bswap.
3638 if (DestByte == ByteValues.size()) return true;
3640 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3642 if (SI->getOpcode() == Instruction::Shl)
3643 SrcByte = DestByte - ShiftBytes;
3645 SrcByte = DestByte + ShiftBytes;
3647 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3648 if (SrcByte != ByteValues.size()-DestByte-1)
3651 // If the destination byte value is already defined, the values are or'd
3652 // together, which isn't a bswap (unless it's an or of the same bits).
3653 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3655 ByteValues[DestByte] = SI->getOperand(0);
3659 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3660 /// If so, insert the new bswap intrinsic and return it.
3661 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3662 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3663 if (!ITy || ITy->getBitWidth() % 16)
3664 return 0; // Can only bswap pairs of bytes. Can't do vectors.
3666 /// ByteValues - For each byte of the result, we keep track of which value
3667 /// defines each byte.
3668 SmallVector<Value*, 8> ByteValues;
3669 ByteValues.resize(ITy->getBitWidth()/8);
3671 // Try to find all the pieces corresponding to the bswap.
3672 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3673 CollectBSwapParts(I.getOperand(1), ByteValues))
3676 // Check to see if all of the bytes come from the same value.
3677 Value *V = ByteValues[0];
3678 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3680 // Check to make sure that all of the bytes come from the same value.
3681 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3682 if (ByteValues[i] != V)
3684 const Type *Tys[] = { ITy, ITy };
3685 Module *M = I.getParent()->getParent()->getParent();
3686 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 2);
3687 return new CallInst(F, V);
3691 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3692 bool Changed = SimplifyCommutative(I);
3693 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3695 if (isa<UndefValue>(Op1)) // X | undef -> -1
3696 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
3700 return ReplaceInstUsesWith(I, Op0);
3702 // See if we can simplify any instructions used by the instruction whose sole
3703 // purpose is to compute bits we don't care about.
3704 if (!isa<VectorType>(I.getType())) {
3705 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3706 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3707 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3708 KnownZero, KnownOne))
3713 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3714 ConstantInt *C1 = 0; Value *X = 0;
3715 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3716 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3717 Instruction *Or = BinaryOperator::createOr(X, RHS);
3718 InsertNewInstBefore(Or, I);
3720 return BinaryOperator::createAnd(Or,
3721 ConstantInt::get(RHS->getValue() | C1->getValue()));
3724 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3725 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3726 Instruction *Or = BinaryOperator::createOr(X, RHS);
3727 InsertNewInstBefore(Or, I);
3729 return BinaryOperator::createXor(Or,
3730 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3733 // Try to fold constant and into select arguments.
3734 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3735 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3737 if (isa<PHINode>(Op0))
3738 if (Instruction *NV = FoldOpIntoPhi(I))
3742 Value *A = 0, *B = 0;
3743 ConstantInt *C1 = 0, *C2 = 0;
3745 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3746 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3747 return ReplaceInstUsesWith(I, Op1);
3748 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3749 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3750 return ReplaceInstUsesWith(I, Op0);
3752 // (A | B) | C and A | (B | C) -> bswap if possible.
3753 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
3754 if (match(Op0, m_Or(m_Value(), m_Value())) ||
3755 match(Op1, m_Or(m_Value(), m_Value())) ||
3756 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3757 match(Op1, m_Shift(m_Value(), m_Value())))) {
3758 if (Instruction *BSwap = MatchBSwap(I))
3762 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3763 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3764 MaskedValueIsZero(Op1, C1->getValue())) {
3765 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3766 InsertNewInstBefore(NOr, I);
3768 return BinaryOperator::createXor(NOr, C1);
3771 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3772 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3773 MaskedValueIsZero(Op0, C1->getValue())) {
3774 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3775 InsertNewInstBefore(NOr, I);
3777 return BinaryOperator::createXor(NOr, C1);
3782 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3783 match(Op1, m_And(m_Value(B), m_Value(D)))) {
3784 Value *V1 = 0, *V2 = 0, *V3 = 0;
3785 C1 = dyn_cast<ConstantInt>(C);
3786 C2 = dyn_cast<ConstantInt>(D);
3787 if (C1 && C2) { // (A & C1)|(B & C2)
3788 // If we have: ((V + N) & C1) | (V & C2)
3789 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3790 // replace with V+N.
3791 if (C1->getValue() == ~C2->getValue()) {
3792 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3793 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3794 // Add commutes, try both ways.
3795 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3796 return ReplaceInstUsesWith(I, A);
3797 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3798 return ReplaceInstUsesWith(I, A);
3800 // Or commutes, try both ways.
3801 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3802 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3803 // Add commutes, try both ways.
3804 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3805 return ReplaceInstUsesWith(I, B);
3806 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3807 return ReplaceInstUsesWith(I, B);
3810 V1 = 0; V2 = 0; V3 = 0;
3813 // Check to see if we have any common things being and'ed. If so, find the
3814 // terms for V1 & (V2|V3).
3815 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
3816 if (A == B) // (A & C)|(A & D) == A & (C|D)
3817 V1 = A, V2 = C, V3 = D;
3818 else if (A == D) // (A & C)|(B & A) == A & (B|C)
3819 V1 = A, V2 = B, V3 = C;
3820 else if (C == B) // (A & C)|(C & D) == C & (A|D)
3821 V1 = C, V2 = A, V3 = D;
3822 else if (C == D) // (A & C)|(B & C) == C & (A|B)
3823 V1 = C, V2 = A, V3 = B;
3827 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
3828 return BinaryOperator::createAnd(V1, Or);
3831 // (V1 & V3)|(V2 & ~V3) -> ((V1 ^ V2) & V3) ^ V2
3832 if (isOnlyUse(Op0) && isOnlyUse(Op1)) {
3833 // Try all combination of terms to find V3 and ~V3.
3834 if (A->hasOneUse() && match(A, m_Not(m_Value(V3)))) {
3840 if (B->hasOneUse() && match(B, m_Not(m_Value(V3)))) {
3846 if (C->hasOneUse() && match(C, m_Not(m_Value(V3)))) {
3852 if (D->hasOneUse() && match(D, m_Not(m_Value(V3)))) {
3859 A = InsertNewInstBefore(BinaryOperator::createXor(V1, V2, "tmp"), I);
3860 A = InsertNewInstBefore(BinaryOperator::createAnd(A, V3, "tmp"), I);
3861 return BinaryOperator::createXor(A, V2);
3867 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3868 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3869 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3870 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
3871 SI0->getOperand(1) == SI1->getOperand(1) &&
3872 (SI0->hasOneUse() || SI1->hasOneUse())) {
3873 Instruction *NewOp =
3874 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3876 SI0->getName()), I);
3877 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3878 SI1->getOperand(1));
3882 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3883 if (A == Op1) // ~A | A == -1
3884 return ReplaceInstUsesWith(I,
3885 ConstantInt::getAllOnesValue(I.getType()));
3889 // Note, A is still live here!
3890 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3892 return ReplaceInstUsesWith(I,
3893 ConstantInt::getAllOnesValue(I.getType()));
3895 // (~A | ~B) == (~(A & B)) - De Morgan's Law
3896 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3897 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3898 I.getName()+".demorgan"), I);
3899 return BinaryOperator::createNot(And);
3903 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3904 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3905 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3908 Value *LHSVal, *RHSVal;
3909 ConstantInt *LHSCst, *RHSCst;
3910 ICmpInst::Predicate LHSCC, RHSCC;
3911 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3912 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3913 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3914 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3915 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3916 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3917 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3918 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3919 // Ensure that the larger constant is on the RHS.
3920 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3921 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3922 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3923 ICmpInst *LHS = cast<ICmpInst>(Op0);
3924 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3925 std::swap(LHS, RHS);
3926 std::swap(LHSCst, RHSCst);
3927 std::swap(LHSCC, RHSCC);
3930 // At this point, we know we have have two icmp instructions
3931 // comparing a value against two constants and or'ing the result
3932 // together. Because of the above check, we know that we only have
3933 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3934 // FoldICmpLogical check above), that the two constants are not
3936 assert(LHSCst != RHSCst && "Compares not folded above?");
3939 default: assert(0 && "Unknown integer condition code!");
3940 case ICmpInst::ICMP_EQ:
3942 default: assert(0 && "Unknown integer condition code!");
3943 case ICmpInst::ICMP_EQ:
3944 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3945 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3946 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3947 LHSVal->getName()+".off");
3948 InsertNewInstBefore(Add, I);
3949 AddCST = Subtract(AddOne(RHSCst), LHSCst);
3950 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
3952 break; // (X == 13 | X == 15) -> no change
3953 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3954 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
3956 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3957 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3958 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
3959 return ReplaceInstUsesWith(I, RHS);
3962 case ICmpInst::ICMP_NE:
3964 default: assert(0 && "Unknown integer condition code!");
3965 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3966 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3967 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
3968 return ReplaceInstUsesWith(I, LHS);
3969 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3970 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3971 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
3972 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3975 case ICmpInst::ICMP_ULT:
3977 default: assert(0 && "Unknown integer condition code!");
3978 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
3980 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
3981 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
3983 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
3985 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
3986 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
3987 return ReplaceInstUsesWith(I, RHS);
3988 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
3992 case ICmpInst::ICMP_SLT:
3994 default: assert(0 && "Unknown integer condition code!");
3995 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
3997 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
3998 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4000 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4002 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4003 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4004 return ReplaceInstUsesWith(I, RHS);
4005 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4009 case ICmpInst::ICMP_UGT:
4011 default: assert(0 && "Unknown integer condition code!");
4012 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4013 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4014 return ReplaceInstUsesWith(I, LHS);
4015 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4017 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4018 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4019 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4020 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4024 case ICmpInst::ICMP_SGT:
4026 default: assert(0 && "Unknown integer condition code!");
4027 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4028 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4029 return ReplaceInstUsesWith(I, LHS);
4030 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4032 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4033 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4034 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4035 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4043 // fold (or (cast A), (cast B)) -> (cast (or A, B))
4044 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4045 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4046 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4047 const Type *SrcTy = Op0C->getOperand(0)->getType();
4048 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4049 // Only do this if the casts both really cause code to be generated.
4050 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4052 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4054 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4055 Op1C->getOperand(0),
4057 InsertNewInstBefore(NewOp, I);
4058 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4063 return Changed ? &I : 0;
4066 // XorSelf - Implements: X ^ X --> 0
4069 XorSelf(Value *rhs) : RHS(rhs) {}
4070 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4071 Instruction *apply(BinaryOperator &Xor) const {
4077 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4078 bool Changed = SimplifyCommutative(I);
4079 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4081 if (isa<UndefValue>(Op1))
4082 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4084 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4085 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4086 assert(Result == &I && "AssociativeOpt didn't work?");
4087 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4090 // See if we can simplify any instructions used by the instruction whose sole
4091 // purpose is to compute bits we don't care about.
4092 if (!isa<VectorType>(I.getType())) {
4093 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4094 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4095 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4096 KnownZero, KnownOne))
4100 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4101 // xor (icmp A, B), true = not (icmp A, B) = !icmp A, B
4102 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4103 if (RHS == ConstantInt::getTrue() && ICI->hasOneUse())
4104 return new ICmpInst(ICI->getInversePredicate(),
4105 ICI->getOperand(0), ICI->getOperand(1));
4107 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4108 // ~(c-X) == X-c-1 == X+(-c-1)
4109 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4110 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4111 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4112 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4113 ConstantInt::get(I.getType(), 1));
4114 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
4117 // ~(~X & Y) --> (X | ~Y)
4118 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
4119 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4120 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4122 BinaryOperator::createNot(Op0I->getOperand(1),
4123 Op0I->getOperand(1)->getName()+".not");
4124 InsertNewInstBefore(NotY, I);
4125 return BinaryOperator::createOr(Op0NotVal, NotY);
4129 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4130 if (Op0I->getOpcode() == Instruction::Add) {
4131 // ~(X-c) --> (-c-1)-X
4132 if (RHS->isAllOnesValue()) {
4133 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4134 return BinaryOperator::createSub(
4135 ConstantExpr::getSub(NegOp0CI,
4136 ConstantInt::get(I.getType(), 1)),
4137 Op0I->getOperand(0));
4138 } else if (RHS->getValue().isSignBit()) {
4139 // (X + C) ^ signbit -> (X + C + signbit)
4140 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4141 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
4144 } else if (Op0I->getOpcode() == Instruction::Or) {
4145 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4146 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4147 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4148 // Anything in both C1 and C2 is known to be zero, remove it from
4150 Constant *CommonBits = And(Op0CI, RHS);
4151 NewRHS = ConstantExpr::getAnd(NewRHS,
4152 ConstantExpr::getNot(CommonBits));
4153 AddToWorkList(Op0I);
4154 I.setOperand(0, Op0I->getOperand(0));
4155 I.setOperand(1, NewRHS);
4161 // Try to fold constant and into select arguments.
4162 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4163 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4165 if (isa<PHINode>(Op0))
4166 if (Instruction *NV = FoldOpIntoPhi(I))
4170 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4172 return ReplaceInstUsesWith(I,
4173 ConstantInt::getAllOnesValue(I.getType()));
4175 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4177 return ReplaceInstUsesWith(I, ConstantInt::getAllOnesValue(I.getType()));
4180 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4183 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4184 if (A == Op0) { // B^(B|A) == (A|B)^B
4185 Op1I->swapOperands();
4187 std::swap(Op0, Op1);
4188 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4189 I.swapOperands(); // Simplified below.
4190 std::swap(Op0, Op1);
4192 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4193 if (Op0 == A) // A^(A^B) == B
4194 return ReplaceInstUsesWith(I, B);
4195 else if (Op0 == B) // A^(B^A) == B
4196 return ReplaceInstUsesWith(I, A);
4197 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4198 if (A == Op0) { // A^(A&B) -> A^(B&A)
4199 Op1I->swapOperands();
4202 if (B == Op0) { // A^(B&A) -> (B&A)^A
4203 I.swapOperands(); // Simplified below.
4204 std::swap(Op0, Op1);
4209 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4212 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4213 if (A == Op1) // (B|A)^B == (A|B)^B
4215 if (B == Op1) { // (A|B)^B == A & ~B
4217 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4218 return BinaryOperator::createAnd(A, NotB);
4220 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4221 if (Op1 == A) // (A^B)^A == B
4222 return ReplaceInstUsesWith(I, B);
4223 else if (Op1 == B) // (B^A)^A == B
4224 return ReplaceInstUsesWith(I, A);
4225 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4226 if (A == Op1) // (A&B)^A -> (B&A)^A
4228 if (B == Op1 && // (B&A)^A == ~B & A
4229 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
4231 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
4232 return BinaryOperator::createAnd(N, Op1);
4237 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4238 if (Op0I && Op1I && Op0I->isShift() &&
4239 Op0I->getOpcode() == Op1I->getOpcode() &&
4240 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4241 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4242 Instruction *NewOp =
4243 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4244 Op1I->getOperand(0),
4245 Op0I->getName()), I);
4246 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4247 Op1I->getOperand(1));
4251 Value *A, *B, *C, *D;
4252 // (A & B)^(A | B) -> A ^ B
4253 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4254 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4255 if ((A == C && B == D) || (A == D && B == C))
4256 return BinaryOperator::createXor(A, B);
4258 // (A | B)^(A & B) -> A ^ B
4259 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4260 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4261 if ((A == C && B == D) || (A == D && B == C))
4262 return BinaryOperator::createXor(A, B);
4266 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4267 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4268 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4269 // (X & Y)^(X & Y) -> (Y^Z) & X
4270 Value *X = 0, *Y = 0, *Z = 0;
4272 X = A, Y = B, Z = D;
4274 X = A, Y = B, Z = C;
4276 X = B, Y = A, Z = D;
4278 X = B, Y = A, Z = C;
4281 Instruction *NewOp =
4282 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4283 return BinaryOperator::createAnd(NewOp, X);
4288 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4289 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4290 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4293 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4294 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4295 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4296 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4297 const Type *SrcTy = Op0C->getOperand(0)->getType();
4298 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4299 // Only do this if the casts both really cause code to be generated.
4300 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4302 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4304 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4305 Op1C->getOperand(0),
4307 InsertNewInstBefore(NewOp, I);
4308 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4312 return Changed ? &I : 0;
4315 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4316 /// overflowed for this type.
4317 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4318 ConstantInt *In2, bool IsSigned = false) {
4319 Result = cast<ConstantInt>(Add(In1, In2));
4322 if (In2->getValue().isNegative())
4323 return Result->getValue().sgt(In1->getValue());
4325 return Result->getValue().slt(In1->getValue());
4327 return Result->getValue().ult(In1->getValue());
4330 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4331 /// code necessary to compute the offset from the base pointer (without adding
4332 /// in the base pointer). Return the result as a signed integer of intptr size.
4333 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4334 TargetData &TD = IC.getTargetData();
4335 gep_type_iterator GTI = gep_type_begin(GEP);
4336 const Type *IntPtrTy = TD.getIntPtrType();
4337 Value *Result = Constant::getNullValue(IntPtrTy);
4339 // Build a mask for high order bits.
4340 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
4342 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4343 Value *Op = GEP->getOperand(i);
4344 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
4345 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4346 if (Constant *OpC = dyn_cast<Constant>(Op)) {
4347 if (!OpC->isNullValue()) {
4348 OpC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4349 Scale = ConstantExpr::getMul(OpC, Scale);
4350 if (Constant *RC = dyn_cast<Constant>(Result))
4351 Result = ConstantExpr::getAdd(RC, Scale);
4353 // Emit an add instruction.
4354 Result = IC.InsertNewInstBefore(
4355 BinaryOperator::createAdd(Result, Scale,
4356 GEP->getName()+".offs"), I);
4360 // Convert to correct type.
4361 Op = IC.InsertNewInstBefore(CastInst::createSExtOrBitCast(Op, IntPtrTy,
4362 Op->getName()+".c"), I);
4364 // We'll let instcombine(mul) convert this to a shl if possible.
4365 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4366 GEP->getName()+".idx"), I);
4368 // Emit an add instruction.
4369 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4370 GEP->getName()+".offs"), I);
4376 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4377 /// else. At this point we know that the GEP is on the LHS of the comparison.
4378 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4379 ICmpInst::Predicate Cond,
4381 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4383 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4384 if (isa<PointerType>(CI->getOperand(0)->getType()))
4385 RHS = CI->getOperand(0);
4387 Value *PtrBase = GEPLHS->getOperand(0);
4388 if (PtrBase == RHS) {
4389 // As an optimization, we don't actually have to compute the actual value of
4390 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4391 // each index is zero or not.
4392 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4393 Instruction *InVal = 0;
4394 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4395 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4397 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4398 if (isa<UndefValue>(C)) // undef index -> undef.
4399 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4400 if (C->isNullValue())
4402 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4403 EmitIt = false; // This is indexing into a zero sized array?
4404 } else if (isa<ConstantInt>(C))
4405 return ReplaceInstUsesWith(I, // No comparison is needed here.
4406 ConstantInt::get(Type::Int1Ty,
4407 Cond == ICmpInst::ICMP_NE));
4412 new ICmpInst(Cond, GEPLHS->getOperand(i),
4413 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4417 InVal = InsertNewInstBefore(InVal, I);
4418 InsertNewInstBefore(Comp, I);
4419 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
4420 InVal = BinaryOperator::createOr(InVal, Comp);
4421 else // True if all are equal
4422 InVal = BinaryOperator::createAnd(InVal, Comp);
4430 // No comparison is needed here, all indexes = 0
4431 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4432 Cond == ICmpInst::ICMP_EQ));
4435 // Only lower this if the icmp is the only user of the GEP or if we expect
4436 // the result to fold to a constant!
4437 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4438 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4439 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4440 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4441 Constant::getNullValue(Offset->getType()));
4443 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4444 // If the base pointers are different, but the indices are the same, just
4445 // compare the base pointer.
4446 if (PtrBase != GEPRHS->getOperand(0)) {
4447 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4448 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4449 GEPRHS->getOperand(0)->getType();
4451 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4452 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4453 IndicesTheSame = false;
4457 // If all indices are the same, just compare the base pointers.
4459 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4460 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4462 // Otherwise, the base pointers are different and the indices are
4463 // different, bail out.
4467 // If one of the GEPs has all zero indices, recurse.
4468 bool AllZeros = true;
4469 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4470 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4471 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4476 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4477 ICmpInst::getSwappedPredicate(Cond), I);
4479 // If the other GEP has all zero indices, recurse.
4481 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4482 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4483 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4488 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4490 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4491 // If the GEPs only differ by one index, compare it.
4492 unsigned NumDifferences = 0; // Keep track of # differences.
4493 unsigned DiffOperand = 0; // The operand that differs.
4494 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4495 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4496 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4497 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4498 // Irreconcilable differences.
4502 if (NumDifferences++) break;
4507 if (NumDifferences == 0) // SAME GEP?
4508 return ReplaceInstUsesWith(I, // No comparison is needed here.
4509 ConstantInt::get(Type::Int1Ty,
4510 Cond == ICmpInst::ICMP_EQ));
4511 else if (NumDifferences == 1) {
4512 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4513 Value *RHSV = GEPRHS->getOperand(DiffOperand);
4514 // Make sure we do a signed comparison here.
4515 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4519 // Only lower this if the icmp is the only user of the GEP or if we expect
4520 // the result to fold to a constant!
4521 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4522 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4523 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4524 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4525 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4526 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4532 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4533 bool Changed = SimplifyCompare(I);
4534 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4536 // Fold trivial predicates.
4537 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4538 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4539 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4540 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4542 // Simplify 'fcmp pred X, X'
4544 switch (I.getPredicate()) {
4545 default: assert(0 && "Unknown predicate!");
4546 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4547 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4548 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4549 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4550 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4551 case FCmpInst::FCMP_OLT: // True if ordered and less than
4552 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4553 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4555 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4556 case FCmpInst::FCMP_ULT: // True if unordered or less than
4557 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4558 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4559 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4560 I.setPredicate(FCmpInst::FCMP_UNO);
4561 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4564 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4565 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4566 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4567 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4568 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4569 I.setPredicate(FCmpInst::FCMP_ORD);
4570 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4575 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
4576 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4578 // Handle fcmp with constant RHS
4579 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4580 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4581 switch (LHSI->getOpcode()) {
4582 case Instruction::PHI:
4583 if (Instruction *NV = FoldOpIntoPhi(I))
4586 case Instruction::Select:
4587 // If either operand of the select is a constant, we can fold the
4588 // comparison into the select arms, which will cause one to be
4589 // constant folded and the select turned into a bitwise or.
4590 Value *Op1 = 0, *Op2 = 0;
4591 if (LHSI->hasOneUse()) {
4592 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4593 // Fold the known value into the constant operand.
4594 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4595 // Insert a new FCmp of the other select operand.
4596 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4597 LHSI->getOperand(2), RHSC,
4599 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4600 // Fold the known value into the constant operand.
4601 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4602 // Insert a new FCmp of the other select operand.
4603 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4604 LHSI->getOperand(1), RHSC,
4610 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4615 return Changed ? &I : 0;
4618 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4619 bool Changed = SimplifyCompare(I);
4620 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4621 const Type *Ty = Op0->getType();
4625 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4626 isTrueWhenEqual(I)));
4628 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
4629 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4631 // icmp of GlobalValues can never equal each other as long as they aren't
4632 // external weak linkage type.
4633 if (GlobalValue *GV0 = dyn_cast<GlobalValue>(Op0))
4634 if (GlobalValue *GV1 = dyn_cast<GlobalValue>(Op1))
4635 if (!GV0->hasExternalWeakLinkage() || !GV1->hasExternalWeakLinkage())
4636 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4637 !isTrueWhenEqual(I)));
4639 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4640 // addresses never equal each other! We already know that Op0 != Op1.
4641 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4642 isa<ConstantPointerNull>(Op0)) &&
4643 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4644 isa<ConstantPointerNull>(Op1)))
4645 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4646 !isTrueWhenEqual(I)));
4648 // icmp's with boolean values can always be turned into bitwise operations
4649 if (Ty == Type::Int1Ty) {
4650 switch (I.getPredicate()) {
4651 default: assert(0 && "Invalid icmp instruction!");
4652 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
4653 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4654 InsertNewInstBefore(Xor, I);
4655 return BinaryOperator::createNot(Xor);
4657 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
4658 return BinaryOperator::createXor(Op0, Op1);
4660 case ICmpInst::ICMP_UGT:
4661 case ICmpInst::ICMP_SGT:
4662 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
4664 case ICmpInst::ICMP_ULT:
4665 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
4666 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4667 InsertNewInstBefore(Not, I);
4668 return BinaryOperator::createAnd(Not, Op1);
4670 case ICmpInst::ICMP_UGE:
4671 case ICmpInst::ICMP_SGE:
4672 std::swap(Op0, Op1); // Change icmp ge -> icmp le
4674 case ICmpInst::ICMP_ULE:
4675 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
4676 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4677 InsertNewInstBefore(Not, I);
4678 return BinaryOperator::createOr(Not, Op1);
4683 // See if we are doing a comparison between a constant and an instruction that
4684 // can be folded into the comparison.
4685 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4686 switch (I.getPredicate()) {
4688 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4689 if (CI->isMinValue(false))
4690 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4691 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4692 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4693 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4694 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4695 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
4696 if (CI->isMinValue(true))
4697 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4698 ConstantInt::getAllOnesValue(Op0->getType()));
4702 case ICmpInst::ICMP_SLT:
4703 if (CI->isMinValue(true)) // A <s MIN -> FALSE
4704 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4705 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4706 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4707 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4708 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4711 case ICmpInst::ICMP_UGT:
4712 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
4713 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4714 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4715 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4716 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4717 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4719 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
4720 if (CI->isMaxValue(true))
4721 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4722 ConstantInt::getNullValue(Op0->getType()));
4725 case ICmpInst::ICMP_SGT:
4726 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
4727 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4728 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4729 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4730 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4731 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4734 case ICmpInst::ICMP_ULE:
4735 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
4736 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4737 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4738 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4739 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4740 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4743 case ICmpInst::ICMP_SLE:
4744 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
4745 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4746 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4747 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4748 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4749 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4752 case ICmpInst::ICMP_UGE:
4753 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
4754 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4755 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4756 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4757 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4758 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4761 case ICmpInst::ICMP_SGE:
4762 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
4763 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4764 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4765 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4766 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4767 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4771 // If we still have a icmp le or icmp ge instruction, turn it into the
4772 // appropriate icmp lt or icmp gt instruction. Since the border cases have
4773 // already been handled above, this requires little checking.
4775 switch (I.getPredicate()) {
4777 case ICmpInst::ICMP_ULE:
4778 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4779 case ICmpInst::ICMP_SLE:
4780 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4781 case ICmpInst::ICMP_UGE:
4782 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4783 case ICmpInst::ICMP_SGE:
4784 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4787 // See if we can fold the comparison based on bits known to be zero or one
4789 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4790 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4791 if (SimplifyDemandedBits(Op0, APInt::getAllOnesValue(BitWidth),
4792 KnownZero, KnownOne, 0))
4795 // Given the known and unknown bits, compute a range that the LHS could be
4797 if ((KnownOne | KnownZero) != 0) {
4798 // Compute the Min, Max and RHS values based on the known bits. For the
4799 // EQ and NE we use unsigned values.
4800 APInt Min(BitWidth, 0), Max(BitWidth, 0);
4801 const APInt& RHSVal = CI->getValue();
4802 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4803 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4806 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4809 switch (I.getPredicate()) { // LE/GE have been folded already.
4810 default: assert(0 && "Unknown icmp opcode!");
4811 case ICmpInst::ICMP_EQ:
4812 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
4813 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4815 case ICmpInst::ICMP_NE:
4816 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
4817 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4819 case ICmpInst::ICMP_ULT:
4820 if (Max.ult(RHSVal))
4821 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4822 if (Min.uge(RHSVal))
4823 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4825 case ICmpInst::ICMP_UGT:
4826 if (Min.ugt(RHSVal))
4827 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4828 if (Max.ule(RHSVal))
4829 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4831 case ICmpInst::ICMP_SLT:
4832 if (Max.slt(RHSVal))
4833 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4834 if (Min.sgt(RHSVal))
4835 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4837 case ICmpInst::ICMP_SGT:
4838 if (Min.sgt(RHSVal))
4839 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4840 if (Max.sle(RHSVal))
4841 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4846 // Since the RHS is a ConstantInt (CI), if the left hand side is an
4847 // instruction, see if that instruction also has constants so that the
4848 // instruction can be folded into the icmp
4849 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4850 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
4854 // Handle icmp with constant (but not simple integer constant) RHS
4855 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4856 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4857 switch (LHSI->getOpcode()) {
4858 case Instruction::GetElementPtr:
4859 if (RHSC->isNullValue()) {
4860 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
4861 bool isAllZeros = true;
4862 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4863 if (!isa<Constant>(LHSI->getOperand(i)) ||
4864 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4869 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
4870 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4874 case Instruction::PHI:
4875 if (Instruction *NV = FoldOpIntoPhi(I))
4878 case Instruction::Select: {
4879 // If either operand of the select is a constant, we can fold the
4880 // comparison into the select arms, which will cause one to be
4881 // constant folded and the select turned into a bitwise or.
4882 Value *Op1 = 0, *Op2 = 0;
4883 if (LHSI->hasOneUse()) {
4884 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4885 // Fold the known value into the constant operand.
4886 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
4887 // Insert a new ICmp of the other select operand.
4888 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
4889 LHSI->getOperand(2), RHSC,
4891 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4892 // Fold the known value into the constant operand.
4893 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
4894 // Insert a new ICmp of the other select operand.
4895 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
4896 LHSI->getOperand(1), RHSC,
4902 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4905 case Instruction::Malloc:
4906 // If we have (malloc != null), and if the malloc has a single use, we
4907 // can assume it is successful and remove the malloc.
4908 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
4909 AddToWorkList(LHSI);
4910 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4911 !isTrueWhenEqual(I)));
4917 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
4918 if (User *GEP = dyn_castGetElementPtr(Op0))
4919 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
4921 if (User *GEP = dyn_castGetElementPtr(Op1))
4922 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
4923 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
4926 // Test to see if the operands of the icmp are casted versions of other
4927 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
4929 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
4930 if (isa<PointerType>(Op0->getType()) &&
4931 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
4932 // We keep moving the cast from the left operand over to the right
4933 // operand, where it can often be eliminated completely.
4934 Op0 = CI->getOperand(0);
4936 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
4937 // so eliminate it as well.
4938 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
4939 Op1 = CI2->getOperand(0);
4941 // If Op1 is a constant, we can fold the cast into the constant.
4942 if (Op0->getType() != Op1->getType())
4943 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
4944 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
4946 // Otherwise, cast the RHS right before the icmp
4947 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
4949 return new ICmpInst(I.getPredicate(), Op0, Op1);
4953 if (isa<CastInst>(Op0)) {
4954 // Handle the special case of: icmp (cast bool to X), <cst>
4955 // This comes up when you have code like
4958 // For generality, we handle any zero-extension of any operand comparison
4959 // with a constant or another cast from the same type.
4960 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
4961 if (Instruction *R = visitICmpInstWithCastAndCast(I))
4965 if (I.isEquality()) {
4966 Value *A, *B, *C, *D;
4967 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4968 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
4969 Value *OtherVal = A == Op1 ? B : A;
4970 return new ICmpInst(I.getPredicate(), OtherVal,
4971 Constant::getNullValue(A->getType()));
4974 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
4975 // A^c1 == C^c2 --> A == C^(c1^c2)
4976 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
4977 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
4978 if (Op1->hasOneUse()) {
4979 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
4980 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
4981 return new ICmpInst(I.getPredicate(), A,
4982 InsertNewInstBefore(Xor, I));
4985 // A^B == A^D -> B == D
4986 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
4987 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
4988 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
4989 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
4993 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
4994 (A == Op0 || B == Op0)) {
4995 // A == (A^B) -> B == 0
4996 Value *OtherVal = A == Op0 ? B : A;
4997 return new ICmpInst(I.getPredicate(), OtherVal,
4998 Constant::getNullValue(A->getType()));
5000 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5001 // (A-B) == A -> B == 0
5002 return new ICmpInst(I.getPredicate(), B,
5003 Constant::getNullValue(B->getType()));
5005 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5006 // A == (A-B) -> B == 0
5007 return new ICmpInst(I.getPredicate(), B,
5008 Constant::getNullValue(B->getType()));
5011 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5012 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5013 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5014 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5015 Value *X = 0, *Y = 0, *Z = 0;
5018 X = B; Y = D; Z = A;
5019 } else if (A == D) {
5020 X = B; Y = C; Z = A;
5021 } else if (B == C) {
5022 X = A; Y = D; Z = B;
5023 } else if (B == D) {
5024 X = A; Y = C; Z = B;
5027 if (X) { // Build (X^Y) & Z
5028 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5029 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5030 I.setOperand(0, Op1);
5031 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5036 return Changed ? &I : 0;
5039 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5041 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5044 const APInt &RHSV = RHS->getValue();
5046 switch (LHSI->getOpcode()) {
5047 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
5048 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5049 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5051 if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5052 ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5053 Value *CompareVal = LHSI->getOperand(0);
5055 // If the sign bit of the XorCST is not set, there is no change to
5056 // the operation, just stop using the Xor.
5057 if (!XorCST->getValue().isNegative()) {
5058 ICI.setOperand(0, CompareVal);
5059 AddToWorkList(LHSI);
5063 // Was the old condition true if the operand is positive?
5064 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5066 // If so, the new one isn't.
5067 isTrueIfPositive ^= true;
5069 if (isTrueIfPositive)
5070 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5072 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5076 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5077 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5078 LHSI->getOperand(0)->hasOneUse()) {
5079 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5081 // If the LHS is an AND of a truncating cast, we can widen the
5082 // and/compare to be the input width without changing the value
5083 // produced, eliminating a cast.
5084 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5085 // We can do this transformation if either the AND constant does not
5086 // have its sign bit set or if it is an equality comparison.
5087 // Extending a relational comparison when we're checking the sign
5088 // bit would not work.
5089 if (Cast->hasOneUse() &&
5090 (ICI.isEquality() || AndCST->getValue().isPositive() &&
5091 RHSV.isPositive())) {
5093 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5094 APInt NewCST = AndCST->getValue();
5095 NewCST.zext(BitWidth);
5097 NewCI.zext(BitWidth);
5098 Instruction *NewAnd =
5099 BinaryOperator::createAnd(Cast->getOperand(0),
5100 ConstantInt::get(NewCST),LHSI->getName());
5101 InsertNewInstBefore(NewAnd, ICI);
5102 return new ICmpInst(ICI.getPredicate(), NewAnd,
5103 ConstantInt::get(NewCI));
5107 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5108 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5109 // happens a LOT in code produced by the C front-end, for bitfield
5111 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5112 if (Shift && !Shift->isShift())
5116 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5117 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5118 const Type *AndTy = AndCST->getType(); // Type of the and.
5120 // We can fold this as long as we can't shift unknown bits
5121 // into the mask. This can only happen with signed shift
5122 // rights, as they sign-extend.
5124 bool CanFold = Shift->isLogicalShift();
5126 // To test for the bad case of the signed shr, see if any
5127 // of the bits shifted in could be tested after the mask.
5128 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5129 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5131 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5132 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5133 AndCST->getValue()) == 0)
5139 if (Shift->getOpcode() == Instruction::Shl)
5140 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5142 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5144 // Check to see if we are shifting out any of the bits being
5146 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5147 // If we shifted bits out, the fold is not going to work out.
5148 // As a special case, check to see if this means that the
5149 // result is always true or false now.
5150 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5151 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5152 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5153 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5155 ICI.setOperand(1, NewCst);
5156 Constant *NewAndCST;
5157 if (Shift->getOpcode() == Instruction::Shl)
5158 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5160 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5161 LHSI->setOperand(1, NewAndCST);
5162 LHSI->setOperand(0, Shift->getOperand(0));
5163 AddToWorkList(Shift); // Shift is dead.
5164 AddUsesToWorkList(ICI);
5170 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5171 // preferable because it allows the C<<Y expression to be hoisted out
5172 // of a loop if Y is invariant and X is not.
5173 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5174 ICI.isEquality() && !Shift->isArithmeticShift() &&
5175 isa<Instruction>(Shift->getOperand(0))) {
5178 if (Shift->getOpcode() == Instruction::LShr) {
5179 NS = BinaryOperator::createShl(AndCST,
5180 Shift->getOperand(1), "tmp");
5182 // Insert a logical shift.
5183 NS = BinaryOperator::createLShr(AndCST,
5184 Shift->getOperand(1), "tmp");
5186 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5188 // Compute X & (C << Y).
5189 Instruction *NewAnd =
5190 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5191 InsertNewInstBefore(NewAnd, ICI);
5193 ICI.setOperand(0, NewAnd);
5199 case Instruction::Shl: // (icmp pred (shl X, ShAmt), CI)
5200 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5201 if (ICI.isEquality()) {
5202 uint32_t TypeBits = RHSV.getBitWidth();
5204 // Check that the shift amount is in range. If not, don't perform
5205 // undefined shifts. When the shift is visited it will be
5207 if (ShAmt->uge(TypeBits))
5210 // If we are comparing against bits always shifted out, the
5211 // comparison cannot succeed.
5213 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5214 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5215 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5216 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5217 return ReplaceInstUsesWith(ICI, Cst);
5220 if (LHSI->hasOneUse()) {
5221 // Otherwise strength reduce the shift into an and.
5222 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5224 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5227 BinaryOperator::createAnd(LHSI->getOperand(0),
5228 Mask, LHSI->getName()+".mask");
5229 Value *And = InsertNewInstBefore(AndI, ICI);
5230 return new ICmpInst(ICI.getPredicate(), And,
5231 ConstantInt::get(RHSV.lshr(ShAmtVal)));
5237 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
5238 case Instruction::AShr:
5239 if (ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5240 if (ICI.isEquality()) {
5241 // Check that the shift amount is in range. If not, don't perform
5242 // undefined shifts. When the shift is visited it will be
5244 uint32_t TypeBits = RHSV.getBitWidth();
5245 if (ShAmt->uge(TypeBits))
5247 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5249 // If we are comparing against bits always shifted out, the
5250 // comparison cannot succeed.
5251 APInt Comp = RHSV << ShAmtVal;
5252 if (LHSI->getOpcode() == Instruction::LShr)
5253 Comp = Comp.lshr(ShAmtVal);
5255 Comp = Comp.ashr(ShAmtVal);
5257 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5258 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5259 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5260 return ReplaceInstUsesWith(ICI, Cst);
5263 if (LHSI->hasOneUse() || RHSV == 0) {
5264 // Otherwise strength reduce the shift into an and.
5265 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5266 Constant *Mask = ConstantInt::get(Val);
5269 BinaryOperator::createAnd(LHSI->getOperand(0),
5270 Mask, LHSI->getName()+".mask");
5271 Value *And = InsertNewInstBefore(AndI, ICI);
5272 return new ICmpInst(ICI.getPredicate(), And,
5273 ConstantExpr::getShl(RHS, ShAmt));
5279 case Instruction::SDiv:
5280 case Instruction::UDiv:
5281 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5282 // Fold this div into the comparison, producing a range check.
5283 // Determine, based on the divide type, what the range is being
5284 // checked. If there is an overflow on the low or high side, remember
5285 // it, otherwise compute the range [low, hi) bounding the new value.
5286 // See: InsertRangeTest above for the kinds of replacements possible.
5287 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5288 // FIXME: If the operand types don't match the type of the divide
5289 // then don't attempt this transform. The code below doesn't have the
5290 // logic to deal with a signed divide and an unsigned compare (and
5291 // vice versa). This is because (x /s C1) <s C2 produces different
5292 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5293 // (x /u C1) <u C2. Simply casting the operands and result won't
5294 // work. :( The if statement below tests that condition and bails
5296 bool DivIsSigned = LHSI->getOpcode() == Instruction::SDiv;
5297 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5299 if (DivRHS->isZero())
5300 break; // Don't hack on div by zero
5302 // Initialize the variables that will indicate the nature of the
5304 bool LoOverflow = false, HiOverflow = false;
5305 ConstantInt *LoBound = 0, *HiBound = 0;
5307 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5308 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5309 // C2 (CI). By solving for X we can turn this into a range check
5310 // instead of computing a divide.
5311 ConstantInt *Prod = Multiply(RHS, DivRHS);
5313 // Determine if the product overflows by seeing if the product is
5314 // not equal to the divide. Make sure we do the same kind of divide
5315 // as in the LHS instruction that we're folding.
5316 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5317 ConstantExpr::getUDiv(Prod, DivRHS)) != RHS;
5319 // Get the ICmp opcode
5320 ICmpInst::Predicate predicate = ICI.getPredicate();
5322 if (!DivIsSigned) { // udiv
5324 LoOverflow = ProdOV;
5325 HiOverflow = ProdOV ||
5326 AddWithOverflow(HiBound, LoBound, DivRHS, false);
5327 } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
5328 if (RHSV == 0) { // (X / pos) op 0
5330 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5332 } else if (RHSV.isPositive()) { // (X / pos) op pos
5334 LoOverflow = ProdOV;
5335 HiOverflow = ProdOV ||
5336 AddWithOverflow(HiBound, Prod, DivRHS, true);
5337 } else { // (X / pos) op neg
5338 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5339 LoOverflow = AddWithOverflow(LoBound, Prod,
5340 cast<ConstantInt>(DivRHSH), true);
5341 HiBound = AddOne(Prod);
5342 HiOverflow = ProdOV;
5344 } else { // Divisor is < 0.
5345 if (RHSV == 0) { // (X / neg) op 0
5346 LoBound = AddOne(DivRHS);
5347 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5348 if (HiBound == DivRHS)
5349 LoBound = 0; // - INTMIN = INTMIN
5350 } else if (RHSV.isPositive()) { // (X / neg) op pos
5351 HiOverflow = LoOverflow = ProdOV;
5353 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS),
5355 HiBound = AddOne(Prod);
5356 } else { // (X / neg) op neg
5358 LoOverflow = HiOverflow = ProdOV;
5359 HiBound = Subtract(Prod, DivRHS);
5362 // Dividing by a negate swaps the condition.
5363 predicate = ICmpInst::getSwappedPredicate(predicate);
5367 Value *X = LHSI->getOperand(0);
5368 switch (predicate) {
5369 default: assert(0 && "Unhandled icmp opcode!");
5370 case ICmpInst::ICMP_EQ:
5371 if (LoOverflow && HiOverflow)
5372 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5373 else if (HiOverflow)
5374 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5375 ICmpInst::ICMP_UGE, X, LoBound);
5376 else if (LoOverflow)
5377 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5378 ICmpInst::ICMP_ULT, X, HiBound);
5380 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5382 case ICmpInst::ICMP_NE:
5383 if (LoOverflow && HiOverflow)
5384 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5385 else if (HiOverflow)
5386 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5387 ICmpInst::ICMP_ULT, X, LoBound);
5388 else if (LoOverflow)
5389 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5390 ICmpInst::ICMP_UGE, X, HiBound);
5392 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned,
5394 case ICmpInst::ICMP_ULT:
5395 case ICmpInst::ICMP_SLT:
5397 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5398 return new ICmpInst(predicate, X, LoBound);
5399 case ICmpInst::ICMP_UGT:
5400 case ICmpInst::ICMP_SGT:
5402 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5403 if (predicate == ICmpInst::ICMP_UGT)
5404 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5406 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5413 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5414 if (ICI.isEquality()) {
5415 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5417 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5418 // the second operand is a constant, simplify a bit.
5419 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5420 switch (BO->getOpcode()) {
5421 case Instruction::SRem:
5422 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5423 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5424 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5425 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5426 Instruction *NewRem =
5427 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5429 InsertNewInstBefore(NewRem, ICI);
5430 return new ICmpInst(ICI.getPredicate(), NewRem,
5431 Constant::getNullValue(BO->getType()));
5435 case Instruction::Add:
5436 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5437 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5438 if (BO->hasOneUse())
5439 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5440 Subtract(RHS, BOp1C));
5441 } else if (RHSV == 0) {
5442 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5443 // efficiently invertible, or if the add has just this one use.
5444 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5446 if (Value *NegVal = dyn_castNegVal(BOp1))
5447 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5448 else if (Value *NegVal = dyn_castNegVal(BOp0))
5449 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5450 else if (BO->hasOneUse()) {
5451 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5452 InsertNewInstBefore(Neg, ICI);
5454 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5458 case Instruction::Xor:
5459 // For the xor case, we can xor two constants together, eliminating
5460 // the explicit xor.
5461 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5462 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5463 ConstantExpr::getXor(RHS, BOC));
5466 case Instruction::Sub:
5467 // Replace (([sub|xor] A, B) != 0) with (A != B)
5469 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5473 case Instruction::Or:
5474 // If bits are being or'd in that are not present in the constant we
5475 // are comparing against, then the comparison could never succeed!
5476 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5477 Constant *NotCI = ConstantExpr::getNot(RHS);
5478 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5479 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5484 case Instruction::And:
5485 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5486 // If bits are being compared against that are and'd out, then the
5487 // comparison can never succeed!
5488 if ((RHSV & ~BOC->getValue()) != 0)
5489 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5492 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5493 if (RHS == BOC && RHSV.isPowerOf2())
5494 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5495 ICmpInst::ICMP_NE, LHSI,
5496 Constant::getNullValue(RHS->getType()));
5498 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5499 if (isSignBit(BOC)) {
5500 Value *X = BO->getOperand(0);
5501 Constant *Zero = Constant::getNullValue(X->getType());
5502 ICmpInst::Predicate pred = isICMP_NE ?
5503 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5504 return new ICmpInst(pred, X, Zero);
5507 // ((X & ~7) == 0) --> X < 8
5508 if (RHSV == 0 && isHighOnes(BOC)) {
5509 Value *X = BO->getOperand(0);
5510 Constant *NegX = ConstantExpr::getNeg(BOC);
5511 ICmpInst::Predicate pred = isICMP_NE ?
5512 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5513 return new ICmpInst(pred, X, NegX);
5518 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5519 // Handle icmp {eq|ne} <intrinsic>, intcst.
5520 if (II->getIntrinsicID() == Intrinsic::bswap) {
5522 ICI.setOperand(0, II->getOperand(1));
5523 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5527 } else { // Not a ICMP_EQ/ICMP_NE
5528 // If the LHS is a cast from an integral value of the same size,
5529 // then since we know the RHS is a constant, try to simlify.
5530 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5531 Value *CastOp = Cast->getOperand(0);
5532 const Type *SrcTy = CastOp->getType();
5533 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5534 if (SrcTy->isInteger() &&
5535 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5536 // If this is an unsigned comparison, try to make the comparison use
5537 // smaller constant values.
5538 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5539 // X u< 128 => X s> -1
5540 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5541 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5542 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5543 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5544 // X u> 127 => X s< 0
5545 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5546 Constant::getNullValue(SrcTy));
5554 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5555 /// We only handle extending casts so far.
5557 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5558 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5559 Value *LHSCIOp = LHSCI->getOperand(0);
5560 const Type *SrcTy = LHSCIOp->getType();
5561 const Type *DestTy = LHSCI->getType();
5564 // We only handle extension cast instructions, so far. Enforce this.
5565 if (LHSCI->getOpcode() != Instruction::ZExt &&
5566 LHSCI->getOpcode() != Instruction::SExt)
5569 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5570 bool isSignedCmp = ICI.isSignedPredicate();
5572 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5573 // Not an extension from the same type?
5574 RHSCIOp = CI->getOperand(0);
5575 if (RHSCIOp->getType() != LHSCIOp->getType())
5578 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5579 // and the other is a zext), then we can't handle this.
5580 if (CI->getOpcode() != LHSCI->getOpcode())
5583 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5584 // then we can't handle this.
5585 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5588 // Okay, just insert a compare of the reduced operands now!
5589 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5592 // If we aren't dealing with a constant on the RHS, exit early
5593 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5597 // Compute the constant that would happen if we truncated to SrcTy then
5598 // reextended to DestTy.
5599 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5600 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5602 // If the re-extended constant didn't change...
5604 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5605 // For example, we might have:
5606 // %A = sext short %X to uint
5607 // %B = icmp ugt uint %A, 1330
5608 // It is incorrect to transform this into
5609 // %B = icmp ugt short %X, 1330
5610 // because %A may have negative value.
5612 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5613 // OR operation is EQ/NE.
5614 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5615 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5620 // The re-extended constant changed so the constant cannot be represented
5621 // in the shorter type. Consequently, we cannot emit a simple comparison.
5623 // First, handle some easy cases. We know the result cannot be equal at this
5624 // point so handle the ICI.isEquality() cases
5625 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5626 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5627 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5628 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5630 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5631 // should have been folded away previously and not enter in here.
5634 // We're performing a signed comparison.
5635 if (cast<ConstantInt>(CI)->getValue().isNegative())
5636 Result = ConstantInt::getFalse(); // X < (small) --> false
5638 Result = ConstantInt::getTrue(); // X < (large) --> true
5640 // We're performing an unsigned comparison.
5642 // We're performing an unsigned comp with a sign extended value.
5643 // This is true if the input is >= 0. [aka >s -1]
5644 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5645 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5646 NegOne, ICI.getName()), ICI);
5648 // Unsigned extend & unsigned compare -> always true.
5649 Result = ConstantInt::getTrue();
5653 // Finally, return the value computed.
5654 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5655 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5656 return ReplaceInstUsesWith(ICI, Result);
5658 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5659 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5660 "ICmp should be folded!");
5661 if (Constant *CI = dyn_cast<Constant>(Result))
5662 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5664 return BinaryOperator::createNot(Result);
5668 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5669 return commonShiftTransforms(I);
5672 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5673 return commonShiftTransforms(I);
5676 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5677 return commonShiftTransforms(I);
5680 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5681 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
5682 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5684 // shl X, 0 == X and shr X, 0 == X
5685 // shl 0, X == 0 and shr 0, X == 0
5686 if (Op1 == Constant::getNullValue(Op1->getType()) ||
5687 Op0 == Constant::getNullValue(Op0->getType()))
5688 return ReplaceInstUsesWith(I, Op0);
5690 if (isa<UndefValue>(Op0)) {
5691 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
5692 return ReplaceInstUsesWith(I, Op0);
5693 else // undef << X -> 0, undef >>u X -> 0
5694 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5696 if (isa<UndefValue>(Op1)) {
5697 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5698 return ReplaceInstUsesWith(I, Op0);
5699 else // X << undef, X >>u undef -> 0
5700 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5703 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5704 if (I.getOpcode() == Instruction::AShr)
5705 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5706 if (CSI->isAllOnesValue())
5707 return ReplaceInstUsesWith(I, CSI);
5709 // Try to fold constant and into select arguments.
5710 if (isa<Constant>(Op0))
5711 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5712 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5715 // See if we can turn a signed shr into an unsigned shr.
5716 if (I.isArithmeticShift()) {
5717 if (MaskedValueIsZero(Op0,
5718 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()))) {
5719 return BinaryOperator::createLShr(Op0, Op1, I.getName());
5723 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5724 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5729 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5730 BinaryOperator &I) {
5731 bool isLeftShift = I.getOpcode() == Instruction::Shl;
5733 // See if we can simplify any instructions used by the instruction whose sole
5734 // purpose is to compute bits we don't care about.
5735 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5736 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5737 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
5738 KnownZero, KnownOne))
5741 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5742 // of a signed value.
5744 if (Op1->uge(TypeBits)) {
5745 if (I.getOpcode() != Instruction::AShr)
5746 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5748 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
5753 // ((X*C1) << C2) == (X * (C1 << C2))
5754 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5755 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5756 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5757 return BinaryOperator::createMul(BO->getOperand(0),
5758 ConstantExpr::getShl(BOOp, Op1));
5760 // Try to fold constant and into select arguments.
5761 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5762 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5764 if (isa<PHINode>(Op0))
5765 if (Instruction *NV = FoldOpIntoPhi(I))
5768 if (Op0->hasOneUse()) {
5769 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5770 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5773 switch (Op0BO->getOpcode()) {
5775 case Instruction::Add:
5776 case Instruction::And:
5777 case Instruction::Or:
5778 case Instruction::Xor: {
5779 // These operators commute.
5780 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
5781 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5782 match(Op0BO->getOperand(1),
5783 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5784 Instruction *YS = BinaryOperator::createShl(
5785 Op0BO->getOperand(0), Op1,
5787 InsertNewInstBefore(YS, I); // (Y << C)
5789 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5790 Op0BO->getOperand(1)->getName());
5791 InsertNewInstBefore(X, I); // (X + (Y << C))
5792 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
5793 return BinaryOperator::createAnd(X, ConstantInt::get(
5794 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
5797 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5798 Value *Op0BOOp1 = Op0BO->getOperand(1);
5799 if (isLeftShift && Op0BOOp1->hasOneUse() &&
5801 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
5802 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
5804 Instruction *YS = BinaryOperator::createShl(
5805 Op0BO->getOperand(0), Op1,
5807 InsertNewInstBefore(YS, I); // (Y << C)
5809 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5810 V1->getName()+".mask");
5811 InsertNewInstBefore(XM, I); // X & (CC << C)
5813 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5818 case Instruction::Sub: {
5819 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5820 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5821 match(Op0BO->getOperand(0),
5822 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5823 Instruction *YS = BinaryOperator::createShl(
5824 Op0BO->getOperand(1), Op1,
5826 InsertNewInstBefore(YS, I); // (Y << C)
5828 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5829 Op0BO->getOperand(0)->getName());
5830 InsertNewInstBefore(X, I); // (X + (Y << C))
5831 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
5832 return BinaryOperator::createAnd(X, ConstantInt::get(
5833 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
5836 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
5837 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5838 match(Op0BO->getOperand(0),
5839 m_And(m_Shr(m_Value(V1), m_Value(V2)),
5840 m_ConstantInt(CC))) && V2 == Op1 &&
5841 cast<BinaryOperator>(Op0BO->getOperand(0))
5842 ->getOperand(0)->hasOneUse()) {
5843 Instruction *YS = BinaryOperator::createShl(
5844 Op0BO->getOperand(1), Op1,
5846 InsertNewInstBefore(YS, I); // (Y << C)
5848 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5849 V1->getName()+".mask");
5850 InsertNewInstBefore(XM, I); // X & (CC << C)
5852 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5860 // If the operand is an bitwise operator with a constant RHS, and the
5861 // shift is the only use, we can pull it out of the shift.
5862 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5863 bool isValid = true; // Valid only for And, Or, Xor
5864 bool highBitSet = false; // Transform if high bit of constant set?
5866 switch (Op0BO->getOpcode()) {
5867 default: isValid = false; break; // Do not perform transform!
5868 case Instruction::Add:
5869 isValid = isLeftShift;
5871 case Instruction::Or:
5872 case Instruction::Xor:
5875 case Instruction::And:
5880 // If this is a signed shift right, and the high bit is modified
5881 // by the logical operation, do not perform the transformation.
5882 // The highBitSet boolean indicates the value of the high bit of
5883 // the constant which would cause it to be modified for this
5886 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
5887 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
5891 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
5893 Instruction *NewShift =
5894 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
5895 InsertNewInstBefore(NewShift, I);
5896 NewShift->takeName(Op0BO);
5898 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
5905 // Find out if this is a shift of a shift by a constant.
5906 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
5907 if (ShiftOp && !ShiftOp->isShift())
5910 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
5911 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
5912 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
5913 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
5914 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
5915 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
5916 Value *X = ShiftOp->getOperand(0);
5918 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
5919 if (AmtSum > TypeBits)
5922 const IntegerType *Ty = cast<IntegerType>(I.getType());
5924 // Check for (X << c1) << c2 and (X >> c1) >> c2
5925 if (I.getOpcode() == ShiftOp->getOpcode()) {
5926 return BinaryOperator::create(I.getOpcode(), X,
5927 ConstantInt::get(Ty, AmtSum));
5928 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
5929 I.getOpcode() == Instruction::AShr) {
5930 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
5931 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
5932 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
5933 I.getOpcode() == Instruction::LShr) {
5934 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
5935 Instruction *Shift =
5936 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
5937 InsertNewInstBefore(Shift, I);
5939 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
5940 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
5943 // Okay, if we get here, one shift must be left, and the other shift must be
5944 // right. See if the amounts are equal.
5945 if (ShiftAmt1 == ShiftAmt2) {
5946 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
5947 if (I.getOpcode() == Instruction::Shl) {
5948 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
5949 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
5951 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
5952 if (I.getOpcode() == Instruction::LShr) {
5953 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
5954 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
5956 // We can simplify ((X << C) >>s C) into a trunc + sext.
5957 // NOTE: we could do this for any C, but that would make 'unusual' integer
5958 // types. For now, just stick to ones well-supported by the code
5960 const Type *SExtType = 0;
5961 switch (Ty->getBitWidth() - ShiftAmt1) {
5968 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
5973 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
5974 InsertNewInstBefore(NewTrunc, I);
5975 return new SExtInst(NewTrunc, Ty);
5977 // Otherwise, we can't handle it yet.
5978 } else if (ShiftAmt1 < ShiftAmt2) {
5979 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
5981 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
5982 if (I.getOpcode() == Instruction::Shl) {
5983 assert(ShiftOp->getOpcode() == Instruction::LShr ||
5984 ShiftOp->getOpcode() == Instruction::AShr);
5985 Instruction *Shift =
5986 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
5987 InsertNewInstBefore(Shift, I);
5989 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
5990 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
5993 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
5994 if (I.getOpcode() == Instruction::LShr) {
5995 assert(ShiftOp->getOpcode() == Instruction::Shl);
5996 Instruction *Shift =
5997 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
5998 InsertNewInstBefore(Shift, I);
6000 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6001 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6004 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6006 assert(ShiftAmt2 < ShiftAmt1);
6007 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6009 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6010 if (I.getOpcode() == Instruction::Shl) {
6011 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6012 ShiftOp->getOpcode() == Instruction::AShr);
6013 Instruction *Shift =
6014 BinaryOperator::create(ShiftOp->getOpcode(), X,
6015 ConstantInt::get(Ty, ShiftDiff));
6016 InsertNewInstBefore(Shift, I);
6018 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6019 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6022 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
6023 if (I.getOpcode() == Instruction::LShr) {
6024 assert(ShiftOp->getOpcode() == Instruction::Shl);
6025 Instruction *Shift =
6026 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6027 InsertNewInstBefore(Shift, I);
6029 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6030 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6033 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6040 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6041 /// expression. If so, decompose it, returning some value X, such that Val is
6044 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6046 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6047 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6048 Offset = CI->getZExtValue();
6050 return ConstantInt::get(Type::Int32Ty, 0);
6051 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
6052 if (I->getNumOperands() == 2) {
6053 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6054 if (I->getOpcode() == Instruction::Shl) {
6055 // This is a value scaled by '1 << the shift amt'.
6056 Scale = 1U << CUI->getZExtValue();
6058 return I->getOperand(0);
6059 } else if (I->getOpcode() == Instruction::Mul) {
6060 // This value is scaled by 'CUI'.
6061 Scale = CUI->getZExtValue();
6063 return I->getOperand(0);
6064 } else if (I->getOpcode() == Instruction::Add) {
6065 // We have X+C. Check to see if we really have (X*C2)+C1,
6066 // where C1 is divisible by C2.
6069 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6070 Offset += CUI->getZExtValue();
6071 if (SubScale > 1 && (Offset % SubScale == 0)) {
6080 // Otherwise, we can't look past this.
6087 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6088 /// try to eliminate the cast by moving the type information into the alloc.
6089 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6090 AllocationInst &AI) {
6091 const PointerType *PTy = cast<PointerType>(CI.getType());
6093 // Remove any uses of AI that are dead.
6094 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6096 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6097 Instruction *User = cast<Instruction>(*UI++);
6098 if (isInstructionTriviallyDead(User)) {
6099 while (UI != E && *UI == User)
6100 ++UI; // If this instruction uses AI more than once, don't break UI.
6103 DOUT << "IC: DCE: " << *User;
6104 EraseInstFromFunction(*User);
6108 // Get the type really allocated and the type casted to.
6109 const Type *AllocElTy = AI.getAllocatedType();
6110 const Type *CastElTy = PTy->getElementType();
6111 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6113 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6114 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6115 if (CastElTyAlign < AllocElTyAlign) return 0;
6117 // If the allocation has multiple uses, only promote it if we are strictly
6118 // increasing the alignment of the resultant allocation. If we keep it the
6119 // same, we open the door to infinite loops of various kinds.
6120 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6122 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
6123 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
6124 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6126 // See if we can satisfy the modulus by pulling a scale out of the array
6128 unsigned ArraySizeScale;
6130 Value *NumElements = // See if the array size is a decomposable linear expr.
6131 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6133 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6135 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6136 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
6138 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6143 // If the allocation size is constant, form a constant mul expression
6144 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6145 if (isa<ConstantInt>(NumElements))
6146 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6147 // otherwise multiply the amount and the number of elements
6148 else if (Scale != 1) {
6149 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6150 Amt = InsertNewInstBefore(Tmp, AI);
6154 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6155 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6156 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6157 Amt = InsertNewInstBefore(Tmp, AI);
6160 AllocationInst *New;
6161 if (isa<MallocInst>(AI))
6162 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6164 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6165 InsertNewInstBefore(New, AI);
6168 // If the allocation has multiple uses, insert a cast and change all things
6169 // that used it to use the new cast. This will also hack on CI, but it will
6171 if (!AI.hasOneUse()) {
6172 AddUsesToWorkList(AI);
6173 // New is the allocation instruction, pointer typed. AI is the original
6174 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6175 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6176 InsertNewInstBefore(NewCast, AI);
6177 AI.replaceAllUsesWith(NewCast);
6179 return ReplaceInstUsesWith(CI, New);
6182 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6183 /// and return it as type Ty without inserting any new casts and without
6184 /// changing the computed value. This is used by code that tries to decide
6185 /// whether promoting or shrinking integer operations to wider or smaller types
6186 /// will allow us to eliminate a truncate or extend.
6188 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6189 /// extension operation if Ty is larger.
6190 static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6191 int &NumCastsRemoved) {
6192 // We can always evaluate constants in another type.
6193 if (isa<ConstantInt>(V))
6196 Instruction *I = dyn_cast<Instruction>(V);
6197 if (!I) return false;
6199 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6201 switch (I->getOpcode()) {
6202 case Instruction::Add:
6203 case Instruction::Sub:
6204 case Instruction::And:
6205 case Instruction::Or:
6206 case Instruction::Xor:
6207 if (!I->hasOneUse()) return false;
6208 // These operators can all arbitrarily be extended or truncated.
6209 return CanEvaluateInDifferentType(I->getOperand(0), Ty, NumCastsRemoved) &&
6210 CanEvaluateInDifferentType(I->getOperand(1), Ty, NumCastsRemoved);
6212 case Instruction::Shl:
6213 if (!I->hasOneUse()) return false;
6214 // If we are truncating the result of this SHL, and if it's a shift of a
6215 // constant amount, we can always perform a SHL in a smaller type.
6216 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6217 uint32_t BitWidth = Ty->getBitWidth();
6218 if (BitWidth < OrigTy->getBitWidth() &&
6219 CI->getLimitedValue(BitWidth) < BitWidth)
6220 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6223 case Instruction::LShr:
6224 if (!I->hasOneUse()) return false;
6225 // If this is a truncate of a logical shr, we can truncate it to a smaller
6226 // lshr iff we know that the bits we would otherwise be shifting in are
6228 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6229 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6230 uint32_t BitWidth = Ty->getBitWidth();
6231 if (BitWidth < OrigBitWidth &&
6232 MaskedValueIsZero(I->getOperand(0),
6233 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6234 CI->getLimitedValue(BitWidth) < BitWidth) {
6235 return CanEvaluateInDifferentType(I->getOperand(0), Ty,NumCastsRemoved);
6239 case Instruction::Trunc:
6240 case Instruction::ZExt:
6241 case Instruction::SExt:
6242 // If this is a cast from the destination type, we can trivially eliminate
6243 // it, and this will remove a cast overall.
6244 if (I->getOperand(0)->getType() == Ty) {
6245 // If the first operand is itself a cast, and is eliminable, do not count
6246 // this as an eliminable cast. We would prefer to eliminate those two
6248 if (isa<CastInst>(I->getOperand(0)))
6256 // TODO: Can handle more cases here.
6263 /// EvaluateInDifferentType - Given an expression that
6264 /// CanEvaluateInDifferentType returns true for, actually insert the code to
6265 /// evaluate the expression.
6266 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
6268 if (Constant *C = dyn_cast<Constant>(V))
6269 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6271 // Otherwise, it must be an instruction.
6272 Instruction *I = cast<Instruction>(V);
6273 Instruction *Res = 0;
6274 switch (I->getOpcode()) {
6275 case Instruction::Add:
6276 case Instruction::Sub:
6277 case Instruction::And:
6278 case Instruction::Or:
6279 case Instruction::Xor:
6280 case Instruction::AShr:
6281 case Instruction::LShr:
6282 case Instruction::Shl: {
6283 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6284 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6285 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6286 LHS, RHS, I->getName());
6289 case Instruction::Trunc:
6290 case Instruction::ZExt:
6291 case Instruction::SExt:
6292 case Instruction::BitCast:
6293 // If the source type of the cast is the type we're trying for then we can
6294 // just return the source. There's no need to insert it because its not new.
6295 if (I->getOperand(0)->getType() == Ty)
6296 return I->getOperand(0);
6298 // Some other kind of cast, which shouldn't happen, so just ..
6301 // TODO: Can handle more cases here.
6302 assert(0 && "Unreachable!");
6306 return InsertNewInstBefore(Res, *I);
6309 /// @brief Implement the transforms common to all CastInst visitors.
6310 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6311 Value *Src = CI.getOperand(0);
6313 // Casting undef to anything results in undef so might as just replace it and
6314 // get rid of the cast.
6315 if (isa<UndefValue>(Src)) // cast undef -> undef
6316 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
6318 // Many cases of "cast of a cast" are eliminable. If its eliminable we just
6319 // eliminate it now.
6320 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
6321 if (Instruction::CastOps opc =
6322 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6323 // The first cast (CSrc) is eliminable so we need to fix up or replace
6324 // the second cast (CI). CSrc will then have a good chance of being dead.
6325 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
6329 // If we are casting a select then fold the cast into the select
6330 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6331 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6334 // If we are casting a PHI then fold the cast into the PHI
6335 if (isa<PHINode>(Src))
6336 if (Instruction *NV = FoldOpIntoPhi(CI))
6342 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6343 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6344 Value *Src = CI.getOperand(0);
6346 // If casting the result of a getelementptr instruction with no offset, turn
6347 // this into a cast of the original pointer!
6349 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6350 if (GEP->hasAllZeroIndices()) {
6351 // Changing the cast operand is usually not a good idea but it is safe
6352 // here because the pointer operand is being replaced with another
6353 // pointer operand so the opcode doesn't need to change.
6354 CI.setOperand(0, GEP->getOperand(0));
6359 return commonCastTransforms(CI);
6364 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6365 /// integer types. This function implements the common transforms for all those
6367 /// @brief Implement the transforms common to CastInst with integer operands
6368 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6369 if (Instruction *Result = commonCastTransforms(CI))
6372 Value *Src = CI.getOperand(0);
6373 const Type *SrcTy = Src->getType();
6374 const Type *DestTy = CI.getType();
6375 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6376 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
6378 // See if we can simplify any instructions used by the LHS whose sole
6379 // purpose is to compute bits we don't care about.
6380 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6381 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
6382 KnownZero, KnownOne))
6385 // If the source isn't an instruction or has more than one use then we
6386 // can't do anything more.
6387 Instruction *SrcI = dyn_cast<Instruction>(Src);
6388 if (!SrcI || !Src->hasOneUse())
6391 // Attempt to propagate the cast into the instruction for int->int casts.
6392 int NumCastsRemoved = 0;
6393 if (!isa<BitCastInst>(CI) &&
6394 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
6396 // If this cast is a truncate, evaluting in a different type always
6397 // eliminates the cast, so it is always a win. If this is a noop-cast
6398 // this just removes a noop cast which isn't pointful, but simplifies
6399 // the code. If this is a zero-extension, we need to do an AND to
6400 // maintain the clear top-part of the computation, so we require that
6401 // the input have eliminated at least one cast. If this is a sign
6402 // extension, we insert two new casts (to do the extension) so we
6403 // require that two casts have been eliminated.
6405 switch (CI.getOpcode()) {
6407 // All the others use floating point so we shouldn't actually
6408 // get here because of the check above.
6409 assert(0 && "Unknown cast type");
6410 case Instruction::Trunc:
6413 case Instruction::ZExt:
6414 DoXForm = NumCastsRemoved >= 1;
6416 case Instruction::SExt:
6417 DoXForm = NumCastsRemoved >= 2;
6419 case Instruction::BitCast:
6425 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6426 CI.getOpcode() == Instruction::SExt);
6427 assert(Res->getType() == DestTy);
6428 switch (CI.getOpcode()) {
6429 default: assert(0 && "Unknown cast type!");
6430 case Instruction::Trunc:
6431 case Instruction::BitCast:
6432 // Just replace this cast with the result.
6433 return ReplaceInstUsesWith(CI, Res);
6434 case Instruction::ZExt: {
6435 // We need to emit an AND to clear the high bits.
6436 assert(SrcBitSize < DestBitSize && "Not a zext?");
6437 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6439 return BinaryOperator::createAnd(Res, C);
6441 case Instruction::SExt:
6442 // We need to emit a cast to truncate, then a cast to sext.
6443 return CastInst::create(Instruction::SExt,
6444 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6450 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6451 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6453 switch (SrcI->getOpcode()) {
6454 case Instruction::Add:
6455 case Instruction::Mul:
6456 case Instruction::And:
6457 case Instruction::Or:
6458 case Instruction::Xor:
6459 // If we are discarding information, rewrite.
6460 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6461 // Don't insert two casts if they cannot be eliminated. We allow
6462 // two casts to be inserted if the sizes are the same. This could
6463 // only be converting signedness, which is a noop.
6464 if (DestBitSize == SrcBitSize ||
6465 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6466 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6467 Instruction::CastOps opcode = CI.getOpcode();
6468 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6469 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6470 return BinaryOperator::create(
6471 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6475 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6476 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6477 SrcI->getOpcode() == Instruction::Xor &&
6478 Op1 == ConstantInt::getTrue() &&
6479 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6480 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6481 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6484 case Instruction::SDiv:
6485 case Instruction::UDiv:
6486 case Instruction::SRem:
6487 case Instruction::URem:
6488 // If we are just changing the sign, rewrite.
6489 if (DestBitSize == SrcBitSize) {
6490 // Don't insert two casts if they cannot be eliminated. We allow
6491 // two casts to be inserted if the sizes are the same. This could
6492 // only be converting signedness, which is a noop.
6493 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6494 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6495 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6497 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6499 return BinaryOperator::create(
6500 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6505 case Instruction::Shl:
6506 // Allow changing the sign of the source operand. Do not allow
6507 // changing the size of the shift, UNLESS the shift amount is a
6508 // constant. We must not change variable sized shifts to a smaller
6509 // size, because it is undefined to shift more bits out than exist
6511 if (DestBitSize == SrcBitSize ||
6512 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6513 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6514 Instruction::BitCast : Instruction::Trunc);
6515 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6516 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6517 return BinaryOperator::createShl(Op0c, Op1c);
6520 case Instruction::AShr:
6521 // If this is a signed shr, and if all bits shifted in are about to be
6522 // truncated off, turn it into an unsigned shr to allow greater
6524 if (DestBitSize < SrcBitSize &&
6525 isa<ConstantInt>(Op1)) {
6526 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
6527 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6528 // Insert the new logical shift right.
6529 return BinaryOperator::createLShr(Op0, Op1);
6537 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
6538 if (Instruction *Result = commonIntCastTransforms(CI))
6541 Value *Src = CI.getOperand(0);
6542 const Type *Ty = CI.getType();
6543 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
6544 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
6546 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6547 switch (SrcI->getOpcode()) {
6549 case Instruction::LShr:
6550 // We can shrink lshr to something smaller if we know the bits shifted in
6551 // are already zeros.
6552 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6553 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
6555 // Get a mask for the bits shifting in.
6556 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
6557 Value* SrcIOp0 = SrcI->getOperand(0);
6558 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6559 if (ShAmt >= DestBitWidth) // All zeros.
6560 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6562 // Okay, we can shrink this. Truncate the input, then return a new
6564 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6565 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6567 return BinaryOperator::createLShr(V1, V2);
6569 } else { // This is a variable shr.
6571 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6572 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6573 // loop-invariant and CSE'd.
6574 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
6575 Value *One = ConstantInt::get(SrcI->getType(), 1);
6577 Value *V = InsertNewInstBefore(
6578 BinaryOperator::createShl(One, SrcI->getOperand(1),
6580 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6581 SrcI->getOperand(0),
6583 Value *Zero = Constant::getNullValue(V->getType());
6584 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
6594 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
6595 // If one of the common conversion will work ..
6596 if (Instruction *Result = commonIntCastTransforms(CI))
6599 Value *Src = CI.getOperand(0);
6601 // If this is a cast of a cast
6602 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
6603 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6604 // types and if the sizes are just right we can convert this into a logical
6605 // 'and' which will be much cheaper than the pair of casts.
6606 if (isa<TruncInst>(CSrc)) {
6607 // Get the sizes of the types involved
6608 Value *A = CSrc->getOperand(0);
6609 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
6610 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6611 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
6612 // If we're actually extending zero bits and the trunc is a no-op
6613 if (MidSize < DstSize && SrcSize == DstSize) {
6614 // Replace both of the casts with an And of the type mask.
6615 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
6616 Constant *AndConst = ConstantInt::get(AndValue);
6618 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6619 // Unfortunately, if the type changed, we need to cast it back.
6620 if (And->getType() != CI.getType()) {
6621 And->setName(CSrc->getName()+".mask");
6622 InsertNewInstBefore(And, CI);
6623 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
6630 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
6631 // If we are just checking for a icmp eq of a single bit and zext'ing it
6632 // to an integer, then shift the bit to the appropriate place and then
6633 // cast to integer to avoid the comparison.
6634 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
6635 const APInt &Op1CV = Op1C->getValue();
6637 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
6638 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
6639 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
6640 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
6641 Value *In = ICI->getOperand(0);
6642 Value *Sh = ConstantInt::get(In->getType(),
6643 In->getType()->getPrimitiveSizeInBits()-1);
6644 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
6645 In->getName()+".lobit"),
6647 if (In->getType() != CI.getType())
6648 In = CastInst::createIntegerCast(In, CI.getType(),
6649 false/*ZExt*/, "tmp", &CI);
6651 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
6652 Constant *One = ConstantInt::get(In->getType(), 1);
6653 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
6654 In->getName()+".not"),
6658 return ReplaceInstUsesWith(CI, In);
6663 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
6664 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
6665 // zext (X == 1) to i32 --> X iff X has only the low bit set.
6666 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
6667 // zext (X != 0) to i32 --> X iff X has only the low bit set.
6668 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
6669 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
6670 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
6671 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
6672 // This only works for EQ and NE
6673 ICI->isEquality()) {
6674 // If Op1C some other power of two, convert:
6675 uint32_t BitWidth = Op1C->getType()->getBitWidth();
6676 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
6677 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
6678 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
6680 APInt KnownZeroMask(~KnownZero);
6681 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
6682 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
6683 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
6684 // (X&4) == 2 --> false
6685 // (X&4) != 2 --> true
6686 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
6687 Res = ConstantExpr::getZExt(Res, CI.getType());
6688 return ReplaceInstUsesWith(CI, Res);
6691 uint32_t ShiftAmt = KnownZeroMask.logBase2();
6692 Value *In = ICI->getOperand(0);
6694 // Perform a logical shr by shiftamt.
6695 // Insert the shift to put the result in the low bit.
6696 In = InsertNewInstBefore(
6697 BinaryOperator::createLShr(In,
6698 ConstantInt::get(In->getType(), ShiftAmt),
6699 In->getName()+".lobit"), CI);
6702 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6703 Constant *One = ConstantInt::get(In->getType(), 1);
6704 In = BinaryOperator::createXor(In, One, "tmp");
6705 InsertNewInstBefore(cast<Instruction>(In), CI);
6708 if (CI.getType() == In->getType())
6709 return ReplaceInstUsesWith(CI, In);
6711 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6719 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
6720 if (Instruction *I = commonIntCastTransforms(CI))
6723 Value *Src = CI.getOperand(0);
6725 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
6726 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
6727 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
6728 // If we are just checking for a icmp eq of a single bit and zext'ing it
6729 // to an integer, then shift the bit to the appropriate place and then
6730 // cast to integer to avoid the comparison.
6731 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
6732 const APInt &Op1CV = Op1C->getValue();
6734 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
6735 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
6736 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
6737 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
6738 Value *In = ICI->getOperand(0);
6739 Value *Sh = ConstantInt::get(In->getType(),
6740 In->getType()->getPrimitiveSizeInBits()-1);
6741 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
6742 In->getName()+".lobit"),
6744 if (In->getType() != CI.getType())
6745 In = CastInst::createIntegerCast(In, CI.getType(),
6746 true/*SExt*/, "tmp", &CI);
6748 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
6749 In = InsertNewInstBefore(BinaryOperator::createNot(In,
6750 In->getName()+".not"), CI);
6752 return ReplaceInstUsesWith(CI, In);
6760 Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6761 return commonCastTransforms(CI);
6764 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6765 return commonCastTransforms(CI);
6768 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
6769 return commonCastTransforms(CI);
6772 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
6773 return commonCastTransforms(CI);
6776 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
6777 return commonCastTransforms(CI);
6780 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
6781 return commonCastTransforms(CI);
6784 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
6785 return commonPointerCastTransforms(CI);
6788 Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
6789 return commonCastTransforms(CI);
6792 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
6793 // If the operands are integer typed then apply the integer transforms,
6794 // otherwise just apply the common ones.
6795 Value *Src = CI.getOperand(0);
6796 const Type *SrcTy = Src->getType();
6797 const Type *DestTy = CI.getType();
6799 if (SrcTy->isInteger() && DestTy->isInteger()) {
6800 if (Instruction *Result = commonIntCastTransforms(CI))
6802 } else if (isa<PointerType>(SrcTy)) {
6803 if (Instruction *I = commonPointerCastTransforms(CI))
6806 if (Instruction *Result = commonCastTransforms(CI))
6811 // Get rid of casts from one type to the same type. These are useless and can
6812 // be replaced by the operand.
6813 if (DestTy == Src->getType())
6814 return ReplaceInstUsesWith(CI, Src);
6816 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
6817 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
6818 const Type *DstElTy = DstPTy->getElementType();
6819 const Type *SrcElTy = SrcPTy->getElementType();
6821 // If we are casting a malloc or alloca to a pointer to a type of the same
6822 // size, rewrite the allocation instruction to allocate the "right" type.
6823 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
6824 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
6827 // If the source and destination are pointers, and this cast is equivalent to
6828 // a getelementptr X, 0, 0, 0... turn it into the appropriate getelementptr.
6829 // This can enhance SROA and other transforms that want type-safe pointers.
6830 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
6831 unsigned NumZeros = 0;
6832 while (SrcElTy != DstElTy &&
6833 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
6834 SrcElTy->getNumContainedTypes() /* not "{}" */) {
6835 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
6839 // If we found a path from the src to dest, create the getelementptr now.
6840 if (SrcElTy == DstElTy) {
6841 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
6842 return new GetElementPtrInst(Src, &Idxs[0], Idxs.size());
6846 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
6847 if (SVI->hasOneUse()) {
6848 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
6849 // a bitconvert to a vector with the same # elts.
6850 if (isa<VectorType>(DestTy) &&
6851 cast<VectorType>(DestTy)->getNumElements() ==
6852 SVI->getType()->getNumElements()) {
6854 // If either of the operands is a cast from CI.getType(), then
6855 // evaluating the shuffle in the casted destination's type will allow
6856 // us to eliminate at least one cast.
6857 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
6858 Tmp->getOperand(0)->getType() == DestTy) ||
6859 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
6860 Tmp->getOperand(0)->getType() == DestTy)) {
6861 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
6862 SVI->getOperand(0), DestTy, &CI);
6863 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
6864 SVI->getOperand(1), DestTy, &CI);
6865 // Return a new shuffle vector. Use the same element ID's, as we
6866 // know the vector types match #elts.
6867 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
6875 /// GetSelectFoldableOperands - We want to turn code that looks like this:
6877 /// %D = select %cond, %C, %A
6879 /// %C = select %cond, %B, 0
6882 /// Assuming that the specified instruction is an operand to the select, return
6883 /// a bitmask indicating which operands of this instruction are foldable if they
6884 /// equal the other incoming value of the select.
6886 static unsigned GetSelectFoldableOperands(Instruction *I) {
6887 switch (I->getOpcode()) {
6888 case Instruction::Add:
6889 case Instruction::Mul:
6890 case Instruction::And:
6891 case Instruction::Or:
6892 case Instruction::Xor:
6893 return 3; // Can fold through either operand.
6894 case Instruction::Sub: // Can only fold on the amount subtracted.
6895 case Instruction::Shl: // Can only fold on the shift amount.
6896 case Instruction::LShr:
6897 case Instruction::AShr:
6900 return 0; // Cannot fold
6904 /// GetSelectFoldableConstant - For the same transformation as the previous
6905 /// function, return the identity constant that goes into the select.
6906 static Constant *GetSelectFoldableConstant(Instruction *I) {
6907 switch (I->getOpcode()) {
6908 default: assert(0 && "This cannot happen!"); abort();
6909 case Instruction::Add:
6910 case Instruction::Sub:
6911 case Instruction::Or:
6912 case Instruction::Xor:
6913 case Instruction::Shl:
6914 case Instruction::LShr:
6915 case Instruction::AShr:
6916 return Constant::getNullValue(I->getType());
6917 case Instruction::And:
6918 return ConstantInt::getAllOnesValue(I->getType());
6919 case Instruction::Mul:
6920 return ConstantInt::get(I->getType(), 1);
6924 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
6925 /// have the same opcode and only one use each. Try to simplify this.
6926 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
6928 if (TI->getNumOperands() == 1) {
6929 // If this is a non-volatile load or a cast from the same type,
6932 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
6935 return 0; // unknown unary op.
6938 // Fold this by inserting a select from the input values.
6939 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
6940 FI->getOperand(0), SI.getName()+".v");
6941 InsertNewInstBefore(NewSI, SI);
6942 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
6946 // Only handle binary operators here.
6947 if (!isa<BinaryOperator>(TI))
6950 // Figure out if the operations have any operands in common.
6951 Value *MatchOp, *OtherOpT, *OtherOpF;
6953 if (TI->getOperand(0) == FI->getOperand(0)) {
6954 MatchOp = TI->getOperand(0);
6955 OtherOpT = TI->getOperand(1);
6956 OtherOpF = FI->getOperand(1);
6957 MatchIsOpZero = true;
6958 } else if (TI->getOperand(1) == FI->getOperand(1)) {
6959 MatchOp = TI->getOperand(1);
6960 OtherOpT = TI->getOperand(0);
6961 OtherOpF = FI->getOperand(0);
6962 MatchIsOpZero = false;
6963 } else if (!TI->isCommutative()) {
6965 } else if (TI->getOperand(0) == FI->getOperand(1)) {
6966 MatchOp = TI->getOperand(0);
6967 OtherOpT = TI->getOperand(1);
6968 OtherOpF = FI->getOperand(0);
6969 MatchIsOpZero = true;
6970 } else if (TI->getOperand(1) == FI->getOperand(0)) {
6971 MatchOp = TI->getOperand(1);
6972 OtherOpT = TI->getOperand(0);
6973 OtherOpF = FI->getOperand(1);
6974 MatchIsOpZero = true;
6979 // If we reach here, they do have operations in common.
6980 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
6981 OtherOpF, SI.getName()+".v");
6982 InsertNewInstBefore(NewSI, SI);
6984 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
6986 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
6988 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
6990 assert(0 && "Shouldn't get here");
6994 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
6995 Value *CondVal = SI.getCondition();
6996 Value *TrueVal = SI.getTrueValue();
6997 Value *FalseVal = SI.getFalseValue();
6999 // select true, X, Y -> X
7000 // select false, X, Y -> Y
7001 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7002 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7004 // select C, X, X -> X
7005 if (TrueVal == FalseVal)
7006 return ReplaceInstUsesWith(SI, TrueVal);
7008 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7009 return ReplaceInstUsesWith(SI, FalseVal);
7010 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7011 return ReplaceInstUsesWith(SI, TrueVal);
7012 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7013 if (isa<Constant>(TrueVal))
7014 return ReplaceInstUsesWith(SI, TrueVal);
7016 return ReplaceInstUsesWith(SI, FalseVal);
7019 if (SI.getType() == Type::Int1Ty) {
7020 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7021 if (C->getZExtValue()) {
7022 // Change: A = select B, true, C --> A = or B, C
7023 return BinaryOperator::createOr(CondVal, FalseVal);
7025 // Change: A = select B, false, C --> A = and !B, C
7027 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7028 "not."+CondVal->getName()), SI);
7029 return BinaryOperator::createAnd(NotCond, FalseVal);
7031 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7032 if (C->getZExtValue() == false) {
7033 // Change: A = select B, C, false --> A = and B, C
7034 return BinaryOperator::createAnd(CondVal, TrueVal);
7036 // Change: A = select B, C, true --> A = or !B, C
7038 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7039 "not."+CondVal->getName()), SI);
7040 return BinaryOperator::createOr(NotCond, TrueVal);
7045 // Selecting between two integer constants?
7046 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7047 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7048 // select C, 1, 0 -> zext C to int
7049 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
7050 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
7051 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
7052 // select C, 0, 1 -> zext !C to int
7054 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7055 "not."+CondVal->getName()), SI);
7056 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
7059 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
7061 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
7063 // (x <s 0) ? -1 : 0 -> ashr x, 31
7064 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
7065 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
7066 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
7067 // The comparison constant and the result are not neccessarily the
7068 // same width. Make an all-ones value by inserting a AShr.
7069 Value *X = IC->getOperand(0);
7070 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
7071 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7072 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7074 InsertNewInstBefore(SRA, SI);
7076 // Finally, convert to the type of the select RHS. We figure out
7077 // if this requires a SExt, Trunc or BitCast based on the sizes.
7078 Instruction::CastOps opc = Instruction::BitCast;
7079 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7080 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
7081 if (SRASize < SISize)
7082 opc = Instruction::SExt;
7083 else if (SRASize > SISize)
7084 opc = Instruction::Trunc;
7085 return CastInst::create(opc, SRA, SI.getType());
7090 // If one of the constants is zero (we know they can't both be) and we
7091 // have an icmp instruction with zero, and we have an 'and' with the
7092 // non-constant value, eliminate this whole mess. This corresponds to
7093 // cases like this: ((X & 27) ? 27 : 0)
7094 if (TrueValC->isZero() || FalseValC->isZero())
7095 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
7096 cast<Constant>(IC->getOperand(1))->isNullValue())
7097 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7098 if (ICA->getOpcode() == Instruction::And &&
7099 isa<ConstantInt>(ICA->getOperand(1)) &&
7100 (ICA->getOperand(1) == TrueValC ||
7101 ICA->getOperand(1) == FalseValC) &&
7102 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7103 // Okay, now we know that everything is set up, we just don't
7104 // know whether we have a icmp_ne or icmp_eq and whether the
7105 // true or false val is the zero.
7106 bool ShouldNotVal = !TrueValC->isZero();
7107 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
7110 V = InsertNewInstBefore(BinaryOperator::create(
7111 Instruction::Xor, V, ICA->getOperand(1)), SI);
7112 return ReplaceInstUsesWith(SI, V);
7117 // See if we are selecting two values based on a comparison of the two values.
7118 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7119 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
7120 // Transform (X == Y) ? X : Y -> Y
7121 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
7122 return ReplaceInstUsesWith(SI, FalseVal);
7123 // Transform (X != Y) ? X : Y -> X
7124 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7125 return ReplaceInstUsesWith(SI, TrueVal);
7126 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7128 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
7129 // Transform (X == Y) ? Y : X -> X
7130 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
7131 return ReplaceInstUsesWith(SI, FalseVal);
7132 // Transform (X != Y) ? Y : X -> Y
7133 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7134 return ReplaceInstUsesWith(SI, TrueVal);
7135 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7139 // See if we are selecting two values based on a comparison of the two values.
7140 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7141 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7142 // Transform (X == Y) ? X : Y -> Y
7143 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7144 return ReplaceInstUsesWith(SI, FalseVal);
7145 // Transform (X != Y) ? X : Y -> X
7146 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7147 return ReplaceInstUsesWith(SI, TrueVal);
7148 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7150 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7151 // Transform (X == Y) ? Y : X -> X
7152 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7153 return ReplaceInstUsesWith(SI, FalseVal);
7154 // Transform (X != Y) ? Y : X -> Y
7155 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7156 return ReplaceInstUsesWith(SI, TrueVal);
7157 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7161 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7162 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7163 if (TI->hasOneUse() && FI->hasOneUse()) {
7164 Instruction *AddOp = 0, *SubOp = 0;
7166 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7167 if (TI->getOpcode() == FI->getOpcode())
7168 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7171 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7172 // even legal for FP.
7173 if (TI->getOpcode() == Instruction::Sub &&
7174 FI->getOpcode() == Instruction::Add) {
7175 AddOp = FI; SubOp = TI;
7176 } else if (FI->getOpcode() == Instruction::Sub &&
7177 TI->getOpcode() == Instruction::Add) {
7178 AddOp = TI; SubOp = FI;
7182 Value *OtherAddOp = 0;
7183 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7184 OtherAddOp = AddOp->getOperand(1);
7185 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7186 OtherAddOp = AddOp->getOperand(0);
7190 // So at this point we know we have (Y -> OtherAddOp):
7191 // select C, (add X, Y), (sub X, Z)
7192 Value *NegVal; // Compute -Z
7193 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7194 NegVal = ConstantExpr::getNeg(C);
7196 NegVal = InsertNewInstBefore(
7197 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
7200 Value *NewTrueOp = OtherAddOp;
7201 Value *NewFalseOp = NegVal;
7203 std::swap(NewTrueOp, NewFalseOp);
7204 Instruction *NewSel =
7205 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7207 NewSel = InsertNewInstBefore(NewSel, SI);
7208 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
7213 // See if we can fold the select into one of our operands.
7214 if (SI.getType()->isInteger()) {
7215 // See the comment above GetSelectFoldableOperands for a description of the
7216 // transformation we are doing here.
7217 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7218 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7219 !isa<Constant>(FalseVal))
7220 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7221 unsigned OpToFold = 0;
7222 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7224 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7229 Constant *C = GetSelectFoldableConstant(TVI);
7230 Instruction *NewSel =
7231 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
7232 InsertNewInstBefore(NewSel, SI);
7233 NewSel->takeName(TVI);
7234 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7235 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
7237 assert(0 && "Unknown instruction!!");
7242 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7243 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7244 !isa<Constant>(TrueVal))
7245 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7246 unsigned OpToFold = 0;
7247 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7249 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7254 Constant *C = GetSelectFoldableConstant(FVI);
7255 Instruction *NewSel =
7256 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
7257 InsertNewInstBefore(NewSel, SI);
7258 NewSel->takeName(FVI);
7259 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7260 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
7262 assert(0 && "Unknown instruction!!");
7267 if (BinaryOperator::isNot(CondVal)) {
7268 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7269 SI.setOperand(1, FalseVal);
7270 SI.setOperand(2, TrueVal);
7277 /// GetKnownAlignment - If the specified pointer has an alignment that we can
7278 /// determine, return it, otherwise return 0.
7279 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
7280 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7281 unsigned Align = GV->getAlignment();
7282 if (Align == 0 && TD)
7283 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
7285 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7286 unsigned Align = AI->getAlignment();
7287 if (Align == 0 && TD) {
7288 if (isa<AllocaInst>(AI))
7289 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
7290 else if (isa<MallocInst>(AI)) {
7291 // Malloc returns maximally aligned memory.
7292 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
7295 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
7298 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
7302 } else if (isa<BitCastInst>(V) ||
7303 (isa<ConstantExpr>(V) &&
7304 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
7305 User *CI = cast<User>(V);
7306 if (isa<PointerType>(CI->getOperand(0)->getType()))
7307 return GetKnownAlignment(CI->getOperand(0), TD);
7309 } else if (isa<GetElementPtrInst>(V) ||
7310 (isa<ConstantExpr>(V) &&
7311 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
7312 User *GEPI = cast<User>(V);
7313 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
7314 if (BaseAlignment == 0) return 0;
7316 // If all indexes are zero, it is just the alignment of the base pointer.
7317 bool AllZeroOperands = true;
7318 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7319 if (!isa<Constant>(GEPI->getOperand(i)) ||
7320 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7321 AllZeroOperands = false;
7324 if (AllZeroOperands)
7325 return BaseAlignment;
7327 // Otherwise, if the base alignment is >= the alignment we expect for the
7328 // base pointer type, then we know that the resultant pointer is aligned at
7329 // least as much as its type requires.
7332 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
7333 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
7334 if (TD->getABITypeAlignment(PtrTy->getElementType())
7336 const Type *GEPTy = GEPI->getType();
7337 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
7338 return TD->getABITypeAlignment(GEPPtrTy->getElementType());
7346 /// visitCallInst - CallInst simplification. This mostly only handles folding
7347 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7348 /// the heavy lifting.
7350 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
7351 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7352 if (!II) return visitCallSite(&CI);
7354 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7356 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
7357 bool Changed = false;
7359 // memmove/cpy/set of zero bytes is a noop.
7360 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7361 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7363 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
7364 if (CI->getZExtValue() == 1) {
7365 // Replace the instruction with just byte operations. We would
7366 // transform other cases to loads/stores, but we don't know if
7367 // alignment is sufficient.
7371 // If we have a memmove and the source operation is a constant global,
7372 // then the source and dest pointers can't alias, so we can change this
7373 // into a call to memcpy.
7374 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
7375 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7376 if (GVSrc->isConstant()) {
7377 Module *M = CI.getParent()->getParent()->getParent();
7379 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
7381 Name = "llvm.memcpy.i32";
7383 Name = "llvm.memcpy.i64";
7384 Constant *MemCpy = M->getOrInsertFunction(Name,
7385 CI.getCalledFunction()->getFunctionType());
7386 CI.setOperand(0, MemCpy);
7391 // If we can determine a pointer alignment that is bigger than currently
7392 // set, update the alignment.
7393 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
7394 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
7395 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
7396 unsigned Align = std::min(Alignment1, Alignment2);
7397 if (MI->getAlignment()->getZExtValue() < Align) {
7398 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
7401 } else if (isa<MemSetInst>(MI)) {
7402 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
7403 if (MI->getAlignment()->getZExtValue() < Alignment) {
7404 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
7409 if (Changed) return II;
7411 switch (II->getIntrinsicID()) {
7413 case Intrinsic::ppc_altivec_lvx:
7414 case Intrinsic::ppc_altivec_lvxl:
7415 case Intrinsic::x86_sse_loadu_ps:
7416 case Intrinsic::x86_sse2_loadu_pd:
7417 case Intrinsic::x86_sse2_loadu_dq:
7418 // Turn PPC lvx -> load if the pointer is known aligned.
7419 // Turn X86 loadups -> load if the pointer is known aligned.
7420 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7421 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7422 PointerType::get(II->getType()), CI);
7423 return new LoadInst(Ptr);
7426 case Intrinsic::ppc_altivec_stvx:
7427 case Intrinsic::ppc_altivec_stvxl:
7428 // Turn stvx -> store if the pointer is known aligned.
7429 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
7430 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
7431 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7433 return new StoreInst(II->getOperand(1), Ptr);
7436 case Intrinsic::x86_sse_storeu_ps:
7437 case Intrinsic::x86_sse2_storeu_pd:
7438 case Intrinsic::x86_sse2_storeu_dq:
7439 case Intrinsic::x86_sse2_storel_dq:
7440 // Turn X86 storeu -> store if the pointer is known aligned.
7441 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
7442 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
7443 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7445 return new StoreInst(II->getOperand(2), Ptr);
7449 case Intrinsic::x86_sse_cvttss2si: {
7450 // These intrinsics only demands the 0th element of its input vector. If
7451 // we can simplify the input based on that, do so now.
7453 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7455 II->setOperand(1, V);
7461 case Intrinsic::ppc_altivec_vperm:
7462 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7463 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
7464 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7466 // Check that all of the elements are integer constants or undefs.
7467 bool AllEltsOk = true;
7468 for (unsigned i = 0; i != 16; ++i) {
7469 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7470 !isa<UndefValue>(Mask->getOperand(i))) {
7477 // Cast the input vectors to byte vectors.
7478 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7479 II->getOperand(1), Mask->getType(), CI);
7480 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7481 II->getOperand(2), Mask->getType(), CI);
7482 Value *Result = UndefValue::get(Op0->getType());
7484 // Only extract each element once.
7485 Value *ExtractedElts[32];
7486 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7488 for (unsigned i = 0; i != 16; ++i) {
7489 if (isa<UndefValue>(Mask->getOperand(i)))
7491 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
7492 Idx &= 31; // Match the hardware behavior.
7494 if (ExtractedElts[Idx] == 0) {
7496 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
7497 InsertNewInstBefore(Elt, CI);
7498 ExtractedElts[Idx] = Elt;
7501 // Insert this value into the result vector.
7502 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
7503 InsertNewInstBefore(cast<Instruction>(Result), CI);
7505 return CastInst::create(Instruction::BitCast, Result, CI.getType());
7510 case Intrinsic::stackrestore: {
7511 // If the save is right next to the restore, remove the restore. This can
7512 // happen when variable allocas are DCE'd.
7513 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7514 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7515 BasicBlock::iterator BI = SS;
7517 return EraseInstFromFunction(CI);
7521 // If the stack restore is in a return/unwind block and if there are no
7522 // allocas or calls between the restore and the return, nuke the restore.
7523 TerminatorInst *TI = II->getParent()->getTerminator();
7524 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7525 BasicBlock::iterator BI = II;
7526 bool CannotRemove = false;
7527 for (++BI; &*BI != TI; ++BI) {
7528 if (isa<AllocaInst>(BI) ||
7529 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7530 CannotRemove = true;
7535 return EraseInstFromFunction(CI);
7542 return visitCallSite(II);
7545 // InvokeInst simplification
7547 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
7548 return visitCallSite(&II);
7551 // visitCallSite - Improvements for call and invoke instructions.
7553 Instruction *InstCombiner::visitCallSite(CallSite CS) {
7554 bool Changed = false;
7556 // If the callee is a constexpr cast of a function, attempt to move the cast
7557 // to the arguments of the call/invoke.
7558 if (transformConstExprCastCall(CS)) return 0;
7560 Value *Callee = CS.getCalledValue();
7562 if (Function *CalleeF = dyn_cast<Function>(Callee))
7563 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7564 Instruction *OldCall = CS.getInstruction();
7565 // If the call and callee calling conventions don't match, this call must
7566 // be unreachable, as the call is undefined.
7567 new StoreInst(ConstantInt::getTrue(),
7568 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
7569 if (!OldCall->use_empty())
7570 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7571 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7572 return EraseInstFromFunction(*OldCall);
7576 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7577 // This instruction is not reachable, just remove it. We insert a store to
7578 // undef so that we know that this code is not reachable, despite the fact
7579 // that we can't modify the CFG here.
7580 new StoreInst(ConstantInt::getTrue(),
7581 UndefValue::get(PointerType::get(Type::Int1Ty)),
7582 CS.getInstruction());
7584 if (!CS.getInstruction()->use_empty())
7585 CS.getInstruction()->
7586 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7588 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7589 // Don't break the CFG, insert a dummy cond branch.
7590 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
7591 ConstantInt::getTrue(), II);
7593 return EraseInstFromFunction(*CS.getInstruction());
7596 const PointerType *PTy = cast<PointerType>(Callee->getType());
7597 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7598 if (FTy->isVarArg()) {
7599 // See if we can optimize any arguments passed through the varargs area of
7601 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7602 E = CS.arg_end(); I != E; ++I)
7603 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7604 // If this cast does not effect the value passed through the varargs
7605 // area, we can eliminate the use of the cast.
7606 Value *Op = CI->getOperand(0);
7607 if (CI->isLosslessCast()) {
7614 return Changed ? CS.getInstruction() : 0;
7617 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
7618 // attempt to move the cast to the arguments of the call/invoke.
7620 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7621 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
7622 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
7623 if (CE->getOpcode() != Instruction::BitCast ||
7624 !isa<Function>(CE->getOperand(0)))
7626 Function *Callee = cast<Function>(CE->getOperand(0));
7627 Instruction *Caller = CS.getInstruction();
7629 // Okay, this is a cast from a function to a different type. Unless doing so
7630 // would cause a type conversion of one of our arguments, change this call to
7631 // be a direct call with arguments casted to the appropriate types.
7633 const FunctionType *FT = Callee->getFunctionType();
7634 const Type *OldRetTy = Caller->getType();
7636 // Check to see if we are changing the return type...
7637 if (OldRetTy != FT->getReturnType()) {
7638 if (Callee->isDeclaration() && !Caller->use_empty() &&
7639 // Conversion is ok if changing from pointer to int of same size.
7640 !(isa<PointerType>(FT->getReturnType()) &&
7641 TD->getIntPtrType() == OldRetTy))
7642 return false; // Cannot transform this return value.
7644 // If the callsite is an invoke instruction, and the return value is used by
7645 // a PHI node in a successor, we cannot change the return type of the call
7646 // because there is no place to put the cast instruction (without breaking
7647 // the critical edge). Bail out in this case.
7648 if (!Caller->use_empty())
7649 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
7650 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
7652 if (PHINode *PN = dyn_cast<PHINode>(*UI))
7653 if (PN->getParent() == II->getNormalDest() ||
7654 PN->getParent() == II->getUnwindDest())
7658 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
7659 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
7661 CallSite::arg_iterator AI = CS.arg_begin();
7662 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
7663 const Type *ParamTy = FT->getParamType(i);
7664 const Type *ActTy = (*AI)->getType();
7665 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
7666 //Some conversions are safe even if we do not have a body.
7667 //Either we can cast directly, or we can upconvert the argument
7668 bool isConvertible = ActTy == ParamTy ||
7669 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
7670 (ParamTy->isInteger() && ActTy->isInteger() &&
7671 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
7672 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
7673 && c->getValue().isStrictlyPositive());
7674 if (Callee->isDeclaration() && !isConvertible) return false;
7676 // Most other conversions can be done if we have a body, even if these
7677 // lose information, e.g. int->short.
7678 // Some conversions cannot be done at all, e.g. float to pointer.
7679 // Logic here parallels CastInst::getCastOpcode (the design there
7680 // requires legality checks like this be done before calling it).
7681 if (ParamTy->isInteger()) {
7682 if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7683 if (VActTy->getBitWidth() != ParamTy->getPrimitiveSizeInBits())
7686 if (!ActTy->isInteger() && !ActTy->isFloatingPoint() &&
7687 !isa<PointerType>(ActTy))
7689 } else if (ParamTy->isFloatingPoint()) {
7690 if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7691 if (VActTy->getBitWidth() != ParamTy->getPrimitiveSizeInBits())
7694 if (!ActTy->isInteger() && !ActTy->isFloatingPoint())
7696 } else if (const VectorType *VParamTy = dyn_cast<VectorType>(ParamTy)) {
7697 if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
7698 if (VActTy->getBitWidth() != VParamTy->getBitWidth())
7701 if (VParamTy->getBitWidth() != ActTy->getPrimitiveSizeInBits())
7703 } else if (isa<PointerType>(ParamTy)) {
7704 if (!ActTy->isInteger() && !isa<PointerType>(ActTy))
7711 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
7712 Callee->isDeclaration())
7713 return false; // Do not delete arguments unless we have a function body...
7715 // Okay, we decided that this is a safe thing to do: go ahead and start
7716 // inserting cast instructions as necessary...
7717 std::vector<Value*> Args;
7718 Args.reserve(NumActualArgs);
7720 AI = CS.arg_begin();
7721 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
7722 const Type *ParamTy = FT->getParamType(i);
7723 if ((*AI)->getType() == ParamTy) {
7724 Args.push_back(*AI);
7726 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
7727 false, ParamTy, false);
7728 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
7729 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
7733 // If the function takes more arguments than the call was taking, add them
7735 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
7736 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
7738 // If we are removing arguments to the function, emit an obnoxious warning...
7739 if (FT->getNumParams() < NumActualArgs)
7740 if (!FT->isVarArg()) {
7741 cerr << "WARNING: While resolving call to function '"
7742 << Callee->getName() << "' arguments were dropped!\n";
7744 // Add all of the arguments in their promoted form to the arg list...
7745 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
7746 const Type *PTy = getPromotedType((*AI)->getType());
7747 if (PTy != (*AI)->getType()) {
7748 // Must promote to pass through va_arg area!
7749 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
7751 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
7752 InsertNewInstBefore(Cast, *Caller);
7753 Args.push_back(Cast);
7755 Args.push_back(*AI);
7760 if (FT->getReturnType() == Type::VoidTy)
7761 Caller->setName(""); // Void type should not have a name.
7764 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7765 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
7766 &Args[0], Args.size(), Caller->getName(), Caller);
7767 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
7769 NC = new CallInst(Callee, &Args[0], Args.size(), Caller->getName(), Caller);
7770 if (cast<CallInst>(Caller)->isTailCall())
7771 cast<CallInst>(NC)->setTailCall();
7772 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
7775 // Insert a cast of the return type as necessary.
7777 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
7778 if (NV->getType() != Type::VoidTy) {
7779 const Type *CallerTy = Caller->getType();
7780 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
7782 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
7784 // If this is an invoke instruction, we should insert it after the first
7785 // non-phi, instruction in the normal successor block.
7786 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7787 BasicBlock::iterator I = II->getNormalDest()->begin();
7788 while (isa<PHINode>(I)) ++I;
7789 InsertNewInstBefore(NC, *I);
7791 // Otherwise, it's a call, just insert cast right after the call instr
7792 InsertNewInstBefore(NC, *Caller);
7794 AddUsersToWorkList(*Caller);
7796 NV = UndefValue::get(Caller->getType());
7800 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7801 Caller->replaceAllUsesWith(NV);
7802 Caller->eraseFromParent();
7803 RemoveFromWorkList(Caller);
7807 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
7808 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
7809 /// and a single binop.
7810 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
7811 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7812 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
7813 isa<CmpInst>(FirstInst));
7814 unsigned Opc = FirstInst->getOpcode();
7815 Value *LHSVal = FirstInst->getOperand(0);
7816 Value *RHSVal = FirstInst->getOperand(1);
7818 const Type *LHSType = LHSVal->getType();
7819 const Type *RHSType = RHSVal->getType();
7821 // Scan to see if all operands are the same opcode, all have one use, and all
7822 // kill their operands (i.e. the operands have one use).
7823 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
7824 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
7825 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
7826 // Verify type of the LHS matches so we don't fold cmp's of different
7827 // types or GEP's with different index types.
7828 I->getOperand(0)->getType() != LHSType ||
7829 I->getOperand(1)->getType() != RHSType)
7832 // If they are CmpInst instructions, check their predicates
7833 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
7834 if (cast<CmpInst>(I)->getPredicate() !=
7835 cast<CmpInst>(FirstInst)->getPredicate())
7838 // Keep track of which operand needs a phi node.
7839 if (I->getOperand(0) != LHSVal) LHSVal = 0;
7840 if (I->getOperand(1) != RHSVal) RHSVal = 0;
7843 // Otherwise, this is safe to transform, determine if it is profitable.
7845 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
7846 // Indexes are often folded into load/store instructions, so we don't want to
7847 // hide them behind a phi.
7848 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
7851 Value *InLHS = FirstInst->getOperand(0);
7852 Value *InRHS = FirstInst->getOperand(1);
7853 PHINode *NewLHS = 0, *NewRHS = 0;
7855 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
7856 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
7857 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
7858 InsertNewInstBefore(NewLHS, PN);
7863 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
7864 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
7865 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
7866 InsertNewInstBefore(NewRHS, PN);
7870 // Add all operands to the new PHIs.
7871 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7873 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
7874 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
7877 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
7878 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
7882 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
7883 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
7884 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
7885 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
7888 assert(isa<GetElementPtrInst>(FirstInst));
7889 return new GetElementPtrInst(LHSVal, RHSVal);
7893 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
7894 /// of the block that defines it. This means that it must be obvious the value
7895 /// of the load is not changed from the point of the load to the end of the
7898 /// Finally, it is safe, but not profitable, to sink a load targetting a
7899 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
7901 static bool isSafeToSinkLoad(LoadInst *L) {
7902 BasicBlock::iterator BBI = L, E = L->getParent()->end();
7904 for (++BBI; BBI != E; ++BBI)
7905 if (BBI->mayWriteToMemory())
7908 // Check for non-address taken alloca. If not address-taken already, it isn't
7909 // profitable to do this xform.
7910 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
7911 bool isAddressTaken = false;
7912 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
7914 if (isa<LoadInst>(UI)) continue;
7915 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
7916 // If storing TO the alloca, then the address isn't taken.
7917 if (SI->getOperand(1) == AI) continue;
7919 isAddressTaken = true;
7923 if (!isAddressTaken)
7931 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
7932 // operator and they all are only used by the PHI, PHI together their
7933 // inputs, and do the operation once, to the result of the PHI.
7934 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
7935 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
7937 // Scan the instruction, looking for input operations that can be folded away.
7938 // If all input operands to the phi are the same instruction (e.g. a cast from
7939 // the same type or "+42") we can pull the operation through the PHI, reducing
7940 // code size and simplifying code.
7941 Constant *ConstantOp = 0;
7942 const Type *CastSrcTy = 0;
7943 bool isVolatile = false;
7944 if (isa<CastInst>(FirstInst)) {
7945 CastSrcTy = FirstInst->getOperand(0)->getType();
7946 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
7947 // Can fold binop, compare or shift here if the RHS is a constant,
7948 // otherwise call FoldPHIArgBinOpIntoPHI.
7949 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
7950 if (ConstantOp == 0)
7951 return FoldPHIArgBinOpIntoPHI(PN);
7952 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
7953 isVolatile = LI->isVolatile();
7954 // We can't sink the load if the loaded value could be modified between the
7955 // load and the PHI.
7956 if (LI->getParent() != PN.getIncomingBlock(0) ||
7957 !isSafeToSinkLoad(LI))
7959 } else if (isa<GetElementPtrInst>(FirstInst)) {
7960 if (FirstInst->getNumOperands() == 2)
7961 return FoldPHIArgBinOpIntoPHI(PN);
7962 // Can't handle general GEPs yet.
7965 return 0; // Cannot fold this operation.
7968 // Check to see if all arguments are the same operation.
7969 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
7970 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
7971 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
7972 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
7975 if (I->getOperand(0)->getType() != CastSrcTy)
7976 return 0; // Cast operation must match.
7977 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
7978 // We can't sink the load if the loaded value could be modified between
7979 // the load and the PHI.
7980 if (LI->isVolatile() != isVolatile ||
7981 LI->getParent() != PN.getIncomingBlock(i) ||
7982 !isSafeToSinkLoad(LI))
7984 } else if (I->getOperand(1) != ConstantOp) {
7989 // Okay, they are all the same operation. Create a new PHI node of the
7990 // correct type, and PHI together all of the LHS's of the instructions.
7991 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
7992 PN.getName()+".in");
7993 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
7995 Value *InVal = FirstInst->getOperand(0);
7996 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
7998 // Add all operands to the new PHI.
7999 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8000 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8001 if (NewInVal != InVal)
8003 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8008 // The new PHI unions all of the same values together. This is really
8009 // common, so we handle it intelligently here for compile-time speed.
8013 InsertNewInstBefore(NewPN, PN);
8017 // Insert and return the new operation.
8018 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8019 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
8020 else if (isa<LoadInst>(FirstInst))
8021 return new LoadInst(PhiVal, "", isVolatile);
8022 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8023 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
8024 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8025 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
8026 PhiVal, ConstantOp);
8028 assert(0 && "Unknown operation");
8032 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8034 static bool DeadPHICycle(PHINode *PN,
8035 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
8036 if (PN->use_empty()) return true;
8037 if (!PN->hasOneUse()) return false;
8039 // Remember this node, and if we find the cycle, return.
8040 if (!PotentiallyDeadPHIs.insert(PN))
8043 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8044 return DeadPHICycle(PU, PotentiallyDeadPHIs);
8049 // PHINode simplification
8051 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
8052 // If LCSSA is around, don't mess with Phi nodes
8053 if (MustPreserveLCSSA) return 0;
8055 if (Value *V = PN.hasConstantValue())
8056 return ReplaceInstUsesWith(PN, V);
8058 // If all PHI operands are the same operation, pull them through the PHI,
8059 // reducing code size.
8060 if (isa<Instruction>(PN.getIncomingValue(0)) &&
8061 PN.getIncomingValue(0)->hasOneUse())
8062 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8065 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
8066 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8067 // PHI)... break the cycle.
8068 if (PN.hasOneUse()) {
8069 Instruction *PHIUser = cast<Instruction>(PN.use_back());
8070 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
8071 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
8072 PotentiallyDeadPHIs.insert(&PN);
8073 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8074 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8077 // If this phi has a single use, and if that use just computes a value for
8078 // the next iteration of a loop, delete the phi. This occurs with unused
8079 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
8080 // common case here is good because the only other things that catch this
8081 // are induction variable analysis (sometimes) and ADCE, which is only run
8083 if (PHIUser->hasOneUse() &&
8084 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8085 PHIUser->use_back() == &PN) {
8086 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8093 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
8094 Instruction *InsertPoint,
8096 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
8097 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
8098 // We must cast correctly to the pointer type. Ensure that we
8099 // sign extend the integer value if it is smaller as this is
8100 // used for address computation.
8101 Instruction::CastOps opcode =
8102 (VTySize < PtrSize ? Instruction::SExt :
8103 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8104 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
8108 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
8109 Value *PtrOp = GEP.getOperand(0);
8110 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
8111 // If so, eliminate the noop.
8112 if (GEP.getNumOperands() == 1)
8113 return ReplaceInstUsesWith(GEP, PtrOp);
8115 if (isa<UndefValue>(GEP.getOperand(0)))
8116 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8118 bool HasZeroPointerIndex = false;
8119 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8120 HasZeroPointerIndex = C->isNullValue();
8122 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
8123 return ReplaceInstUsesWith(GEP, PtrOp);
8125 // Keep track of whether all indices are zero constants integers.
8126 bool AllZeroIndices = true;
8128 // Eliminate unneeded casts for indices.
8129 bool MadeChange = false;
8131 gep_type_iterator GTI = gep_type_begin(GEP);
8132 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
8133 // Track whether this GEP has all zero indices, if so, it doesn't move the
8134 // input pointer, it just changes its type.
8135 if (AllZeroIndices) {
8136 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(i)))
8137 AllZeroIndices = CI->isZero();
8139 AllZeroIndices = false;
8141 if (isa<SequentialType>(*GTI)) {
8142 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
8143 if (CI->getOpcode() == Instruction::ZExt ||
8144 CI->getOpcode() == Instruction::SExt) {
8145 const Type *SrcTy = CI->getOperand(0)->getType();
8146 // We can eliminate a cast from i32 to i64 iff the target
8147 // is a 32-bit pointer target.
8148 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8150 GEP.setOperand(i, CI->getOperand(0));
8154 // If we are using a wider index than needed for this platform, shrink it
8155 // to what we need. If the incoming value needs a cast instruction,
8156 // insert it. This explicit cast can make subsequent optimizations more
8158 Value *Op = GEP.getOperand(i);
8159 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
8160 if (Constant *C = dyn_cast<Constant>(Op)) {
8161 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
8164 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8166 GEP.setOperand(i, Op);
8171 if (MadeChange) return &GEP;
8173 // If this GEP instruction doesn't move the pointer, and if the input operand
8174 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
8175 // real input to the dest type.
8176 if (AllZeroIndices && isa<BitCastInst>(GEP.getOperand(0)))
8177 return new BitCastInst(cast<BitCastInst>(GEP.getOperand(0))->getOperand(0),
8180 // Combine Indices - If the source pointer to this getelementptr instruction
8181 // is a getelementptr instruction, combine the indices of the two
8182 // getelementptr instructions into a single instruction.
8184 SmallVector<Value*, 8> SrcGEPOperands;
8185 if (User *Src = dyn_castGetElementPtr(PtrOp))
8186 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
8188 if (!SrcGEPOperands.empty()) {
8189 // Note that if our source is a gep chain itself that we wait for that
8190 // chain to be resolved before we perform this transformation. This
8191 // avoids us creating a TON of code in some cases.
8193 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8194 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8195 return 0; // Wait until our source is folded to completion.
8197 SmallVector<Value*, 8> Indices;
8199 // Find out whether the last index in the source GEP is a sequential idx.
8200 bool EndsWithSequential = false;
8201 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8202 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
8203 EndsWithSequential = !isa<StructType>(*I);
8205 // Can we combine the two pointer arithmetics offsets?
8206 if (EndsWithSequential) {
8207 // Replace: gep (gep %P, long B), long A, ...
8208 // With: T = long A+B; gep %P, T, ...
8210 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
8211 if (SO1 == Constant::getNullValue(SO1->getType())) {
8213 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8216 // If they aren't the same type, convert both to an integer of the
8217 // target's pointer size.
8218 if (SO1->getType() != GO1->getType()) {
8219 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
8220 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
8221 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
8222 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
8224 unsigned PS = TD->getPointerSize();
8225 if (TD->getTypeSize(SO1->getType()) == PS) {
8226 // Convert GO1 to SO1's type.
8227 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
8229 } else if (TD->getTypeSize(GO1->getType()) == PS) {
8230 // Convert SO1 to GO1's type.
8231 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
8233 const Type *PT = TD->getIntPtrType();
8234 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8235 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
8239 if (isa<Constant>(SO1) && isa<Constant>(GO1))
8240 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8242 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8243 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
8247 // Recycle the GEP we already have if possible.
8248 if (SrcGEPOperands.size() == 2) {
8249 GEP.setOperand(0, SrcGEPOperands[0]);
8250 GEP.setOperand(1, Sum);
8253 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8254 SrcGEPOperands.end()-1);
8255 Indices.push_back(Sum);
8256 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8258 } else if (isa<Constant>(*GEP.idx_begin()) &&
8259 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
8260 SrcGEPOperands.size() != 1) {
8261 // Otherwise we can do the fold if the first index of the GEP is a zero
8262 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8263 SrcGEPOperands.end());
8264 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8267 if (!Indices.empty())
8268 return new GetElementPtrInst(SrcGEPOperands[0], &Indices[0],
8269 Indices.size(), GEP.getName());
8271 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
8272 // GEP of global variable. If all of the indices for this GEP are
8273 // constants, we can promote this to a constexpr instead of an instruction.
8275 // Scan for nonconstants...
8276 SmallVector<Constant*, 8> Indices;
8277 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8278 for (; I != E && isa<Constant>(*I); ++I)
8279 Indices.push_back(cast<Constant>(*I));
8281 if (I == E) { // If they are all constants...
8282 Constant *CE = ConstantExpr::getGetElementPtr(GV,
8283 &Indices[0],Indices.size());
8285 // Replace all uses of the GEP with the new constexpr...
8286 return ReplaceInstUsesWith(GEP, CE);
8288 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
8289 if (!isa<PointerType>(X->getType())) {
8290 // Not interesting. Source pointer must be a cast from pointer.
8291 } else if (HasZeroPointerIndex) {
8292 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8293 // into : GEP [10 x ubyte]* X, long 0, ...
8295 // This occurs when the program declares an array extern like "int X[];"
8297 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8298 const PointerType *XTy = cast<PointerType>(X->getType());
8299 if (const ArrayType *XATy =
8300 dyn_cast<ArrayType>(XTy->getElementType()))
8301 if (const ArrayType *CATy =
8302 dyn_cast<ArrayType>(CPTy->getElementType()))
8303 if (CATy->getElementType() == XATy->getElementType()) {
8304 // At this point, we know that the cast source type is a pointer
8305 // to an array of the same type as the destination pointer
8306 // array. Because the array type is never stepped over (there
8307 // is a leading zero) we can fold the cast into this GEP.
8308 GEP.setOperand(0, X);
8311 } else if (GEP.getNumOperands() == 2) {
8312 // Transform things like:
8313 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8314 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
8315 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8316 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8317 if (isa<ArrayType>(SrcElTy) &&
8318 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8319 TD->getTypeSize(ResElTy)) {
8320 Value *V = InsertNewInstBefore(
8321 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
8322 GEP.getOperand(1), GEP.getName()), GEP);
8323 // V and GEP are both pointer types --> BitCast
8324 return new BitCastInst(V, GEP.getType());
8327 // Transform things like:
8328 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8329 // (where tmp = 8*tmp2) into:
8330 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8332 if (isa<ArrayType>(SrcElTy) &&
8333 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
8334 uint64_t ArrayEltSize =
8335 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8337 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
8338 // allow either a mul, shift, or constant here.
8340 ConstantInt *Scale = 0;
8341 if (ArrayEltSize == 1) {
8342 NewIdx = GEP.getOperand(1);
8343 Scale = ConstantInt::get(NewIdx->getType(), 1);
8344 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
8345 NewIdx = ConstantInt::get(CI->getType(), 1);
8347 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8348 if (Inst->getOpcode() == Instruction::Shl &&
8349 isa<ConstantInt>(Inst->getOperand(1))) {
8350 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
8351 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
8352 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
8353 NewIdx = Inst->getOperand(0);
8354 } else if (Inst->getOpcode() == Instruction::Mul &&
8355 isa<ConstantInt>(Inst->getOperand(1))) {
8356 Scale = cast<ConstantInt>(Inst->getOperand(1));
8357 NewIdx = Inst->getOperand(0);
8361 // If the index will be to exactly the right offset with the scale taken
8362 // out, perform the transformation.
8363 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
8364 if (isa<ConstantInt>(Scale))
8365 Scale = ConstantInt::get(Scale->getType(),
8366 Scale->getZExtValue() / ArrayEltSize);
8367 if (Scale->getZExtValue() != 1) {
8368 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8370 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8371 NewIdx = InsertNewInstBefore(Sc, GEP);
8374 // Insert the new GEP instruction.
8375 Instruction *NewGEP =
8376 new GetElementPtrInst(X, Constant::getNullValue(Type::Int32Ty),
8377 NewIdx, GEP.getName());
8378 NewGEP = InsertNewInstBefore(NewGEP, GEP);
8379 // The NewGEP must be pointer typed, so must the old one -> BitCast
8380 return new BitCastInst(NewGEP, GEP.getType());
8389 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8390 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8391 if (AI.isArrayAllocation()) // Check C != 1
8392 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8394 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
8395 AllocationInst *New = 0;
8397 // Create and insert the replacement instruction...
8398 if (isa<MallocInst>(AI))
8399 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
8401 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
8402 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
8405 InsertNewInstBefore(New, AI);
8407 // Scan to the end of the allocation instructions, to skip over a block of
8408 // allocas if possible...
8410 BasicBlock::iterator It = New;
8411 while (isa<AllocationInst>(*It)) ++It;
8413 // Now that I is pointing to the first non-allocation-inst in the block,
8414 // insert our getelementptr instruction...
8416 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
8417 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
8418 New->getName()+".sub", It);
8420 // Now make everything use the getelementptr instead of the original
8422 return ReplaceInstUsesWith(AI, V);
8423 } else if (isa<UndefValue>(AI.getArraySize())) {
8424 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8427 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8428 // Note that we only do this for alloca's, because malloc should allocate and
8429 // return a unique pointer, even for a zero byte allocation.
8430 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
8431 TD->getTypeSize(AI.getAllocatedType()) == 0)
8432 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8437 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8438 Value *Op = FI.getOperand(0);
8440 // free undef -> unreachable.
8441 if (isa<UndefValue>(Op)) {
8442 // Insert a new store to null because we cannot modify the CFG here.
8443 new StoreInst(ConstantInt::getTrue(),
8444 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
8445 return EraseInstFromFunction(FI);
8448 // If we have 'free null' delete the instruction. This can happen in stl code
8449 // when lots of inlining happens.
8450 if (isa<ConstantPointerNull>(Op))
8451 return EraseInstFromFunction(FI);
8453 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8454 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
8455 FI.setOperand(0, CI->getOperand(0));
8459 // Change free (gep X, 0,0,0,0) into free(X)
8460 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
8461 if (GEPI->hasAllZeroIndices()) {
8462 AddToWorkList(GEPI);
8463 FI.setOperand(0, GEPI->getOperand(0));
8468 // Change free(malloc) into nothing, if the malloc has a single use.
8469 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
8470 if (MI->hasOneUse()) {
8471 EraseInstFromFunction(FI);
8472 return EraseInstFromFunction(*MI);
8479 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
8480 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8481 User *CI = cast<User>(LI.getOperand(0));
8482 Value *CastOp = CI->getOperand(0);
8484 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8485 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8486 const Type *SrcPTy = SrcTy->getElementType();
8488 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
8489 isa<VectorType>(DestPTy)) {
8490 // If the source is an array, the code below will not succeed. Check to
8491 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8493 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8494 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8495 if (ASrcTy->getNumElements() != 0) {
8497 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8498 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
8499 SrcTy = cast<PointerType>(CastOp->getType());
8500 SrcPTy = SrcTy->getElementType();
8503 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
8504 isa<VectorType>(SrcPTy)) &&
8505 // Do not allow turning this into a load of an integer, which is then
8506 // casted to a pointer, this pessimizes pointer analysis a lot.
8507 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
8508 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8509 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
8511 // Okay, we are casting from one integer or pointer type to another of
8512 // the same size. Instead of casting the pointer before the load, cast
8513 // the result of the loaded value.
8514 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8516 LI.isVolatile()),LI);
8517 // Now cast the result of the load.
8518 return new BitCastInst(NewLoad, LI.getType());
8525 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
8526 /// from this value cannot trap. If it is not obviously safe to load from the
8527 /// specified pointer, we do a quick local scan of the basic block containing
8528 /// ScanFrom, to determine if the address is already accessed.
8529 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8530 // If it is an alloca or global variable, it is always safe to load from.
8531 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8533 // Otherwise, be a little bit agressive by scanning the local block where we
8534 // want to check to see if the pointer is already being loaded or stored
8535 // from/to. If so, the previous load or store would have already trapped,
8536 // so there is no harm doing an extra load (also, CSE will later eliminate
8537 // the load entirely).
8538 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8543 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8544 if (LI->getOperand(0) == V) return true;
8545 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8546 if (SI->getOperand(1) == V) return true;
8552 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8553 Value *Op = LI.getOperand(0);
8555 // load (cast X) --> cast (load X) iff safe
8556 if (isa<CastInst>(Op))
8557 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8560 // None of the following transforms are legal for volatile loads.
8561 if (LI.isVolatile()) return 0;
8563 if (&LI.getParent()->front() != &LI) {
8564 BasicBlock::iterator BBI = &LI; --BBI;
8565 // If the instruction immediately before this is a store to the same
8566 // address, do a simple form of store->load forwarding.
8567 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8568 if (SI->getOperand(1) == LI.getOperand(0))
8569 return ReplaceInstUsesWith(LI, SI->getOperand(0));
8570 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8571 if (LIB->getOperand(0) == LI.getOperand(0))
8572 return ReplaceInstUsesWith(LI, LIB);
8575 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8576 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
8577 isa<UndefValue>(GEPI->getOperand(0))) {
8578 // Insert a new store to null instruction before the load to indicate
8579 // that this code is not reachable. We do this instead of inserting
8580 // an unreachable instruction directly because we cannot modify the
8582 new StoreInst(UndefValue::get(LI.getType()),
8583 Constant::getNullValue(Op->getType()), &LI);
8584 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8587 if (Constant *C = dyn_cast<Constant>(Op)) {
8588 // load null/undef -> undef
8589 if ((C->isNullValue() || isa<UndefValue>(C))) {
8590 // Insert a new store to null instruction before the load to indicate that
8591 // this code is not reachable. We do this instead of inserting an
8592 // unreachable instruction directly because we cannot modify the CFG.
8593 new StoreInst(UndefValue::get(LI.getType()),
8594 Constant::getNullValue(Op->getType()), &LI);
8595 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8598 // Instcombine load (constant global) into the value loaded.
8599 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
8600 if (GV->isConstant() && !GV->isDeclaration())
8601 return ReplaceInstUsesWith(LI, GV->getInitializer());
8603 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
8604 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
8605 if (CE->getOpcode() == Instruction::GetElementPtr) {
8606 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
8607 if (GV->isConstant() && !GV->isDeclaration())
8609 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
8610 return ReplaceInstUsesWith(LI, V);
8611 if (CE->getOperand(0)->isNullValue()) {
8612 // Insert a new store to null instruction before the load to indicate
8613 // that this code is not reachable. We do this instead of inserting
8614 // an unreachable instruction directly because we cannot modify the
8616 new StoreInst(UndefValue::get(LI.getType()),
8617 Constant::getNullValue(Op->getType()), &LI);
8618 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8621 } else if (CE->isCast()) {
8622 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8627 if (Op->hasOneUse()) {
8628 // Change select and PHI nodes to select values instead of addresses: this
8629 // helps alias analysis out a lot, allows many others simplifications, and
8630 // exposes redundancy in the code.
8632 // Note that we cannot do the transformation unless we know that the
8633 // introduced loads cannot trap! Something like this is valid as long as
8634 // the condition is always false: load (select bool %C, int* null, int* %G),
8635 // but it would not be valid if we transformed it to load from null
8638 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
8639 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
8640 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
8641 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
8642 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
8643 SI->getOperand(1)->getName()+".val"), LI);
8644 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
8645 SI->getOperand(2)->getName()+".val"), LI);
8646 return new SelectInst(SI->getCondition(), V1, V2);
8649 // load (select (cond, null, P)) -> load P
8650 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
8651 if (C->isNullValue()) {
8652 LI.setOperand(0, SI->getOperand(2));
8656 // load (select (cond, P, null)) -> load P
8657 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
8658 if (C->isNullValue()) {
8659 LI.setOperand(0, SI->getOperand(1));
8667 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
8669 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
8670 User *CI = cast<User>(SI.getOperand(1));
8671 Value *CastOp = CI->getOperand(0);
8673 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8674 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8675 const Type *SrcPTy = SrcTy->getElementType();
8677 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
8678 // If the source is an array, the code below will not succeed. Check to
8679 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8681 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8682 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8683 if (ASrcTy->getNumElements() != 0) {
8685 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8686 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
8687 SrcTy = cast<PointerType>(CastOp->getType());
8688 SrcPTy = SrcTy->getElementType();
8691 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
8692 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8693 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
8695 // Okay, we are casting from one integer or pointer type to another of
8696 // the same size. Instead of casting the pointer before
8697 // the store, cast the value to be stored.
8699 Value *SIOp0 = SI.getOperand(0);
8700 Instruction::CastOps opcode = Instruction::BitCast;
8701 const Type* CastSrcTy = SIOp0->getType();
8702 const Type* CastDstTy = SrcPTy;
8703 if (isa<PointerType>(CastDstTy)) {
8704 if (CastSrcTy->isInteger())
8705 opcode = Instruction::IntToPtr;
8706 } else if (isa<IntegerType>(CastDstTy)) {
8707 if (isa<PointerType>(SIOp0->getType()))
8708 opcode = Instruction::PtrToInt;
8710 if (Constant *C = dyn_cast<Constant>(SIOp0))
8711 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
8713 NewCast = IC.InsertNewInstBefore(
8714 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
8716 return new StoreInst(NewCast, CastOp);
8723 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
8724 Value *Val = SI.getOperand(0);
8725 Value *Ptr = SI.getOperand(1);
8727 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
8728 EraseInstFromFunction(SI);
8733 // If the RHS is an alloca with a single use, zapify the store, making the
8735 if (Ptr->hasOneUse()) {
8736 if (isa<AllocaInst>(Ptr)) {
8737 EraseInstFromFunction(SI);
8742 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
8743 if (isa<AllocaInst>(GEP->getOperand(0)) &&
8744 GEP->getOperand(0)->hasOneUse()) {
8745 EraseInstFromFunction(SI);
8751 // Do really simple DSE, to catch cases where there are several consequtive
8752 // stores to the same location, separated by a few arithmetic operations. This
8753 // situation often occurs with bitfield accesses.
8754 BasicBlock::iterator BBI = &SI;
8755 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
8759 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
8760 // Prev store isn't volatile, and stores to the same location?
8761 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
8764 EraseInstFromFunction(*PrevSI);
8770 // If this is a load, we have to stop. However, if the loaded value is from
8771 // the pointer we're loading and is producing the pointer we're storing,
8772 // then *this* store is dead (X = load P; store X -> P).
8773 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8774 if (LI == Val && LI->getOperand(0) == Ptr) {
8775 EraseInstFromFunction(SI);
8779 // Otherwise, this is a load from some other location. Stores before it
8784 // Don't skip over loads or things that can modify memory.
8785 if (BBI->mayWriteToMemory())
8790 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
8792 // store X, null -> turns into 'unreachable' in SimplifyCFG
8793 if (isa<ConstantPointerNull>(Ptr)) {
8794 if (!isa<UndefValue>(Val)) {
8795 SI.setOperand(0, UndefValue::get(Val->getType()));
8796 if (Instruction *U = dyn_cast<Instruction>(Val))
8797 AddToWorkList(U); // Dropped a use.
8800 return 0; // Do not modify these!
8803 // store undef, Ptr -> noop
8804 if (isa<UndefValue>(Val)) {
8805 EraseInstFromFunction(SI);
8810 // If the pointer destination is a cast, see if we can fold the cast into the
8812 if (isa<CastInst>(Ptr))
8813 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8815 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
8817 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
8821 // If this store is the last instruction in the basic block, and if the block
8822 // ends with an unconditional branch, try to move it to the successor block.
8824 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
8825 if (BI->isUnconditional())
8826 if (SimplifyStoreAtEndOfBlock(SI))
8827 return 0; // xform done!
8832 /// SimplifyStoreAtEndOfBlock - Turn things like:
8833 /// if () { *P = v1; } else { *P = v2 }
8834 /// into a phi node with a store in the successor.
8836 /// Simplify things like:
8837 /// *P = v1; if () { *P = v2; }
8838 /// into a phi node with a store in the successor.
8840 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
8841 BasicBlock *StoreBB = SI.getParent();
8843 // Check to see if the successor block has exactly two incoming edges. If
8844 // so, see if the other predecessor contains a store to the same location.
8845 // if so, insert a PHI node (if needed) and move the stores down.
8846 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
8848 // Determine whether Dest has exactly two predecessors and, if so, compute
8849 // the other predecessor.
8850 pred_iterator PI = pred_begin(DestBB);
8851 BasicBlock *OtherBB = 0;
8855 if (PI == pred_end(DestBB))
8858 if (*PI != StoreBB) {
8863 if (++PI != pred_end(DestBB))
8867 // Verify that the other block ends in a branch and is not otherwise empty.
8868 BasicBlock::iterator BBI = OtherBB->getTerminator();
8869 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
8870 if (!OtherBr || BBI == OtherBB->begin())
8873 // If the other block ends in an unconditional branch, check for the 'if then
8874 // else' case. there is an instruction before the branch.
8875 StoreInst *OtherStore = 0;
8876 if (OtherBr->isUnconditional()) {
8877 // If this isn't a store, or isn't a store to the same location, bail out.
8879 OtherStore = dyn_cast<StoreInst>(BBI);
8880 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
8883 // Otherwise, the other block ended with a conditional branch. If one of the
8884 // destinations is StoreBB, then we have the if/then case.
8885 if (OtherBr->getSuccessor(0) != StoreBB &&
8886 OtherBr->getSuccessor(1) != StoreBB)
8889 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
8890 // if/then triangle. See if there is a store to the same ptr as SI that lives
8893 // Check to see if we find the matching store.
8894 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
8895 if (OtherStore->getOperand(1) != SI.getOperand(1))
8899 // If we find something that may be using the stored value, or if we run out
8900 // of instructions, we can't do the xform.
8901 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
8902 BBI == OtherBB->begin())
8906 // In order to eliminate the store in OtherBr, we have to
8907 // make sure nothing reads the stored value in StoreBB.
8908 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
8909 // FIXME: This should really be AA driven.
8910 if (isa<LoadInst>(I) || I->mayWriteToMemory())
8915 // Insert a PHI node now if we need it.
8916 Value *MergedVal = OtherStore->getOperand(0);
8917 if (MergedVal != SI.getOperand(0)) {
8918 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
8919 PN->reserveOperandSpace(2);
8920 PN->addIncoming(SI.getOperand(0), SI.getParent());
8921 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
8922 MergedVal = InsertNewInstBefore(PN, DestBB->front());
8925 // Advance to a place where it is safe to insert the new store and
8927 BBI = DestBB->begin();
8928 while (isa<PHINode>(BBI)) ++BBI;
8929 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
8930 OtherStore->isVolatile()), *BBI);
8932 // Nuke the old stores.
8933 EraseInstFromFunction(SI);
8934 EraseInstFromFunction(*OtherStore);
8940 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
8941 // Change br (not X), label True, label False to: br X, label False, True
8943 BasicBlock *TrueDest;
8944 BasicBlock *FalseDest;
8945 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
8946 !isa<Constant>(X)) {
8947 // Swap Destinations and condition...
8949 BI.setSuccessor(0, FalseDest);
8950 BI.setSuccessor(1, TrueDest);
8954 // Cannonicalize fcmp_one -> fcmp_oeq
8955 FCmpInst::Predicate FPred; Value *Y;
8956 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
8957 TrueDest, FalseDest)))
8958 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
8959 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
8960 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
8961 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
8962 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
8963 NewSCC->takeName(I);
8964 // Swap Destinations and condition...
8965 BI.setCondition(NewSCC);
8966 BI.setSuccessor(0, FalseDest);
8967 BI.setSuccessor(1, TrueDest);
8968 RemoveFromWorkList(I);
8969 I->eraseFromParent();
8970 AddToWorkList(NewSCC);
8974 // Cannonicalize icmp_ne -> icmp_eq
8975 ICmpInst::Predicate IPred;
8976 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
8977 TrueDest, FalseDest)))
8978 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
8979 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
8980 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
8981 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
8982 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
8983 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
8984 NewSCC->takeName(I);
8985 // Swap Destinations and condition...
8986 BI.setCondition(NewSCC);
8987 BI.setSuccessor(0, FalseDest);
8988 BI.setSuccessor(1, TrueDest);
8989 RemoveFromWorkList(I);
8990 I->eraseFromParent();;
8991 AddToWorkList(NewSCC);
8998 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
8999 Value *Cond = SI.getCondition();
9000 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
9001 if (I->getOpcode() == Instruction::Add)
9002 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
9003 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
9004 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
9005 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
9007 SI.setOperand(0, I->getOperand(0));
9015 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
9016 /// is to leave as a vector operation.
9017 static bool CheapToScalarize(Value *V, bool isConstant) {
9018 if (isa<ConstantAggregateZero>(V))
9020 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
9021 if (isConstant) return true;
9022 // If all elts are the same, we can extract.
9023 Constant *Op0 = C->getOperand(0);
9024 for (unsigned i = 1; i < C->getNumOperands(); ++i)
9025 if (C->getOperand(i) != Op0)
9029 Instruction *I = dyn_cast<Instruction>(V);
9030 if (!I) return false;
9032 // Insert element gets simplified to the inserted element or is deleted if
9033 // this is constant idx extract element and its a constant idx insertelt.
9034 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
9035 isa<ConstantInt>(I->getOperand(2)))
9037 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
9039 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
9040 if (BO->hasOneUse() &&
9041 (CheapToScalarize(BO->getOperand(0), isConstant) ||
9042 CheapToScalarize(BO->getOperand(1), isConstant)))
9044 if (CmpInst *CI = dyn_cast<CmpInst>(I))
9045 if (CI->hasOneUse() &&
9046 (CheapToScalarize(CI->getOperand(0), isConstant) ||
9047 CheapToScalarize(CI->getOperand(1), isConstant)))
9053 /// Read and decode a shufflevector mask.
9055 /// It turns undef elements into values that are larger than the number of
9056 /// elements in the input.
9057 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
9058 unsigned NElts = SVI->getType()->getNumElements();
9059 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
9060 return std::vector<unsigned>(NElts, 0);
9061 if (isa<UndefValue>(SVI->getOperand(2)))
9062 return std::vector<unsigned>(NElts, 2*NElts);
9064 std::vector<unsigned> Result;
9065 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
9066 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
9067 if (isa<UndefValue>(CP->getOperand(i)))
9068 Result.push_back(NElts*2); // undef -> 8
9070 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
9074 /// FindScalarElement - Given a vector and an element number, see if the scalar
9075 /// value is already around as a register, for example if it were inserted then
9076 /// extracted from the vector.
9077 static Value *FindScalarElement(Value *V, unsigned EltNo) {
9078 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
9079 const VectorType *PTy = cast<VectorType>(V->getType());
9080 unsigned Width = PTy->getNumElements();
9081 if (EltNo >= Width) // Out of range access.
9082 return UndefValue::get(PTy->getElementType());
9084 if (isa<UndefValue>(V))
9085 return UndefValue::get(PTy->getElementType());
9086 else if (isa<ConstantAggregateZero>(V))
9087 return Constant::getNullValue(PTy->getElementType());
9088 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
9089 return CP->getOperand(EltNo);
9090 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
9091 // If this is an insert to a variable element, we don't know what it is.
9092 if (!isa<ConstantInt>(III->getOperand(2)))
9094 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
9096 // If this is an insert to the element we are looking for, return the
9099 return III->getOperand(1);
9101 // Otherwise, the insertelement doesn't modify the value, recurse on its
9103 return FindScalarElement(III->getOperand(0), EltNo);
9104 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
9105 unsigned InEl = getShuffleMask(SVI)[EltNo];
9107 return FindScalarElement(SVI->getOperand(0), InEl);
9108 else if (InEl < Width*2)
9109 return FindScalarElement(SVI->getOperand(1), InEl - Width);
9111 return UndefValue::get(PTy->getElementType());
9114 // Otherwise, we don't know.
9118 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
9120 // If packed val is undef, replace extract with scalar undef.
9121 if (isa<UndefValue>(EI.getOperand(0)))
9122 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9124 // If packed val is constant 0, replace extract with scalar 0.
9125 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
9126 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
9128 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
9129 // If packed val is constant with uniform operands, replace EI
9130 // with that operand
9131 Constant *op0 = C->getOperand(0);
9132 for (unsigned i = 1; i < C->getNumOperands(); ++i)
9133 if (C->getOperand(i) != op0) {
9138 return ReplaceInstUsesWith(EI, op0);
9141 // If extracting a specified index from the vector, see if we can recursively
9142 // find a previously computed scalar that was inserted into the vector.
9143 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9144 unsigned IndexVal = IdxC->getZExtValue();
9145 unsigned VectorWidth =
9146 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
9148 // If this is extracting an invalid index, turn this into undef, to avoid
9149 // crashing the code below.
9150 if (IndexVal >= VectorWidth)
9151 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9153 // This instruction only demands the single element from the input vector.
9154 // If the input vector has a single use, simplify it based on this use
9156 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
9158 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
9161 EI.setOperand(0, V);
9166 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
9167 return ReplaceInstUsesWith(EI, Elt);
9169 // If the this extractelement is directly using a bitcast from a vector of
9170 // the same number of elements, see if we can find the source element from
9171 // it. In this case, we will end up needing to bitcast the scalars.
9172 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
9173 if (const VectorType *VT =
9174 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
9175 if (VT->getNumElements() == VectorWidth)
9176 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
9177 return new BitCastInst(Elt, EI.getType());
9181 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
9182 if (I->hasOneUse()) {
9183 // Push extractelement into predecessor operation if legal and
9184 // profitable to do so
9185 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
9186 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
9187 if (CheapToScalarize(BO, isConstantElt)) {
9188 ExtractElementInst *newEI0 =
9189 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
9190 EI.getName()+".lhs");
9191 ExtractElementInst *newEI1 =
9192 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
9193 EI.getName()+".rhs");
9194 InsertNewInstBefore(newEI0, EI);
9195 InsertNewInstBefore(newEI1, EI);
9196 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
9198 } else if (isa<LoadInst>(I)) {
9199 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
9200 PointerType::get(EI.getType()), EI);
9201 GetElementPtrInst *GEP =
9202 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
9203 InsertNewInstBefore(GEP, EI);
9204 return new LoadInst(GEP);
9207 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
9208 // Extracting the inserted element?
9209 if (IE->getOperand(2) == EI.getOperand(1))
9210 return ReplaceInstUsesWith(EI, IE->getOperand(1));
9211 // If the inserted and extracted elements are constants, they must not
9212 // be the same value, extract from the pre-inserted value instead.
9213 if (isa<Constant>(IE->getOperand(2)) &&
9214 isa<Constant>(EI.getOperand(1))) {
9215 AddUsesToWorkList(EI);
9216 EI.setOperand(0, IE->getOperand(0));
9219 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
9220 // If this is extracting an element from a shufflevector, figure out where
9221 // it came from and extract from the appropriate input element instead.
9222 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9223 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
9225 if (SrcIdx < SVI->getType()->getNumElements())
9226 Src = SVI->getOperand(0);
9227 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
9228 SrcIdx -= SVI->getType()->getNumElements();
9229 Src = SVI->getOperand(1);
9231 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9233 return new ExtractElementInst(Src, SrcIdx);
9240 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
9241 /// elements from either LHS or RHS, return the shuffle mask and true.
9242 /// Otherwise, return false.
9243 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
9244 std::vector<Constant*> &Mask) {
9245 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
9246 "Invalid CollectSingleShuffleElements");
9247 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
9249 if (isa<UndefValue>(V)) {
9250 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
9252 } else if (V == LHS) {
9253 for (unsigned i = 0; i != NumElts; ++i)
9254 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
9256 } else if (V == RHS) {
9257 for (unsigned i = 0; i != NumElts; ++i)
9258 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
9260 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9261 // If this is an insert of an extract from some other vector, include it.
9262 Value *VecOp = IEI->getOperand(0);
9263 Value *ScalarOp = IEI->getOperand(1);
9264 Value *IdxOp = IEI->getOperand(2);
9266 if (!isa<ConstantInt>(IdxOp))
9268 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9270 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
9271 // Okay, we can handle this if the vector we are insertinting into is
9273 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9274 // If so, update the mask to reflect the inserted undef.
9275 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
9278 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
9279 if (isa<ConstantInt>(EI->getOperand(1)) &&
9280 EI->getOperand(0)->getType() == V->getType()) {
9281 unsigned ExtractedIdx =
9282 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9284 // This must be extracting from either LHS or RHS.
9285 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
9286 // Okay, we can handle this if the vector we are insertinting into is
9288 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9289 // If so, update the mask to reflect the inserted value.
9290 if (EI->getOperand(0) == LHS) {
9291 Mask[InsertedIdx & (NumElts-1)] =
9292 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
9294 assert(EI->getOperand(0) == RHS);
9295 Mask[InsertedIdx & (NumElts-1)] =
9296 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
9305 // TODO: Handle shufflevector here!
9310 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9311 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
9312 /// that computes V and the LHS value of the shuffle.
9313 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
9315 assert(isa<VectorType>(V->getType()) &&
9316 (RHS == 0 || V->getType() == RHS->getType()) &&
9317 "Invalid shuffle!");
9318 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
9320 if (isa<UndefValue>(V)) {
9321 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
9323 } else if (isa<ConstantAggregateZero>(V)) {
9324 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
9326 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9327 // If this is an insert of an extract from some other vector, include it.
9328 Value *VecOp = IEI->getOperand(0);
9329 Value *ScalarOp = IEI->getOperand(1);
9330 Value *IdxOp = IEI->getOperand(2);
9332 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9333 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9334 EI->getOperand(0)->getType() == V->getType()) {
9335 unsigned ExtractedIdx =
9336 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9337 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9339 // Either the extracted from or inserted into vector must be RHSVec,
9340 // otherwise we'd end up with a shuffle of three inputs.
9341 if (EI->getOperand(0) == RHS || RHS == 0) {
9342 RHS = EI->getOperand(0);
9343 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
9344 Mask[InsertedIdx & (NumElts-1)] =
9345 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
9350 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
9351 // Everything but the extracted element is replaced with the RHS.
9352 for (unsigned i = 0; i != NumElts; ++i) {
9353 if (i != InsertedIdx)
9354 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
9359 // If this insertelement is a chain that comes from exactly these two
9360 // vectors, return the vector and the effective shuffle.
9361 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9362 return EI->getOperand(0);
9367 // TODO: Handle shufflevector here!
9369 // Otherwise, can't do anything fancy. Return an identity vector.
9370 for (unsigned i = 0; i != NumElts; ++i)
9371 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
9375 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9376 Value *VecOp = IE.getOperand(0);
9377 Value *ScalarOp = IE.getOperand(1);
9378 Value *IdxOp = IE.getOperand(2);
9380 // Inserting an undef or into an undefined place, remove this.
9381 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
9382 ReplaceInstUsesWith(IE, VecOp);
9384 // If the inserted element was extracted from some other vector, and if the
9385 // indexes are constant, try to turn this into a shufflevector operation.
9386 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9387 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9388 EI->getOperand(0)->getType() == IE.getType()) {
9389 unsigned NumVectorElts = IE.getType()->getNumElements();
9390 unsigned ExtractedIdx =
9391 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9392 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9394 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9395 return ReplaceInstUsesWith(IE, VecOp);
9397 if (InsertedIdx >= NumVectorElts) // Out of range insert.
9398 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9400 // If we are extracting a value from a vector, then inserting it right
9401 // back into the same place, just use the input vector.
9402 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9403 return ReplaceInstUsesWith(IE, VecOp);
9405 // We could theoretically do this for ANY input. However, doing so could
9406 // turn chains of insertelement instructions into a chain of shufflevector
9407 // instructions, and right now we do not merge shufflevectors. As such,
9408 // only do this in a situation where it is clear that there is benefit.
9409 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9410 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
9411 // the values of VecOp, except then one read from EIOp0.
9412 // Build a new shuffle mask.
9413 std::vector<Constant*> Mask;
9414 if (isa<UndefValue>(VecOp))
9415 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
9417 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
9418 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
9421 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
9422 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
9423 ConstantVector::get(Mask));
9426 // If this insertelement isn't used by some other insertelement, turn it
9427 // (and any insertelements it points to), into one big shuffle.
9428 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9429 std::vector<Constant*> Mask;
9431 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9432 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9433 // We now have a shuffle of LHS, RHS, Mask.
9434 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
9443 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9444 Value *LHS = SVI.getOperand(0);
9445 Value *RHS = SVI.getOperand(1);
9446 std::vector<unsigned> Mask = getShuffleMask(&SVI);
9448 bool MadeChange = false;
9450 // Undefined shuffle mask -> undefined value.
9451 if (isa<UndefValue>(SVI.getOperand(2)))
9452 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9454 // If we have shuffle(x, undef, mask) and any elements of mask refer to
9455 // the undef, change them to undefs.
9456 if (isa<UndefValue>(SVI.getOperand(1))) {
9457 // Scan to see if there are any references to the RHS. If so, replace them
9458 // with undef element refs and set MadeChange to true.
9459 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9460 if (Mask[i] >= e && Mask[i] != 2*e) {
9467 // Remap any references to RHS to use LHS.
9468 std::vector<Constant*> Elts;
9469 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9471 Elts.push_back(UndefValue::get(Type::Int32Ty));
9473 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9475 SVI.setOperand(2, ConstantVector::get(Elts));
9479 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9480 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9481 if (LHS == RHS || isa<UndefValue>(LHS)) {
9482 if (isa<UndefValue>(LHS) && LHS == RHS) {
9483 // shuffle(undef,undef,mask) -> undef.
9484 return ReplaceInstUsesWith(SVI, LHS);
9487 // Remap any references to RHS to use LHS.
9488 std::vector<Constant*> Elts;
9489 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9491 Elts.push_back(UndefValue::get(Type::Int32Ty));
9493 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9494 (Mask[i] < e && isa<UndefValue>(LHS)))
9495 Mask[i] = 2*e; // Turn into undef.
9497 Mask[i] &= (e-1); // Force to LHS.
9498 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9501 SVI.setOperand(0, SVI.getOperand(1));
9502 SVI.setOperand(1, UndefValue::get(RHS->getType()));
9503 SVI.setOperand(2, ConstantVector::get(Elts));
9504 LHS = SVI.getOperand(0);
9505 RHS = SVI.getOperand(1);
9509 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
9510 bool isLHSID = true, isRHSID = true;
9512 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9513 if (Mask[i] >= e*2) continue; // Ignore undef values.
9514 // Is this an identity shuffle of the LHS value?
9515 isLHSID &= (Mask[i] == i);
9517 // Is this an identity shuffle of the RHS value?
9518 isRHSID &= (Mask[i]-e == i);
9521 // Eliminate identity shuffles.
9522 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9523 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
9525 // If the LHS is a shufflevector itself, see if we can combine it with this
9526 // one without producing an unusual shuffle. Here we are really conservative:
9527 // we are absolutely afraid of producing a shuffle mask not in the input
9528 // program, because the code gen may not be smart enough to turn a merged
9529 // shuffle into two specific shuffles: it may produce worse code. As such,
9530 // we only merge two shuffles if the result is one of the two input shuffle
9531 // masks. In this case, merging the shuffles just removes one instruction,
9532 // which we know is safe. This is good for things like turning:
9533 // (splat(splat)) -> splat.
9534 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9535 if (isa<UndefValue>(RHS)) {
9536 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9538 std::vector<unsigned> NewMask;
9539 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9541 NewMask.push_back(2*e);
9543 NewMask.push_back(LHSMask[Mask[i]]);
9545 // If the result mask is equal to the src shuffle or this shuffle mask, do
9547 if (NewMask == LHSMask || NewMask == Mask) {
9548 std::vector<Constant*> Elts;
9549 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9550 if (NewMask[i] >= e*2) {
9551 Elts.push_back(UndefValue::get(Type::Int32Ty));
9553 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
9556 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9557 LHSSVI->getOperand(1),
9558 ConstantVector::get(Elts));
9563 return MadeChange ? &SVI : 0;
9569 /// TryToSinkInstruction - Try to move the specified instruction from its
9570 /// current block into the beginning of DestBlock, which can only happen if it's
9571 /// safe to move the instruction past all of the instructions between it and the
9572 /// end of its block.
9573 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
9574 assert(I->hasOneUse() && "Invariants didn't hold!");
9576 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
9577 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
9579 // Do not sink alloca instructions out of the entry block.
9580 if (isa<AllocaInst>(I) && I->getParent() ==
9581 &DestBlock->getParent()->getEntryBlock())
9584 // We can only sink load instructions if there is nothing between the load and
9585 // the end of block that could change the value.
9586 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9587 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
9589 if (Scan->mayWriteToMemory())
9593 BasicBlock::iterator InsertPos = DestBlock->begin();
9594 while (isa<PHINode>(InsertPos)) ++InsertPos;
9596 I->moveBefore(InsertPos);
9602 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
9603 /// all reachable code to the worklist.
9605 /// This has a couple of tricks to make the code faster and more powerful. In
9606 /// particular, we constant fold and DCE instructions as we go, to avoid adding
9607 /// them to the worklist (this significantly speeds up instcombine on code where
9608 /// many instructions are dead or constant). Additionally, if we find a branch
9609 /// whose condition is a known constant, we only visit the reachable successors.
9611 static void AddReachableCodeToWorklist(BasicBlock *BB,
9612 SmallPtrSet<BasicBlock*, 64> &Visited,
9614 const TargetData *TD) {
9615 std::vector<BasicBlock*> Worklist;
9616 Worklist.push_back(BB);
9618 while (!Worklist.empty()) {
9619 BB = Worklist.back();
9620 Worklist.pop_back();
9622 // We have now visited this block! If we've already been here, ignore it.
9623 if (!Visited.insert(BB)) continue;
9625 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
9626 Instruction *Inst = BBI++;
9628 // DCE instruction if trivially dead.
9629 if (isInstructionTriviallyDead(Inst)) {
9631 DOUT << "IC: DCE: " << *Inst;
9632 Inst->eraseFromParent();
9636 // ConstantProp instruction if trivially constant.
9637 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
9638 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
9639 Inst->replaceAllUsesWith(C);
9641 Inst->eraseFromParent();
9645 IC.AddToWorkList(Inst);
9648 // Recursively visit successors. If this is a branch or switch on a
9649 // constant, only visit the reachable successor.
9650 TerminatorInst *TI = BB->getTerminator();
9651 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
9652 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
9653 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
9654 Worklist.push_back(BI->getSuccessor(!CondVal));
9657 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
9658 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
9659 // See if this is an explicit destination.
9660 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
9661 if (SI->getCaseValue(i) == Cond) {
9662 Worklist.push_back(SI->getSuccessor(i));
9666 // Otherwise it is the default destination.
9667 Worklist.push_back(SI->getSuccessor(0));
9672 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
9673 Worklist.push_back(TI->getSuccessor(i));
9677 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
9678 bool Changed = false;
9679 TD = &getAnalysis<TargetData>();
9681 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
9682 << F.getNameStr() << "\n");
9685 // Do a depth-first traversal of the function, populate the worklist with
9686 // the reachable instructions. Ignore blocks that are not reachable. Keep
9687 // track of which blocks we visit.
9688 SmallPtrSet<BasicBlock*, 64> Visited;
9689 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
9691 // Do a quick scan over the function. If we find any blocks that are
9692 // unreachable, remove any instructions inside of them. This prevents
9693 // the instcombine code from having to deal with some bad special cases.
9694 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
9695 if (!Visited.count(BB)) {
9696 Instruction *Term = BB->getTerminator();
9697 while (Term != BB->begin()) { // Remove instrs bottom-up
9698 BasicBlock::iterator I = Term; --I;
9700 DOUT << "IC: DCE: " << *I;
9703 if (!I->use_empty())
9704 I->replaceAllUsesWith(UndefValue::get(I->getType()));
9705 I->eraseFromParent();
9710 while (!Worklist.empty()) {
9711 Instruction *I = RemoveOneFromWorkList();
9712 if (I == 0) continue; // skip null values.
9714 // Check to see if we can DCE the instruction.
9715 if (isInstructionTriviallyDead(I)) {
9716 // Add operands to the worklist.
9717 if (I->getNumOperands() < 4)
9718 AddUsesToWorkList(*I);
9721 DOUT << "IC: DCE: " << *I;
9723 I->eraseFromParent();
9724 RemoveFromWorkList(I);
9728 // Instruction isn't dead, see if we can constant propagate it.
9729 if (Constant *C = ConstantFoldInstruction(I, TD)) {
9730 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
9732 // Add operands to the worklist.
9733 AddUsesToWorkList(*I);
9734 ReplaceInstUsesWith(*I, C);
9737 I->eraseFromParent();
9738 RemoveFromWorkList(I);
9742 // See if we can trivially sink this instruction to a successor basic block.
9743 if (I->hasOneUse()) {
9744 BasicBlock *BB = I->getParent();
9745 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
9746 if (UserParent != BB) {
9747 bool UserIsSuccessor = false;
9748 // See if the user is one of our successors.
9749 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
9750 if (*SI == UserParent) {
9751 UserIsSuccessor = true;
9755 // If the user is one of our immediate successors, and if that successor
9756 // only has us as a predecessors (we'd have to split the critical edge
9757 // otherwise), we can keep going.
9758 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
9759 next(pred_begin(UserParent)) == pred_end(UserParent))
9760 // Okay, the CFG is simple enough, try to sink this instruction.
9761 Changed |= TryToSinkInstruction(I, UserParent);
9765 // Now that we have an instruction, try combining it to simplify it...
9769 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
9770 if (Instruction *Result = visit(*I)) {
9772 // Should we replace the old instruction with a new one?
9774 DOUT << "IC: Old = " << *I
9775 << " New = " << *Result;
9777 // Everything uses the new instruction now.
9778 I->replaceAllUsesWith(Result);
9780 // Push the new instruction and any users onto the worklist.
9781 AddToWorkList(Result);
9782 AddUsersToWorkList(*Result);
9784 // Move the name to the new instruction first.
9785 Result->takeName(I);
9787 // Insert the new instruction into the basic block...
9788 BasicBlock *InstParent = I->getParent();
9789 BasicBlock::iterator InsertPos = I;
9791 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
9792 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
9795 InstParent->getInstList().insert(InsertPos, Result);
9797 // Make sure that we reprocess all operands now that we reduced their
9799 AddUsesToWorkList(*I);
9801 // Instructions can end up on the worklist more than once. Make sure
9802 // we do not process an instruction that has been deleted.
9803 RemoveFromWorkList(I);
9805 // Erase the old instruction.
9806 InstParent->getInstList().erase(I);
9809 DOUT << "IC: Mod = " << OrigI
9813 // If the instruction was modified, it's possible that it is now dead.
9814 // if so, remove it.
9815 if (isInstructionTriviallyDead(I)) {
9816 // Make sure we process all operands now that we are reducing their
9818 AddUsesToWorkList(*I);
9820 // Instructions may end up in the worklist more than once. Erase all
9821 // occurrences of this instruction.
9822 RemoveFromWorkList(I);
9823 I->eraseFromParent();
9826 AddUsersToWorkList(*I);
9833 assert(WorklistMap.empty() && "Worklist empty, but map not?");
9838 bool InstCombiner::runOnFunction(Function &F) {
9839 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
9841 bool EverMadeChange = false;
9843 // Iterate while there is work to do.
9844 unsigned Iteration = 0;
9845 while (DoOneIteration(F, Iteration++))
9846 EverMadeChange = true;
9847 return EverMadeChange;
9850 FunctionPass *llvm::createInstructionCombiningPass() {
9851 return new InstCombiner();