1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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
12 // algebraic 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/ConstantRange.h"
48 #include "llvm/Support/Debug.h"
49 #include "llvm/Support/GetElementPtrTypeIterator.h"
50 #include "llvm/Support/InstVisitor.h"
51 #include "llvm/Support/MathExtras.h"
52 #include "llvm/Support/PatternMatch.h"
53 #include "llvm/Support/Compiler.h"
54 #include "llvm/ADT/DenseMap.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/SmallPtrSet.h"
57 #include "llvm/ADT/Statistic.h"
58 #include "llvm/ADT/STLExtras.h"
63 using namespace llvm::PatternMatch;
65 STATISTIC(NumCombined , "Number of insts combined");
66 STATISTIC(NumConstProp, "Number of constant folds");
67 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
68 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
69 STATISTIC(NumSunkInst , "Number of instructions sunk");
72 class VISIBILITY_HIDDEN InstCombiner
73 : public FunctionPass,
74 public InstVisitor<InstCombiner, Instruction*> {
75 // Worklist of all of the instructions that need to be simplified.
76 std::vector<Instruction*> Worklist;
77 DenseMap<Instruction*, unsigned> WorklistMap;
79 bool MustPreserveLCSSA;
81 static char ID; // Pass identification, replacement for typeid
82 InstCombiner() : FunctionPass((intptr_t)&ID) {}
84 /// AddToWorkList - Add the specified instruction to the worklist if it
85 /// isn't already in it.
86 void AddToWorkList(Instruction *I) {
87 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
88 Worklist.push_back(I);
91 // RemoveFromWorkList - remove I from the worklist if it exists.
92 void RemoveFromWorkList(Instruction *I) {
93 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
94 if (It == WorklistMap.end()) return; // Not in worklist.
96 // Don't bother moving everything down, just null out the slot.
97 Worklist[It->second] = 0;
99 WorklistMap.erase(It);
102 Instruction *RemoveOneFromWorkList() {
103 Instruction *I = Worklist.back();
105 WorklistMap.erase(I);
110 /// AddUsersToWorkList - When an instruction is simplified, add all users of
111 /// the instruction to the work lists because they might get more simplified
114 void AddUsersToWorkList(Value &I) {
115 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
117 AddToWorkList(cast<Instruction>(*UI));
120 /// AddUsesToWorkList - When an instruction is simplified, add operands to
121 /// the work lists because they might get more simplified now.
123 void AddUsesToWorkList(Instruction &I) {
124 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
125 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
129 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
130 /// dead. Add all of its operands to the worklist, turning them into
131 /// undef's to reduce the number of uses of those instructions.
133 /// Return the specified operand before it is turned into an undef.
135 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
136 Value *R = I.getOperand(op);
138 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
139 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
141 // Set the operand to undef to drop the use.
142 I.setOperand(i, UndefValue::get(Op->getType()));
149 virtual bool runOnFunction(Function &F);
151 bool DoOneIteration(Function &F, unsigned ItNum);
153 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
154 AU.addRequired<TargetData>();
155 AU.addPreservedID(LCSSAID);
156 AU.setPreservesCFG();
159 TargetData &getTargetData() const { return *TD; }
161 // Visitation implementation - Implement instruction combining for different
162 // instruction types. The semantics are as follows:
164 // null - No change was made
165 // I - Change was made, I is still valid, I may be dead though
166 // otherwise - Change was made, replace I with returned instruction
168 Instruction *visitAdd(BinaryOperator &I);
169 Instruction *visitSub(BinaryOperator &I);
170 Instruction *visitMul(BinaryOperator &I);
171 Instruction *visitURem(BinaryOperator &I);
172 Instruction *visitSRem(BinaryOperator &I);
173 Instruction *visitFRem(BinaryOperator &I);
174 Instruction *commonRemTransforms(BinaryOperator &I);
175 Instruction *commonIRemTransforms(BinaryOperator &I);
176 Instruction *commonDivTransforms(BinaryOperator &I);
177 Instruction *commonIDivTransforms(BinaryOperator &I);
178 Instruction *visitUDiv(BinaryOperator &I);
179 Instruction *visitSDiv(BinaryOperator &I);
180 Instruction *visitFDiv(BinaryOperator &I);
181 Instruction *visitAnd(BinaryOperator &I);
182 Instruction *visitOr (BinaryOperator &I);
183 Instruction *visitXor(BinaryOperator &I);
184 Instruction *visitShl(BinaryOperator &I);
185 Instruction *visitAShr(BinaryOperator &I);
186 Instruction *visitLShr(BinaryOperator &I);
187 Instruction *commonShiftTransforms(BinaryOperator &I);
188 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
190 Instruction *visitFCmpInst(FCmpInst &I);
191 Instruction *visitICmpInst(ICmpInst &I);
192 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
193 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
196 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
197 ConstantInt *DivRHS);
199 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
200 ICmpInst::Predicate Cond, Instruction &I);
201 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
203 Instruction *commonCastTransforms(CastInst &CI);
204 Instruction *commonIntCastTransforms(CastInst &CI);
205 Instruction *commonPointerCastTransforms(CastInst &CI);
206 Instruction *visitTrunc(TruncInst &CI);
207 Instruction *visitZExt(ZExtInst &CI);
208 Instruction *visitSExt(SExtInst &CI);
209 Instruction *visitFPTrunc(FPTruncInst &CI);
210 Instruction *visitFPExt(CastInst &CI);
211 Instruction *visitFPToUI(FPToUIInst &FI);
212 Instruction *visitFPToSI(FPToSIInst &FI);
213 Instruction *visitUIToFP(CastInst &CI);
214 Instruction *visitSIToFP(CastInst &CI);
215 Instruction *visitPtrToInt(CastInst &CI);
216 Instruction *visitIntToPtr(IntToPtrInst &CI);
217 Instruction *visitBitCast(BitCastInst &CI);
218 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
220 Instruction *visitSelectInst(SelectInst &CI);
221 Instruction *visitCallInst(CallInst &CI);
222 Instruction *visitInvokeInst(InvokeInst &II);
223 Instruction *visitPHINode(PHINode &PN);
224 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
225 Instruction *visitAllocationInst(AllocationInst &AI);
226 Instruction *visitFreeInst(FreeInst &FI);
227 Instruction *visitLoadInst(LoadInst &LI);
228 Instruction *visitStoreInst(StoreInst &SI);
229 Instruction *visitBranchInst(BranchInst &BI);
230 Instruction *visitSwitchInst(SwitchInst &SI);
231 Instruction *visitInsertElementInst(InsertElementInst &IE);
232 Instruction *visitExtractElementInst(ExtractElementInst &EI);
233 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
235 // visitInstruction - Specify what to return for unhandled instructions...
236 Instruction *visitInstruction(Instruction &I) { return 0; }
239 Instruction *visitCallSite(CallSite CS);
240 bool transformConstExprCastCall(CallSite CS);
241 Instruction *transformCallThroughTrampoline(CallSite CS);
242 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
243 bool DoXform = true);
244 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
247 // InsertNewInstBefore - insert an instruction New before instruction Old
248 // in the program. Add the new instruction to the worklist.
250 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
251 assert(New && New->getParent() == 0 &&
252 "New instruction already inserted into a basic block!");
253 BasicBlock *BB = Old.getParent();
254 BB->getInstList().insert(&Old, New); // Insert inst
259 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
260 /// This also adds the cast to the worklist. Finally, this returns the
262 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
264 if (V->getType() == Ty) return V;
266 if (Constant *CV = dyn_cast<Constant>(V))
267 return ConstantExpr::getCast(opc, CV, Ty);
269 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
274 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
275 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
279 // ReplaceInstUsesWith - This method is to be used when an instruction is
280 // found to be dead, replacable with another preexisting expression. Here
281 // we add all uses of I to the worklist, replace all uses of I with the new
282 // value, then return I, so that the inst combiner will know that I was
285 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
286 AddUsersToWorkList(I); // Add all modified instrs to worklist
288 I.replaceAllUsesWith(V);
291 // If we are replacing the instruction with itself, this must be in a
292 // segment of unreachable code, so just clobber the instruction.
293 I.replaceAllUsesWith(UndefValue::get(I.getType()));
298 // UpdateValueUsesWith - This method is to be used when an value is
299 // found to be replacable with another preexisting expression or was
300 // updated. Here we add all uses of I to the worklist, replace all uses of
301 // I with the new value (unless the instruction was just updated), then
302 // return true, so that the inst combiner will know that I was modified.
304 bool UpdateValueUsesWith(Value *Old, Value *New) {
305 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
307 Old->replaceAllUsesWith(New);
308 if (Instruction *I = dyn_cast<Instruction>(Old))
310 if (Instruction *I = dyn_cast<Instruction>(New))
315 // EraseInstFromFunction - When dealing with an instruction that has side
316 // effects or produces a void value, we can't rely on DCE to delete the
317 // instruction. Instead, visit methods should return the value returned by
319 Instruction *EraseInstFromFunction(Instruction &I) {
320 assert(I.use_empty() && "Cannot erase instruction that is used!");
321 AddUsesToWorkList(I);
322 RemoveFromWorkList(&I);
324 return 0; // Don't do anything with FI
328 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
329 /// InsertBefore instruction. This is specialized a bit to avoid inserting
330 /// casts that are known to not do anything...
332 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
333 Value *V, const Type *DestTy,
334 Instruction *InsertBefore);
336 /// SimplifyCommutative - This performs a few simplifications for
337 /// commutative operators.
338 bool SimplifyCommutative(BinaryOperator &I);
340 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
341 /// most-complex to least-complex order.
342 bool SimplifyCompare(CmpInst &I);
344 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
345 /// on the demanded bits.
346 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
347 APInt& KnownZero, APInt& KnownOne,
350 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
351 uint64_t &UndefElts, unsigned Depth = 0);
353 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
354 // PHI node as operand #0, see if we can fold the instruction into the PHI
355 // (which is only possible if all operands to the PHI are constants).
356 Instruction *FoldOpIntoPhi(Instruction &I);
358 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
359 // operator and they all are only used by the PHI, PHI together their
360 // inputs, and do the operation once, to the result of the PHI.
361 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
362 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
365 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
366 ConstantInt *AndRHS, BinaryOperator &TheAnd);
368 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
369 bool isSub, Instruction &I);
370 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
371 bool isSigned, bool Inside, Instruction &IB);
372 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
373 Instruction *MatchBSwap(BinaryOperator &I);
374 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
375 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
376 Instruction *SimplifyMemSet(MemSetInst *MI);
379 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
381 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
382 APInt& KnownOne, unsigned Depth = 0) const;
383 bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0);
384 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const;
385 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
387 int &NumCastsRemoved);
388 unsigned GetOrEnforceKnownAlignment(Value *V,
389 unsigned PrefAlign = 0);
393 char InstCombiner::ID = 0;
394 static RegisterPass<InstCombiner>
395 X("instcombine", "Combine redundant instructions");
397 // getComplexity: Assign a complexity or rank value to LLVM Values...
398 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
399 static unsigned getComplexity(Value *V) {
400 if (isa<Instruction>(V)) {
401 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
405 if (isa<Argument>(V)) return 3;
406 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
409 // isOnlyUse - Return true if this instruction will be deleted if we stop using
411 static bool isOnlyUse(Value *V) {
412 return V->hasOneUse() || isa<Constant>(V);
415 // getPromotedType - Return the specified type promoted as it would be to pass
416 // though a va_arg area...
417 static const Type *getPromotedType(const Type *Ty) {
418 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
419 if (ITy->getBitWidth() < 32)
420 return Type::Int32Ty;
425 /// getBitCastOperand - If the specified operand is a CastInst or a constant
426 /// expression bitcast, return the operand value, otherwise return null.
427 static Value *getBitCastOperand(Value *V) {
428 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
429 return I->getOperand(0);
430 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
431 if (CE->getOpcode() == Instruction::BitCast)
432 return CE->getOperand(0);
436 /// This function is a wrapper around CastInst::isEliminableCastPair. It
437 /// simply extracts arguments and returns what that function returns.
438 static Instruction::CastOps
439 isEliminableCastPair(
440 const CastInst *CI, ///< The first cast instruction
441 unsigned opcode, ///< The opcode of the second cast instruction
442 const Type *DstTy, ///< The target type for the second cast instruction
443 TargetData *TD ///< The target data for pointer size
446 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
447 const Type *MidTy = CI->getType(); // B from above
449 // Get the opcodes of the two Cast instructions
450 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
451 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
453 return Instruction::CastOps(
454 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
455 DstTy, TD->getIntPtrType()));
458 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
459 /// in any code being generated. It does not require codegen if V is simple
460 /// enough or if the cast can be folded into other casts.
461 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
462 const Type *Ty, TargetData *TD) {
463 if (V->getType() == Ty || isa<Constant>(V)) return false;
465 // If this is another cast that can be eliminated, it isn't codegen either.
466 if (const CastInst *CI = dyn_cast<CastInst>(V))
467 if (isEliminableCastPair(CI, opcode, Ty, TD))
472 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
473 /// InsertBefore instruction. This is specialized a bit to avoid inserting
474 /// casts that are known to not do anything...
476 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
477 Value *V, const Type *DestTy,
478 Instruction *InsertBefore) {
479 if (V->getType() == DestTy) return V;
480 if (Constant *C = dyn_cast<Constant>(V))
481 return ConstantExpr::getCast(opcode, C, DestTy);
483 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
486 // SimplifyCommutative - This performs a few simplifications for commutative
489 // 1. Order operands such that they are listed from right (least complex) to
490 // left (most complex). This puts constants before unary operators before
493 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
494 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
496 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
497 bool Changed = false;
498 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
499 Changed = !I.swapOperands();
501 if (!I.isAssociative()) return Changed;
502 Instruction::BinaryOps Opcode = I.getOpcode();
503 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
504 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
505 if (isa<Constant>(I.getOperand(1))) {
506 Constant *Folded = ConstantExpr::get(I.getOpcode(),
507 cast<Constant>(I.getOperand(1)),
508 cast<Constant>(Op->getOperand(1)));
509 I.setOperand(0, Op->getOperand(0));
510 I.setOperand(1, Folded);
512 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
513 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
514 isOnlyUse(Op) && isOnlyUse(Op1)) {
515 Constant *C1 = cast<Constant>(Op->getOperand(1));
516 Constant *C2 = cast<Constant>(Op1->getOperand(1));
518 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
519 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
520 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
524 I.setOperand(0, New);
525 I.setOperand(1, Folded);
532 /// SimplifyCompare - For a CmpInst this function just orders the operands
533 /// so that theyare listed from right (least complex) to left (most complex).
534 /// This puts constants before unary operators before binary operators.
535 bool InstCombiner::SimplifyCompare(CmpInst &I) {
536 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
539 // Compare instructions are not associative so there's nothing else we can do.
543 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
544 // if the LHS is a constant zero (which is the 'negate' form).
546 static inline Value *dyn_castNegVal(Value *V) {
547 if (BinaryOperator::isNeg(V))
548 return BinaryOperator::getNegArgument(V);
550 // Constants can be considered to be negated values if they can be folded.
551 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
552 return ConstantExpr::getNeg(C);
556 static inline Value *dyn_castNotVal(Value *V) {
557 if (BinaryOperator::isNot(V))
558 return BinaryOperator::getNotArgument(V);
560 // Constants can be considered to be not'ed values...
561 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
562 return ConstantInt::get(~C->getValue());
566 // dyn_castFoldableMul - If this value is a multiply that can be folded into
567 // other computations (because it has a constant operand), return the
568 // non-constant operand of the multiply, and set CST to point to the multiplier.
569 // Otherwise, return null.
571 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
572 if (V->hasOneUse() && V->getType()->isInteger())
573 if (Instruction *I = dyn_cast<Instruction>(V)) {
574 if (I->getOpcode() == Instruction::Mul)
575 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
576 return I->getOperand(0);
577 if (I->getOpcode() == Instruction::Shl)
578 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
579 // The multiplier is really 1 << CST.
580 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
581 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
582 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
583 return I->getOperand(0);
589 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
590 /// expression, return it.
591 static User *dyn_castGetElementPtr(Value *V) {
592 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
593 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
594 if (CE->getOpcode() == Instruction::GetElementPtr)
595 return cast<User>(V);
599 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
600 /// opcode value. Otherwise return UserOp1.
601 static unsigned getOpcode(Value *V) {
602 if (Instruction *I = dyn_cast<Instruction>(V))
603 return I->getOpcode();
604 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
605 return CE->getOpcode();
606 // Use UserOp1 to mean there's no opcode.
607 return Instruction::UserOp1;
610 /// AddOne - Add one to a ConstantInt
611 static ConstantInt *AddOne(ConstantInt *C) {
612 APInt Val(C->getValue());
613 return ConstantInt::get(++Val);
615 /// SubOne - Subtract one from a ConstantInt
616 static ConstantInt *SubOne(ConstantInt *C) {
617 APInt Val(C->getValue());
618 return ConstantInt::get(--Val);
620 /// Add - Add two ConstantInts together
621 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
622 return ConstantInt::get(C1->getValue() + C2->getValue());
624 /// And - Bitwise AND two ConstantInts together
625 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
626 return ConstantInt::get(C1->getValue() & C2->getValue());
628 /// Subtract - Subtract one ConstantInt from another
629 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
630 return ConstantInt::get(C1->getValue() - C2->getValue());
632 /// Multiply - Multiply two ConstantInts together
633 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
634 return ConstantInt::get(C1->getValue() * C2->getValue());
636 /// MultiplyOverflows - True if the multiply can not be expressed in an int
638 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
639 uint32_t W = C1->getBitWidth();
640 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
649 APInt MulExt = LHSExt * RHSExt;
652 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
653 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
654 return MulExt.slt(Min) || MulExt.sgt(Max);
656 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
659 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
660 /// known to be either zero or one and return them in the KnownZero/KnownOne
661 /// bit sets. This code only analyzes bits in Mask, in order to short-circuit
663 /// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
664 /// we cannot optimize based on the assumption that it is zero without changing
665 /// it to be an explicit zero. If we don't change it to zero, other code could
666 /// optimized based on the contradictory assumption that it is non-zero.
667 /// Because instcombine aggressively folds operations with undef args anyway,
668 /// this won't lose us code quality.
669 void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
670 APInt& KnownZero, APInt& KnownOne,
671 unsigned Depth) const {
672 assert(V && "No Value?");
673 assert(Depth <= 6 && "Limit Search Depth");
674 uint32_t BitWidth = Mask.getBitWidth();
675 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
676 "Not integer or pointer type!");
677 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
678 (!isa<IntegerType>(V->getType()) ||
679 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
680 KnownZero.getBitWidth() == BitWidth &&
681 KnownOne.getBitWidth() == BitWidth &&
682 "V, Mask, KnownOne and KnownZero should have same BitWidth");
684 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
685 // We know all of the bits for a constant!
686 KnownOne = CI->getValue() & Mask;
687 KnownZero = ~KnownOne & Mask;
690 // Null is all-zeros.
691 if (isa<ConstantPointerNull>(V)) {
696 // The address of an aligned GlobalValue has trailing zeros.
697 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
698 unsigned Align = GV->getAlignment();
699 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
700 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
702 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
703 CountTrailingZeros_32(Align));
710 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
712 if (Depth == 6 || Mask == 0)
713 return; // Limit search depth.
715 User *I = dyn_cast<User>(V);
718 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
719 switch (getOpcode(I)) {
721 case Instruction::And: {
722 // If either the LHS or the RHS are Zero, the result is zero.
723 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
724 APInt Mask2(Mask & ~KnownZero);
725 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
726 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
727 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
729 // Output known-1 bits are only known if set in both the LHS & RHS.
730 KnownOne &= KnownOne2;
731 // Output known-0 are known to be clear if zero in either the LHS | RHS.
732 KnownZero |= KnownZero2;
735 case Instruction::Or: {
736 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
737 APInt Mask2(Mask & ~KnownOne);
738 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
739 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
740 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
742 // Output known-0 bits are only known if clear in both the LHS & RHS.
743 KnownZero &= KnownZero2;
744 // Output known-1 are known to be set if set in either the LHS | RHS.
745 KnownOne |= KnownOne2;
748 case Instruction::Xor: {
749 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
750 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
751 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
752 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
754 // Output known-0 bits are known if clear or set in both the LHS & RHS.
755 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
756 // Output known-1 are known to be set if set in only one of the LHS, RHS.
757 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
758 KnownZero = KnownZeroOut;
761 case Instruction::Mul: {
762 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
763 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
764 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
765 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
766 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
768 // If low bits are zero in either operand, output low known-0 bits.
769 // Also compute a conserative estimate for high known-0 bits.
770 // More trickiness is possible, but this is sufficient for the
771 // interesting case of alignment computation.
773 unsigned TrailZ = KnownZero.countTrailingOnes() +
774 KnownZero2.countTrailingOnes();
775 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
776 KnownZero2.countLeadingOnes(),
777 BitWidth) - BitWidth;
779 TrailZ = std::min(TrailZ, BitWidth);
780 LeadZ = std::min(LeadZ, BitWidth);
781 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
782 APInt::getHighBitsSet(BitWidth, LeadZ);
786 case Instruction::UDiv: {
787 // For the purposes of computing leading zeros we can conservatively
788 // treat a udiv as a logical right shift by the power of 2 known to
789 // be less than the denominator.
790 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
791 ComputeMaskedBits(I->getOperand(0),
792 AllOnes, KnownZero2, KnownOne2, Depth+1);
793 unsigned LeadZ = KnownZero2.countLeadingOnes();
797 ComputeMaskedBits(I->getOperand(1),
798 AllOnes, KnownZero2, KnownOne2, Depth+1);
799 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
800 if (RHSUnknownLeadingOnes != BitWidth)
801 LeadZ = std::min(BitWidth,
802 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
804 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
807 case Instruction::Select:
808 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
809 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
810 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
811 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
813 // Only known if known in both the LHS and RHS.
814 KnownOne &= KnownOne2;
815 KnownZero &= KnownZero2;
817 case Instruction::FPTrunc:
818 case Instruction::FPExt:
819 case Instruction::FPToUI:
820 case Instruction::FPToSI:
821 case Instruction::SIToFP:
822 case Instruction::UIToFP:
823 return; // Can't work with floating point.
824 case Instruction::PtrToInt:
825 case Instruction::IntToPtr:
826 // We can't handle these if we don't know the pointer size.
828 // FALL THROUGH and handle them the same as zext/trunc.
829 case Instruction::ZExt:
830 case Instruction::Trunc: {
831 // Note that we handle pointer operands here because of inttoptr/ptrtoint
832 // which fall through here.
833 const Type *SrcTy = I->getOperand(0)->getType();
834 uint32_t SrcBitWidth = TD ?
835 TD->getTypeSizeInBits(SrcTy) :
836 SrcTy->getPrimitiveSizeInBits();
838 MaskIn.zextOrTrunc(SrcBitWidth);
839 KnownZero.zextOrTrunc(SrcBitWidth);
840 KnownOne.zextOrTrunc(SrcBitWidth);
841 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
842 KnownZero.zextOrTrunc(BitWidth);
843 KnownOne.zextOrTrunc(BitWidth);
844 // Any top bits are known to be zero.
845 if (BitWidth > SrcBitWidth)
846 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
849 case Instruction::BitCast: {
850 const Type *SrcTy = I->getOperand(0)->getType();
851 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
852 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
857 case Instruction::SExt: {
858 // Compute the bits in the result that are not present in the input.
859 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
860 uint32_t SrcBitWidth = SrcTy->getBitWidth();
863 MaskIn.trunc(SrcBitWidth);
864 KnownZero.trunc(SrcBitWidth);
865 KnownOne.trunc(SrcBitWidth);
866 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
867 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
868 KnownZero.zext(BitWidth);
869 KnownOne.zext(BitWidth);
871 // If the sign bit of the input is known set or clear, then we know the
872 // top bits of the result.
873 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
874 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
875 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
876 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
879 case Instruction::Shl:
880 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
881 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
882 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
883 APInt Mask2(Mask.lshr(ShiftAmt));
884 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
885 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
886 KnownZero <<= ShiftAmt;
887 KnownOne <<= ShiftAmt;
888 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
892 case Instruction::LShr:
893 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
894 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
895 // Compute the new bits that are at the top now.
896 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
898 // Unsigned shift right.
899 APInt Mask2(Mask.shl(ShiftAmt));
900 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
901 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
902 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
903 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
904 // high bits known zero.
905 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
909 case Instruction::AShr:
910 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
911 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
912 // Compute the new bits that are at the top now.
913 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
915 // Signed shift right.
916 APInt Mask2(Mask.shl(ShiftAmt));
917 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
918 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
919 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
920 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
922 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
923 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
924 KnownZero |= HighBits;
925 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
926 KnownOne |= HighBits;
930 case Instruction::Sub: {
931 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
932 // We know that the top bits of C-X are clear if X contains less bits
933 // than C (i.e. no wrap-around can happen). For example, 20-X is
934 // positive if we can prove that X is >= 0 and < 16.
935 if (!CLHS->getValue().isNegative()) {
936 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
937 // NLZ can't be BitWidth with no sign bit
938 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
939 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
942 // If all of the MaskV bits are known to be zero, then we know the
943 // output top bits are zero, because we now know that the output is
945 if ((KnownZero2 & MaskV) == MaskV) {
946 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
947 // Top bits known zero.
948 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
954 case Instruction::Add: {
955 // Output known-0 bits are known if clear or set in both the low clear bits
956 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
958 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
959 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
960 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
961 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
963 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
964 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
965 KnownZeroOut = std::min(KnownZeroOut,
966 KnownZero2.countTrailingOnes());
968 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
971 case Instruction::SRem:
972 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
973 APInt RA = Rem->getValue();
974 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
975 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
976 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
977 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
979 // The sign of a remainder is equal to the sign of the first
980 // operand (zero being positive).
981 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
982 KnownZero2 |= ~LowBits;
983 else if (KnownOne2[BitWidth-1])
984 KnownOne2 |= ~LowBits;
986 KnownZero |= KnownZero2 & Mask;
987 KnownOne |= KnownOne2 & Mask;
989 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
993 case Instruction::URem: {
994 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
995 APInt RA = Rem->getValue();
996 if (RA.isPowerOf2()) {
997 APInt LowBits = (RA - 1);
998 APInt Mask2 = LowBits & Mask;
999 KnownZero |= ~LowBits & Mask;
1000 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
1001 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1006 // Since the result is less than or equal to either operand, any leading
1007 // zero bits in either operand must also exist in the result.
1008 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1009 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1011 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1014 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1015 KnownZero2.countLeadingOnes());
1017 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
1021 case Instruction::Alloca:
1022 case Instruction::Malloc: {
1023 AllocationInst *AI = cast<AllocationInst>(V);
1024 unsigned Align = AI->getAlignment();
1025 if (Align == 0 && TD) {
1026 if (isa<AllocaInst>(AI))
1027 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1028 else if (isa<MallocInst>(AI)) {
1029 // Malloc returns maximally aligned memory.
1030 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1033 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1036 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1041 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1042 CountTrailingZeros_32(Align));
1045 case Instruction::GetElementPtr: {
1046 // Analyze all of the subscripts of this getelementptr instruction
1047 // to determine if we can prove known low zero bits.
1048 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1049 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1050 ComputeMaskedBits(I->getOperand(0), LocalMask,
1051 LocalKnownZero, LocalKnownOne, Depth+1);
1052 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1054 gep_type_iterator GTI = gep_type_begin(I);
1055 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1056 Value *Index = I->getOperand(i);
1057 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1058 // Handle struct member offset arithmetic.
1060 const StructLayout *SL = TD->getStructLayout(STy);
1061 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1062 uint64_t Offset = SL->getElementOffset(Idx);
1063 TrailZ = std::min(TrailZ,
1064 CountTrailingZeros_64(Offset));
1066 // Handle array index arithmetic.
1067 const Type *IndexedTy = GTI.getIndexedType();
1068 if (!IndexedTy->isSized()) return;
1069 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1070 uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1071 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1072 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1073 ComputeMaskedBits(Index, LocalMask,
1074 LocalKnownZero, LocalKnownOne, Depth+1);
1075 TrailZ = std::min(TrailZ,
1076 CountTrailingZeros_64(TypeSize) +
1077 LocalKnownZero.countTrailingOnes());
1081 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1084 case Instruction::PHI: {
1085 PHINode *P = cast<PHINode>(I);
1086 // Handle the case of a simple two-predecessor recurrence PHI.
1087 // There's a lot more that could theoretically be done here, but
1088 // this is sufficient to catch some interesting cases.
1089 if (P->getNumIncomingValues() == 2) {
1090 for (unsigned i = 0; i != 2; ++i) {
1091 Value *L = P->getIncomingValue(i);
1092 Value *R = P->getIncomingValue(!i);
1093 User *LU = dyn_cast<User>(L);
1094 unsigned Opcode = LU ? getOpcode(LU) : (unsigned)Instruction::UserOp1;
1095 // Check for operations that have the property that if
1096 // both their operands have low zero bits, the result
1097 // will have low zero bits.
1098 if (Opcode == Instruction::Add ||
1099 Opcode == Instruction::Sub ||
1100 Opcode == Instruction::And ||
1101 Opcode == Instruction::Or ||
1102 Opcode == Instruction::Mul) {
1103 Value *LL = LU->getOperand(0);
1104 Value *LR = LU->getOperand(1);
1105 // Find a recurrence.
1112 // Ok, we have a PHI of the form L op= R. Check for low
1114 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1115 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1116 Mask2 = APInt::getLowBitsSet(BitWidth,
1117 KnownZero2.countTrailingOnes());
1120 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1122 APInt::getLowBitsSet(BitWidth,
1123 KnownZero2.countTrailingOnes());
1130 case Instruction::Call:
1131 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1132 switch (II->getIntrinsicID()) {
1134 case Intrinsic::ctpop:
1135 case Intrinsic::ctlz:
1136 case Intrinsic::cttz: {
1137 unsigned LowBits = Log2_32(BitWidth)+1;
1138 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1147 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1148 /// this predicate to simplify operations downstream. Mask is known to be zero
1149 /// for bits that V cannot have.
1150 bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1152 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1153 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1154 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1155 return (KnownZero & Mask) == Mask;
1158 /// ShrinkDemandedConstant - Check to see if the specified operand of the
1159 /// specified instruction is a constant integer. If so, check to see if there
1160 /// are any bits set in the constant that are not demanded. If so, shrink the
1161 /// constant and return true.
1162 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
1164 assert(I && "No instruction?");
1165 assert(OpNo < I->getNumOperands() && "Operand index too large");
1167 // If the operand is not a constant integer, nothing to do.
1168 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1169 if (!OpC) return false;
1171 // If there are no bits set that aren't demanded, nothing to do.
1172 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1173 if ((~Demanded & OpC->getValue()) == 0)
1176 // This instruction is producing bits that are not demanded. Shrink the RHS.
1177 Demanded &= OpC->getValue();
1178 I->setOperand(OpNo, ConstantInt::get(Demanded));
1182 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1183 // set of known zero and one bits, compute the maximum and minimum values that
1184 // could have the specified known zero and known one bits, returning them in
1186 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
1187 const APInt& KnownZero,
1188 const APInt& KnownOne,
1189 APInt& Min, APInt& Max) {
1190 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1191 assert(KnownZero.getBitWidth() == BitWidth &&
1192 KnownOne.getBitWidth() == BitWidth &&
1193 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1194 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1195 APInt UnknownBits = ~(KnownZero|KnownOne);
1197 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1198 // bit if it is unknown.
1200 Max = KnownOne|UnknownBits;
1202 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
1203 Min.set(BitWidth-1);
1204 Max.clear(BitWidth-1);
1208 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1209 // a set of known zero and one bits, compute the maximum and minimum values that
1210 // could have the specified known zero and known one bits, returning them in
1212 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
1213 const APInt &KnownZero,
1214 const APInt &KnownOne,
1215 APInt &Min, APInt &Max) {
1216 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
1217 assert(KnownZero.getBitWidth() == BitWidth &&
1218 KnownOne.getBitWidth() == BitWidth &&
1219 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1220 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1221 APInt UnknownBits = ~(KnownZero|KnownOne);
1223 // The minimum value is when the unknown bits are all zeros.
1225 // The maximum value is when the unknown bits are all ones.
1226 Max = KnownOne|UnknownBits;
1229 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
1230 /// value based on the demanded bits. When this function is called, it is known
1231 /// that only the bits set in DemandedMask of the result of V are ever used
1232 /// downstream. Consequently, depending on the mask and V, it may be possible
1233 /// to replace V with a constant or one of its operands. In such cases, this
1234 /// function does the replacement and returns true. In all other cases, it
1235 /// returns false after analyzing the expression and setting KnownOne and known
1236 /// to be one in the expression. KnownZero contains all the bits that are known
1237 /// to be zero in the expression. These are provided to potentially allow the
1238 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1239 /// the expression. KnownOne and KnownZero always follow the invariant that
1240 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1241 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
1242 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1243 /// and KnownOne must all be the same.
1244 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1245 APInt& KnownZero, APInt& KnownOne,
1247 assert(V != 0 && "Null pointer of Value???");
1248 assert(Depth <= 6 && "Limit Search Depth");
1249 uint32_t BitWidth = DemandedMask.getBitWidth();
1250 const IntegerType *VTy = cast<IntegerType>(V->getType());
1251 assert(VTy->getBitWidth() == BitWidth &&
1252 KnownZero.getBitWidth() == BitWidth &&
1253 KnownOne.getBitWidth() == BitWidth &&
1254 "Value *V, DemandedMask, KnownZero and KnownOne \
1255 must have same BitWidth");
1256 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1257 // We know all of the bits for a constant!
1258 KnownOne = CI->getValue() & DemandedMask;
1259 KnownZero = ~KnownOne & DemandedMask;
1265 if (!V->hasOneUse()) { // Other users may use these bits.
1266 if (Depth != 0) { // Not at the root.
1267 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1268 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1271 // If this is the root being simplified, allow it to have multiple uses,
1272 // just set the DemandedMask to all bits.
1273 DemandedMask = APInt::getAllOnesValue(BitWidth);
1274 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1275 if (V != UndefValue::get(VTy))
1276 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1278 } else if (Depth == 6) { // Limit search depth.
1282 Instruction *I = dyn_cast<Instruction>(V);
1283 if (!I) return false; // Only analyze instructions.
1285 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1286 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1287 switch (I->getOpcode()) {
1289 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1291 case Instruction::And:
1292 // If either the LHS or the RHS are Zero, the result is zero.
1293 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1294 RHSKnownZero, RHSKnownOne, Depth+1))
1296 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1297 "Bits known to be one AND zero?");
1299 // If something is known zero on the RHS, the bits aren't demanded on the
1301 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1302 LHSKnownZero, LHSKnownOne, Depth+1))
1304 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1305 "Bits known to be one AND zero?");
1307 // If all of the demanded bits are known 1 on one side, return the other.
1308 // These bits cannot contribute to the result of the 'and'.
1309 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1310 (DemandedMask & ~LHSKnownZero))
1311 return UpdateValueUsesWith(I, I->getOperand(0));
1312 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1313 (DemandedMask & ~RHSKnownZero))
1314 return UpdateValueUsesWith(I, I->getOperand(1));
1316 // If all of the demanded bits in the inputs are known zeros, return zero.
1317 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1318 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1320 // If the RHS is a constant, see if we can simplify it.
1321 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1322 return UpdateValueUsesWith(I, I);
1324 // Output known-1 bits are only known if set in both the LHS & RHS.
1325 RHSKnownOne &= LHSKnownOne;
1326 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1327 RHSKnownZero |= LHSKnownZero;
1329 case Instruction::Or:
1330 // If either the LHS or the RHS are One, the result is One.
1331 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1332 RHSKnownZero, RHSKnownOne, Depth+1))
1334 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1335 "Bits known to be one AND zero?");
1336 // If something is known one on the RHS, the bits aren't demanded on the
1338 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1339 LHSKnownZero, LHSKnownOne, Depth+1))
1341 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1342 "Bits known to be one AND zero?");
1344 // If all of the demanded bits are known zero on one side, return the other.
1345 // These bits cannot contribute to the result of the 'or'.
1346 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1347 (DemandedMask & ~LHSKnownOne))
1348 return UpdateValueUsesWith(I, I->getOperand(0));
1349 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1350 (DemandedMask & ~RHSKnownOne))
1351 return UpdateValueUsesWith(I, I->getOperand(1));
1353 // If all of the potentially set bits on one side are known to be set on
1354 // the other side, just use the 'other' side.
1355 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1356 (DemandedMask & (~RHSKnownZero)))
1357 return UpdateValueUsesWith(I, I->getOperand(0));
1358 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1359 (DemandedMask & (~LHSKnownZero)))
1360 return UpdateValueUsesWith(I, I->getOperand(1));
1362 // If the RHS is a constant, see if we can simplify it.
1363 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1364 return UpdateValueUsesWith(I, I);
1366 // Output known-0 bits are only known if clear in both the LHS & RHS.
1367 RHSKnownZero &= LHSKnownZero;
1368 // Output known-1 are known to be set if set in either the LHS | RHS.
1369 RHSKnownOne |= LHSKnownOne;
1371 case Instruction::Xor: {
1372 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1373 RHSKnownZero, RHSKnownOne, Depth+1))
1375 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1376 "Bits known to be one AND zero?");
1377 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1378 LHSKnownZero, LHSKnownOne, Depth+1))
1380 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1381 "Bits known to be one AND zero?");
1383 // If all of the demanded bits are known zero on one side, return the other.
1384 // These bits cannot contribute to the result of the 'xor'.
1385 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1386 return UpdateValueUsesWith(I, I->getOperand(0));
1387 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1388 return UpdateValueUsesWith(I, I->getOperand(1));
1390 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1391 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1392 (RHSKnownOne & LHSKnownOne);
1393 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1394 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1395 (RHSKnownOne & LHSKnownZero);
1397 // If all of the demanded bits are known to be zero on one side or the
1398 // other, turn this into an *inclusive* or.
1399 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1400 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1402 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1404 InsertNewInstBefore(Or, *I);
1405 return UpdateValueUsesWith(I, Or);
1408 // If all of the demanded bits on one side are known, and all of the set
1409 // bits on that side are also known to be set on the other side, turn this
1410 // into an AND, as we know the bits will be cleared.
1411 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1412 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1414 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1415 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1417 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1418 InsertNewInstBefore(And, *I);
1419 return UpdateValueUsesWith(I, And);
1423 // If the RHS is a constant, see if we can simplify it.
1424 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1425 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1426 return UpdateValueUsesWith(I, I);
1428 RHSKnownZero = KnownZeroOut;
1429 RHSKnownOne = KnownOneOut;
1432 case Instruction::Select:
1433 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1434 RHSKnownZero, RHSKnownOne, Depth+1))
1436 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1437 LHSKnownZero, LHSKnownOne, Depth+1))
1439 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1440 "Bits known to be one AND zero?");
1441 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1442 "Bits known to be one AND zero?");
1444 // If the operands are constants, see if we can simplify them.
1445 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1446 return UpdateValueUsesWith(I, I);
1447 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1448 return UpdateValueUsesWith(I, I);
1450 // Only known if known in both the LHS and RHS.
1451 RHSKnownOne &= LHSKnownOne;
1452 RHSKnownZero &= LHSKnownZero;
1454 case Instruction::Trunc: {
1456 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1457 DemandedMask.zext(truncBf);
1458 RHSKnownZero.zext(truncBf);
1459 RHSKnownOne.zext(truncBf);
1460 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1461 RHSKnownZero, RHSKnownOne, Depth+1))
1463 DemandedMask.trunc(BitWidth);
1464 RHSKnownZero.trunc(BitWidth);
1465 RHSKnownOne.trunc(BitWidth);
1466 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1467 "Bits known to be one AND zero?");
1470 case Instruction::BitCast:
1471 if (!I->getOperand(0)->getType()->isInteger())
1474 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1475 RHSKnownZero, RHSKnownOne, Depth+1))
1477 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1478 "Bits known to be one AND zero?");
1480 case Instruction::ZExt: {
1481 // Compute the bits in the result that are not present in the input.
1482 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1483 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1485 DemandedMask.trunc(SrcBitWidth);
1486 RHSKnownZero.trunc(SrcBitWidth);
1487 RHSKnownOne.trunc(SrcBitWidth);
1488 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1489 RHSKnownZero, RHSKnownOne, Depth+1))
1491 DemandedMask.zext(BitWidth);
1492 RHSKnownZero.zext(BitWidth);
1493 RHSKnownOne.zext(BitWidth);
1494 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1495 "Bits known to be one AND zero?");
1496 // The top bits are known to be zero.
1497 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1500 case Instruction::SExt: {
1501 // Compute the bits in the result that are not present in the input.
1502 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1503 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1505 APInt InputDemandedBits = DemandedMask &
1506 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1508 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1509 // If any of the sign extended bits are demanded, we know that the sign
1511 if ((NewBits & DemandedMask) != 0)
1512 InputDemandedBits.set(SrcBitWidth-1);
1514 InputDemandedBits.trunc(SrcBitWidth);
1515 RHSKnownZero.trunc(SrcBitWidth);
1516 RHSKnownOne.trunc(SrcBitWidth);
1517 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1518 RHSKnownZero, RHSKnownOne, Depth+1))
1520 InputDemandedBits.zext(BitWidth);
1521 RHSKnownZero.zext(BitWidth);
1522 RHSKnownOne.zext(BitWidth);
1523 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1524 "Bits known to be one AND zero?");
1526 // If the sign bit of the input is known set or clear, then we know the
1527 // top bits of the result.
1529 // If the input sign bit is known zero, or if the NewBits are not demanded
1530 // convert this into a zero extension.
1531 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1533 // Convert to ZExt cast
1534 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1535 return UpdateValueUsesWith(I, NewCast);
1536 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1537 RHSKnownOne |= NewBits;
1541 case Instruction::Add: {
1542 // Figure out what the input bits are. If the top bits of the and result
1543 // are not demanded, then the add doesn't demand them from its input
1545 uint32_t NLZ = DemandedMask.countLeadingZeros();
1547 // If there is a constant on the RHS, there are a variety of xformations
1549 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1550 // If null, this should be simplified elsewhere. Some of the xforms here
1551 // won't work if the RHS is zero.
1555 // If the top bit of the output is demanded, demand everything from the
1556 // input. Otherwise, we demand all the input bits except NLZ top bits.
1557 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1559 // Find information about known zero/one bits in the input.
1560 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1561 LHSKnownZero, LHSKnownOne, Depth+1))
1564 // If the RHS of the add has bits set that can't affect the input, reduce
1566 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1567 return UpdateValueUsesWith(I, I);
1569 // Avoid excess work.
1570 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1573 // Turn it into OR if input bits are zero.
1574 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1576 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1578 InsertNewInstBefore(Or, *I);
1579 return UpdateValueUsesWith(I, Or);
1582 // We can say something about the output known-zero and known-one bits,
1583 // depending on potential carries from the input constant and the
1584 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1585 // bits set and the RHS constant is 0x01001, then we know we have a known
1586 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1588 // To compute this, we first compute the potential carry bits. These are
1589 // the bits which may be modified. I'm not aware of a better way to do
1591 const APInt& RHSVal = RHS->getValue();
1592 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1594 // Now that we know which bits have carries, compute the known-1/0 sets.
1596 // Bits are known one if they are known zero in one operand and one in the
1597 // other, and there is no input carry.
1598 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1599 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1601 // Bits are known zero if they are known zero in both operands and there
1602 // is no input carry.
1603 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1605 // If the high-bits of this ADD are not demanded, then it does not demand
1606 // the high bits of its LHS or RHS.
1607 if (DemandedMask[BitWidth-1] == 0) {
1608 // Right fill the mask of bits for this ADD to demand the most
1609 // significant bit and all those below it.
1610 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1611 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1612 LHSKnownZero, LHSKnownOne, Depth+1))
1614 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1615 LHSKnownZero, LHSKnownOne, Depth+1))
1621 case Instruction::Sub:
1622 // If the high-bits of this SUB are not demanded, then it does not demand
1623 // the high bits of its LHS or RHS.
1624 if (DemandedMask[BitWidth-1] == 0) {
1625 // Right fill the mask of bits for this SUB to demand the most
1626 // significant bit and all those below it.
1627 uint32_t NLZ = DemandedMask.countLeadingZeros();
1628 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1629 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1630 LHSKnownZero, LHSKnownOne, Depth+1))
1632 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1633 LHSKnownZero, LHSKnownOne, Depth+1))
1636 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1637 // the known zeros and ones.
1638 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1640 case Instruction::Shl:
1641 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1642 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1643 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1644 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1645 RHSKnownZero, RHSKnownOne, Depth+1))
1647 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1648 "Bits known to be one AND zero?");
1649 RHSKnownZero <<= ShiftAmt;
1650 RHSKnownOne <<= ShiftAmt;
1651 // low bits known zero.
1653 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1656 case Instruction::LShr:
1657 // For a logical shift right
1658 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1659 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1661 // Unsigned shift right.
1662 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1663 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1664 RHSKnownZero, RHSKnownOne, Depth+1))
1666 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1667 "Bits known to be one AND zero?");
1668 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1669 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1671 // Compute the new bits that are at the top now.
1672 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1673 RHSKnownZero |= HighBits; // high bits known zero.
1677 case Instruction::AShr:
1678 // If this is an arithmetic shift right and only the low-bit is set, we can
1679 // always convert this into a logical shr, even if the shift amount is
1680 // variable. The low bit of the shift cannot be an input sign bit unless
1681 // the shift amount is >= the size of the datatype, which is undefined.
1682 if (DemandedMask == 1) {
1683 // Perform the logical shift right.
1684 Value *NewVal = BinaryOperator::CreateLShr(
1685 I->getOperand(0), I->getOperand(1), I->getName());
1686 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1687 return UpdateValueUsesWith(I, NewVal);
1690 // If the sign bit is the only bit demanded by this ashr, then there is no
1691 // need to do it, the shift doesn't change the high bit.
1692 if (DemandedMask.isSignBit())
1693 return UpdateValueUsesWith(I, I->getOperand(0));
1695 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1696 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1698 // Signed shift right.
1699 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1700 // If any of the "high bits" are demanded, we should set the sign bit as
1702 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1703 DemandedMaskIn.set(BitWidth-1);
1704 if (SimplifyDemandedBits(I->getOperand(0),
1706 RHSKnownZero, RHSKnownOne, Depth+1))
1708 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1709 "Bits known to be one AND zero?");
1710 // Compute the new bits that are at the top now.
1711 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1712 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1713 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1715 // Handle the sign bits.
1716 APInt SignBit(APInt::getSignBit(BitWidth));
1717 // Adjust to where it is now in the mask.
1718 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1720 // If the input sign bit is known to be zero, or if none of the top bits
1721 // are demanded, turn this into an unsigned shift right.
1722 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
1723 (HighBits & ~DemandedMask) == HighBits) {
1724 // Perform the logical shift right.
1725 Value *NewVal = BinaryOperator::CreateLShr(
1726 I->getOperand(0), SA, I->getName());
1727 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1728 return UpdateValueUsesWith(I, NewVal);
1729 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1730 RHSKnownOne |= HighBits;
1734 case Instruction::SRem:
1735 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1736 APInt RA = Rem->getValue();
1737 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1738 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1739 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1740 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1741 LHSKnownZero, LHSKnownOne, Depth+1))
1744 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1745 LHSKnownZero |= ~LowBits;
1746 else if (LHSKnownOne[BitWidth-1])
1747 LHSKnownOne |= ~LowBits;
1749 KnownZero |= LHSKnownZero & DemandedMask;
1750 KnownOne |= LHSKnownOne & DemandedMask;
1752 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1756 case Instruction::URem: {
1757 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1758 APInt RA = Rem->getValue();
1759 if (RA.isPowerOf2()) {
1760 APInt LowBits = (RA - 1);
1761 APInt Mask2 = LowBits & DemandedMask;
1762 KnownZero |= ~LowBits & DemandedMask;
1763 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1764 KnownZero, KnownOne, Depth+1))
1767 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1772 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1773 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1774 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1775 KnownZero2, KnownOne2, Depth+1))
1778 uint32_t Leaders = KnownZero2.countLeadingOnes();
1779 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1780 KnownZero2, KnownOne2, Depth+1))
1783 Leaders = std::max(Leaders,
1784 KnownZero2.countLeadingOnes());
1785 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1790 // If the client is only demanding bits that we know, return the known
1792 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1793 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1798 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1799 /// 64 or fewer elements. DemandedElts contains the set of elements that are
1800 /// actually used by the caller. This method analyzes which elements of the
1801 /// operand are undef and returns that information in UndefElts.
1803 /// If the information about demanded elements can be used to simplify the
1804 /// operation, the operation is simplified, then the resultant value is
1805 /// returned. This returns null if no change was made.
1806 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1807 uint64_t &UndefElts,
1809 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1810 assert(VWidth <= 64 && "Vector too wide to analyze!");
1811 uint64_t EltMask = ~0ULL >> (64-VWidth);
1812 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1813 "Invalid DemandedElts!");
1815 if (isa<UndefValue>(V)) {
1816 // If the entire vector is undefined, just return this info.
1817 UndefElts = EltMask;
1819 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1820 UndefElts = EltMask;
1821 return UndefValue::get(V->getType());
1825 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1826 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1827 Constant *Undef = UndefValue::get(EltTy);
1829 std::vector<Constant*> Elts;
1830 for (unsigned i = 0; i != VWidth; ++i)
1831 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1832 Elts.push_back(Undef);
1833 UndefElts |= (1ULL << i);
1834 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1835 Elts.push_back(Undef);
1836 UndefElts |= (1ULL << i);
1837 } else { // Otherwise, defined.
1838 Elts.push_back(CP->getOperand(i));
1841 // If we changed the constant, return it.
1842 Constant *NewCP = ConstantVector::get(Elts);
1843 return NewCP != CP ? NewCP : 0;
1844 } else if (isa<ConstantAggregateZero>(V)) {
1845 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1847 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1848 Constant *Zero = Constant::getNullValue(EltTy);
1849 Constant *Undef = UndefValue::get(EltTy);
1850 std::vector<Constant*> Elts;
1851 for (unsigned i = 0; i != VWidth; ++i)
1852 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1853 UndefElts = DemandedElts ^ EltMask;
1854 return ConstantVector::get(Elts);
1857 if (!V->hasOneUse()) { // Other users may use these bits.
1858 if (Depth != 0) { // Not at the root.
1859 // TODO: Just compute the UndefElts information recursively.
1863 } else if (Depth == 10) { // Limit search depth.
1867 Instruction *I = dyn_cast<Instruction>(V);
1868 if (!I) return false; // Only analyze instructions.
1870 bool MadeChange = false;
1871 uint64_t UndefElts2;
1873 switch (I->getOpcode()) {
1876 case Instruction::InsertElement: {
1877 // If this is a variable index, we don't know which element it overwrites.
1878 // demand exactly the same input as we produce.
1879 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1881 // Note that we can't propagate undef elt info, because we don't know
1882 // which elt is getting updated.
1883 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1884 UndefElts2, Depth+1);
1885 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1889 // If this is inserting an element that isn't demanded, remove this
1891 unsigned IdxNo = Idx->getZExtValue();
1892 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1893 return AddSoonDeadInstToWorklist(*I, 0);
1895 // Otherwise, the element inserted overwrites whatever was there, so the
1896 // input demanded set is simpler than the output set.
1897 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1898 DemandedElts & ~(1ULL << IdxNo),
1899 UndefElts, Depth+1);
1900 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1902 // The inserted element is defined.
1903 UndefElts |= 1ULL << IdxNo;
1906 case Instruction::BitCast: {
1907 // Vector->vector casts only.
1908 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1910 unsigned InVWidth = VTy->getNumElements();
1911 uint64_t InputDemandedElts = 0;
1914 if (VWidth == InVWidth) {
1915 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1916 // elements as are demanded of us.
1918 InputDemandedElts = DemandedElts;
1919 } else if (VWidth > InVWidth) {
1923 // If there are more elements in the result than there are in the source,
1924 // then an input element is live if any of the corresponding output
1925 // elements are live.
1926 Ratio = VWidth/InVWidth;
1927 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1928 if (DemandedElts & (1ULL << OutIdx))
1929 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1935 // If there are more elements in the source than there are in the result,
1936 // then an input element is live if the corresponding output element is
1938 Ratio = InVWidth/VWidth;
1939 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1940 if (DemandedElts & (1ULL << InIdx/Ratio))
1941 InputDemandedElts |= 1ULL << InIdx;
1944 // div/rem demand all inputs, because they don't want divide by zero.
1945 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1946 UndefElts2, Depth+1);
1948 I->setOperand(0, TmpV);
1952 UndefElts = UndefElts2;
1953 if (VWidth > InVWidth) {
1954 assert(0 && "Unimp");
1955 // If there are more elements in the result than there are in the source,
1956 // then an output element is undef if the corresponding input element is
1958 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1959 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1960 UndefElts |= 1ULL << OutIdx;
1961 } else if (VWidth < InVWidth) {
1962 assert(0 && "Unimp");
1963 // If there are more elements in the source than there are in the result,
1964 // then a result element is undef if all of the corresponding input
1965 // elements are undef.
1966 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1967 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1968 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1969 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1973 case Instruction::And:
1974 case Instruction::Or:
1975 case Instruction::Xor:
1976 case Instruction::Add:
1977 case Instruction::Sub:
1978 case Instruction::Mul:
1979 // div/rem demand all inputs, because they don't want divide by zero.
1980 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1981 UndefElts, Depth+1);
1982 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1983 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1984 UndefElts2, Depth+1);
1985 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1987 // Output elements are undefined if both are undefined. Consider things
1988 // like undef&0. The result is known zero, not undef.
1989 UndefElts &= UndefElts2;
1992 case Instruction::Call: {
1993 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1995 switch (II->getIntrinsicID()) {
1998 // Binary vector operations that work column-wise. A dest element is a
1999 // function of the corresponding input elements from the two inputs.
2000 case Intrinsic::x86_sse_sub_ss:
2001 case Intrinsic::x86_sse_mul_ss:
2002 case Intrinsic::x86_sse_min_ss:
2003 case Intrinsic::x86_sse_max_ss:
2004 case Intrinsic::x86_sse2_sub_sd:
2005 case Intrinsic::x86_sse2_mul_sd:
2006 case Intrinsic::x86_sse2_min_sd:
2007 case Intrinsic::x86_sse2_max_sd:
2008 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2009 UndefElts, Depth+1);
2010 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2011 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2012 UndefElts2, Depth+1);
2013 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2015 // If only the low elt is demanded and this is a scalarizable intrinsic,
2016 // scalarize it now.
2017 if (DemandedElts == 1) {
2018 switch (II->getIntrinsicID()) {
2020 case Intrinsic::x86_sse_sub_ss:
2021 case Intrinsic::x86_sse_mul_ss:
2022 case Intrinsic::x86_sse2_sub_sd:
2023 case Intrinsic::x86_sse2_mul_sd:
2024 // TODO: Lower MIN/MAX/ABS/etc
2025 Value *LHS = II->getOperand(1);
2026 Value *RHS = II->getOperand(2);
2027 // Extract the element as scalars.
2028 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2029 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2031 switch (II->getIntrinsicID()) {
2032 default: assert(0 && "Case stmts out of sync!");
2033 case Intrinsic::x86_sse_sub_ss:
2034 case Intrinsic::x86_sse2_sub_sd:
2035 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
2036 II->getName()), *II);
2038 case Intrinsic::x86_sse_mul_ss:
2039 case Intrinsic::x86_sse2_mul_sd:
2040 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
2041 II->getName()), *II);
2046 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2048 InsertNewInstBefore(New, *II);
2049 AddSoonDeadInstToWorklist(*II, 0);
2054 // Output elements are undefined if both are undefined. Consider things
2055 // like undef&0. The result is known zero, not undef.
2056 UndefElts &= UndefElts2;
2062 return MadeChange ? I : 0;
2065 /// ComputeNumSignBits - Return the number of times the sign bit of the
2066 /// register is replicated into the other bits. We know that at least 1 bit
2067 /// is always equal to the sign bit (itself), but other cases can give us
2068 /// information. For example, immediately after an "ashr X, 2", we know that
2069 /// the top 3 bits are all equal to each other, so we return 3.
2071 unsigned InstCombiner::ComputeNumSignBits(Value *V, unsigned Depth) const{
2072 const IntegerType *Ty = cast<IntegerType>(V->getType());
2073 unsigned TyBits = Ty->getBitWidth();
2077 return 1; // Limit search depth.
2079 User *U = dyn_cast<User>(V);
2080 switch (getOpcode(V)) {
2082 case Instruction::SExt:
2083 Tmp = TyBits-cast<IntegerType>(U->getOperand(0)->getType())->getBitWidth();
2084 return ComputeNumSignBits(U->getOperand(0), Depth+1) + Tmp;
2086 case Instruction::AShr:
2087 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2088 // SRA X, C -> adds C sign bits.
2089 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2090 Tmp += C->getZExtValue();
2091 if (Tmp > TyBits) Tmp = TyBits;
2094 case Instruction::Shl:
2095 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2096 // shl destroys sign bits.
2097 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2098 if (C->getZExtValue() >= TyBits || // Bad shift.
2099 C->getZExtValue() >= Tmp) break; // Shifted all sign bits out.
2100 return Tmp - C->getZExtValue();
2103 case Instruction::And:
2104 // Logical binary ops preserve the number of sign bits at the worst.
2105 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2107 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2108 Tmp = std::min(Tmp, Tmp2);
2111 // X & C has sign bits equal to C if C's top bits are zeros.
2112 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2113 // See what bits are known to be zero on the output.
2114 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2115 APInt Mask = APInt::getAllOnesValue(TyBits);
2116 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2118 KnownZero |= ~C->getValue();
2119 // If we know that we have leading zeros, we know we have at least that
2121 Tmp = std::max(Tmp, KnownZero.countLeadingOnes());
2125 case Instruction::Or:
2126 // Logical binary ops preserve the number of sign bits at the worst.
2127 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2129 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2130 Tmp = std::min(Tmp, Tmp2);
2132 // X & C has sign bits equal to C if C's top bits are zeros.
2133 if (ConstantInt *C = dyn_cast<ConstantInt>(U->getOperand(1))) {
2134 // See what bits are known to be one on the output.
2135 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2136 APInt Mask = APInt::getAllOnesValue(TyBits);
2137 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2139 KnownOne |= C->getValue();
2140 // If we know that we have leading ones, we know we have at least that
2142 Tmp = std::max(Tmp, KnownOne.countLeadingOnes());
2146 case Instruction::Xor: // NOT is handled here.
2147 // Logical binary ops preserve the number of sign bits.
2148 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2149 if (Tmp == 1) return 1; // Early out.
2150 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2151 return std::min(Tmp, Tmp2);
2153 case Instruction::Select:
2154 Tmp = ComputeNumSignBits(U->getOperand(1), Depth+1);
2155 if (Tmp == 1) return 1; // Early out.
2156 Tmp2 = ComputeNumSignBits(U->getOperand(2), Depth+1);
2157 return std::min(Tmp, Tmp2);
2159 case Instruction::Add:
2160 // Add can have at most one carry bit. Thus we know that the output
2161 // is, at worst, one more bit than the inputs.
2162 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2163 if (Tmp == 1) return 1; // Early out.
2165 // Special case decrementing a value (ADD X, -1):
2166 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2167 if (CRHS->isAllOnesValue()) {
2168 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2169 APInt Mask = APInt::getAllOnesValue(TyBits);
2170 ComputeMaskedBits(U->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2172 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2174 if ((KnownZero | APInt(TyBits, 1)) == Mask)
2177 // If we are subtracting one from a positive number, there is no carry
2178 // out of the result.
2179 if (KnownZero.isNegative())
2183 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2184 if (Tmp2 == 1) return 1;
2185 return std::min(Tmp, Tmp2)-1;
2188 case Instruction::Sub:
2189 Tmp2 = ComputeNumSignBits(U->getOperand(1), Depth+1);
2190 if (Tmp2 == 1) return 1;
2193 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(U->getOperand(0)))
2194 if (CLHS->isNullValue()) {
2195 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2196 APInt Mask = APInt::getAllOnesValue(TyBits);
2197 ComputeMaskedBits(U->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2198 // If the input is known to be 0 or 1, the output is 0/-1, which is all
2200 if ((KnownZero | APInt(TyBits, 1)) == Mask)
2203 // If the input is known to be positive (the sign bit is known clear),
2204 // the output of the NEG has the same number of sign bits as the input.
2205 if (KnownZero.isNegative())
2208 // Otherwise, we treat this like a SUB.
2211 // Sub can have at most one carry bit. Thus we know that the output
2212 // is, at worst, one more bit than the inputs.
2213 Tmp = ComputeNumSignBits(U->getOperand(0), Depth+1);
2214 if (Tmp == 1) return 1; // Early out.
2215 return std::min(Tmp, Tmp2)-1;
2217 case Instruction::Trunc:
2218 // FIXME: it's tricky to do anything useful for this, but it is an important
2219 // case for targets like X86.
2223 // Finally, if we can prove that the top bits of the result are 0's or 1's,
2224 // use this information.
2225 APInt KnownZero(TyBits, 0), KnownOne(TyBits, 0);
2226 APInt Mask = APInt::getAllOnesValue(TyBits);
2227 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
2229 if (KnownZero.isNegative()) { // sign bit is 0
2231 } else if (KnownOne.isNegative()) { // sign bit is 1;
2238 // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
2239 // the number of identical bits in the top of the input value.
2241 Mask <<= Mask.getBitWidth()-TyBits;
2242 // Return # leading zeros. We use 'min' here in case Val was zero before
2243 // shifting. We don't want to return '64' as for an i32 "0".
2244 return std::min(TyBits, Mask.countLeadingZeros());
2248 /// AssociativeOpt - Perform an optimization on an associative operator. This
2249 /// function is designed to check a chain of associative operators for a
2250 /// potential to apply a certain optimization. Since the optimization may be
2251 /// applicable if the expression was reassociated, this checks the chain, then
2252 /// reassociates the expression as necessary to expose the optimization
2253 /// opportunity. This makes use of a special Functor, which must define
2254 /// 'shouldApply' and 'apply' methods.
2256 template<typename Functor>
2257 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2258 unsigned Opcode = Root.getOpcode();
2259 Value *LHS = Root.getOperand(0);
2261 // Quick check, see if the immediate LHS matches...
2262 if (F.shouldApply(LHS))
2263 return F.apply(Root);
2265 // Otherwise, if the LHS is not of the same opcode as the root, return.
2266 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2267 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
2268 // Should we apply this transform to the RHS?
2269 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2271 // If not to the RHS, check to see if we should apply to the LHS...
2272 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2273 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2277 // If the functor wants to apply the optimization to the RHS of LHSI,
2278 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2280 BasicBlock *BB = Root.getParent();
2282 // Now all of the instructions are in the current basic block, go ahead
2283 // and perform the reassociation.
2284 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2286 // First move the selected RHS to the LHS of the root...
2287 Root.setOperand(0, LHSI->getOperand(1));
2289 // Make what used to be the LHS of the root be the user of the root...
2290 Value *ExtraOperand = TmpLHSI->getOperand(1);
2291 if (&Root == TmpLHSI) {
2292 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2295 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
2296 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
2297 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2298 BasicBlock::iterator ARI = &Root; ++ARI;
2299 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2302 // Now propagate the ExtraOperand down the chain of instructions until we
2304 while (TmpLHSI != LHSI) {
2305 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
2306 // Move the instruction to immediately before the chain we are
2307 // constructing to avoid breaking dominance properties.
2308 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2309 BB->getInstList().insert(ARI, NextLHSI);
2312 Value *NextOp = NextLHSI->getOperand(1);
2313 NextLHSI->setOperand(1, ExtraOperand);
2315 ExtraOperand = NextOp;
2318 // Now that the instructions are reassociated, have the functor perform
2319 // the transformation...
2320 return F.apply(Root);
2323 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2330 // AddRHS - Implements: X + X --> X << 1
2333 AddRHS(Value *rhs) : RHS(rhs) {}
2334 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2335 Instruction *apply(BinaryOperator &Add) const {
2336 return BinaryOperator::CreateShl(Add.getOperand(0),
2337 ConstantInt::get(Add.getType(), 1));
2341 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2343 struct AddMaskingAnd {
2345 AddMaskingAnd(Constant *c) : C2(c) {}
2346 bool shouldApply(Value *LHS) const {
2348 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
2349 ConstantExpr::getAnd(C1, C2)->isNullValue();
2351 Instruction *apply(BinaryOperator &Add) const {
2352 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
2358 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
2360 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
2361 if (Constant *SOC = dyn_cast<Constant>(SO))
2362 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
2364 return IC->InsertNewInstBefore(CastInst::Create(
2365 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
2368 // Figure out if the constant is the left or the right argument.
2369 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2370 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
2372 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2374 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2375 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
2378 Value *Op0 = SO, *Op1 = ConstOperand;
2380 std::swap(Op0, Op1);
2382 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2383 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
2384 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2385 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
2386 SO->getName()+".cmp");
2388 assert(0 && "Unknown binary instruction type!");
2391 return IC->InsertNewInstBefore(New, I);
2394 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
2395 // constant as the other operand, try to fold the binary operator into the
2396 // select arguments. This also works for Cast instructions, which obviously do
2397 // not have a second operand.
2398 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2400 // Don't modify shared select instructions
2401 if (!SI->hasOneUse()) return 0;
2402 Value *TV = SI->getOperand(1);
2403 Value *FV = SI->getOperand(2);
2405 if (isa<Constant>(TV) || isa<Constant>(FV)) {
2406 // Bool selects with constant operands can be folded to logical ops.
2407 if (SI->getType() == Type::Int1Ty) return 0;
2409 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2410 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2412 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2419 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2420 /// node as operand #0, see if we can fold the instruction into the PHI (which
2421 /// is only possible if all operands to the PHI are constants).
2422 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2423 PHINode *PN = cast<PHINode>(I.getOperand(0));
2424 unsigned NumPHIValues = PN->getNumIncomingValues();
2425 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
2427 // Check to see if all of the operands of the PHI are constants. If there is
2428 // one non-constant value, remember the BB it is. If there is more than one
2429 // or if *it* is a PHI, bail out.
2430 BasicBlock *NonConstBB = 0;
2431 for (unsigned i = 0; i != NumPHIValues; ++i)
2432 if (!isa<Constant>(PN->getIncomingValue(i))) {
2433 if (NonConstBB) return 0; // More than one non-const value.
2434 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
2435 NonConstBB = PN->getIncomingBlock(i);
2437 // If the incoming non-constant value is in I's block, we have an infinite
2439 if (NonConstBB == I.getParent())
2443 // If there is exactly one non-constant value, we can insert a copy of the
2444 // operation in that block. However, if this is a critical edge, we would be
2445 // inserting the computation one some other paths (e.g. inside a loop). Only
2446 // do this if the pred block is unconditionally branching into the phi block.
2448 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2449 if (!BI || !BI->isUnconditional()) return 0;
2452 // Okay, we can do the transformation: create the new PHI node.
2453 PHINode *NewPN = PHINode::Create(I.getType(), "");
2454 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2455 InsertNewInstBefore(NewPN, *PN);
2456 NewPN->takeName(PN);
2458 // Next, add all of the operands to the PHI.
2459 if (I.getNumOperands() == 2) {
2460 Constant *C = cast<Constant>(I.getOperand(1));
2461 for (unsigned i = 0; i != NumPHIValues; ++i) {
2463 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2464 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2465 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2467 InV = ConstantExpr::get(I.getOpcode(), InC, C);
2469 assert(PN->getIncomingBlock(i) == NonConstBB);
2470 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2471 InV = BinaryOperator::Create(BO->getOpcode(),
2472 PN->getIncomingValue(i), C, "phitmp",
2473 NonConstBB->getTerminator());
2474 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2475 InV = CmpInst::Create(CI->getOpcode(),
2477 PN->getIncomingValue(i), C, "phitmp",
2478 NonConstBB->getTerminator());
2480 assert(0 && "Unknown binop!");
2482 AddToWorkList(cast<Instruction>(InV));
2484 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2487 CastInst *CI = cast<CastInst>(&I);
2488 const Type *RetTy = CI->getType();
2489 for (unsigned i = 0; i != NumPHIValues; ++i) {
2491 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2492 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2494 assert(PN->getIncomingBlock(i) == NonConstBB);
2495 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
2496 I.getType(), "phitmp",
2497 NonConstBB->getTerminator());
2498 AddToWorkList(cast<Instruction>(InV));
2500 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2503 return ReplaceInstUsesWith(I, NewPN);
2507 /// CannotBeNegativeZero - Return true if we can prove that the specified FP
2508 /// value is never equal to -0.0.
2510 /// Note that this function will need to be revisited when we support nondefault
2513 static bool CannotBeNegativeZero(const Value *V) {
2514 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2515 return !CFP->getValueAPF().isNegZero();
2517 if (const Instruction *I = dyn_cast<Instruction>(V)) {
2518 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2519 if (I->getOpcode() == Instruction::Add &&
2520 isa<ConstantFP>(I->getOperand(1)) &&
2521 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2524 // sitofp and uitofp turn into +0.0 for zero.
2525 if (isa<SIToFPInst>(I) || isa<UIToFPInst>(I))
2528 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2529 if (II->getIntrinsicID() == Intrinsic::sqrt)
2530 return CannotBeNegativeZero(II->getOperand(1));
2532 if (const CallInst *CI = dyn_cast<CallInst>(I))
2533 if (const Function *F = CI->getCalledFunction()) {
2534 if (F->isDeclaration()) {
2535 switch (F->getNameLen()) {
2536 case 3: // abs(x) != -0.0
2537 if (!strcmp(F->getNameStart(), "abs")) return true;
2539 case 4: // abs[lf](x) != -0.0
2540 if (!strcmp(F->getNameStart(), "absf")) return true;
2541 if (!strcmp(F->getNameStart(), "absl")) return true;
2551 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2552 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2553 /// This basically requires proving that the add in the original type would not
2554 /// overflow to change the sign bit or have a carry out.
2555 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2556 // There are different heuristics we can use for this. Here are some simple
2559 // Add has the property that adding any two 2's complement numbers can only
2560 // have one carry bit which can change a sign. As such, if LHS and RHS each
2561 // have at least two sign bits, we know that the addition of the two values will
2562 // sign extend fine.
2563 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2567 // If one of the operands only has one non-zero bit, and if the other operand
2568 // has a known-zero bit in a more significant place than it (not including the
2569 // sign bit) the ripple may go up to and fill the zero, but won't change the
2570 // sign. For example, (X & ~4) + 1.
2578 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2579 bool Changed = SimplifyCommutative(I);
2580 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2582 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2583 // X + undef -> undef
2584 if (isa<UndefValue>(RHS))
2585 return ReplaceInstUsesWith(I, RHS);
2588 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2589 if (RHSC->isNullValue())
2590 return ReplaceInstUsesWith(I, LHS);
2591 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2592 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2593 (I.getType())->getValueAPF()))
2594 return ReplaceInstUsesWith(I, LHS);
2597 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2598 // X + (signbit) --> X ^ signbit
2599 const APInt& Val = CI->getValue();
2600 uint32_t BitWidth = Val.getBitWidth();
2601 if (Val == APInt::getSignBit(BitWidth))
2602 return BinaryOperator::CreateXor(LHS, RHS);
2604 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2605 // (X & 254)+1 -> (X&254)|1
2606 if (!isa<VectorType>(I.getType())) {
2607 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2608 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2609 KnownZero, KnownOne))
2614 if (isa<PHINode>(LHS))
2615 if (Instruction *NV = FoldOpIntoPhi(I))
2618 ConstantInt *XorRHS = 0;
2620 if (isa<ConstantInt>(RHSC) &&
2621 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2622 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2623 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2625 uint32_t Size = TySizeBits / 2;
2626 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2627 APInt CFF80Val(-C0080Val);
2629 if (TySizeBits > Size) {
2630 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2631 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2632 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2633 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2634 // This is a sign extend if the top bits are known zero.
2635 if (!MaskedValueIsZero(XorLHS,
2636 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2637 Size = 0; // Not a sign ext, but can't be any others either.
2642 C0080Val = APIntOps::lshr(C0080Val, Size);
2643 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2644 } while (Size >= 1);
2646 // FIXME: This shouldn't be necessary. When the backends can handle types
2647 // with funny bit widths then this switch statement should be removed. It
2648 // is just here to get the size of the "middle" type back up to something
2649 // that the back ends can handle.
2650 const Type *MiddleType = 0;
2653 case 32: MiddleType = Type::Int32Ty; break;
2654 case 16: MiddleType = Type::Int16Ty; break;
2655 case 8: MiddleType = Type::Int8Ty; break;
2658 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2659 InsertNewInstBefore(NewTrunc, I);
2660 return new SExtInst(NewTrunc, I.getType(), I.getName());
2666 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2667 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2669 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2670 if (RHSI->getOpcode() == Instruction::Sub)
2671 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2672 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2674 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2675 if (LHSI->getOpcode() == Instruction::Sub)
2676 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2677 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2682 // -A + -B --> -(A + B)
2683 if (Value *LHSV = dyn_castNegVal(LHS)) {
2684 if (LHS->getType()->isIntOrIntVector()) {
2685 if (Value *RHSV = dyn_castNegVal(RHS)) {
2686 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2687 InsertNewInstBefore(NewAdd, I);
2688 return BinaryOperator::CreateNeg(NewAdd);
2692 return BinaryOperator::CreateSub(RHS, LHSV);
2696 if (!isa<Constant>(RHS))
2697 if (Value *V = dyn_castNegVal(RHS))
2698 return BinaryOperator::CreateSub(LHS, V);
2702 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2703 if (X == RHS) // X*C + X --> X * (C+1)
2704 return BinaryOperator::CreateMul(RHS, AddOne(C2));
2706 // X*C1 + X*C2 --> X * (C1+C2)
2708 if (X == dyn_castFoldableMul(RHS, C1))
2709 return BinaryOperator::CreateMul(X, Add(C1, C2));
2712 // X + X*C --> X * (C+1)
2713 if (dyn_castFoldableMul(RHS, C2) == LHS)
2714 return BinaryOperator::CreateMul(LHS, AddOne(C2));
2716 // X + ~X --> -1 since ~X = -X-1
2717 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2718 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2721 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2722 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2723 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2726 // A+B --> A|B iff A and B have no bits set in common.
2727 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2728 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2729 APInt LHSKnownOne(IT->getBitWidth(), 0);
2730 APInt LHSKnownZero(IT->getBitWidth(), 0);
2731 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2732 if (LHSKnownZero != 0) {
2733 APInt RHSKnownOne(IT->getBitWidth(), 0);
2734 APInt RHSKnownZero(IT->getBitWidth(), 0);
2735 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2737 // No bits in common -> bitwise or.
2738 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2739 return BinaryOperator::CreateOr(LHS, RHS);
2743 // W*X + Y*Z --> W * (X+Z) iff W == Y
2744 if (I.getType()->isIntOrIntVector()) {
2745 Value *W, *X, *Y, *Z;
2746 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2747 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2751 } else if (Y == X) {
2753 } else if (X == Z) {
2760 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2761 LHS->getName()), I);
2762 return BinaryOperator::CreateMul(W, NewAdd);
2767 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2769 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2770 return BinaryOperator::CreateSub(SubOne(CRHS), X);
2772 // (X & FF00) + xx00 -> (X+xx00) & FF00
2773 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2774 Constant *Anded = And(CRHS, C2);
2775 if (Anded == CRHS) {
2776 // See if all bits from the first bit set in the Add RHS up are included
2777 // in the mask. First, get the rightmost bit.
2778 const APInt& AddRHSV = CRHS->getValue();
2780 // Form a mask of all bits from the lowest bit added through the top.
2781 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2783 // See if the and mask includes all of these bits.
2784 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2786 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2787 // Okay, the xform is safe. Insert the new add pronto.
2788 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2789 LHS->getName()), I);
2790 return BinaryOperator::CreateAnd(NewAdd, C2);
2795 // Try to fold constant add into select arguments.
2796 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2797 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2801 // add (cast *A to intptrtype) B ->
2802 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
2804 CastInst *CI = dyn_cast<CastInst>(LHS);
2807 CI = dyn_cast<CastInst>(RHS);
2810 if (CI && CI->getType()->isSized() &&
2811 (CI->getType()->getPrimitiveSizeInBits() ==
2812 TD->getIntPtrType()->getPrimitiveSizeInBits())
2813 && isa<PointerType>(CI->getOperand(0)->getType())) {
2815 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2816 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2817 PointerType::get(Type::Int8Ty, AS), I);
2818 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2819 return new PtrToIntInst(I2, CI->getType());
2823 // add (select X 0 (sub n A)) A --> select X A n
2825 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2828 SI = dyn_cast<SelectInst>(RHS);
2831 if (SI && SI->hasOneUse()) {
2832 Value *TV = SI->getTrueValue();
2833 Value *FV = SI->getFalseValue();
2836 // Can we fold the add into the argument of the select?
2837 // We check both true and false select arguments for a matching subtract.
2838 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2839 A == Other) // Fold the add into the true select value.
2840 return SelectInst::Create(SI->getCondition(), N, A);
2841 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2842 A == Other) // Fold the add into the false select value.
2843 return SelectInst::Create(SI->getCondition(), A, N);
2847 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2848 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2849 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2850 return ReplaceInstUsesWith(I, LHS);
2852 // Check for (add (sext x), y), see if we can merge this into an
2853 // integer add followed by a sext.
2854 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2855 // (add (sext x), cst) --> (sext (add x, cst'))
2856 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2858 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2859 if (LHSConv->hasOneUse() &&
2860 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2861 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2862 // Insert the new, smaller add.
2863 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2865 InsertNewInstBefore(NewAdd, I);
2866 return new SExtInst(NewAdd, I.getType());
2870 // (add (sext x), (sext y)) --> (sext (add int x, y))
2871 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2872 // Only do this if x/y have the same type, if at last one of them has a
2873 // single use (so we don't increase the number of sexts), and if the
2874 // integer add will not overflow.
2875 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2876 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2877 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2878 RHSConv->getOperand(0))) {
2879 // Insert the new integer add.
2880 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2881 RHSConv->getOperand(0),
2883 InsertNewInstBefore(NewAdd, I);
2884 return new SExtInst(NewAdd, I.getType());
2889 // Check for (add double (sitofp x), y), see if we can merge this into an
2890 // integer add followed by a promotion.
2891 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2892 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2893 // ... if the constant fits in the integer value. This is useful for things
2894 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2895 // requires a constant pool load, and generally allows the add to be better
2897 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2899 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2900 if (LHSConv->hasOneUse() &&
2901 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2902 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2903 // Insert the new integer add.
2904 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2906 InsertNewInstBefore(NewAdd, I);
2907 return new SIToFPInst(NewAdd, I.getType());
2911 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2912 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2913 // Only do this if x/y have the same type, if at last one of them has a
2914 // single use (so we don't increase the number of int->fp conversions),
2915 // and if the integer add will not overflow.
2916 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2917 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2918 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2919 RHSConv->getOperand(0))) {
2920 // Insert the new integer add.
2921 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2922 RHSConv->getOperand(0),
2924 InsertNewInstBefore(NewAdd, I);
2925 return new SIToFPInst(NewAdd, I.getType());
2930 return Changed ? &I : 0;
2933 // isSignBit - Return true if the value represented by the constant only has the
2934 // highest order bit set.
2935 static bool isSignBit(ConstantInt *CI) {
2936 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2937 return CI->getValue() == APInt::getSignBit(NumBits);
2940 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2941 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2943 if (Op0 == Op1) // sub X, X -> 0
2944 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2946 // If this is a 'B = x-(-A)', change to B = x+A...
2947 if (Value *V = dyn_castNegVal(Op1))
2948 return BinaryOperator::CreateAdd(Op0, V);
2950 if (isa<UndefValue>(Op0))
2951 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2952 if (isa<UndefValue>(Op1))
2953 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2955 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2956 // Replace (-1 - A) with (~A)...
2957 if (C->isAllOnesValue())
2958 return BinaryOperator::CreateNot(Op1);
2960 // C - ~X == X + (1+C)
2962 if (match(Op1, m_Not(m_Value(X))))
2963 return BinaryOperator::CreateAdd(X, AddOne(C));
2965 // -(X >>u 31) -> (X >>s 31)
2966 // -(X >>s 31) -> (X >>u 31)
2968 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2969 if (SI->getOpcode() == Instruction::LShr) {
2970 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2971 // Check to see if we are shifting out everything but the sign bit.
2972 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2973 SI->getType()->getPrimitiveSizeInBits()-1) {
2974 // Ok, the transformation is safe. Insert AShr.
2975 return BinaryOperator::Create(Instruction::AShr,
2976 SI->getOperand(0), CU, SI->getName());
2980 else if (SI->getOpcode() == Instruction::AShr) {
2981 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2982 // Check to see if we are shifting out everything but the sign bit.
2983 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2984 SI->getType()->getPrimitiveSizeInBits()-1) {
2985 // Ok, the transformation is safe. Insert LShr.
2986 return BinaryOperator::CreateLShr(
2987 SI->getOperand(0), CU, SI->getName());
2994 // Try to fold constant sub into select arguments.
2995 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2996 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2999 if (isa<PHINode>(Op0))
3000 if (Instruction *NV = FoldOpIntoPhi(I))
3004 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
3005 if (Op1I->getOpcode() == Instruction::Add &&
3006 !Op0->getType()->isFPOrFPVector()) {
3007 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
3008 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
3009 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
3010 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
3011 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
3012 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
3013 // C1-(X+C2) --> (C1-C2)-X
3014 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
3015 Op1I->getOperand(0));
3019 if (Op1I->hasOneUse()) {
3020 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
3021 // is not used by anyone else...
3023 if (Op1I->getOpcode() == Instruction::Sub &&
3024 !Op1I->getType()->isFPOrFPVector()) {
3025 // Swap the two operands of the subexpr...
3026 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
3027 Op1I->setOperand(0, IIOp1);
3028 Op1I->setOperand(1, IIOp0);
3030 // Create the new top level add instruction...
3031 return BinaryOperator::CreateAdd(Op0, Op1);
3034 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
3036 if (Op1I->getOpcode() == Instruction::And &&
3037 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
3038 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
3041 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
3042 return BinaryOperator::CreateAnd(Op0, NewNot);
3045 // 0 - (X sdiv C) -> (X sdiv -C)
3046 if (Op1I->getOpcode() == Instruction::SDiv)
3047 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
3049 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
3050 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
3051 ConstantExpr::getNeg(DivRHS));
3053 // X - X*C --> X * (1-C)
3054 ConstantInt *C2 = 0;
3055 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
3056 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
3057 return BinaryOperator::CreateMul(Op0, CP1);
3060 // X - ((X / Y) * Y) --> X % Y
3061 if (Op1I->getOpcode() == Instruction::Mul)
3062 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
3063 if (Op0 == I->getOperand(0) &&
3064 Op1I->getOperand(1) == I->getOperand(1)) {
3065 if (I->getOpcode() == Instruction::SDiv)
3066 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
3067 if (I->getOpcode() == Instruction::UDiv)
3068 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
3073 if (!Op0->getType()->isFPOrFPVector())
3074 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
3075 if (Op0I->getOpcode() == Instruction::Add) {
3076 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
3077 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3078 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
3079 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3080 } else if (Op0I->getOpcode() == Instruction::Sub) {
3081 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
3082 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
3087 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
3088 if (X == Op1) // X*C - X --> X * (C-1)
3089 return BinaryOperator::CreateMul(Op1, SubOne(C1));
3091 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
3092 if (X == dyn_castFoldableMul(Op1, C2))
3093 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
3098 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
3099 /// comparison only checks the sign bit. If it only checks the sign bit, set
3100 /// TrueIfSigned if the result of the comparison is true when the input value is
3102 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
3103 bool &TrueIfSigned) {
3105 case ICmpInst::ICMP_SLT: // True if LHS s< 0
3106 TrueIfSigned = true;
3107 return RHS->isZero();
3108 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
3109 TrueIfSigned = true;
3110 return RHS->isAllOnesValue();
3111 case ICmpInst::ICMP_SGT: // True if LHS s> -1
3112 TrueIfSigned = false;
3113 return RHS->isAllOnesValue();
3114 case ICmpInst::ICMP_UGT:
3115 // True if LHS u> RHS and RHS == high-bit-mask - 1
3116 TrueIfSigned = true;
3117 return RHS->getValue() ==
3118 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
3119 case ICmpInst::ICMP_UGE:
3120 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
3121 TrueIfSigned = true;
3122 return RHS->getValue() ==
3123 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
3129 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
3130 bool Changed = SimplifyCommutative(I);
3131 Value *Op0 = I.getOperand(0);
3133 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
3134 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3136 // Simplify mul instructions with a constant RHS...
3137 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
3138 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3140 // ((X << C1)*C2) == (X * (C2 << C1))
3141 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
3142 if (SI->getOpcode() == Instruction::Shl)
3143 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
3144 return BinaryOperator::CreateMul(SI->getOperand(0),
3145 ConstantExpr::getShl(CI, ShOp));
3148 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
3149 if (CI->equalsInt(1)) // X * 1 == X
3150 return ReplaceInstUsesWith(I, Op0);
3151 if (CI->isAllOnesValue()) // X * -1 == 0 - X
3152 return BinaryOperator::CreateNeg(Op0, I.getName());
3154 const APInt& Val = cast<ConstantInt>(CI)->getValue();
3155 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
3156 return BinaryOperator::CreateShl(Op0,
3157 ConstantInt::get(Op0->getType(), Val.logBase2()));
3159 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
3160 if (Op1F->isNullValue())
3161 return ReplaceInstUsesWith(I, Op1);
3163 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3164 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3165 // We need a better interface for long double here.
3166 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
3167 if (Op1F->isExactlyValue(1.0))
3168 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
3171 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3172 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
3173 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
3174 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
3175 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
3177 InsertNewInstBefore(Add, I);
3178 Value *C1C2 = ConstantExpr::getMul(Op1,
3179 cast<Constant>(Op0I->getOperand(1)));
3180 return BinaryOperator::CreateAdd(Add, C1C2);
3184 // Try to fold constant mul into select arguments.
3185 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3186 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3189 if (isa<PHINode>(Op0))
3190 if (Instruction *NV = FoldOpIntoPhi(I))
3194 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
3195 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
3196 return BinaryOperator::CreateMul(Op0v, Op1v);
3198 // If one of the operands of the multiply is a cast from a boolean value, then
3199 // we know the bool is either zero or one, so this is a 'masking' multiply.
3200 // See if we can simplify things based on how the boolean was originally
3202 CastInst *BoolCast = 0;
3203 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
3204 if (CI->getOperand(0)->getType() == Type::Int1Ty)
3207 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
3208 if (CI->getOperand(0)->getType() == Type::Int1Ty)
3211 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
3212 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
3213 const Type *SCOpTy = SCIOp0->getType();
3216 // If the icmp is true iff the sign bit of X is set, then convert this
3217 // multiply into a shift/and combination.
3218 if (isa<ConstantInt>(SCIOp1) &&
3219 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
3221 // Shift the X value right to turn it into "all signbits".
3222 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
3223 SCOpTy->getPrimitiveSizeInBits()-1);
3225 InsertNewInstBefore(
3226 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
3227 BoolCast->getOperand(0)->getName()+
3230 // If the multiply type is not the same as the source type, sign extend
3231 // or truncate to the multiply type.
3232 if (I.getType() != V->getType()) {
3233 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
3234 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
3235 Instruction::CastOps opcode =
3236 (SrcBits == DstBits ? Instruction::BitCast :
3237 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
3238 V = InsertCastBefore(opcode, V, I.getType(), I);
3241 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
3242 return BinaryOperator::CreateAnd(V, OtherOp);
3247 return Changed ? &I : 0;
3250 /// This function implements the transforms on div instructions that work
3251 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3252 /// used by the visitors to those instructions.
3253 /// @brief Transforms common to all three div instructions
3254 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
3255 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3257 // undef / X -> 0 for integer.
3258 // undef / X -> undef for FP (the undef could be a snan).
3259 if (isa<UndefValue>(Op0)) {
3260 if (Op0->getType()->isFPOrFPVector())
3261 return ReplaceInstUsesWith(I, Op0);
3262 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3265 // X / undef -> undef
3266 if (isa<UndefValue>(Op1))
3267 return ReplaceInstUsesWith(I, Op1);
3269 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3270 // This does not apply for fdiv.
3271 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3272 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
3273 // the same basic block, then we replace the select with Y, and the
3274 // condition of the select with false (if the cond value is in the same BB).
3275 // If the select has uses other than the div, this allows them to be
3276 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
3277 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
3278 if (ST->isNullValue()) {
3279 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3280 if (CondI && CondI->getParent() == I.getParent())
3281 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3282 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3283 I.setOperand(1, SI->getOperand(2));
3285 UpdateValueUsesWith(SI, SI->getOperand(2));
3289 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
3290 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
3291 if (ST->isNullValue()) {
3292 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3293 if (CondI && CondI->getParent() == I.getParent())
3294 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3295 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3296 I.setOperand(1, SI->getOperand(1));
3298 UpdateValueUsesWith(SI, SI->getOperand(1));
3306 /// This function implements the transforms common to both integer division
3307 /// instructions (udiv and sdiv). It is called by the visitors to those integer
3308 /// division instructions.
3309 /// @brief Common integer divide transforms
3310 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3311 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3313 // (sdiv X, X) --> 1 (udiv X, X) --> 1
3315 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
3317 if (Instruction *Common = commonDivTransforms(I))
3320 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3322 if (RHS->equalsInt(1))
3323 return ReplaceInstUsesWith(I, Op0);
3325 // (X / C1) / C2 -> X / (C1*C2)
3326 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3327 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3328 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3329 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3330 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3332 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3333 Multiply(RHS, LHSRHS));
3336 if (!RHS->isZero()) { // avoid X udiv 0
3337 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3338 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3340 if (isa<PHINode>(Op0))
3341 if (Instruction *NV = FoldOpIntoPhi(I))
3346 // 0 / X == 0, we don't need to preserve faults!
3347 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3348 if (LHS->equalsInt(0))
3349 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3354 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3355 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3357 // Handle the integer div common cases
3358 if (Instruction *Common = commonIDivTransforms(I))
3361 // X udiv C^2 -> X >> C
3362 // Check to see if this is an unsigned division with an exact power of 2,
3363 // if so, convert to a right shift.
3364 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3365 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
3366 return BinaryOperator::CreateLShr(Op0,
3367 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3370 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3371 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3372 if (RHSI->getOpcode() == Instruction::Shl &&
3373 isa<ConstantInt>(RHSI->getOperand(0))) {
3374 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3375 if (C1.isPowerOf2()) {
3376 Value *N = RHSI->getOperand(1);
3377 const Type *NTy = N->getType();
3378 if (uint32_t C2 = C1.logBase2()) {
3379 Constant *C2V = ConstantInt::get(NTy, C2);
3380 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3382 return BinaryOperator::CreateLShr(Op0, N);
3387 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3388 // where C1&C2 are powers of two.
3389 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3390 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3391 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3392 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3393 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3394 // Compute the shift amounts
3395 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3396 // Construct the "on true" case of the select
3397 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3398 Instruction *TSI = BinaryOperator::CreateLShr(
3399 Op0, TC, SI->getName()+".t");
3400 TSI = InsertNewInstBefore(TSI, I);
3402 // Construct the "on false" case of the select
3403 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
3404 Instruction *FSI = BinaryOperator::CreateLShr(
3405 Op0, FC, SI->getName()+".f");
3406 FSI = InsertNewInstBefore(FSI, I);
3408 // construct the select instruction and return it.
3409 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3415 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3416 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3418 // Handle the integer div common cases
3419 if (Instruction *Common = commonIDivTransforms(I))
3422 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3424 if (RHS->isAllOnesValue())
3425 return BinaryOperator::CreateNeg(Op0);
3428 if (Value *LHSNeg = dyn_castNegVal(Op0))
3429 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
3432 // If the sign bits of both operands are zero (i.e. we can prove they are
3433 // unsigned inputs), turn this into a udiv.
3434 if (I.getType()->isInteger()) {
3435 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3436 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3437 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3438 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3445 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3446 return commonDivTransforms(I);
3449 /// This function implements the transforms on rem instructions that work
3450 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3451 /// is used by the visitors to those instructions.
3452 /// @brief Transforms common to all three rem instructions
3453 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3454 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3456 // 0 % X == 0 for integer, we don't need to preserve faults!
3457 if (Constant *LHS = dyn_cast<Constant>(Op0))
3458 if (LHS->isNullValue())
3459 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3461 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3462 if (I.getType()->isFPOrFPVector())
3463 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
3464 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3466 if (isa<UndefValue>(Op1))
3467 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3469 // Handle cases involving: rem X, (select Cond, Y, Z)
3470 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3471 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3472 // the same basic block, then we replace the select with Y, and the
3473 // condition of the select with false (if the cond value is in the same
3474 // BB). If the select has uses other than the div, this allows them to be
3476 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3477 if (ST->isNullValue()) {
3478 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3479 if (CondI && CondI->getParent() == I.getParent())
3480 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3481 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3482 I.setOperand(1, SI->getOperand(2));
3484 UpdateValueUsesWith(SI, SI->getOperand(2));
3487 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3488 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3489 if (ST->isNullValue()) {
3490 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3491 if (CondI && CondI->getParent() == I.getParent())
3492 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3493 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3494 I.setOperand(1, SI->getOperand(1));
3496 UpdateValueUsesWith(SI, SI->getOperand(1));
3504 /// This function implements the transforms common to both integer remainder
3505 /// instructions (urem and srem). It is called by the visitors to those integer
3506 /// remainder instructions.
3507 /// @brief Common integer remainder transforms
3508 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3509 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3511 if (Instruction *common = commonRemTransforms(I))
3514 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3515 // X % 0 == undef, we don't need to preserve faults!
3516 if (RHS->equalsInt(0))
3517 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3519 if (RHS->equalsInt(1)) // X % 1 == 0
3520 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3522 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3523 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3524 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3526 } else if (isa<PHINode>(Op0I)) {
3527 if (Instruction *NV = FoldOpIntoPhi(I))
3531 // See if we can fold away this rem instruction.
3532 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3533 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3534 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3535 KnownZero, KnownOne))
3543 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3544 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3546 if (Instruction *common = commonIRemTransforms(I))
3549 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3550 // X urem C^2 -> X and C
3551 // Check to see if this is an unsigned remainder with an exact power of 2,
3552 // if so, convert to a bitwise and.
3553 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3554 if (C->getValue().isPowerOf2())
3555 return BinaryOperator::CreateAnd(Op0, SubOne(C));
3558 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3559 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3560 if (RHSI->getOpcode() == Instruction::Shl &&
3561 isa<ConstantInt>(RHSI->getOperand(0))) {
3562 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3563 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3564 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3566 return BinaryOperator::CreateAnd(Op0, Add);
3571 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3572 // where C1&C2 are powers of two.
3573 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3574 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3575 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3576 // STO == 0 and SFO == 0 handled above.
3577 if ((STO->getValue().isPowerOf2()) &&
3578 (SFO->getValue().isPowerOf2())) {
3579 Value *TrueAnd = InsertNewInstBefore(
3580 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3581 Value *FalseAnd = InsertNewInstBefore(
3582 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3583 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3591 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3592 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3594 // Handle the integer rem common cases
3595 if (Instruction *common = commonIRemTransforms(I))
3598 if (Value *RHSNeg = dyn_castNegVal(Op1))
3599 if (!isa<ConstantInt>(RHSNeg) ||
3600 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
3602 AddUsesToWorkList(I);
3603 I.setOperand(1, RHSNeg);
3607 // If the sign bits of both operands are zero (i.e. we can prove they are
3608 // unsigned inputs), turn this into a urem.
3609 if (I.getType()->isInteger()) {
3610 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3611 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3612 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3613 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3620 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3621 return commonRemTransforms(I);
3624 // isMaxValueMinusOne - return true if this is Max-1
3625 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
3626 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3628 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3629 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
3632 // isMinValuePlusOne - return true if this is Min+1
3633 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
3635 return C->getValue() == 1; // unsigned
3637 // Calculate 1111111111000000000000
3638 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3639 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
3642 // isOneBitSet - Return true if there is exactly one bit set in the specified
3644 static bool isOneBitSet(const ConstantInt *CI) {
3645 return CI->getValue().isPowerOf2();
3648 // isHighOnes - Return true if the constant is of the form 1+0+.
3649 // This is the same as lowones(~X).
3650 static bool isHighOnes(const ConstantInt *CI) {
3651 return (~CI->getValue() + 1).isPowerOf2();
3654 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3655 /// are carefully arranged to allow folding of expressions such as:
3657 /// (A < B) | (A > B) --> (A != B)
3659 /// Note that this is only valid if the first and second predicates have the
3660 /// same sign. Is illegal to do: (A u< B) | (A s> B)
3662 /// Three bits are used to represent the condition, as follows:
3667 /// <=> Value Definition
3668 /// 000 0 Always false
3675 /// 111 7 Always true
3677 static unsigned getICmpCode(const ICmpInst *ICI) {
3678 switch (ICI->getPredicate()) {
3680 case ICmpInst::ICMP_UGT: return 1; // 001
3681 case ICmpInst::ICMP_SGT: return 1; // 001
3682 case ICmpInst::ICMP_EQ: return 2; // 010
3683 case ICmpInst::ICMP_UGE: return 3; // 011
3684 case ICmpInst::ICMP_SGE: return 3; // 011
3685 case ICmpInst::ICMP_ULT: return 4; // 100
3686 case ICmpInst::ICMP_SLT: return 4; // 100
3687 case ICmpInst::ICMP_NE: return 5; // 101
3688 case ICmpInst::ICMP_ULE: return 6; // 110
3689 case ICmpInst::ICMP_SLE: return 6; // 110
3692 assert(0 && "Invalid ICmp predicate!");
3697 /// getICmpValue - This is the complement of getICmpCode, which turns an
3698 /// opcode and two operands into either a constant true or false, or a brand
3699 /// new ICmp instruction. The sign is passed in to determine which kind
3700 /// of predicate to use in new icmp instructions.
3701 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3703 default: assert(0 && "Illegal ICmp code!");
3704 case 0: return ConstantInt::getFalse();
3707 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3709 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3710 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3713 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3715 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3718 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3720 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3721 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3724 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3726 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3727 case 7: return ConstantInt::getTrue();
3731 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3732 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3733 (ICmpInst::isSignedPredicate(p1) &&
3734 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3735 (ICmpInst::isSignedPredicate(p2) &&
3736 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3740 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3741 struct FoldICmpLogical {
3744 ICmpInst::Predicate pred;
3745 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3746 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3747 pred(ICI->getPredicate()) {}
3748 bool shouldApply(Value *V) const {
3749 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3750 if (PredicatesFoldable(pred, ICI->getPredicate()))
3751 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3752 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3755 Instruction *apply(Instruction &Log) const {
3756 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3757 if (ICI->getOperand(0) != LHS) {
3758 assert(ICI->getOperand(1) == LHS);
3759 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3762 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3763 unsigned LHSCode = getICmpCode(ICI);
3764 unsigned RHSCode = getICmpCode(RHSICI);
3766 switch (Log.getOpcode()) {
3767 case Instruction::And: Code = LHSCode & RHSCode; break;
3768 case Instruction::Or: Code = LHSCode | RHSCode; break;
3769 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3770 default: assert(0 && "Illegal logical opcode!"); return 0;
3773 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3774 ICmpInst::isSignedPredicate(ICI->getPredicate());
3776 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3777 if (Instruction *I = dyn_cast<Instruction>(RV))
3779 // Otherwise, it's a constant boolean value...
3780 return IC.ReplaceInstUsesWith(Log, RV);
3783 } // end anonymous namespace
3785 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3786 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3787 // guaranteed to be a binary operator.
3788 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3790 ConstantInt *AndRHS,
3791 BinaryOperator &TheAnd) {
3792 Value *X = Op->getOperand(0);
3793 Constant *Together = 0;
3795 Together = And(AndRHS, OpRHS);
3797 switch (Op->getOpcode()) {
3798 case Instruction::Xor:
3799 if (Op->hasOneUse()) {
3800 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3801 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3802 InsertNewInstBefore(And, TheAnd);
3804 return BinaryOperator::CreateXor(And, Together);
3807 case Instruction::Or:
3808 if (Together == AndRHS) // (X | C) & C --> C
3809 return ReplaceInstUsesWith(TheAnd, AndRHS);
3811 if (Op->hasOneUse() && Together != OpRHS) {
3812 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3813 Instruction *Or = BinaryOperator::CreateOr(X, Together);
3814 InsertNewInstBefore(Or, TheAnd);
3816 return BinaryOperator::CreateAnd(Or, AndRHS);
3819 case Instruction::Add:
3820 if (Op->hasOneUse()) {
3821 // Adding a one to a single bit bit-field should be turned into an XOR
3822 // of the bit. First thing to check is to see if this AND is with a
3823 // single bit constant.
3824 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3826 // If there is only one bit set...
3827 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3828 // Ok, at this point, we know that we are masking the result of the
3829 // ADD down to exactly one bit. If the constant we are adding has
3830 // no bits set below this bit, then we can eliminate the ADD.
3831 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3833 // Check to see if any bits below the one bit set in AndRHSV are set.
3834 if ((AddRHS & (AndRHSV-1)) == 0) {
3835 // If not, the only thing that can effect the output of the AND is
3836 // the bit specified by AndRHSV. If that bit is set, the effect of
3837 // the XOR is to toggle the bit. If it is clear, then the ADD has
3839 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3840 TheAnd.setOperand(0, X);
3843 // Pull the XOR out of the AND.
3844 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3845 InsertNewInstBefore(NewAnd, TheAnd);
3846 NewAnd->takeName(Op);
3847 return BinaryOperator::CreateXor(NewAnd, AndRHS);
3854 case Instruction::Shl: {
3855 // We know that the AND will not produce any of the bits shifted in, so if
3856 // the anded constant includes them, clear them now!
3858 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3859 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3860 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3861 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3863 if (CI->getValue() == ShlMask) {
3864 // Masking out bits that the shift already masks
3865 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3866 } else if (CI != AndRHS) { // Reducing bits set in and.
3867 TheAnd.setOperand(1, CI);
3872 case Instruction::LShr:
3874 // We know that the AND will not produce any of the bits shifted in, so if
3875 // the anded constant includes them, clear them now! This only applies to
3876 // unsigned shifts, because a signed shr may bring in set bits!
3878 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3879 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3880 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3881 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3883 if (CI->getValue() == ShrMask) {
3884 // Masking out bits that the shift already masks.
3885 return ReplaceInstUsesWith(TheAnd, Op);
3886 } else if (CI != AndRHS) {
3887 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3892 case Instruction::AShr:
3894 // See if this is shifting in some sign extension, then masking it out
3896 if (Op->hasOneUse()) {
3897 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3898 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3899 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3900 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3901 if (C == AndRHS) { // Masking out bits shifted in.
3902 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3903 // Make the argument unsigned.
3904 Value *ShVal = Op->getOperand(0);
3905 ShVal = InsertNewInstBefore(
3906 BinaryOperator::CreateLShr(ShVal, OpRHS,
3907 Op->getName()), TheAnd);
3908 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3917 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3918 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3919 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3920 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3921 /// insert new instructions.
3922 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3923 bool isSigned, bool Inside,
3925 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3926 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3927 "Lo is not <= Hi in range emission code!");
3930 if (Lo == Hi) // Trivially false.
3931 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3933 // V >= Min && V < Hi --> V < Hi
3934 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3935 ICmpInst::Predicate pred = (isSigned ?
3936 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3937 return new ICmpInst(pred, V, Hi);
3940 // Emit V-Lo <u Hi-Lo
3941 Constant *NegLo = ConstantExpr::getNeg(Lo);
3942 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3943 InsertNewInstBefore(Add, IB);
3944 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3945 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3948 if (Lo == Hi) // Trivially true.
3949 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3951 // V < Min || V >= Hi -> V > Hi-1
3952 Hi = SubOne(cast<ConstantInt>(Hi));
3953 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3954 ICmpInst::Predicate pred = (isSigned ?
3955 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3956 return new ICmpInst(pred, V, Hi);
3959 // Emit V-Lo >u Hi-1-Lo
3960 // Note that Hi has already had one subtracted from it, above.
3961 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3962 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3963 InsertNewInstBefore(Add, IB);
3964 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3965 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3968 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3969 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3970 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3971 // not, since all 1s are not contiguous.
3972 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3973 const APInt& V = Val->getValue();
3974 uint32_t BitWidth = Val->getType()->getBitWidth();
3975 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3977 // look for the first zero bit after the run of ones
3978 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3979 // look for the first non-zero bit
3980 ME = V.getActiveBits();
3984 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3985 /// where isSub determines whether the operator is a sub. If we can fold one of
3986 /// the following xforms:
3988 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3989 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3990 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3992 /// return (A +/- B).
3994 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3995 ConstantInt *Mask, bool isSub,
3997 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3998 if (!LHSI || LHSI->getNumOperands() != 2 ||
3999 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4001 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4003 switch (LHSI->getOpcode()) {
4005 case Instruction::And:
4006 if (And(N, Mask) == Mask) {
4007 // If the AndRHS is a power of two minus one (0+1+), this is simple.
4008 if ((Mask->getValue().countLeadingZeros() +
4009 Mask->getValue().countPopulation()) ==
4010 Mask->getValue().getBitWidth())
4013 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4014 // part, we don't need any explicit masks to take them out of A. If that
4015 // is all N is, ignore it.
4016 uint32_t MB = 0, ME = 0;
4017 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
4018 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
4019 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
4020 if (MaskedValueIsZero(RHS, Mask))
4025 case Instruction::Or:
4026 case Instruction::Xor:
4027 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
4028 if ((Mask->getValue().countLeadingZeros() +
4029 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
4030 && And(N, Mask)->isZero())
4037 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
4039 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
4040 return InsertNewInstBefore(New, I);
4043 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4044 bool Changed = SimplifyCommutative(I);
4045 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4047 if (isa<UndefValue>(Op1)) // X & undef -> 0
4048 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4052 return ReplaceInstUsesWith(I, Op1);
4054 // See if we can simplify any instructions used by the instruction whose sole
4055 // purpose is to compute bits we don't care about.
4056 if (!isa<VectorType>(I.getType())) {
4057 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4058 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4059 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4060 KnownZero, KnownOne))
4063 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4064 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
4065 return ReplaceInstUsesWith(I, I.getOperand(0));
4066 } else if (isa<ConstantAggregateZero>(Op1)) {
4067 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
4071 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4072 const APInt& AndRHSMask = AndRHS->getValue();
4073 APInt NotAndRHS(~AndRHSMask);
4075 // Optimize a variety of ((val OP C1) & C2) combinations...
4076 if (isa<BinaryOperator>(Op0)) {
4077 Instruction *Op0I = cast<Instruction>(Op0);
4078 Value *Op0LHS = Op0I->getOperand(0);
4079 Value *Op0RHS = Op0I->getOperand(1);
4080 switch (Op0I->getOpcode()) {
4081 case Instruction::Xor:
4082 case Instruction::Or:
4083 // If the mask is only needed on one incoming arm, push it up.
4084 if (Op0I->hasOneUse()) {
4085 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4086 // Not masking anything out for the LHS, move to RHS.
4087 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4088 Op0RHS->getName()+".masked");
4089 InsertNewInstBefore(NewRHS, I);
4090 return BinaryOperator::Create(
4091 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4093 if (!isa<Constant>(Op0RHS) &&
4094 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4095 // Not masking anything out for the RHS, move to LHS.
4096 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4097 Op0LHS->getName()+".masked");
4098 InsertNewInstBefore(NewLHS, I);
4099 return BinaryOperator::Create(
4100 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4105 case Instruction::Add:
4106 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4107 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4108 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4109 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4110 return BinaryOperator::CreateAnd(V, AndRHS);
4111 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4112 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
4115 case Instruction::Sub:
4116 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4117 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4118 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4119 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4120 return BinaryOperator::CreateAnd(V, AndRHS);
4124 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4125 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4127 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4128 // If this is an integer truncation or change from signed-to-unsigned, and
4129 // if the source is an and/or with immediate, transform it. This
4130 // frequently occurs for bitfield accesses.
4131 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4132 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4133 CastOp->getNumOperands() == 2)
4134 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4135 if (CastOp->getOpcode() == Instruction::And) {
4136 // Change: and (cast (and X, C1) to T), C2
4137 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4138 // This will fold the two constants together, which may allow
4139 // other simplifications.
4140 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4141 CastOp->getOperand(0), I.getType(),
4142 CastOp->getName()+".shrunk");
4143 NewCast = InsertNewInstBefore(NewCast, I);
4144 // trunc_or_bitcast(C1)&C2
4145 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4146 C3 = ConstantExpr::getAnd(C3, AndRHS);
4147 return BinaryOperator::CreateAnd(NewCast, C3);
4148 } else if (CastOp->getOpcode() == Instruction::Or) {
4149 // Change: and (cast (or X, C1) to T), C2
4150 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4151 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4152 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
4153 return ReplaceInstUsesWith(I, AndRHS);
4159 // Try to fold constant and into select arguments.
4160 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4161 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4163 if (isa<PHINode>(Op0))
4164 if (Instruction *NV = FoldOpIntoPhi(I))
4168 Value *Op0NotVal = dyn_castNotVal(Op0);
4169 Value *Op1NotVal = dyn_castNotVal(Op1);
4171 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4172 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4174 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4175 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4176 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4177 I.getName()+".demorgan");
4178 InsertNewInstBefore(Or, I);
4179 return BinaryOperator::CreateNot(Or);
4183 Value *A = 0, *B = 0, *C = 0, *D = 0;
4184 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4185 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4186 return ReplaceInstUsesWith(I, Op1);
4188 // (A|B) & ~(A&B) -> A^B
4189 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4190 if ((A == C && B == D) || (A == D && B == C))
4191 return BinaryOperator::CreateXor(A, B);
4195 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4196 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4197 return ReplaceInstUsesWith(I, Op0);
4199 // ~(A&B) & (A|B) -> A^B
4200 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4201 if ((A == C && B == D) || (A == D && B == C))
4202 return BinaryOperator::CreateXor(A, B);
4206 if (Op0->hasOneUse() &&
4207 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4208 if (A == Op1) { // (A^B)&A -> A&(A^B)
4209 I.swapOperands(); // Simplify below
4210 std::swap(Op0, Op1);
4211 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4212 cast<BinaryOperator>(Op0)->swapOperands();
4213 I.swapOperands(); // Simplify below
4214 std::swap(Op0, Op1);
4217 if (Op1->hasOneUse() &&
4218 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4219 if (B == Op0) { // B&(A^B) -> B&(B^A)
4220 cast<BinaryOperator>(Op1)->swapOperands();
4223 if (A == Op0) { // A&(A^B) -> A & ~B
4224 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4225 InsertNewInstBefore(NotB, I);
4226 return BinaryOperator::CreateAnd(A, NotB);
4231 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4232 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4233 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4236 Value *LHSVal, *RHSVal;
4237 ConstantInt *LHSCst, *RHSCst;
4238 ICmpInst::Predicate LHSCC, RHSCC;
4239 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4240 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4241 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
4242 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
4243 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4244 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4245 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4246 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4248 // Don't try to fold ICMP_SLT + ICMP_ULT.
4249 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
4250 ICmpInst::isSignedPredicate(LHSCC) ==
4251 ICmpInst::isSignedPredicate(RHSCC))) {
4252 // Ensure that the larger constant is on the RHS.
4253 ICmpInst::Predicate GT;
4254 if (ICmpInst::isSignedPredicate(LHSCC) ||
4255 (ICmpInst::isEquality(LHSCC) &&
4256 ICmpInst::isSignedPredicate(RHSCC)))
4257 GT = ICmpInst::ICMP_SGT;
4259 GT = ICmpInst::ICMP_UGT;
4261 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
4262 ICmpInst *LHS = cast<ICmpInst>(Op0);
4263 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
4264 std::swap(LHS, RHS);
4265 std::swap(LHSCst, RHSCst);
4266 std::swap(LHSCC, RHSCC);
4269 // At this point, we know we have have two icmp instructions
4270 // comparing a value against two constants and and'ing the result
4271 // together. Because of the above check, we know that we only have
4272 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4273 // (from the FoldICmpLogical check above), that the two constants
4274 // are not equal and that the larger constant is on the RHS
4275 assert(LHSCst != RHSCst && "Compares not folded above?");
4278 default: assert(0 && "Unknown integer condition code!");
4279 case ICmpInst::ICMP_EQ:
4281 default: assert(0 && "Unknown integer condition code!");
4282 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4283 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4284 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
4285 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4286 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4287 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4288 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4289 return ReplaceInstUsesWith(I, LHS);
4291 case ICmpInst::ICMP_NE:
4293 default: assert(0 && "Unknown integer condition code!");
4294 case ICmpInst::ICMP_ULT:
4295 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4296 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4297 break; // (X != 13 & X u< 15) -> no change
4298 case ICmpInst::ICMP_SLT:
4299 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4300 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4301 break; // (X != 13 & X s< 15) -> no change
4302 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4303 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4304 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4305 return ReplaceInstUsesWith(I, RHS);
4306 case ICmpInst::ICMP_NE:
4307 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
4308 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4309 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4310 LHSVal->getName()+".off");
4311 InsertNewInstBefore(Add, I);
4312 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4313 ConstantInt::get(Add->getType(), 1));
4315 break; // (X != 13 & X != 15) -> no change
4318 case ICmpInst::ICMP_ULT:
4320 default: assert(0 && "Unknown integer condition code!");
4321 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4322 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
4323 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4324 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4326 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4327 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4328 return ReplaceInstUsesWith(I, LHS);
4329 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4333 case ICmpInst::ICMP_SLT:
4335 default: assert(0 && "Unknown integer condition code!");
4336 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4337 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
4338 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4339 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4341 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4342 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4343 return ReplaceInstUsesWith(I, LHS);
4344 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4348 case ICmpInst::ICMP_UGT:
4350 default: assert(0 && "Unknown integer condition code!");
4351 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4352 return ReplaceInstUsesWith(I, LHS);
4353 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4354 return ReplaceInstUsesWith(I, RHS);
4355 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4357 case ICmpInst::ICMP_NE:
4358 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4359 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4360 break; // (X u> 13 & X != 15) -> no change
4361 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4362 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4364 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4368 case ICmpInst::ICMP_SGT:
4370 default: assert(0 && "Unknown integer condition code!");
4371 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
4372 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4373 return ReplaceInstUsesWith(I, RHS);
4374 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4376 case ICmpInst::ICMP_NE:
4377 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4378 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4379 break; // (X s> 13 & X != 15) -> no change
4380 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4381 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4383 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4391 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4392 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4393 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4394 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4395 const Type *SrcTy = Op0C->getOperand(0)->getType();
4396 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4397 // Only do this if the casts both really cause code to be generated.
4398 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4400 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4402 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4403 Op1C->getOperand(0),
4405 InsertNewInstBefore(NewOp, I);
4406 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4410 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4411 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4412 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4413 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4414 SI0->getOperand(1) == SI1->getOperand(1) &&
4415 (SI0->hasOneUse() || SI1->hasOneUse())) {
4416 Instruction *NewOp =
4417 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4419 SI0->getName()), I);
4420 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4421 SI1->getOperand(1));
4425 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4426 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4427 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4428 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4429 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4430 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4431 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4432 // If either of the constants are nans, then the whole thing returns
4434 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4435 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4436 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4437 RHS->getOperand(0));
4442 return Changed ? &I : 0;
4445 /// CollectBSwapParts - Look to see if the specified value defines a single byte
4446 /// in the result. If it does, and if the specified byte hasn't been filled in
4447 /// yet, fill it in and return false.
4448 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
4449 Instruction *I = dyn_cast<Instruction>(V);
4450 if (I == 0) return true;
4452 // If this is an or instruction, it is an inner node of the bswap.
4453 if (I->getOpcode() == Instruction::Or)
4454 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4455 CollectBSwapParts(I->getOperand(1), ByteValues);
4457 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
4458 // If this is a shift by a constant int, and it is "24", then its operand
4459 // defines a byte. We only handle unsigned types here.
4460 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
4461 // Not shifting the entire input by N-1 bytes?
4462 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
4463 8*(ByteValues.size()-1))
4467 if (I->getOpcode() == Instruction::Shl) {
4468 // X << 24 defines the top byte with the lowest of the input bytes.
4469 DestNo = ByteValues.size()-1;
4471 // X >>u 24 defines the low byte with the highest of the input bytes.
4475 // If the destination byte value is already defined, the values are or'd
4476 // together, which isn't a bswap (unless it's an or of the same bits).
4477 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4479 ByteValues[DestNo] = I->getOperand(0);
4483 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4485 Value *Shift = 0, *ShiftLHS = 0;
4486 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4487 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4488 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4490 Instruction *SI = cast<Instruction>(Shift);
4492 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
4493 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4494 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
4497 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4499 if (AndAmt->getValue().getActiveBits() > 64)
4501 uint64_t AndAmtVal = AndAmt->getZExtValue();
4502 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
4503 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
4505 // Unknown mask for bswap.
4506 if (DestByte == ByteValues.size()) return true;
4508 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
4510 if (SI->getOpcode() == Instruction::Shl)
4511 SrcByte = DestByte - ShiftBytes;
4513 SrcByte = DestByte + ShiftBytes;
4515 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4516 if (SrcByte != ByteValues.size()-DestByte-1)
4519 // If the destination byte value is already defined, the values are or'd
4520 // together, which isn't a bswap (unless it's an or of the same bits).
4521 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4523 ByteValues[DestByte] = SI->getOperand(0);
4527 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4528 /// If so, insert the new bswap intrinsic and return it.
4529 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4530 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4531 if (!ITy || ITy->getBitWidth() % 16)
4532 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4534 /// ByteValues - For each byte of the result, we keep track of which value
4535 /// defines each byte.
4536 SmallVector<Value*, 8> ByteValues;
4537 ByteValues.resize(ITy->getBitWidth()/8);
4539 // Try to find all the pieces corresponding to the bswap.
4540 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4541 CollectBSwapParts(I.getOperand(1), ByteValues))
4544 // Check to see if all of the bytes come from the same value.
4545 Value *V = ByteValues[0];
4546 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4548 // Check to make sure that all of the bytes come from the same value.
4549 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4550 if (ByteValues[i] != V)
4552 const Type *Tys[] = { ITy };
4553 Module *M = I.getParent()->getParent()->getParent();
4554 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4555 return CallInst::Create(F, V);
4559 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4560 bool Changed = SimplifyCommutative(I);
4561 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4563 if (isa<UndefValue>(Op1)) // X | undef -> -1
4564 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4568 return ReplaceInstUsesWith(I, Op0);
4570 // See if we can simplify any instructions used by the instruction whose sole
4571 // purpose is to compute bits we don't care about.
4572 if (!isa<VectorType>(I.getType())) {
4573 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4574 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4575 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4576 KnownZero, KnownOne))
4578 } else if (isa<ConstantAggregateZero>(Op1)) {
4579 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4580 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4581 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4582 return ReplaceInstUsesWith(I, I.getOperand(1));
4588 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4589 ConstantInt *C1 = 0; Value *X = 0;
4590 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4591 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4592 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4593 InsertNewInstBefore(Or, I);
4595 return BinaryOperator::CreateAnd(Or,
4596 ConstantInt::get(RHS->getValue() | C1->getValue()));
4599 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4600 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4601 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4602 InsertNewInstBefore(Or, I);
4604 return BinaryOperator::CreateXor(Or,
4605 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4608 // Try to fold constant and into select arguments.
4609 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4610 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4612 if (isa<PHINode>(Op0))
4613 if (Instruction *NV = FoldOpIntoPhi(I))
4617 Value *A = 0, *B = 0;
4618 ConstantInt *C1 = 0, *C2 = 0;
4620 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4621 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4622 return ReplaceInstUsesWith(I, Op1);
4623 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4624 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4625 return ReplaceInstUsesWith(I, Op0);
4627 // (A | B) | C and A | (B | C) -> bswap if possible.
4628 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4629 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4630 match(Op1, m_Or(m_Value(), m_Value())) ||
4631 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4632 match(Op1, m_Shift(m_Value(), m_Value())))) {
4633 if (Instruction *BSwap = MatchBSwap(I))
4637 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4638 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4639 MaskedValueIsZero(Op1, C1->getValue())) {
4640 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4641 InsertNewInstBefore(NOr, I);
4643 return BinaryOperator::CreateXor(NOr, C1);
4646 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4647 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4648 MaskedValueIsZero(Op0, C1->getValue())) {
4649 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4650 InsertNewInstBefore(NOr, I);
4652 return BinaryOperator::CreateXor(NOr, C1);
4656 Value *C = 0, *D = 0;
4657 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4658 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4659 Value *V1 = 0, *V2 = 0, *V3 = 0;
4660 C1 = dyn_cast<ConstantInt>(C);
4661 C2 = dyn_cast<ConstantInt>(D);
4662 if (C1 && C2) { // (A & C1)|(B & C2)
4663 // If we have: ((V + N) & C1) | (V & C2)
4664 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4665 // replace with V+N.
4666 if (C1->getValue() == ~C2->getValue()) {
4667 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4668 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4669 // Add commutes, try both ways.
4670 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4671 return ReplaceInstUsesWith(I, A);
4672 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4673 return ReplaceInstUsesWith(I, A);
4675 // Or commutes, try both ways.
4676 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4677 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4678 // Add commutes, try both ways.
4679 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4680 return ReplaceInstUsesWith(I, B);
4681 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4682 return ReplaceInstUsesWith(I, B);
4685 V1 = 0; V2 = 0; V3 = 0;
4688 // Check to see if we have any common things being and'ed. If so, find the
4689 // terms for V1 & (V2|V3).
4690 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4691 if (A == B) // (A & C)|(A & D) == A & (C|D)
4692 V1 = A, V2 = C, V3 = D;
4693 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4694 V1 = A, V2 = B, V3 = C;
4695 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4696 V1 = C, V2 = A, V3 = D;
4697 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4698 V1 = C, V2 = A, V3 = B;
4702 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4703 return BinaryOperator::CreateAnd(V1, Or);
4708 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4709 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4710 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4711 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4712 SI0->getOperand(1) == SI1->getOperand(1) &&
4713 (SI0->hasOneUse() || SI1->hasOneUse())) {
4714 Instruction *NewOp =
4715 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4717 SI0->getName()), I);
4718 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4719 SI1->getOperand(1));
4723 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4724 if (A == Op1) // ~A | A == -1
4725 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4729 // Note, A is still live here!
4730 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4732 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4734 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4735 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4736 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4737 I.getName()+".demorgan"), I);
4738 return BinaryOperator::CreateNot(And);
4742 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4743 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4744 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4747 Value *LHSVal, *RHSVal;
4748 ConstantInt *LHSCst, *RHSCst;
4749 ICmpInst::Predicate LHSCC, RHSCC;
4750 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4751 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4752 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4753 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4754 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4755 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4756 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4757 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4758 // We can't fold (ugt x, C) | (sgt x, C2).
4759 PredicatesFoldable(LHSCC, RHSCC)) {
4760 // Ensure that the larger constant is on the RHS.
4761 ICmpInst *LHS = cast<ICmpInst>(Op0);
4763 if (ICmpInst::isSignedPredicate(LHSCC))
4764 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4766 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4769 std::swap(LHS, RHS);
4770 std::swap(LHSCst, RHSCst);
4771 std::swap(LHSCC, RHSCC);
4774 // At this point, we know we have have two icmp instructions
4775 // comparing a value against two constants and or'ing the result
4776 // together. Because of the above check, we know that we only have
4777 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4778 // FoldICmpLogical check above), that the two constants are not
4780 assert(LHSCst != RHSCst && "Compares not folded above?");
4783 default: assert(0 && "Unknown integer condition code!");
4784 case ICmpInst::ICMP_EQ:
4786 default: assert(0 && "Unknown integer condition code!");
4787 case ICmpInst::ICMP_EQ:
4788 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4789 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4790 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4791 LHSVal->getName()+".off");
4792 InsertNewInstBefore(Add, I);
4793 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4794 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4796 break; // (X == 13 | X == 15) -> no change
4797 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4798 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4800 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4801 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4802 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4803 return ReplaceInstUsesWith(I, RHS);
4806 case ICmpInst::ICMP_NE:
4808 default: assert(0 && "Unknown integer condition code!");
4809 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4810 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4811 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4812 return ReplaceInstUsesWith(I, LHS);
4813 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4814 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4815 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4816 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4819 case ICmpInst::ICMP_ULT:
4821 default: assert(0 && "Unknown integer condition code!");
4822 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4824 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
4825 // If RHSCst is [us]MAXINT, it is always false. Not handling
4826 // this can cause overflow.
4827 if (RHSCst->isMaxValue(false))
4828 return ReplaceInstUsesWith(I, LHS);
4829 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4831 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4833 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4834 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4835 return ReplaceInstUsesWith(I, RHS);
4836 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4840 case ICmpInst::ICMP_SLT:
4842 default: assert(0 && "Unknown integer condition code!");
4843 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4845 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
4846 // If RHSCst is [us]MAXINT, it is always false. Not handling
4847 // this can cause overflow.
4848 if (RHSCst->isMaxValue(true))
4849 return ReplaceInstUsesWith(I, LHS);
4850 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4852 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4854 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4855 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4856 return ReplaceInstUsesWith(I, RHS);
4857 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4861 case ICmpInst::ICMP_UGT:
4863 default: assert(0 && "Unknown integer condition code!");
4864 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4865 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4866 return ReplaceInstUsesWith(I, LHS);
4867 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4869 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4870 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4871 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4872 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4876 case ICmpInst::ICMP_SGT:
4878 default: assert(0 && "Unknown integer condition code!");
4879 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4880 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4881 return ReplaceInstUsesWith(I, LHS);
4882 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4884 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4885 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4886 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4887 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4895 // fold (or (cast A), (cast B)) -> (cast (or A, B))
4896 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4897 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4898 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4899 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4900 !isa<ICmpInst>(Op1C->getOperand(0))) {
4901 const Type *SrcTy = Op0C->getOperand(0)->getType();
4902 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4903 // Only do this if the casts both really cause code to be
4905 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4907 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4909 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4910 Op1C->getOperand(0),
4912 InsertNewInstBefore(NewOp, I);
4913 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4920 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4921 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4922 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4923 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4924 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4925 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
4926 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4927 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4928 // If either of the constants are nans, then the whole thing returns
4930 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4931 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4933 // Otherwise, no need to compare the two constants, compare the
4935 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4936 RHS->getOperand(0));
4941 return Changed ? &I : 0;
4946 // XorSelf - Implements: X ^ X --> 0
4949 XorSelf(Value *rhs) : RHS(rhs) {}
4950 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4951 Instruction *apply(BinaryOperator &Xor) const {
4958 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4959 bool Changed = SimplifyCommutative(I);
4960 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4962 if (isa<UndefValue>(Op1)) {
4963 if (isa<UndefValue>(Op0))
4964 // Handle undef ^ undef -> 0 special case. This is a common
4966 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4967 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4970 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4971 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4972 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4973 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4976 // See if we can simplify any instructions used by the instruction whose sole
4977 // purpose is to compute bits we don't care about.
4978 if (!isa<VectorType>(I.getType())) {
4979 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4980 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4981 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4982 KnownZero, KnownOne))
4984 } else if (isa<ConstantAggregateZero>(Op1)) {
4985 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4988 // Is this a ~ operation?
4989 if (Value *NotOp = dyn_castNotVal(&I)) {
4990 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4991 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4992 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4993 if (Op0I->getOpcode() == Instruction::And ||
4994 Op0I->getOpcode() == Instruction::Or) {
4995 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4996 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4998 BinaryOperator::CreateNot(Op0I->getOperand(1),
4999 Op0I->getOperand(1)->getName()+".not");
5000 InsertNewInstBefore(NotY, I);
5001 if (Op0I->getOpcode() == Instruction::And)
5002 return BinaryOperator::CreateOr(Op0NotVal, NotY);
5004 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5011 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5012 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5013 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
5014 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5015 return new ICmpInst(ICI->getInversePredicate(),
5016 ICI->getOperand(0), ICI->getOperand(1));
5018 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5019 return new FCmpInst(FCI->getInversePredicate(),
5020 FCI->getOperand(0), FCI->getOperand(1));
5023 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5024 // ~(c-X) == X-c-1 == X+(-c-1)
5025 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5026 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5027 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5028 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5029 ConstantInt::get(I.getType(), 1));
5030 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5033 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5034 if (Op0I->getOpcode() == Instruction::Add) {
5035 // ~(X-c) --> (-c-1)-X
5036 if (RHS->isAllOnesValue()) {
5037 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5038 return BinaryOperator::CreateSub(
5039 ConstantExpr::getSub(NegOp0CI,
5040 ConstantInt::get(I.getType(), 1)),
5041 Op0I->getOperand(0));
5042 } else if (RHS->getValue().isSignBit()) {
5043 // (X + C) ^ signbit -> (X + C + signbit)
5044 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
5045 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5048 } else if (Op0I->getOpcode() == Instruction::Or) {
5049 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5050 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5051 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5052 // Anything in both C1 and C2 is known to be zero, remove it from
5054 Constant *CommonBits = And(Op0CI, RHS);
5055 NewRHS = ConstantExpr::getAnd(NewRHS,
5056 ConstantExpr::getNot(CommonBits));
5057 AddToWorkList(Op0I);
5058 I.setOperand(0, Op0I->getOperand(0));
5059 I.setOperand(1, NewRHS);
5066 // Try to fold constant and into select arguments.
5067 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5068 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5070 if (isa<PHINode>(Op0))
5071 if (Instruction *NV = FoldOpIntoPhi(I))
5075 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
5077 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5079 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
5081 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5084 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5087 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5088 if (A == Op0) { // B^(B|A) == (A|B)^B
5089 Op1I->swapOperands();
5091 std::swap(Op0, Op1);
5092 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5093 I.swapOperands(); // Simplified below.
5094 std::swap(Op0, Op1);
5096 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
5097 if (Op0 == A) // A^(A^B) == B
5098 return ReplaceInstUsesWith(I, B);
5099 else if (Op0 == B) // A^(B^A) == B
5100 return ReplaceInstUsesWith(I, A);
5101 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
5102 if (A == Op0) { // A^(A&B) -> A^(B&A)
5103 Op1I->swapOperands();
5106 if (B == Op0) { // A^(B&A) -> (B&A)^A
5107 I.swapOperands(); // Simplified below.
5108 std::swap(Op0, Op1);
5113 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5116 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5117 if (A == Op1) // (B|A)^B == (A|B)^B
5119 if (B == Op1) { // (A|B)^B == A & ~B
5121 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5122 return BinaryOperator::CreateAnd(A, NotB);
5124 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
5125 if (Op1 == A) // (A^B)^A == B
5126 return ReplaceInstUsesWith(I, B);
5127 else if (Op1 == B) // (B^A)^A == B
5128 return ReplaceInstUsesWith(I, A);
5129 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5130 if (A == Op1) // (A&B)^A -> (B&A)^A
5132 if (B == Op1 && // (B&A)^A == ~B & A
5133 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5135 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5136 return BinaryOperator::CreateAnd(N, Op1);
5141 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5142 if (Op0I && Op1I && Op0I->isShift() &&
5143 Op0I->getOpcode() == Op1I->getOpcode() &&
5144 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5145 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5146 Instruction *NewOp =
5147 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5148 Op1I->getOperand(0),
5149 Op0I->getName()), I);
5150 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
5151 Op1I->getOperand(1));
5155 Value *A, *B, *C, *D;
5156 // (A & B)^(A | B) -> A ^ B
5157 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5158 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5159 if ((A == C && B == D) || (A == D && B == C))
5160 return BinaryOperator::CreateXor(A, B);
5162 // (A | B)^(A & B) -> A ^ B
5163 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5164 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5165 if ((A == C && B == D) || (A == D && B == C))
5166 return BinaryOperator::CreateXor(A, B);
5170 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5171 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5172 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5173 // (X & Y)^(X & Y) -> (Y^Z) & X
5174 Value *X = 0, *Y = 0, *Z = 0;
5176 X = A, Y = B, Z = D;
5178 X = A, Y = B, Z = C;
5180 X = B, Y = A, Z = D;
5182 X = B, Y = A, Z = C;
5185 Instruction *NewOp =
5186 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5187 return BinaryOperator::CreateAnd(NewOp, X);
5192 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5193 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5194 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5197 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5198 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5199 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5200 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5201 const Type *SrcTy = Op0C->getOperand(0)->getType();
5202 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5203 // Only do this if the casts both really cause code to be generated.
5204 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5206 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5208 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5209 Op1C->getOperand(0),
5211 InsertNewInstBefore(NewOp, I);
5212 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5216 return Changed ? &I : 0;
5219 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5220 /// overflowed for this type.
5221 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5222 ConstantInt *In2, bool IsSigned = false) {
5223 Result = cast<ConstantInt>(Add(In1, In2));
5226 if (In2->getValue().isNegative())
5227 return Result->getValue().sgt(In1->getValue());
5229 return Result->getValue().slt(In1->getValue());
5231 return Result->getValue().ult(In1->getValue());
5234 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5235 /// code necessary to compute the offset from the base pointer (without adding
5236 /// in the base pointer). Return the result as a signed integer of intptr size.
5237 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5238 TargetData &TD = IC.getTargetData();
5239 gep_type_iterator GTI = gep_type_begin(GEP);
5240 const Type *IntPtrTy = TD.getIntPtrType();
5241 Value *Result = Constant::getNullValue(IntPtrTy);
5243 // Build a mask for high order bits.
5244 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5245 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5247 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
5248 Value *Op = GEP->getOperand(i);
5249 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
5250 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5251 if (OpC->isZero()) continue;
5253 // Handle a struct index, which adds its field offset to the pointer.
5254 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5255 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5257 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5258 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5260 Result = IC.InsertNewInstBefore(
5261 BinaryOperator::CreateAdd(Result,
5262 ConstantInt::get(IntPtrTy, Size),
5263 GEP->getName()+".offs"), I);
5267 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5268 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5269 Scale = ConstantExpr::getMul(OC, Scale);
5270 if (Constant *RC = dyn_cast<Constant>(Result))
5271 Result = ConstantExpr::getAdd(RC, Scale);
5273 // Emit an add instruction.
5274 Result = IC.InsertNewInstBefore(
5275 BinaryOperator::CreateAdd(Result, Scale,
5276 GEP->getName()+".offs"), I);
5280 // Convert to correct type.
5281 if (Op->getType() != IntPtrTy) {
5282 if (Constant *OpC = dyn_cast<Constant>(Op))
5283 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5285 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5286 Op->getName()+".c"), I);
5289 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5290 if (Constant *OpC = dyn_cast<Constant>(Op))
5291 Op = ConstantExpr::getMul(OpC, Scale);
5292 else // We'll let instcombine(mul) convert this to a shl if possible.
5293 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5294 GEP->getName()+".idx"), I);
5297 // Emit an add instruction.
5298 if (isa<Constant>(Op) && isa<Constant>(Result))
5299 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5300 cast<Constant>(Result));
5302 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5303 GEP->getName()+".offs"), I);
5309 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5310 /// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5311 /// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5312 /// complex, and scales are involved. The above expression would also be legal
5313 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5314 /// later form is less amenable to optimization though, and we are allowed to
5315 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5317 /// If we can't emit an optimized form for this expression, this returns null.
5319 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5321 TargetData &TD = IC.getTargetData();
5322 gep_type_iterator GTI = gep_type_begin(GEP);
5324 // Check to see if this gep only has a single variable index. If so, and if
5325 // any constant indices are a multiple of its scale, then we can compute this
5326 // in terms of the scale of the variable index. For example, if the GEP
5327 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5328 // because the expression will cross zero at the same point.
5329 unsigned i, e = GEP->getNumOperands();
5331 for (i = 1; i != e; ++i, ++GTI) {
5332 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5333 // Compute the aggregate offset of constant indices.
5334 if (CI->isZero()) continue;
5336 // Handle a struct index, which adds its field offset to the pointer.
5337 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5338 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5340 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5341 Offset += Size*CI->getSExtValue();
5344 // Found our variable index.
5349 // If there are no variable indices, we must have a constant offset, just
5350 // evaluate it the general way.
5351 if (i == e) return 0;
5353 Value *VariableIdx = GEP->getOperand(i);
5354 // Determine the scale factor of the variable element. For example, this is
5355 // 4 if the variable index is into an array of i32.
5356 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5358 // Verify that there are no other variable indices. If so, emit the hard way.
5359 for (++i, ++GTI; i != e; ++i, ++GTI) {
5360 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5363 // Compute the aggregate offset of constant indices.
5364 if (CI->isZero()) continue;
5366 // Handle a struct index, which adds its field offset to the pointer.
5367 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5368 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5370 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5371 Offset += Size*CI->getSExtValue();
5375 // Okay, we know we have a single variable index, which must be a
5376 // pointer/array/vector index. If there is no offset, life is simple, return
5378 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5380 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5381 // we don't need to bother extending: the extension won't affect where the
5382 // computation crosses zero.
5383 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5384 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5385 VariableIdx->getNameStart(), &I);
5389 // Otherwise, there is an index. The computation we will do will be modulo
5390 // the pointer size, so get it.
5391 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5393 Offset &= PtrSizeMask;
5394 VariableScale &= PtrSizeMask;
5396 // To do this transformation, any constant index must be a multiple of the
5397 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5398 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5399 // multiple of the variable scale.
5400 int64_t NewOffs = Offset / (int64_t)VariableScale;
5401 if (Offset != NewOffs*(int64_t)VariableScale)
5404 // Okay, we can do this evaluation. Start by converting the index to intptr.
5405 const Type *IntPtrTy = TD.getIntPtrType();
5406 if (VariableIdx->getType() != IntPtrTy)
5407 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5409 VariableIdx->getNameStart(), &I);
5410 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5411 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5415 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5416 /// else. At this point we know that the GEP is on the LHS of the comparison.
5417 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5418 ICmpInst::Predicate Cond,
5420 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5422 // Look through bitcasts.
5423 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5424 RHS = BCI->getOperand(0);
5426 Value *PtrBase = GEPLHS->getOperand(0);
5427 if (PtrBase == RHS) {
5428 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
5429 // This transformation (ignoring the base and scales) is valid because we
5430 // know pointers can't overflow. See if we can output an optimized form.
5431 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5433 // If not, synthesize the offset the hard way.
5435 Offset = EmitGEPOffset(GEPLHS, I, *this);
5436 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5437 Constant::getNullValue(Offset->getType()));
5438 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5439 // If the base pointers are different, but the indices are the same, just
5440 // compare the base pointer.
5441 if (PtrBase != GEPRHS->getOperand(0)) {
5442 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5443 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5444 GEPRHS->getOperand(0)->getType();
5446 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5447 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5448 IndicesTheSame = false;
5452 // If all indices are the same, just compare the base pointers.
5454 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5455 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5457 // Otherwise, the base pointers are different and the indices are
5458 // different, bail out.
5462 // If one of the GEPs has all zero indices, recurse.
5463 bool AllZeros = true;
5464 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5465 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5466 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5471 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5472 ICmpInst::getSwappedPredicate(Cond), I);
5474 // If the other GEP has all zero indices, recurse.
5476 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5477 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5478 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5483 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5485 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5486 // If the GEPs only differ by one index, compare it.
5487 unsigned NumDifferences = 0; // Keep track of # differences.
5488 unsigned DiffOperand = 0; // The operand that differs.
5489 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5490 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5491 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5492 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5493 // Irreconcilable differences.
5497 if (NumDifferences++) break;
5502 if (NumDifferences == 0) // SAME GEP?
5503 return ReplaceInstUsesWith(I, // No comparison is needed here.
5504 ConstantInt::get(Type::Int1Ty,
5505 ICmpInst::isTrueWhenEqual(Cond)));
5507 else if (NumDifferences == 1) {
5508 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5509 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5510 // Make sure we do a signed comparison here.
5511 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5515 // Only lower this if the icmp is the only user of the GEP or if we expect
5516 // the result to fold to a constant!
5517 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5518 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5519 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5520 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5521 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5522 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5528 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5530 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5533 if (!isa<ConstantFP>(RHSC)) return 0;
5534 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5536 // Get the width of the mantissa. We don't want to hack on conversions that
5537 // might lose information from the integer, e.g. "i64 -> float"
5538 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5539 if (MantissaWidth == -1) return 0; // Unknown.
5541 // Check to see that the input is converted from an integer type that is small
5542 // enough that preserves all bits. TODO: check here for "known" sign bits.
5543 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5544 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5546 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5547 if (isa<UIToFPInst>(LHSI))
5550 // If the conversion would lose info, don't hack on this.
5551 if ((int)InputSize > MantissaWidth)
5554 // Otherwise, we can potentially simplify the comparison. We know that it
5555 // will always come through as an integer value and we know the constant is
5556 // not a NAN (it would have been previously simplified).
5557 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5559 ICmpInst::Predicate Pred;
5560 switch (I.getPredicate()) {
5561 default: assert(0 && "Unexpected predicate!");
5562 case FCmpInst::FCMP_UEQ:
5563 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
5564 case FCmpInst::FCMP_UGT:
5565 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
5566 case FCmpInst::FCMP_UGE:
5567 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
5568 case FCmpInst::FCMP_ULT:
5569 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
5570 case FCmpInst::FCMP_ULE:
5571 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
5572 case FCmpInst::FCMP_UNE:
5573 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
5574 case FCmpInst::FCMP_ORD:
5575 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5576 case FCmpInst::FCMP_UNO:
5577 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5580 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5582 // Now we know that the APFloat is a normal number, zero or inf.
5584 // See if the FP constant is too large for the integer. For example,
5585 // comparing an i8 to 300.0.
5586 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5588 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5589 // and large values.
5590 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5591 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5592 APFloat::rmNearestTiesToEven);
5593 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5594 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
5595 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5596 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5599 // See if the RHS value is < SignedMin.
5600 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5601 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5602 APFloat::rmNearestTiesToEven);
5603 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5604 if (ICmpInst::ICMP_NE || ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE)
5605 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5606 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5609 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5610 // it may still be fractional. See if it is fractional by casting the FP
5611 // value to the integer value and back, checking for equality. Don't do this
5612 // for zero, because -0.0 is not fractional.
5613 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5614 if (!RHS.isZero() &&
5615 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5616 // If we had a comparison against a fractional value, we have to adjust
5617 // the compare predicate and sometimes the value. RHSC is rounded towards
5618 // zero at this point.
5620 default: assert(0 && "Unexpected integer comparison!");
5621 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5622 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5623 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5624 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5625 case ICmpInst::ICMP_SLE:
5626 // (float)int <= 4.4 --> int <= 4
5627 // (float)int <= -4.4 --> int < -4
5628 if (RHS.isNegative())
5629 Pred = ICmpInst::ICMP_SLT;
5631 case ICmpInst::ICMP_SLT:
5632 // (float)int < -4.4 --> int < -4
5633 // (float)int < 4.4 --> int <= 4
5634 if (!RHS.isNegative())
5635 Pred = ICmpInst::ICMP_SLE;
5637 case ICmpInst::ICMP_SGT:
5638 // (float)int > 4.4 --> int > 4
5639 // (float)int > -4.4 --> int >= -4
5640 if (RHS.isNegative())
5641 Pred = ICmpInst::ICMP_SGE;
5643 case ICmpInst::ICMP_SGE:
5644 // (float)int >= -4.4 --> int >= -4
5645 // (float)int >= 4.4 --> int > 4
5646 if (!RHS.isNegative())
5647 Pred = ICmpInst::ICMP_SGT;
5652 // Lower this FP comparison into an appropriate integer version of the
5654 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5657 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5658 bool Changed = SimplifyCompare(I);
5659 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5661 // Fold trivial predicates.
5662 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5663 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5664 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5665 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5667 // Simplify 'fcmp pred X, X'
5669 switch (I.getPredicate()) {
5670 default: assert(0 && "Unknown predicate!");
5671 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5672 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5673 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5674 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5675 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5676 case FCmpInst::FCMP_OLT: // True if ordered and less than
5677 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5678 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5680 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5681 case FCmpInst::FCMP_ULT: // True if unordered or less than
5682 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5683 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5684 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5685 I.setPredicate(FCmpInst::FCMP_UNO);
5686 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5689 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5690 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5691 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5692 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5693 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5694 I.setPredicate(FCmpInst::FCMP_ORD);
5695 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5700 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5701 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5703 // Handle fcmp with constant RHS
5704 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5705 // If the constant is a nan, see if we can fold the comparison based on it.
5706 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5707 if (CFP->getValueAPF().isNaN()) {
5708 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5709 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5710 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5711 "Comparison must be either ordered or unordered!");
5712 // True if unordered.
5713 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5717 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5718 switch (LHSI->getOpcode()) {
5719 case Instruction::PHI:
5720 if (Instruction *NV = FoldOpIntoPhi(I))
5723 case Instruction::SIToFP:
5724 case Instruction::UIToFP:
5725 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5728 case Instruction::Select:
5729 // If either operand of the select is a constant, we can fold the
5730 // comparison into the select arms, which will cause one to be
5731 // constant folded and the select turned into a bitwise or.
5732 Value *Op1 = 0, *Op2 = 0;
5733 if (LHSI->hasOneUse()) {
5734 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5735 // Fold the known value into the constant operand.
5736 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5737 // Insert a new FCmp of the other select operand.
5738 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5739 LHSI->getOperand(2), RHSC,
5741 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5742 // Fold the known value into the constant operand.
5743 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5744 // Insert a new FCmp of the other select operand.
5745 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5746 LHSI->getOperand(1), RHSC,
5752 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5757 return Changed ? &I : 0;
5760 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5761 bool Changed = SimplifyCompare(I);
5762 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5763 const Type *Ty = Op0->getType();
5767 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5768 I.isTrueWhenEqual()));
5770 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5771 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5773 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5774 // addresses never equal each other! We already know that Op0 != Op1.
5775 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5776 isa<ConstantPointerNull>(Op0)) &&
5777 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5778 isa<ConstantPointerNull>(Op1)))
5779 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5780 !I.isTrueWhenEqual()));
5782 // icmp's with boolean values can always be turned into bitwise operations
5783 if (Ty == Type::Int1Ty) {
5784 switch (I.getPredicate()) {
5785 default: assert(0 && "Invalid icmp instruction!");
5786 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
5787 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5788 InsertNewInstBefore(Xor, I);
5789 return BinaryOperator::CreateNot(Xor);
5791 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
5792 return BinaryOperator::CreateXor(Op0, Op1);
5794 case ICmpInst::ICMP_UGT:
5795 case ICmpInst::ICMP_SGT:
5796 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
5798 case ICmpInst::ICMP_ULT:
5799 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
5800 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5801 InsertNewInstBefore(Not, I);
5802 return BinaryOperator::CreateAnd(Not, Op1);
5804 case ICmpInst::ICMP_UGE:
5805 case ICmpInst::ICMP_SGE:
5806 std::swap(Op0, Op1); // Change icmp ge -> icmp le
5808 case ICmpInst::ICMP_ULE:
5809 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
5810 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5811 InsertNewInstBefore(Not, I);
5812 return BinaryOperator::CreateOr(Not, Op1);
5817 // See if we are doing a comparison between a constant and an instruction that
5818 // can be folded into the comparison.
5819 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5822 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5823 if (I.isEquality() && CI->isNullValue() &&
5824 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5825 // (icmp cond A B) if cond is equality
5826 return new ICmpInst(I.getPredicate(), A, B);
5829 switch (I.getPredicate()) {
5831 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5832 if (CI->isMinValue(false))
5833 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5834 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5835 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5836 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5837 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5838 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5839 if (CI->isMinValue(true))
5840 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5841 ConstantInt::getAllOnesValue(Op0->getType()));
5845 case ICmpInst::ICMP_SLT:
5846 if (CI->isMinValue(true)) // A <s MIN -> FALSE
5847 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5848 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5849 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5850 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5851 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5854 case ICmpInst::ICMP_UGT:
5855 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
5856 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5857 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5858 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5859 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5860 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5862 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5863 if (CI->isMaxValue(true))
5864 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5865 ConstantInt::getNullValue(Op0->getType()));
5868 case ICmpInst::ICMP_SGT:
5869 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
5870 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5871 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5872 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5873 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5874 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5877 case ICmpInst::ICMP_ULE:
5878 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5879 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5880 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5881 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5882 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5883 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5886 case ICmpInst::ICMP_SLE:
5887 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5888 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5889 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5890 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5891 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5892 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5895 case ICmpInst::ICMP_UGE:
5896 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5897 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5898 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5899 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5900 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5901 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5904 case ICmpInst::ICMP_SGE:
5905 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5906 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5907 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5908 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5909 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5910 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5914 // If we still have a icmp le or icmp ge instruction, turn it into the
5915 // appropriate icmp lt or icmp gt instruction. Since the border cases have
5916 // already been handled above, this requires little checking.
5918 switch (I.getPredicate()) {
5920 case ICmpInst::ICMP_ULE:
5921 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5922 case ICmpInst::ICMP_SLE:
5923 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5924 case ICmpInst::ICMP_UGE:
5925 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5926 case ICmpInst::ICMP_SGE:
5927 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5930 // See if we can fold the comparison based on bits known to be zero or one
5931 // in the input. If this comparison is a normal comparison, it demands all
5932 // bits, if it is a sign bit comparison, it only demands the sign bit.
5935 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5937 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5938 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5939 if (SimplifyDemandedBits(Op0,
5940 isSignBit ? APInt::getSignBit(BitWidth)
5941 : APInt::getAllOnesValue(BitWidth),
5942 KnownZero, KnownOne, 0))
5945 // Given the known and unknown bits, compute a range that the LHS could be
5947 if ((KnownOne | KnownZero) != 0) {
5948 // Compute the Min, Max and RHS values based on the known bits. For the
5949 // EQ and NE we use unsigned values.
5950 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5951 const APInt& RHSVal = CI->getValue();
5952 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5953 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5956 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5959 switch (I.getPredicate()) { // LE/GE have been folded already.
5960 default: assert(0 && "Unknown icmp opcode!");
5961 case ICmpInst::ICMP_EQ:
5962 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5963 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5965 case ICmpInst::ICMP_NE:
5966 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5967 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5969 case ICmpInst::ICMP_ULT:
5970 if (Max.ult(RHSVal))
5971 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5972 if (Min.uge(RHSVal))
5973 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5975 case ICmpInst::ICMP_UGT:
5976 if (Min.ugt(RHSVal))
5977 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5978 if (Max.ule(RHSVal))
5979 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5981 case ICmpInst::ICMP_SLT:
5982 if (Max.slt(RHSVal))
5983 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5984 if (Min.sgt(RHSVal))
5985 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5987 case ICmpInst::ICMP_SGT:
5988 if (Min.sgt(RHSVal))
5989 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5990 if (Max.sle(RHSVal))
5991 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5996 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5997 // instruction, see if that instruction also has constants so that the
5998 // instruction can be folded into the icmp
5999 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6000 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6004 // Handle icmp with constant (but not simple integer constant) RHS
6005 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6006 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6007 switch (LHSI->getOpcode()) {
6008 case Instruction::GetElementPtr:
6009 if (RHSC->isNullValue()) {
6010 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6011 bool isAllZeros = true;
6012 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6013 if (!isa<Constant>(LHSI->getOperand(i)) ||
6014 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6019 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6020 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6024 case Instruction::PHI:
6025 if (Instruction *NV = FoldOpIntoPhi(I))
6028 case Instruction::Select: {
6029 // If either operand of the select is a constant, we can fold the
6030 // comparison into the select arms, which will cause one to be
6031 // constant folded and the select turned into a bitwise or.
6032 Value *Op1 = 0, *Op2 = 0;
6033 if (LHSI->hasOneUse()) {
6034 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6035 // Fold the known value into the constant operand.
6036 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6037 // Insert a new ICmp of the other select operand.
6038 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6039 LHSI->getOperand(2), RHSC,
6041 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6042 // Fold the known value into the constant operand.
6043 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6044 // Insert a new ICmp of the other select operand.
6045 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
6046 LHSI->getOperand(1), RHSC,
6052 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6055 case Instruction::Malloc:
6056 // If we have (malloc != null), and if the malloc has a single use, we
6057 // can assume it is successful and remove the malloc.
6058 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6059 AddToWorkList(LHSI);
6060 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
6061 !I.isTrueWhenEqual()));
6067 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6068 if (User *GEP = dyn_castGetElementPtr(Op0))
6069 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6071 if (User *GEP = dyn_castGetElementPtr(Op1))
6072 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6073 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6076 // Test to see if the operands of the icmp are casted versions of other
6077 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6079 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6080 if (isa<PointerType>(Op0->getType()) &&
6081 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6082 // We keep moving the cast from the left operand over to the right
6083 // operand, where it can often be eliminated completely.
6084 Op0 = CI->getOperand(0);
6086 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6087 // so eliminate it as well.
6088 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6089 Op1 = CI2->getOperand(0);
6091 // If Op1 is a constant, we can fold the cast into the constant.
6092 if (Op0->getType() != Op1->getType()) {
6093 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6094 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6096 // Otherwise, cast the RHS right before the icmp
6097 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6100 return new ICmpInst(I.getPredicate(), Op0, Op1);
6104 if (isa<CastInst>(Op0)) {
6105 // Handle the special case of: icmp (cast bool to X), <cst>
6106 // This comes up when you have code like
6109 // For generality, we handle any zero-extension of any operand comparison
6110 // with a constant or another cast from the same type.
6111 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6112 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6116 // ~x < ~y --> y < x
6118 if (match(Op0, m_Not(m_Value(A))) &&
6119 match(Op1, m_Not(m_Value(B))))
6120 return new ICmpInst(I.getPredicate(), B, A);
6123 if (I.isEquality()) {
6124 Value *A, *B, *C, *D;
6126 // -x == -y --> x == y
6127 if (match(Op0, m_Neg(m_Value(A))) &&
6128 match(Op1, m_Neg(m_Value(B))))
6129 return new ICmpInst(I.getPredicate(), A, B);
6131 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6132 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6133 Value *OtherVal = A == Op1 ? B : A;
6134 return new ICmpInst(I.getPredicate(), OtherVal,
6135 Constant::getNullValue(A->getType()));
6138 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6139 // A^c1 == C^c2 --> A == C^(c1^c2)
6140 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
6141 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
6142 if (Op1->hasOneUse()) {
6143 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6144 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6145 return new ICmpInst(I.getPredicate(), A,
6146 InsertNewInstBefore(Xor, I));
6149 // A^B == A^D -> B == D
6150 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6151 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6152 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6153 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6157 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6158 (A == Op0 || B == Op0)) {
6159 // A == (A^B) -> B == 0
6160 Value *OtherVal = A == Op0 ? B : A;
6161 return new ICmpInst(I.getPredicate(), OtherVal,
6162 Constant::getNullValue(A->getType()));
6164 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
6165 // (A-B) == A -> B == 0
6166 return new ICmpInst(I.getPredicate(), B,
6167 Constant::getNullValue(B->getType()));
6169 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
6170 // A == (A-B) -> B == 0
6171 return new ICmpInst(I.getPredicate(), B,
6172 Constant::getNullValue(B->getType()));
6175 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6176 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6177 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6178 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6179 Value *X = 0, *Y = 0, *Z = 0;
6182 X = B; Y = D; Z = A;
6183 } else if (A == D) {
6184 X = B; Y = C; Z = A;
6185 } else if (B == C) {
6186 X = A; Y = D; Z = B;
6187 } else if (B == D) {
6188 X = A; Y = C; Z = B;
6191 if (X) { // Build (X^Y) & Z
6192 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6193 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6194 I.setOperand(0, Op1);
6195 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6200 return Changed ? &I : 0;
6204 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6205 /// and CmpRHS are both known to be integer constants.
6206 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6207 ConstantInt *DivRHS) {
6208 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6209 const APInt &CmpRHSV = CmpRHS->getValue();
6211 // FIXME: If the operand types don't match the type of the divide
6212 // then don't attempt this transform. The code below doesn't have the
6213 // logic to deal with a signed divide and an unsigned compare (and
6214 // vice versa). This is because (x /s C1) <s C2 produces different
6215 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6216 // (x /u C1) <u C2. Simply casting the operands and result won't
6217 // work. :( The if statement below tests that condition and bails
6219 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6220 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6222 if (DivRHS->isZero())
6223 return 0; // The ProdOV computation fails on divide by zero.
6225 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6226 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6227 // C2 (CI). By solving for X we can turn this into a range check
6228 // instead of computing a divide.
6229 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6231 // Determine if the product overflows by seeing if the product is
6232 // not equal to the divide. Make sure we do the same kind of divide
6233 // as in the LHS instruction that we're folding.
6234 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6235 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6237 // Get the ICmp opcode
6238 ICmpInst::Predicate Pred = ICI.getPredicate();
6240 // Figure out the interval that is being checked. For example, a comparison
6241 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6242 // Compute this interval based on the constants involved and the signedness of
6243 // the compare/divide. This computes a half-open interval, keeping track of
6244 // whether either value in the interval overflows. After analysis each
6245 // overflow variable is set to 0 if it's corresponding bound variable is valid
6246 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6247 int LoOverflow = 0, HiOverflow = 0;
6248 ConstantInt *LoBound = 0, *HiBound = 0;
6251 if (!DivIsSigned) { // udiv
6252 // e.g. X/5 op 3 --> [15, 20)
6254 HiOverflow = LoOverflow = ProdOV;
6256 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6257 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6258 if (CmpRHSV == 0) { // (X / pos) op 0
6259 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
6260 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6262 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
6263 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6264 HiOverflow = LoOverflow = ProdOV;
6266 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6267 } else { // (X / pos) op neg
6268 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
6269 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
6270 LoOverflow = AddWithOverflow(LoBound, Prod,
6271 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
6272 HiBound = AddOne(Prod);
6273 HiOverflow = ProdOV ? -1 : 0;
6275 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6276 if (CmpRHSV == 0) { // (X / neg) op 0
6277 // e.g. X/-5 op 0 --> [-4, 5)
6278 LoBound = AddOne(DivRHS);
6279 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6280 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6281 HiOverflow = 1; // [INTMIN+1, overflow)
6282 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6284 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
6285 // e.g. X/-5 op 3 --> [-19, -14)
6286 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6288 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
6289 HiBound = AddOne(Prod);
6290 } else { // (X / neg) op neg
6291 // e.g. X/-5 op -3 --> [15, 20)
6293 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
6294 HiBound = Subtract(Prod, DivRHS);
6297 // Dividing by a negative swaps the condition. LT <-> GT
6298 Pred = ICmpInst::getSwappedPredicate(Pred);
6301 Value *X = DivI->getOperand(0);
6303 default: assert(0 && "Unhandled icmp opcode!");
6304 case ICmpInst::ICMP_EQ:
6305 if (LoOverflow && HiOverflow)
6306 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6307 else if (HiOverflow)
6308 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6309 ICmpInst::ICMP_UGE, X, LoBound);
6310 else if (LoOverflow)
6311 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6312 ICmpInst::ICMP_ULT, X, HiBound);
6314 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6315 case ICmpInst::ICMP_NE:
6316 if (LoOverflow && HiOverflow)
6317 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6318 else if (HiOverflow)
6319 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6320 ICmpInst::ICMP_ULT, X, LoBound);
6321 else if (LoOverflow)
6322 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6323 ICmpInst::ICMP_UGE, X, HiBound);
6325 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6326 case ICmpInst::ICMP_ULT:
6327 case ICmpInst::ICMP_SLT:
6328 if (LoOverflow == +1) // Low bound is greater than input range.
6329 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6330 if (LoOverflow == -1) // Low bound is less than input range.
6331 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6332 return new ICmpInst(Pred, X, LoBound);
6333 case ICmpInst::ICMP_UGT:
6334 case ICmpInst::ICMP_SGT:
6335 if (HiOverflow == +1) // High bound greater than input range.
6336 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6337 else if (HiOverflow == -1) // High bound less than input range.
6338 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6339 if (Pred == ICmpInst::ICMP_UGT)
6340 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6342 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6347 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6349 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6352 const APInt &RHSV = RHS->getValue();
6354 switch (LHSI->getOpcode()) {
6355 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6356 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6357 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6359 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6360 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6361 Value *CompareVal = LHSI->getOperand(0);
6363 // If the sign bit of the XorCST is not set, there is no change to
6364 // the operation, just stop using the Xor.
6365 if (!XorCST->getValue().isNegative()) {
6366 ICI.setOperand(0, CompareVal);
6367 AddToWorkList(LHSI);
6371 // Was the old condition true if the operand is positive?
6372 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6374 // If so, the new one isn't.
6375 isTrueIfPositive ^= true;
6377 if (isTrueIfPositive)
6378 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6380 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6384 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6385 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6386 LHSI->getOperand(0)->hasOneUse()) {
6387 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6389 // If the LHS is an AND of a truncating cast, we can widen the
6390 // and/compare to be the input width without changing the value
6391 // produced, eliminating a cast.
6392 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6393 // We can do this transformation if either the AND constant does not
6394 // have its sign bit set or if it is an equality comparison.
6395 // Extending a relational comparison when we're checking the sign
6396 // bit would not work.
6397 if (Cast->hasOneUse() &&
6398 (ICI.isEquality() ||
6399 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6401 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6402 APInt NewCST = AndCST->getValue();
6403 NewCST.zext(BitWidth);
6405 NewCI.zext(BitWidth);
6406 Instruction *NewAnd =
6407 BinaryOperator::CreateAnd(Cast->getOperand(0),
6408 ConstantInt::get(NewCST),LHSI->getName());
6409 InsertNewInstBefore(NewAnd, ICI);
6410 return new ICmpInst(ICI.getPredicate(), NewAnd,
6411 ConstantInt::get(NewCI));
6415 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6416 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6417 // happens a LOT in code produced by the C front-end, for bitfield
6419 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6420 if (Shift && !Shift->isShift())
6424 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6425 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6426 const Type *AndTy = AndCST->getType(); // Type of the and.
6428 // We can fold this as long as we can't shift unknown bits
6429 // into the mask. This can only happen with signed shift
6430 // rights, as they sign-extend.
6432 bool CanFold = Shift->isLogicalShift();
6434 // To test for the bad case of the signed shr, see if any
6435 // of the bits shifted in could be tested after the mask.
6436 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6437 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6439 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6440 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6441 AndCST->getValue()) == 0)
6447 if (Shift->getOpcode() == Instruction::Shl)
6448 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6450 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6452 // Check to see if we are shifting out any of the bits being
6454 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6455 // If we shifted bits out, the fold is not going to work out.
6456 // As a special case, check to see if this means that the
6457 // result is always true or false now.
6458 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6459 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6460 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6461 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6463 ICI.setOperand(1, NewCst);
6464 Constant *NewAndCST;
6465 if (Shift->getOpcode() == Instruction::Shl)
6466 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6468 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6469 LHSI->setOperand(1, NewAndCST);
6470 LHSI->setOperand(0, Shift->getOperand(0));
6471 AddToWorkList(Shift); // Shift is dead.
6472 AddUsesToWorkList(ICI);
6478 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6479 // preferable because it allows the C<<Y expression to be hoisted out
6480 // of a loop if Y is invariant and X is not.
6481 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6482 ICI.isEquality() && !Shift->isArithmeticShift() &&
6483 isa<Instruction>(Shift->getOperand(0))) {
6486 if (Shift->getOpcode() == Instruction::LShr) {
6487 NS = BinaryOperator::CreateShl(AndCST,
6488 Shift->getOperand(1), "tmp");
6490 // Insert a logical shift.
6491 NS = BinaryOperator::CreateLShr(AndCST,
6492 Shift->getOperand(1), "tmp");
6494 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6496 // Compute X & (C << Y).
6497 Instruction *NewAnd =
6498 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6499 InsertNewInstBefore(NewAnd, ICI);
6501 ICI.setOperand(0, NewAnd);
6507 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6508 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6511 uint32_t TypeBits = RHSV.getBitWidth();
6513 // Check that the shift amount is in range. If not, don't perform
6514 // undefined shifts. When the shift is visited it will be
6516 if (ShAmt->uge(TypeBits))
6519 if (ICI.isEquality()) {
6520 // If we are comparing against bits always shifted out, the
6521 // comparison cannot succeed.
6523 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6524 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6525 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6526 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6527 return ReplaceInstUsesWith(ICI, Cst);
6530 if (LHSI->hasOneUse()) {
6531 // Otherwise strength reduce the shift into an and.
6532 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6534 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6537 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6538 Mask, LHSI->getName()+".mask");
6539 Value *And = InsertNewInstBefore(AndI, ICI);
6540 return new ICmpInst(ICI.getPredicate(), And,
6541 ConstantInt::get(RHSV.lshr(ShAmtVal)));
6545 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6546 bool TrueIfSigned = false;
6547 if (LHSI->hasOneUse() &&
6548 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6549 // (X << 31) <s 0 --> (X&1) != 0
6550 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6551 (TypeBits-ShAmt->getZExtValue()-1));
6553 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6554 Mask, LHSI->getName()+".mask");
6555 Value *And = InsertNewInstBefore(AndI, ICI);
6557 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6558 And, Constant::getNullValue(And->getType()));
6563 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6564 case Instruction::AShr: {
6565 // Only handle equality comparisons of shift-by-constant.
6566 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6567 if (!ShAmt || !ICI.isEquality()) break;
6569 // Check that the shift amount is in range. If not, don't perform
6570 // undefined shifts. When the shift is visited it will be
6572 uint32_t TypeBits = RHSV.getBitWidth();
6573 if (ShAmt->uge(TypeBits))
6576 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6578 // If we are comparing against bits always shifted out, the
6579 // comparison cannot succeed.
6580 APInt Comp = RHSV << ShAmtVal;
6581 if (LHSI->getOpcode() == Instruction::LShr)
6582 Comp = Comp.lshr(ShAmtVal);
6584 Comp = Comp.ashr(ShAmtVal);
6586 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6587 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6588 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6589 return ReplaceInstUsesWith(ICI, Cst);
6592 // Otherwise, check to see if the bits shifted out are known to be zero.
6593 // If so, we can compare against the unshifted value:
6594 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
6595 if (LHSI->hasOneUse() &&
6596 MaskedValueIsZero(LHSI->getOperand(0),
6597 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6598 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6599 ConstantExpr::getShl(RHS, ShAmt));
6602 if (LHSI->hasOneUse()) {
6603 // Otherwise strength reduce the shift into an and.
6604 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6605 Constant *Mask = ConstantInt::get(Val);
6608 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6609 Mask, LHSI->getName()+".mask");
6610 Value *And = InsertNewInstBefore(AndI, ICI);
6611 return new ICmpInst(ICI.getPredicate(), And,
6612 ConstantExpr::getShl(RHS, ShAmt));
6617 case Instruction::SDiv:
6618 case Instruction::UDiv:
6619 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6620 // Fold this div into the comparison, producing a range check.
6621 // Determine, based on the divide type, what the range is being
6622 // checked. If there is an overflow on the low or high side, remember
6623 // it, otherwise compute the range [low, hi) bounding the new value.
6624 // See: InsertRangeTest above for the kinds of replacements possible.
6625 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6626 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6631 case Instruction::Add:
6632 // Fold: icmp pred (add, X, C1), C2
6634 if (!ICI.isEquality()) {
6635 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6637 const APInt &LHSV = LHSC->getValue();
6639 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6642 if (ICI.isSignedPredicate()) {
6643 if (CR.getLower().isSignBit()) {
6644 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6645 ConstantInt::get(CR.getUpper()));
6646 } else if (CR.getUpper().isSignBit()) {
6647 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6648 ConstantInt::get(CR.getLower()));
6651 if (CR.getLower().isMinValue()) {
6652 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6653 ConstantInt::get(CR.getUpper()));
6654 } else if (CR.getUpper().isMinValue()) {
6655 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6656 ConstantInt::get(CR.getLower()));
6663 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6664 if (ICI.isEquality()) {
6665 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6667 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6668 // the second operand is a constant, simplify a bit.
6669 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6670 switch (BO->getOpcode()) {
6671 case Instruction::SRem:
6672 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6673 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6674 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6675 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6676 Instruction *NewRem =
6677 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6679 InsertNewInstBefore(NewRem, ICI);
6680 return new ICmpInst(ICI.getPredicate(), NewRem,
6681 Constant::getNullValue(BO->getType()));
6685 case Instruction::Add:
6686 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6687 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6688 if (BO->hasOneUse())
6689 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6690 Subtract(RHS, BOp1C));
6691 } else if (RHSV == 0) {
6692 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6693 // efficiently invertible, or if the add has just this one use.
6694 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6696 if (Value *NegVal = dyn_castNegVal(BOp1))
6697 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6698 else if (Value *NegVal = dyn_castNegVal(BOp0))
6699 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6700 else if (BO->hasOneUse()) {
6701 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6702 InsertNewInstBefore(Neg, ICI);
6704 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6708 case Instruction::Xor:
6709 // For the xor case, we can xor two constants together, eliminating
6710 // the explicit xor.
6711 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6712 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6713 ConstantExpr::getXor(RHS, BOC));
6716 case Instruction::Sub:
6717 // Replace (([sub|xor] A, B) != 0) with (A != B)
6719 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6723 case Instruction::Or:
6724 // If bits are being or'd in that are not present in the constant we
6725 // are comparing against, then the comparison could never succeed!
6726 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6727 Constant *NotCI = ConstantExpr::getNot(RHS);
6728 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6729 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6734 case Instruction::And:
6735 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6736 // If bits are being compared against that are and'd out, then the
6737 // comparison can never succeed!
6738 if ((RHSV & ~BOC->getValue()) != 0)
6739 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6742 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6743 if (RHS == BOC && RHSV.isPowerOf2())
6744 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6745 ICmpInst::ICMP_NE, LHSI,
6746 Constant::getNullValue(RHS->getType()));
6748 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6749 if (isSignBit(BOC)) {
6750 Value *X = BO->getOperand(0);
6751 Constant *Zero = Constant::getNullValue(X->getType());
6752 ICmpInst::Predicate pred = isICMP_NE ?
6753 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6754 return new ICmpInst(pred, X, Zero);
6757 // ((X & ~7) == 0) --> X < 8
6758 if (RHSV == 0 && isHighOnes(BOC)) {
6759 Value *X = BO->getOperand(0);
6760 Constant *NegX = ConstantExpr::getNeg(BOC);
6761 ICmpInst::Predicate pred = isICMP_NE ?
6762 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6763 return new ICmpInst(pred, X, NegX);
6768 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6769 // Handle icmp {eq|ne} <intrinsic>, intcst.
6770 if (II->getIntrinsicID() == Intrinsic::bswap) {
6772 ICI.setOperand(0, II->getOperand(1));
6773 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6777 } else { // Not a ICMP_EQ/ICMP_NE
6778 // If the LHS is a cast from an integral value of the same size,
6779 // then since we know the RHS is a constant, try to simlify.
6780 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6781 Value *CastOp = Cast->getOperand(0);
6782 const Type *SrcTy = CastOp->getType();
6783 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6784 if (SrcTy->isInteger() &&
6785 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6786 // If this is an unsigned comparison, try to make the comparison use
6787 // smaller constant values.
6788 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6789 // X u< 128 => X s> -1
6790 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6791 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6792 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6793 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6794 // X u> 127 => X s< 0
6795 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6796 Constant::getNullValue(SrcTy));
6804 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6805 /// We only handle extending casts so far.
6807 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6808 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6809 Value *LHSCIOp = LHSCI->getOperand(0);
6810 const Type *SrcTy = LHSCIOp->getType();
6811 const Type *DestTy = LHSCI->getType();
6814 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6815 // integer type is the same size as the pointer type.
6816 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6817 getTargetData().getPointerSizeInBits() ==
6818 cast<IntegerType>(DestTy)->getBitWidth()) {
6820 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6821 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6822 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6823 RHSOp = RHSC->getOperand(0);
6824 // If the pointer types don't match, insert a bitcast.
6825 if (LHSCIOp->getType() != RHSOp->getType())
6826 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6830 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6833 // The code below only handles extension cast instructions, so far.
6835 if (LHSCI->getOpcode() != Instruction::ZExt &&
6836 LHSCI->getOpcode() != Instruction::SExt)
6839 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6840 bool isSignedCmp = ICI.isSignedPredicate();
6842 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6843 // Not an extension from the same type?
6844 RHSCIOp = CI->getOperand(0);
6845 if (RHSCIOp->getType() != LHSCIOp->getType())
6848 // If the signedness of the two casts doesn't agree (i.e. one is a sext
6849 // and the other is a zext), then we can't handle this.
6850 if (CI->getOpcode() != LHSCI->getOpcode())
6853 // Deal with equality cases early.
6854 if (ICI.isEquality())
6855 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6857 // A signed comparison of sign extended values simplifies into a
6858 // signed comparison.
6859 if (isSignedCmp && isSignedExt)
6860 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6862 // The other three cases all fold into an unsigned comparison.
6863 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6866 // If we aren't dealing with a constant on the RHS, exit early
6867 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6871 // Compute the constant that would happen if we truncated to SrcTy then
6872 // reextended to DestTy.
6873 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6874 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6876 // If the re-extended constant didn't change...
6878 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6879 // For example, we might have:
6880 // %A = sext short %X to uint
6881 // %B = icmp ugt uint %A, 1330
6882 // It is incorrect to transform this into
6883 // %B = icmp ugt short %X, 1330
6884 // because %A may have negative value.
6886 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6887 // OR operation is EQ/NE.
6888 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6889 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6894 // The re-extended constant changed so the constant cannot be represented
6895 // in the shorter type. Consequently, we cannot emit a simple comparison.
6897 // First, handle some easy cases. We know the result cannot be equal at this
6898 // point so handle the ICI.isEquality() cases
6899 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6900 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6901 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6902 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6904 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6905 // should have been folded away previously and not enter in here.
6908 // We're performing a signed comparison.
6909 if (cast<ConstantInt>(CI)->getValue().isNegative())
6910 Result = ConstantInt::getFalse(); // X < (small) --> false
6912 Result = ConstantInt::getTrue(); // X < (large) --> true
6914 // We're performing an unsigned comparison.
6916 // We're performing an unsigned comp with a sign extended value.
6917 // This is true if the input is >= 0. [aka >s -1]
6918 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6919 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6920 NegOne, ICI.getName()), ICI);
6922 // Unsigned extend & unsigned compare -> always true.
6923 Result = ConstantInt::getTrue();
6927 // Finally, return the value computed.
6928 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6929 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6930 return ReplaceInstUsesWith(ICI, Result);
6932 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6933 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6934 "ICmp should be folded!");
6935 if (Constant *CI = dyn_cast<Constant>(Result))
6936 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6938 return BinaryOperator::CreateNot(Result);
6942 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6943 return commonShiftTransforms(I);
6946 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6947 return commonShiftTransforms(I);
6950 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6951 if (Instruction *R = commonShiftTransforms(I))
6954 Value *Op0 = I.getOperand(0);
6956 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6957 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6958 if (CSI->isAllOnesValue())
6959 return ReplaceInstUsesWith(I, CSI);
6961 // See if we can turn a signed shr into an unsigned shr.
6962 if (MaskedValueIsZero(Op0,
6963 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6964 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6969 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6970 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6971 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6973 // shl X, 0 == X and shr X, 0 == X
6974 // shl 0, X == 0 and shr 0, X == 0
6975 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6976 Op0 == Constant::getNullValue(Op0->getType()))
6977 return ReplaceInstUsesWith(I, Op0);
6979 if (isa<UndefValue>(Op0)) {
6980 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6981 return ReplaceInstUsesWith(I, Op0);
6982 else // undef << X -> 0, undef >>u X -> 0
6983 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6985 if (isa<UndefValue>(Op1)) {
6986 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6987 return ReplaceInstUsesWith(I, Op0);
6988 else // X << undef, X >>u undef -> 0
6989 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6992 // Try to fold constant and into select arguments.
6993 if (isa<Constant>(Op0))
6994 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6995 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6998 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6999 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7004 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7005 BinaryOperator &I) {
7006 bool isLeftShift = I.getOpcode() == Instruction::Shl;
7008 // See if we can simplify any instructions used by the instruction whose sole
7009 // purpose is to compute bits we don't care about.
7010 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
7011 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
7012 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
7013 KnownZero, KnownOne))
7016 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7017 // of a signed value.
7019 if (Op1->uge(TypeBits)) {
7020 if (I.getOpcode() != Instruction::AShr)
7021 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7023 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7028 // ((X*C1) << C2) == (X * (C1 << C2))
7029 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7030 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7031 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7032 return BinaryOperator::CreateMul(BO->getOperand(0),
7033 ConstantExpr::getShl(BOOp, Op1));
7035 // Try to fold constant and into select arguments.
7036 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7037 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7039 if (isa<PHINode>(Op0))
7040 if (Instruction *NV = FoldOpIntoPhi(I))
7043 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7044 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7045 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7046 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7047 // place. Don't try to do this transformation in this case. Also, we
7048 // require that the input operand is a shift-by-constant so that we have
7049 // confidence that the shifts will get folded together. We could do this
7050 // xform in more cases, but it is unlikely to be profitable.
7051 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7052 isa<ConstantInt>(TrOp->getOperand(1))) {
7053 // Okay, we'll do this xform. Make the shift of shift.
7054 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7055 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7057 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7059 // For logical shifts, the truncation has the effect of making the high
7060 // part of the register be zeros. Emulate this by inserting an AND to
7061 // clear the top bits as needed. This 'and' will usually be zapped by
7062 // other xforms later if dead.
7063 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7064 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7065 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7067 // The mask we constructed says what the trunc would do if occurring
7068 // between the shifts. We want to know the effect *after* the second
7069 // shift. We know that it is a logical shift by a constant, so adjust the
7070 // mask as appropriate.
7071 if (I.getOpcode() == Instruction::Shl)
7072 MaskV <<= Op1->getZExtValue();
7074 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7075 MaskV = MaskV.lshr(Op1->getZExtValue());
7078 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7080 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7082 // Return the value truncated to the interesting size.
7083 return new TruncInst(And, I.getType());
7087 if (Op0->hasOneUse()) {
7088 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7089 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7092 switch (Op0BO->getOpcode()) {
7094 case Instruction::Add:
7095 case Instruction::And:
7096 case Instruction::Or:
7097 case Instruction::Xor: {
7098 // These operators commute.
7099 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7100 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7101 match(Op0BO->getOperand(1),
7102 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
7103 Instruction *YS = BinaryOperator::CreateShl(
7104 Op0BO->getOperand(0), Op1,
7106 InsertNewInstBefore(YS, I); // (Y << C)
7108 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7109 Op0BO->getOperand(1)->getName());
7110 InsertNewInstBefore(X, I); // (X + (Y << C))
7111 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7112 return BinaryOperator::CreateAnd(X, ConstantInt::get(
7113 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7116 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7117 Value *Op0BOOp1 = Op0BO->getOperand(1);
7118 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7120 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
7121 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
7123 Instruction *YS = BinaryOperator::CreateShl(
7124 Op0BO->getOperand(0), Op1,
7126 InsertNewInstBefore(YS, I); // (Y << C)
7128 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7129 V1->getName()+".mask");
7130 InsertNewInstBefore(XM, I); // X & (CC << C)
7132 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7137 case Instruction::Sub: {
7138 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7139 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7140 match(Op0BO->getOperand(0),
7141 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
7142 Instruction *YS = BinaryOperator::CreateShl(
7143 Op0BO->getOperand(1), Op1,
7145 InsertNewInstBefore(YS, I); // (Y << C)
7147 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7148 Op0BO->getOperand(0)->getName());
7149 InsertNewInstBefore(X, I); // (X + (Y << C))
7150 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7151 return BinaryOperator::CreateAnd(X, ConstantInt::get(
7152 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7155 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7156 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7157 match(Op0BO->getOperand(0),
7158 m_And(m_Shr(m_Value(V1), m_Value(V2)),
7159 m_ConstantInt(CC))) && V2 == Op1 &&
7160 cast<BinaryOperator>(Op0BO->getOperand(0))
7161 ->getOperand(0)->hasOneUse()) {
7162 Instruction *YS = BinaryOperator::CreateShl(
7163 Op0BO->getOperand(1), Op1,
7165 InsertNewInstBefore(YS, I); // (Y << C)
7167 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7168 V1->getName()+".mask");
7169 InsertNewInstBefore(XM, I); // X & (CC << C)
7171 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7179 // If the operand is an bitwise operator with a constant RHS, and the
7180 // shift is the only use, we can pull it out of the shift.
7181 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7182 bool isValid = true; // Valid only for And, Or, Xor
7183 bool highBitSet = false; // Transform if high bit of constant set?
7185 switch (Op0BO->getOpcode()) {
7186 default: isValid = false; break; // Do not perform transform!
7187 case Instruction::Add:
7188 isValid = isLeftShift;
7190 case Instruction::Or:
7191 case Instruction::Xor:
7194 case Instruction::And:
7199 // If this is a signed shift right, and the high bit is modified
7200 // by the logical operation, do not perform the transformation.
7201 // The highBitSet boolean indicates the value of the high bit of
7202 // the constant which would cause it to be modified for this
7205 if (isValid && I.getOpcode() == Instruction::AShr)
7206 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7209 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7211 Instruction *NewShift =
7212 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7213 InsertNewInstBefore(NewShift, I);
7214 NewShift->takeName(Op0BO);
7216 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7223 // Find out if this is a shift of a shift by a constant.
7224 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7225 if (ShiftOp && !ShiftOp->isShift())
7228 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7229 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7230 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7231 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7232 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7233 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7234 Value *X = ShiftOp->getOperand(0);
7236 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
7237 if (AmtSum > TypeBits)
7240 const IntegerType *Ty = cast<IntegerType>(I.getType());
7242 // Check for (X << c1) << c2 and (X >> c1) >> c2
7243 if (I.getOpcode() == ShiftOp->getOpcode()) {
7244 return BinaryOperator::Create(I.getOpcode(), X,
7245 ConstantInt::get(Ty, AmtSum));
7246 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7247 I.getOpcode() == Instruction::AShr) {
7248 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
7249 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7250 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7251 I.getOpcode() == Instruction::LShr) {
7252 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7253 Instruction *Shift =
7254 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7255 InsertNewInstBefore(Shift, I);
7257 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7258 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7261 // Okay, if we get here, one shift must be left, and the other shift must be
7262 // right. See if the amounts are equal.
7263 if (ShiftAmt1 == ShiftAmt2) {
7264 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7265 if (I.getOpcode() == Instruction::Shl) {
7266 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7267 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7269 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7270 if (I.getOpcode() == Instruction::LShr) {
7271 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7272 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7274 // We can simplify ((X << C) >>s C) into a trunc + sext.
7275 // NOTE: we could do this for any C, but that would make 'unusual' integer
7276 // types. For now, just stick to ones well-supported by the code
7278 const Type *SExtType = 0;
7279 switch (Ty->getBitWidth() - ShiftAmt1) {
7286 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7291 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7292 InsertNewInstBefore(NewTrunc, I);
7293 return new SExtInst(NewTrunc, Ty);
7295 // Otherwise, we can't handle it yet.
7296 } else if (ShiftAmt1 < ShiftAmt2) {
7297 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7299 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7300 if (I.getOpcode() == Instruction::Shl) {
7301 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7302 ShiftOp->getOpcode() == Instruction::AShr);
7303 Instruction *Shift =
7304 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7305 InsertNewInstBefore(Shift, I);
7307 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7308 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7311 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7312 if (I.getOpcode() == Instruction::LShr) {
7313 assert(ShiftOp->getOpcode() == Instruction::Shl);
7314 Instruction *Shift =
7315 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7316 InsertNewInstBefore(Shift, I);
7318 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7319 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7322 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7324 assert(ShiftAmt2 < ShiftAmt1);
7325 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7327 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7328 if (I.getOpcode() == Instruction::Shl) {
7329 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7330 ShiftOp->getOpcode() == Instruction::AShr);
7331 Instruction *Shift =
7332 BinaryOperator::Create(ShiftOp->getOpcode(), X,
7333 ConstantInt::get(Ty, ShiftDiff));
7334 InsertNewInstBefore(Shift, I);
7336 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7337 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7340 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7341 if (I.getOpcode() == Instruction::LShr) {
7342 assert(ShiftOp->getOpcode() == Instruction::Shl);
7343 Instruction *Shift =
7344 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7345 InsertNewInstBefore(Shift, I);
7347 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7348 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7351 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7358 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7359 /// expression. If so, decompose it, returning some value X, such that Val is
7362 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7364 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7365 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7366 Offset = CI->getZExtValue();
7368 return ConstantInt::get(Type::Int32Ty, 0);
7369 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7370 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7371 if (I->getOpcode() == Instruction::Shl) {
7372 // This is a value scaled by '1 << the shift amt'.
7373 Scale = 1U << RHS->getZExtValue();
7375 return I->getOperand(0);
7376 } else if (I->getOpcode() == Instruction::Mul) {
7377 // This value is scaled by 'RHS'.
7378 Scale = RHS->getZExtValue();
7380 return I->getOperand(0);
7381 } else if (I->getOpcode() == Instruction::Add) {
7382 // We have X+C. Check to see if we really have (X*C2)+C1,
7383 // where C1 is divisible by C2.
7386 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7387 Offset += RHS->getZExtValue();
7394 // Otherwise, we can't look past this.
7401 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7402 /// try to eliminate the cast by moving the type information into the alloc.
7403 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7404 AllocationInst &AI) {
7405 const PointerType *PTy = cast<PointerType>(CI.getType());
7407 // Remove any uses of AI that are dead.
7408 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7410 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7411 Instruction *User = cast<Instruction>(*UI++);
7412 if (isInstructionTriviallyDead(User)) {
7413 while (UI != E && *UI == User)
7414 ++UI; // If this instruction uses AI more than once, don't break UI.
7417 DOUT << "IC: DCE: " << *User;
7418 EraseInstFromFunction(*User);
7422 // Get the type really allocated and the type casted to.
7423 const Type *AllocElTy = AI.getAllocatedType();
7424 const Type *CastElTy = PTy->getElementType();
7425 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7427 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7428 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7429 if (CastElTyAlign < AllocElTyAlign) return 0;
7431 // If the allocation has multiple uses, only promote it if we are strictly
7432 // increasing the alignment of the resultant allocation. If we keep it the
7433 // same, we open the door to infinite loops of various kinds.
7434 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7436 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7437 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
7438 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7440 // See if we can satisfy the modulus by pulling a scale out of the array
7442 unsigned ArraySizeScale;
7444 Value *NumElements = // See if the array size is a decomposable linear expr.
7445 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7447 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7449 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7450 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7452 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7457 // If the allocation size is constant, form a constant mul expression
7458 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7459 if (isa<ConstantInt>(NumElements))
7460 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7461 // otherwise multiply the amount and the number of elements
7462 else if (Scale != 1) {
7463 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7464 Amt = InsertNewInstBefore(Tmp, AI);
7468 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7469 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7470 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7471 Amt = InsertNewInstBefore(Tmp, AI);
7474 AllocationInst *New;
7475 if (isa<MallocInst>(AI))
7476 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7478 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7479 InsertNewInstBefore(New, AI);
7482 // If the allocation has multiple uses, insert a cast and change all things
7483 // that used it to use the new cast. This will also hack on CI, but it will
7485 if (!AI.hasOneUse()) {
7486 AddUsesToWorkList(AI);
7487 // New is the allocation instruction, pointer typed. AI is the original
7488 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7489 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7490 InsertNewInstBefore(NewCast, AI);
7491 AI.replaceAllUsesWith(NewCast);
7493 return ReplaceInstUsesWith(CI, New);
7496 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7497 /// and return it as type Ty without inserting any new casts and without
7498 /// changing the computed value. This is used by code that tries to decide
7499 /// whether promoting or shrinking integer operations to wider or smaller types
7500 /// will allow us to eliminate a truncate or extend.
7502 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7503 /// extension operation if Ty is larger.
7504 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7506 int &NumCastsRemoved) {
7507 // We can always evaluate constants in another type.
7508 if (isa<ConstantInt>(V))
7511 Instruction *I = dyn_cast<Instruction>(V);
7512 if (!I) return false;
7514 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7516 // If this is an extension or truncate, we can often eliminate it.
7517 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7518 // If this is a cast from the destination type, we can trivially eliminate
7519 // it, and this will remove a cast overall.
7520 if (I->getOperand(0)->getType() == Ty) {
7521 // If the first operand is itself a cast, and is eliminable, do not count
7522 // this as an eliminable cast. We would prefer to eliminate those two
7524 if (!isa<CastInst>(I->getOperand(0)))
7530 // We can't extend or shrink something that has multiple uses: doing so would
7531 // require duplicating the instruction in general, which isn't profitable.
7532 if (!I->hasOneUse()) return false;
7534 switch (I->getOpcode()) {
7535 case Instruction::Add:
7536 case Instruction::Sub:
7537 case Instruction::And:
7538 case Instruction::Or:
7539 case Instruction::Xor:
7540 // These operators can all arbitrarily be extended or truncated.
7541 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7543 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7546 case Instruction::Mul:
7547 // A multiply can be truncated by truncating its operands.
7548 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
7549 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7551 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7554 case Instruction::Shl:
7555 // If we are truncating the result of this SHL, and if it's a shift of a
7556 // constant amount, we can always perform a SHL in a smaller type.
7557 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7558 uint32_t BitWidth = Ty->getBitWidth();
7559 if (BitWidth < OrigTy->getBitWidth() &&
7560 CI->getLimitedValue(BitWidth) < BitWidth)
7561 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7565 case Instruction::LShr:
7566 // If this is a truncate of a logical shr, we can truncate it to a smaller
7567 // lshr iff we know that the bits we would otherwise be shifting in are
7569 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7570 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7571 uint32_t BitWidth = Ty->getBitWidth();
7572 if (BitWidth < OrigBitWidth &&
7573 MaskedValueIsZero(I->getOperand(0),
7574 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7575 CI->getLimitedValue(BitWidth) < BitWidth) {
7576 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7581 case Instruction::ZExt:
7582 case Instruction::SExt:
7583 case Instruction::Trunc:
7584 // If this is the same kind of case as our original (e.g. zext+zext), we
7585 // can safely replace it. Note that replacing it does not reduce the number
7586 // of casts in the input.
7587 if (I->getOpcode() == CastOpc)
7592 // TODO: Can handle more cases here.
7599 /// EvaluateInDifferentType - Given an expression that
7600 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7601 /// evaluate the expression.
7602 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7604 if (Constant *C = dyn_cast<Constant>(V))
7605 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7607 // Otherwise, it must be an instruction.
7608 Instruction *I = cast<Instruction>(V);
7609 Instruction *Res = 0;
7610 switch (I->getOpcode()) {
7611 case Instruction::Add:
7612 case Instruction::Sub:
7613 case Instruction::Mul:
7614 case Instruction::And:
7615 case Instruction::Or:
7616 case Instruction::Xor:
7617 case Instruction::AShr:
7618 case Instruction::LShr:
7619 case Instruction::Shl: {
7620 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7621 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7622 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
7623 LHS, RHS, I->getName());
7626 case Instruction::Trunc:
7627 case Instruction::ZExt:
7628 case Instruction::SExt:
7629 // If the source type of the cast is the type we're trying for then we can
7630 // just return the source. There's no need to insert it because it is not
7632 if (I->getOperand(0)->getType() == Ty)
7633 return I->getOperand(0);
7635 // Otherwise, must be the same type of case, so just reinsert a new one.
7636 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7640 // TODO: Can handle more cases here.
7641 assert(0 && "Unreachable!");
7645 return InsertNewInstBefore(Res, *I);
7648 /// @brief Implement the transforms common to all CastInst visitors.
7649 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7650 Value *Src = CI.getOperand(0);
7652 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7653 // eliminate it now.
7654 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7655 if (Instruction::CastOps opc =
7656 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7657 // The first cast (CSrc) is eliminable so we need to fix up or replace
7658 // the second cast (CI). CSrc will then have a good chance of being dead.
7659 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7663 // If we are casting a select then fold the cast into the select
7664 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7665 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7668 // If we are casting a PHI then fold the cast into the PHI
7669 if (isa<PHINode>(Src))
7670 if (Instruction *NV = FoldOpIntoPhi(CI))
7676 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7677 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7678 Value *Src = CI.getOperand(0);
7680 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7681 // If casting the result of a getelementptr instruction with no offset, turn
7682 // this into a cast of the original pointer!
7683 if (GEP->hasAllZeroIndices()) {
7684 // Changing the cast operand is usually not a good idea but it is safe
7685 // here because the pointer operand is being replaced with another
7686 // pointer operand so the opcode doesn't need to change.
7688 CI.setOperand(0, GEP->getOperand(0));
7692 // If the GEP has a single use, and the base pointer is a bitcast, and the
7693 // GEP computes a constant offset, see if we can convert these three
7694 // instructions into fewer. This typically happens with unions and other
7695 // non-type-safe code.
7696 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7697 if (GEP->hasAllConstantIndices()) {
7698 // We are guaranteed to get a constant from EmitGEPOffset.
7699 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7700 int64_t Offset = OffsetV->getSExtValue();
7702 // Get the base pointer input of the bitcast, and the type it points to.
7703 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7704 const Type *GEPIdxTy =
7705 cast<PointerType>(OrigBase->getType())->getElementType();
7706 if (GEPIdxTy->isSized()) {
7707 SmallVector<Value*, 8> NewIndices;
7709 // Start with the index over the outer type. Note that the type size
7710 // might be zero (even if the offset isn't zero) if the indexed type
7711 // is something like [0 x {int, int}]
7712 const Type *IntPtrTy = TD->getIntPtrType();
7713 int64_t FirstIdx = 0;
7714 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7715 FirstIdx = Offset/TySize;
7718 // Handle silly modulus not returning values values [0..TySize).
7722 assert(Offset >= 0);
7724 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7727 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7729 // Index into the types. If we fail, set OrigBase to null.
7731 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7732 const StructLayout *SL = TD->getStructLayout(STy);
7733 if (Offset < (int64_t)SL->getSizeInBytes()) {
7734 unsigned Elt = SL->getElementContainingOffset(Offset);
7735 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7737 Offset -= SL->getElementOffset(Elt);
7738 GEPIdxTy = STy->getElementType(Elt);
7740 // Otherwise, we can't index into this, bail out.
7744 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7745 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7746 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7747 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7750 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7752 GEPIdxTy = STy->getElementType();
7754 // Otherwise, we can't index into this, bail out.
7760 // If we were able to index down into an element, create the GEP
7761 // and bitcast the result. This eliminates one bitcast, potentially
7763 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7765 NewIndices.end(), "");
7766 InsertNewInstBefore(NGEP, CI);
7767 NGEP->takeName(GEP);
7769 if (isa<BitCastInst>(CI))
7770 return new BitCastInst(NGEP, CI.getType());
7771 assert(isa<PtrToIntInst>(CI));
7772 return new PtrToIntInst(NGEP, CI.getType());
7779 return commonCastTransforms(CI);
7784 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7785 /// integer types. This function implements the common transforms for all those
7787 /// @brief Implement the transforms common to CastInst with integer operands
7788 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7789 if (Instruction *Result = commonCastTransforms(CI))
7792 Value *Src = CI.getOperand(0);
7793 const Type *SrcTy = Src->getType();
7794 const Type *DestTy = CI.getType();
7795 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7796 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7798 // See if we can simplify any instructions used by the LHS whose sole
7799 // purpose is to compute bits we don't care about.
7800 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7801 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7802 KnownZero, KnownOne))
7805 // If the source isn't an instruction or has more than one use then we
7806 // can't do anything more.
7807 Instruction *SrcI = dyn_cast<Instruction>(Src);
7808 if (!SrcI || !Src->hasOneUse())
7811 // Attempt to propagate the cast into the instruction for int->int casts.
7812 int NumCastsRemoved = 0;
7813 if (!isa<BitCastInst>(CI) &&
7814 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7815 CI.getOpcode(), NumCastsRemoved)) {
7816 // If this cast is a truncate, evaluting in a different type always
7817 // eliminates the cast, so it is always a win. If this is a zero-extension,
7818 // we need to do an AND to maintain the clear top-part of the computation,
7819 // so we require that the input have eliminated at least one cast. If this
7820 // is a sign extension, we insert two new casts (to do the extension) so we
7821 // require that two casts have been eliminated.
7823 switch (CI.getOpcode()) {
7825 // All the others use floating point so we shouldn't actually
7826 // get here because of the check above.
7827 assert(0 && "Unknown cast type");
7828 case Instruction::Trunc:
7831 case Instruction::ZExt:
7832 DoXForm = NumCastsRemoved >= 1;
7834 case Instruction::SExt:
7835 DoXForm = NumCastsRemoved >= 2;
7840 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7841 CI.getOpcode() == Instruction::SExt);
7842 assert(Res->getType() == DestTy);
7843 switch (CI.getOpcode()) {
7844 default: assert(0 && "Unknown cast type!");
7845 case Instruction::Trunc:
7846 case Instruction::BitCast:
7847 // Just replace this cast with the result.
7848 return ReplaceInstUsesWith(CI, Res);
7849 case Instruction::ZExt: {
7850 // We need to emit an AND to clear the high bits.
7851 assert(SrcBitSize < DestBitSize && "Not a zext?");
7852 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7854 return BinaryOperator::CreateAnd(Res, C);
7856 case Instruction::SExt:
7857 // We need to emit a cast to truncate, then a cast to sext.
7858 return CastInst::Create(Instruction::SExt,
7859 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7865 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7866 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7868 switch (SrcI->getOpcode()) {
7869 case Instruction::Add:
7870 case Instruction::Mul:
7871 case Instruction::And:
7872 case Instruction::Or:
7873 case Instruction::Xor:
7874 // If we are discarding information, rewrite.
7875 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7876 // Don't insert two casts if they cannot be eliminated. We allow
7877 // two casts to be inserted if the sizes are the same. This could
7878 // only be converting signedness, which is a noop.
7879 if (DestBitSize == SrcBitSize ||
7880 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7881 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7882 Instruction::CastOps opcode = CI.getOpcode();
7883 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7884 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7885 return BinaryOperator::Create(
7886 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7890 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7891 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7892 SrcI->getOpcode() == Instruction::Xor &&
7893 Op1 == ConstantInt::getTrue() &&
7894 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7895 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7896 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7899 case Instruction::SDiv:
7900 case Instruction::UDiv:
7901 case Instruction::SRem:
7902 case Instruction::URem:
7903 // If we are just changing the sign, rewrite.
7904 if (DestBitSize == SrcBitSize) {
7905 // Don't insert two casts if they cannot be eliminated. We allow
7906 // two casts to be inserted if the sizes are the same. This could
7907 // only be converting signedness, which is a noop.
7908 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7909 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7910 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7912 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7914 return BinaryOperator::Create(
7915 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7920 case Instruction::Shl:
7921 // Allow changing the sign of the source operand. Do not allow
7922 // changing the size of the shift, UNLESS the shift amount is a
7923 // constant. We must not change variable sized shifts to a smaller
7924 // size, because it is undefined to shift more bits out than exist
7926 if (DestBitSize == SrcBitSize ||
7927 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7928 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7929 Instruction::BitCast : Instruction::Trunc);
7930 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7931 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7932 return BinaryOperator::CreateShl(Op0c, Op1c);
7935 case Instruction::AShr:
7936 // If this is a signed shr, and if all bits shifted in are about to be
7937 // truncated off, turn it into an unsigned shr to allow greater
7939 if (DestBitSize < SrcBitSize &&
7940 isa<ConstantInt>(Op1)) {
7941 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7942 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7943 // Insert the new logical shift right.
7944 return BinaryOperator::CreateLShr(Op0, Op1);
7952 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7953 if (Instruction *Result = commonIntCastTransforms(CI))
7956 Value *Src = CI.getOperand(0);
7957 const Type *Ty = CI.getType();
7958 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7959 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7961 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7962 switch (SrcI->getOpcode()) {
7964 case Instruction::LShr:
7965 // We can shrink lshr to something smaller if we know the bits shifted in
7966 // are already zeros.
7967 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7968 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7970 // Get a mask for the bits shifting in.
7971 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7972 Value* SrcIOp0 = SrcI->getOperand(0);
7973 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7974 if (ShAmt >= DestBitWidth) // All zeros.
7975 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7977 // Okay, we can shrink this. Truncate the input, then return a new
7979 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7980 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7982 return BinaryOperator::CreateLShr(V1, V2);
7984 } else { // This is a variable shr.
7986 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7987 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7988 // loop-invariant and CSE'd.
7989 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7990 Value *One = ConstantInt::get(SrcI->getType(), 1);
7992 Value *V = InsertNewInstBefore(
7993 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
7995 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
7996 SrcI->getOperand(0),
7998 Value *Zero = Constant::getNullValue(V->getType());
7999 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
8009 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8010 /// in order to eliminate the icmp.
8011 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8013 // If we are just checking for a icmp eq of a single bit and zext'ing it
8014 // to an integer, then shift the bit to the appropriate place and then
8015 // cast to integer to avoid the comparison.
8016 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8017 const APInt &Op1CV = Op1C->getValue();
8019 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8020 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8021 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8022 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8023 if (!DoXform) return ICI;
8025 Value *In = ICI->getOperand(0);
8026 Value *Sh = ConstantInt::get(In->getType(),
8027 In->getType()->getPrimitiveSizeInBits()-1);
8028 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8029 In->getName()+".lobit"),
8031 if (In->getType() != CI.getType())
8032 In = CastInst::CreateIntegerCast(In, CI.getType(),
8033 false/*ZExt*/, "tmp", &CI);
8035 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8036 Constant *One = ConstantInt::get(In->getType(), 1);
8037 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8038 In->getName()+".not"),
8042 return ReplaceInstUsesWith(CI, In);
8047 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8048 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8049 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8050 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8051 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8052 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8053 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8054 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8055 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8056 // This only works for EQ and NE
8057 ICI->isEquality()) {
8058 // If Op1C some other power of two, convert:
8059 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8060 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8061 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8062 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8064 APInt KnownZeroMask(~KnownZero);
8065 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8066 if (!DoXform) return ICI;
8068 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8069 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8070 // (X&4) == 2 --> false
8071 // (X&4) != 2 --> true
8072 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8073 Res = ConstantExpr::getZExt(Res, CI.getType());
8074 return ReplaceInstUsesWith(CI, Res);
8077 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8078 Value *In = ICI->getOperand(0);
8080 // Perform a logical shr by shiftamt.
8081 // Insert the shift to put the result in the low bit.
8082 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8083 ConstantInt::get(In->getType(), ShiftAmt),
8084 In->getName()+".lobit"), CI);
8087 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8088 Constant *One = ConstantInt::get(In->getType(), 1);
8089 In = BinaryOperator::CreateXor(In, One, "tmp");
8090 InsertNewInstBefore(cast<Instruction>(In), CI);
8093 if (CI.getType() == In->getType())
8094 return ReplaceInstUsesWith(CI, In);
8096 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8104 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8105 // If one of the common conversion will work ..
8106 if (Instruction *Result = commonIntCastTransforms(CI))
8109 Value *Src = CI.getOperand(0);
8111 // If this is a cast of a cast
8112 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8113 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8114 // types and if the sizes are just right we can convert this into a logical
8115 // 'and' which will be much cheaper than the pair of casts.
8116 if (isa<TruncInst>(CSrc)) {
8117 // Get the sizes of the types involved
8118 Value *A = CSrc->getOperand(0);
8119 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8120 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8121 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
8122 // If we're actually extending zero bits and the trunc is a no-op
8123 if (MidSize < DstSize && SrcSize == DstSize) {
8124 // Replace both of the casts with an And of the type mask.
8125 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8126 Constant *AndConst = ConstantInt::get(AndValue);
8128 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
8129 // Unfortunately, if the type changed, we need to cast it back.
8130 if (And->getType() != CI.getType()) {
8131 And->setName(CSrc->getName()+".mask");
8132 InsertNewInstBefore(And, CI);
8133 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
8140 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8141 return transformZExtICmp(ICI, CI);
8143 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8144 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8145 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8146 // of the (zext icmp) will be transformed.
8147 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8148 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8149 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8150 (transformZExtICmp(LHS, CI, false) ||
8151 transformZExtICmp(RHS, CI, false))) {
8152 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8153 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8154 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8161 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8162 if (Instruction *I = commonIntCastTransforms(CI))
8165 Value *Src = CI.getOperand(0);
8167 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
8168 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
8169 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
8170 // If we are just checking for a icmp eq of a single bit and zext'ing it
8171 // to an integer, then shift the bit to the appropriate place and then
8172 // cast to integer to avoid the comparison.
8173 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8174 const APInt &Op1CV = Op1C->getValue();
8176 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8177 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8178 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8179 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
8180 Value *In = ICI->getOperand(0);
8181 Value *Sh = ConstantInt::get(In->getType(),
8182 In->getType()->getPrimitiveSizeInBits()-1);
8183 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8184 In->getName()+".lobit"),
8186 if (In->getType() != CI.getType())
8187 In = CastInst::CreateIntegerCast(In, CI.getType(),
8188 true/*SExt*/, "tmp", &CI);
8190 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
8191 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8192 In->getName()+".not"), CI);
8194 return ReplaceInstUsesWith(CI, In);
8202 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8203 /// in the specified FP type without changing its value.
8204 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8205 APFloat F = CFP->getValueAPF();
8206 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
8207 return ConstantFP::get(F);
8211 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8212 /// through it until we get the source value.
8213 static Value *LookThroughFPExtensions(Value *V) {
8214 if (Instruction *I = dyn_cast<Instruction>(V))
8215 if (I->getOpcode() == Instruction::FPExt)
8216 return LookThroughFPExtensions(I->getOperand(0));
8218 // If this value is a constant, return the constant in the smallest FP type
8219 // that can accurately represent it. This allows us to turn
8220 // (float)((double)X+2.0) into x+2.0f.
8221 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8222 if (CFP->getType() == Type::PPC_FP128Ty)
8223 return V; // No constant folding of this.
8224 // See if the value can be truncated to float and then reextended.
8225 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8227 if (CFP->getType() == Type::DoubleTy)
8228 return V; // Won't shrink.
8229 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8231 // Don't try to shrink to various long double types.
8237 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8238 if (Instruction *I = commonCastTransforms(CI))
8241 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8242 // smaller than the destination type, we can eliminate the truncate by doing
8243 // the add as the smaller type. This applies to add/sub/mul/div as well as
8244 // many builtins (sqrt, etc).
8245 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8246 if (OpI && OpI->hasOneUse()) {
8247 switch (OpI->getOpcode()) {
8249 case Instruction::Add:
8250 case Instruction::Sub:
8251 case Instruction::Mul:
8252 case Instruction::FDiv:
8253 case Instruction::FRem:
8254 const Type *SrcTy = OpI->getType();
8255 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8256 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8257 if (LHSTrunc->getType() != SrcTy &&
8258 RHSTrunc->getType() != SrcTy) {
8259 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8260 // If the source types were both smaller than the destination type of
8261 // the cast, do this xform.
8262 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8263 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8264 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8266 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8268 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8277 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8278 return commonCastTransforms(CI);
8281 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8282 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
8283 // mantissa to accurately represent all values of X. For example, do not
8284 // do this with i64->float->i64.
8285 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
8286 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8287 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8288 SrcI->getType()->getFPMantissaWidth())
8289 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8291 return commonCastTransforms(FI);
8294 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8295 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
8296 // mantissa to accurately represent all values of X. For example, do not
8297 // do this with i64->float->i64.
8298 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
8299 if (SrcI->getOperand(0)->getType() == FI.getType() &&
8300 (int)FI.getType()->getPrimitiveSizeInBits() <=
8301 SrcI->getType()->getFPMantissaWidth())
8302 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
8304 return commonCastTransforms(FI);
8307 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8308 return commonCastTransforms(CI);
8311 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8312 return commonCastTransforms(CI);
8315 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8316 return commonPointerCastTransforms(CI);
8319 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8320 if (Instruction *I = commonCastTransforms(CI))
8323 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8324 if (!DestPointee->isSized()) return 0;
8326 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8329 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8330 m_ConstantInt(Cst)))) {
8331 // If the source and destination operands have the same type, see if this
8332 // is a single-index GEP.
8333 if (X->getType() == CI.getType()) {
8334 // Get the size of the pointee type.
8335 uint64_t Size = TD->getABITypeSize(DestPointee);
8337 // Convert the constant to intptr type.
8338 APInt Offset = Cst->getValue();
8339 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8341 // If Offset is evenly divisible by Size, we can do this xform.
8342 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8343 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8344 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8347 // TODO: Could handle other cases, e.g. where add is indexing into field of
8349 } else if (CI.getOperand(0)->hasOneUse() &&
8350 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8351 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8352 // "inttoptr+GEP" instead of "add+intptr".
8354 // Get the size of the pointee type.
8355 uint64_t Size = TD->getABITypeSize(DestPointee);
8357 // Convert the constant to intptr type.
8358 APInt Offset = Cst->getValue();
8359 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8361 // If Offset is evenly divisible by Size, we can do this xform.
8362 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8363 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8365 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8367 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8373 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8374 // If the operands are integer typed then apply the integer transforms,
8375 // otherwise just apply the common ones.
8376 Value *Src = CI.getOperand(0);
8377 const Type *SrcTy = Src->getType();
8378 const Type *DestTy = CI.getType();
8380 if (SrcTy->isInteger() && DestTy->isInteger()) {
8381 if (Instruction *Result = commonIntCastTransforms(CI))
8383 } else if (isa<PointerType>(SrcTy)) {
8384 if (Instruction *I = commonPointerCastTransforms(CI))
8387 if (Instruction *Result = commonCastTransforms(CI))
8392 // Get rid of casts from one type to the same type. These are useless and can
8393 // be replaced by the operand.
8394 if (DestTy == Src->getType())
8395 return ReplaceInstUsesWith(CI, Src);
8397 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8398 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8399 const Type *DstElTy = DstPTy->getElementType();
8400 const Type *SrcElTy = SrcPTy->getElementType();
8402 // If the address spaces don't match, don't eliminate the bitcast, which is
8403 // required for changing types.
8404 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8407 // If we are casting a malloc or alloca to a pointer to a type of the same
8408 // size, rewrite the allocation instruction to allocate the "right" type.
8409 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8410 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8413 // If the source and destination are pointers, and this cast is equivalent
8414 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8415 // This can enhance SROA and other transforms that want type-safe pointers.
8416 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8417 unsigned NumZeros = 0;
8418 while (SrcElTy != DstElTy &&
8419 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8420 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8421 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8425 // If we found a path from the src to dest, create the getelementptr now.
8426 if (SrcElTy == DstElTy) {
8427 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8428 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8429 ((Instruction*) NULL));
8433 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8434 if (SVI->hasOneUse()) {
8435 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8436 // a bitconvert to a vector with the same # elts.
8437 if (isa<VectorType>(DestTy) &&
8438 cast<VectorType>(DestTy)->getNumElements() ==
8439 SVI->getType()->getNumElements()) {
8441 // If either of the operands is a cast from CI.getType(), then
8442 // evaluating the shuffle in the casted destination's type will allow
8443 // us to eliminate at least one cast.
8444 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8445 Tmp->getOperand(0)->getType() == DestTy) ||
8446 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8447 Tmp->getOperand(0)->getType() == DestTy)) {
8448 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
8449 SVI->getOperand(0), DestTy, &CI);
8450 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
8451 SVI->getOperand(1), DestTy, &CI);
8452 // Return a new shuffle vector. Use the same element ID's, as we
8453 // know the vector types match #elts.
8454 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8462 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8464 /// %D = select %cond, %C, %A
8466 /// %C = select %cond, %B, 0
8469 /// Assuming that the specified instruction is an operand to the select, return
8470 /// a bitmask indicating which operands of this instruction are foldable if they
8471 /// equal the other incoming value of the select.
8473 static unsigned GetSelectFoldableOperands(Instruction *I) {
8474 switch (I->getOpcode()) {
8475 case Instruction::Add:
8476 case Instruction::Mul:
8477 case Instruction::And:
8478 case Instruction::Or:
8479 case Instruction::Xor:
8480 return 3; // Can fold through either operand.
8481 case Instruction::Sub: // Can only fold on the amount subtracted.
8482 case Instruction::Shl: // Can only fold on the shift amount.
8483 case Instruction::LShr:
8484 case Instruction::AShr:
8487 return 0; // Cannot fold
8491 /// GetSelectFoldableConstant - For the same transformation as the previous
8492 /// function, return the identity constant that goes into the select.
8493 static Constant *GetSelectFoldableConstant(Instruction *I) {
8494 switch (I->getOpcode()) {
8495 default: assert(0 && "This cannot happen!"); abort();
8496 case Instruction::Add:
8497 case Instruction::Sub:
8498 case Instruction::Or:
8499 case Instruction::Xor:
8500 case Instruction::Shl:
8501 case Instruction::LShr:
8502 case Instruction::AShr:
8503 return Constant::getNullValue(I->getType());
8504 case Instruction::And:
8505 return Constant::getAllOnesValue(I->getType());
8506 case Instruction::Mul:
8507 return ConstantInt::get(I->getType(), 1);
8511 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8512 /// have the same opcode and only one use each. Try to simplify this.
8513 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8515 if (TI->getNumOperands() == 1) {
8516 // If this is a non-volatile load or a cast from the same type,
8519 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8522 return 0; // unknown unary op.
8525 // Fold this by inserting a select from the input values.
8526 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8527 FI->getOperand(0), SI.getName()+".v");
8528 InsertNewInstBefore(NewSI, SI);
8529 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
8533 // Only handle binary operators here.
8534 if (!isa<BinaryOperator>(TI))
8537 // Figure out if the operations have any operands in common.
8538 Value *MatchOp, *OtherOpT, *OtherOpF;
8540 if (TI->getOperand(0) == FI->getOperand(0)) {
8541 MatchOp = TI->getOperand(0);
8542 OtherOpT = TI->getOperand(1);
8543 OtherOpF = FI->getOperand(1);
8544 MatchIsOpZero = true;
8545 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8546 MatchOp = TI->getOperand(1);
8547 OtherOpT = TI->getOperand(0);
8548 OtherOpF = FI->getOperand(0);
8549 MatchIsOpZero = false;
8550 } else if (!TI->isCommutative()) {
8552 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8553 MatchOp = TI->getOperand(0);
8554 OtherOpT = TI->getOperand(1);
8555 OtherOpF = FI->getOperand(0);
8556 MatchIsOpZero = true;
8557 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8558 MatchOp = TI->getOperand(1);
8559 OtherOpT = TI->getOperand(0);
8560 OtherOpF = FI->getOperand(1);
8561 MatchIsOpZero = true;
8566 // If we reach here, they do have operations in common.
8567 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8568 OtherOpF, SI.getName()+".v");
8569 InsertNewInstBefore(NewSI, SI);
8571 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8573 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8575 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8577 assert(0 && "Shouldn't get here");
8581 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8582 Value *CondVal = SI.getCondition();
8583 Value *TrueVal = SI.getTrueValue();
8584 Value *FalseVal = SI.getFalseValue();
8586 // select true, X, Y -> X
8587 // select false, X, Y -> Y
8588 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8589 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8591 // select C, X, X -> X
8592 if (TrueVal == FalseVal)
8593 return ReplaceInstUsesWith(SI, TrueVal);
8595 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8596 return ReplaceInstUsesWith(SI, FalseVal);
8597 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8598 return ReplaceInstUsesWith(SI, TrueVal);
8599 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8600 if (isa<Constant>(TrueVal))
8601 return ReplaceInstUsesWith(SI, TrueVal);
8603 return ReplaceInstUsesWith(SI, FalseVal);
8606 if (SI.getType() == Type::Int1Ty) {
8607 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8608 if (C->getZExtValue()) {
8609 // Change: A = select B, true, C --> A = or B, C
8610 return BinaryOperator::CreateOr(CondVal, FalseVal);
8612 // Change: A = select B, false, C --> A = and !B, C
8614 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8615 "not."+CondVal->getName()), SI);
8616 return BinaryOperator::CreateAnd(NotCond, FalseVal);
8618 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8619 if (C->getZExtValue() == false) {
8620 // Change: A = select B, C, false --> A = and B, C
8621 return BinaryOperator::CreateAnd(CondVal, TrueVal);
8623 // Change: A = select B, C, true --> A = or !B, C
8625 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8626 "not."+CondVal->getName()), SI);
8627 return BinaryOperator::CreateOr(NotCond, TrueVal);
8631 // select a, b, a -> a&b
8632 // select a, a, b -> a|b
8633 if (CondVal == TrueVal)
8634 return BinaryOperator::CreateOr(CondVal, FalseVal);
8635 else if (CondVal == FalseVal)
8636 return BinaryOperator::CreateAnd(CondVal, TrueVal);
8639 // Selecting between two integer constants?
8640 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8641 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8642 // select C, 1, 0 -> zext C to int
8643 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8644 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8645 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8646 // select C, 0, 1 -> zext !C to int
8648 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8649 "not."+CondVal->getName()), SI);
8650 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8653 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8655 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8657 // (x <s 0) ? -1 : 0 -> ashr x, 31
8658 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8659 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8660 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8661 // The comparison constant and the result are not neccessarily the
8662 // same width. Make an all-ones value by inserting a AShr.
8663 Value *X = IC->getOperand(0);
8664 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8665 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8666 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8668 InsertNewInstBefore(SRA, SI);
8670 // Finally, convert to the type of the select RHS. We figure out
8671 // if this requires a SExt, Trunc or BitCast based on the sizes.
8672 Instruction::CastOps opc = Instruction::BitCast;
8673 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8674 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
8675 if (SRASize < SISize)
8676 opc = Instruction::SExt;
8677 else if (SRASize > SISize)
8678 opc = Instruction::Trunc;
8679 return CastInst::Create(opc, SRA, SI.getType());
8684 // If one of the constants is zero (we know they can't both be) and we
8685 // have an icmp instruction with zero, and we have an 'and' with the
8686 // non-constant value, eliminate this whole mess. This corresponds to
8687 // cases like this: ((X & 27) ? 27 : 0)
8688 if (TrueValC->isZero() || FalseValC->isZero())
8689 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8690 cast<Constant>(IC->getOperand(1))->isNullValue())
8691 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8692 if (ICA->getOpcode() == Instruction::And &&
8693 isa<ConstantInt>(ICA->getOperand(1)) &&
8694 (ICA->getOperand(1) == TrueValC ||
8695 ICA->getOperand(1) == FalseValC) &&
8696 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8697 // Okay, now we know that everything is set up, we just don't
8698 // know whether we have a icmp_ne or icmp_eq and whether the
8699 // true or false val is the zero.
8700 bool ShouldNotVal = !TrueValC->isZero();
8701 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8704 V = InsertNewInstBefore(BinaryOperator::Create(
8705 Instruction::Xor, V, ICA->getOperand(1)), SI);
8706 return ReplaceInstUsesWith(SI, V);
8711 // See if we are selecting two values based on a comparison of the two values.
8712 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8713 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8714 // Transform (X == Y) ? X : Y -> Y
8715 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8716 // This is not safe in general for floating point:
8717 // consider X== -0, Y== +0.
8718 // It becomes safe if either operand is a nonzero constant.
8719 ConstantFP *CFPt, *CFPf;
8720 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8721 !CFPt->getValueAPF().isZero()) ||
8722 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8723 !CFPf->getValueAPF().isZero()))
8724 return ReplaceInstUsesWith(SI, FalseVal);
8726 // Transform (X != Y) ? X : Y -> X
8727 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8728 return ReplaceInstUsesWith(SI, TrueVal);
8729 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8731 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8732 // Transform (X == Y) ? Y : X -> X
8733 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8734 // This is not safe in general for floating point:
8735 // consider X== -0, Y== +0.
8736 // It becomes safe if either operand is a nonzero constant.
8737 ConstantFP *CFPt, *CFPf;
8738 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8739 !CFPt->getValueAPF().isZero()) ||
8740 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8741 !CFPf->getValueAPF().isZero()))
8742 return ReplaceInstUsesWith(SI, FalseVal);
8744 // Transform (X != Y) ? Y : X -> Y
8745 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8746 return ReplaceInstUsesWith(SI, TrueVal);
8747 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8751 // See if we are selecting two values based on a comparison of the two values.
8752 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8753 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8754 // Transform (X == Y) ? X : Y -> Y
8755 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8756 return ReplaceInstUsesWith(SI, FalseVal);
8757 // Transform (X != Y) ? X : Y -> X
8758 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8759 return ReplaceInstUsesWith(SI, TrueVal);
8760 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8762 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8763 // Transform (X == Y) ? Y : X -> X
8764 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8765 return ReplaceInstUsesWith(SI, FalseVal);
8766 // Transform (X != Y) ? Y : X -> Y
8767 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8768 return ReplaceInstUsesWith(SI, TrueVal);
8769 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8773 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8774 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8775 if (TI->hasOneUse() && FI->hasOneUse()) {
8776 Instruction *AddOp = 0, *SubOp = 0;
8778 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8779 if (TI->getOpcode() == FI->getOpcode())
8780 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8783 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8784 // even legal for FP.
8785 if (TI->getOpcode() == Instruction::Sub &&
8786 FI->getOpcode() == Instruction::Add) {
8787 AddOp = FI; SubOp = TI;
8788 } else if (FI->getOpcode() == Instruction::Sub &&
8789 TI->getOpcode() == Instruction::Add) {
8790 AddOp = TI; SubOp = FI;
8794 Value *OtherAddOp = 0;
8795 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8796 OtherAddOp = AddOp->getOperand(1);
8797 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8798 OtherAddOp = AddOp->getOperand(0);
8802 // So at this point we know we have (Y -> OtherAddOp):
8803 // select C, (add X, Y), (sub X, Z)
8804 Value *NegVal; // Compute -Z
8805 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8806 NegVal = ConstantExpr::getNeg(C);
8808 NegVal = InsertNewInstBefore(
8809 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8812 Value *NewTrueOp = OtherAddOp;
8813 Value *NewFalseOp = NegVal;
8815 std::swap(NewTrueOp, NewFalseOp);
8816 Instruction *NewSel =
8817 SelectInst::Create(CondVal, NewTrueOp,
8818 NewFalseOp, SI.getName() + ".p");
8820 NewSel = InsertNewInstBefore(NewSel, SI);
8821 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8826 // See if we can fold the select into one of our operands.
8827 if (SI.getType()->isInteger()) {
8828 // See the comment above GetSelectFoldableOperands for a description of the
8829 // transformation we are doing here.
8830 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8831 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8832 !isa<Constant>(FalseVal))
8833 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8834 unsigned OpToFold = 0;
8835 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8837 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8842 Constant *C = GetSelectFoldableConstant(TVI);
8843 Instruction *NewSel =
8844 SelectInst::Create(SI.getCondition(),
8845 TVI->getOperand(2-OpToFold), C);
8846 InsertNewInstBefore(NewSel, SI);
8847 NewSel->takeName(TVI);
8848 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8849 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8851 assert(0 && "Unknown instruction!!");
8856 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8857 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8858 !isa<Constant>(TrueVal))
8859 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8860 unsigned OpToFold = 0;
8861 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8863 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8868 Constant *C = GetSelectFoldableConstant(FVI);
8869 Instruction *NewSel =
8870 SelectInst::Create(SI.getCondition(), C,
8871 FVI->getOperand(2-OpToFold));
8872 InsertNewInstBefore(NewSel, SI);
8873 NewSel->takeName(FVI);
8874 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8875 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
8877 assert(0 && "Unknown instruction!!");
8882 if (BinaryOperator::isNot(CondVal)) {
8883 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8884 SI.setOperand(1, FalseVal);
8885 SI.setOperand(2, TrueVal);
8892 /// EnforceKnownAlignment - If the specified pointer points to an object that
8893 /// we control, modify the object's alignment to PrefAlign. This isn't
8894 /// often possible though. If alignment is important, a more reliable approach
8895 /// is to simply align all global variables and allocation instructions to
8896 /// their preferred alignment from the beginning.
8898 static unsigned EnforceKnownAlignment(Value *V,
8899 unsigned Align, unsigned PrefAlign) {
8901 User *U = dyn_cast<User>(V);
8902 if (!U) return Align;
8904 switch (getOpcode(U)) {
8906 case Instruction::BitCast:
8907 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8908 case Instruction::GetElementPtr: {
8909 // If all indexes are zero, it is just the alignment of the base pointer.
8910 bool AllZeroOperands = true;
8911 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8912 if (!isa<Constant>(U->getOperand(i)) ||
8913 !cast<Constant>(U->getOperand(i))->isNullValue()) {
8914 AllZeroOperands = false;
8918 if (AllZeroOperands) {
8919 // Treat this like a bitcast.
8920 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8926 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8927 // If there is a large requested alignment and we can, bump up the alignment
8929 if (!GV->isDeclaration()) {
8930 GV->setAlignment(PrefAlign);
8933 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8934 // If there is a requested alignment and if this is an alloca, round up. We
8935 // don't do this for malloc, because some systems can't respect the request.
8936 if (isa<AllocaInst>(AI)) {
8937 AI->setAlignment(PrefAlign);
8945 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8946 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8947 /// and it is more than the alignment of the ultimate object, see if we can
8948 /// increase the alignment of the ultimate object, making this check succeed.
8949 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8950 unsigned PrefAlign) {
8951 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8952 sizeof(PrefAlign) * CHAR_BIT;
8953 APInt Mask = APInt::getAllOnesValue(BitWidth);
8954 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8955 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8956 unsigned TrailZ = KnownZero.countTrailingOnes();
8957 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8959 if (PrefAlign > Align)
8960 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8962 // We don't need to make any adjustment.
8966 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8967 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8968 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
8969 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8970 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8972 if (CopyAlign < MinAlign) {
8973 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8977 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8979 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8980 if (MemOpLength == 0) return 0;
8982 // Source and destination pointer types are always "i8*" for intrinsic. See
8983 // if the size is something we can handle with a single primitive load/store.
8984 // A single load+store correctly handles overlapping memory in the memmove
8986 unsigned Size = MemOpLength->getZExtValue();
8987 if (Size == 0) return MI; // Delete this mem transfer.
8989 if (Size > 8 || (Size&(Size-1)))
8990 return 0; // If not 1/2/4/8 bytes, exit.
8992 // Use an integer load+store unless we can find something better.
8993 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
8995 // Memcpy forces the use of i8* for the source and destination. That means
8996 // that if you're using memcpy to move one double around, you'll get a cast
8997 // from double* to i8*. We'd much rather use a double load+store rather than
8998 // an i64 load+store, here because this improves the odds that the source or
8999 // dest address will be promotable. See if we can find a better type than the
9000 // integer datatype.
9001 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9002 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9003 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9004 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9005 // down through these levels if so.
9006 while (!SrcETy->isFirstClassType()) {
9007 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9008 if (STy->getNumElements() == 1)
9009 SrcETy = STy->getElementType(0);
9012 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9013 if (ATy->getNumElements() == 1)
9014 SrcETy = ATy->getElementType();
9021 if (SrcETy->isFirstClassType())
9022 NewPtrTy = PointerType::getUnqual(SrcETy);
9027 // If the memcpy/memmove provides better alignment info than we can
9029 SrcAlign = std::max(SrcAlign, CopyAlign);
9030 DstAlign = std::max(DstAlign, CopyAlign);
9032 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9033 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9034 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9035 InsertNewInstBefore(L, *MI);
9036 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9038 // Set the size of the copy to 0, it will be deleted on the next iteration.
9039 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9043 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9044 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9045 if (MI->getAlignment()->getZExtValue() < Alignment) {
9046 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9050 // Extract the length and alignment and fill if they are constant.
9051 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9052 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9053 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9055 uint64_t Len = LenC->getZExtValue();
9056 Alignment = MI->getAlignment()->getZExtValue();
9058 // If the length is zero, this is a no-op
9059 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9061 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9062 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9063 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9065 Value *Dest = MI->getDest();
9066 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9068 // Alignment 0 is identity for alignment 1 for memset, but not store.
9069 if (Alignment == 0) Alignment = 1;
9071 // Extract the fill value and store.
9072 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9073 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9076 // Set the size of the copy to 0, it will be deleted on the next iteration.
9077 MI->setLength(Constant::getNullValue(LenC->getType()));
9085 /// visitCallInst - CallInst simplification. This mostly only handles folding
9086 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9087 /// the heavy lifting.
9089 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9090 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9091 if (!II) return visitCallSite(&CI);
9093 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9095 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9096 bool Changed = false;
9098 // memmove/cpy/set of zero bytes is a noop.
9099 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9100 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9102 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9103 if (CI->getZExtValue() == 1) {
9104 // Replace the instruction with just byte operations. We would
9105 // transform other cases to loads/stores, but we don't know if
9106 // alignment is sufficient.
9110 // If we have a memmove and the source operation is a constant global,
9111 // then the source and dest pointers can't alias, so we can change this
9112 // into a call to memcpy.
9113 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9114 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9115 if (GVSrc->isConstant()) {
9116 Module *M = CI.getParent()->getParent()->getParent();
9117 Intrinsic::ID MemCpyID;
9118 if (CI.getOperand(3)->getType() == Type::Int32Ty)
9119 MemCpyID = Intrinsic::memcpy_i32;
9121 MemCpyID = Intrinsic::memcpy_i64;
9122 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
9127 // If we can determine a pointer alignment that is bigger than currently
9128 // set, update the alignment.
9129 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
9130 if (Instruction *I = SimplifyMemTransfer(MI))
9132 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9133 if (Instruction *I = SimplifyMemSet(MSI))
9137 if (Changed) return II;
9139 switch (II->getIntrinsicID()) {
9141 case Intrinsic::ppc_altivec_lvx:
9142 case Intrinsic::ppc_altivec_lvxl:
9143 case Intrinsic::x86_sse_loadu_ps:
9144 case Intrinsic::x86_sse2_loadu_pd:
9145 case Intrinsic::x86_sse2_loadu_dq:
9146 // Turn PPC lvx -> load if the pointer is known aligned.
9147 // Turn X86 loadups -> load if the pointer is known aligned.
9148 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9149 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9150 PointerType::getUnqual(II->getType()),
9152 return new LoadInst(Ptr);
9155 case Intrinsic::ppc_altivec_stvx:
9156 case Intrinsic::ppc_altivec_stvxl:
9157 // Turn stvx -> store if the pointer is known aligned.
9158 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9159 const Type *OpPtrTy =
9160 PointerType::getUnqual(II->getOperand(1)->getType());
9161 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9162 return new StoreInst(II->getOperand(1), Ptr);
9165 case Intrinsic::x86_sse_storeu_ps:
9166 case Intrinsic::x86_sse2_storeu_pd:
9167 case Intrinsic::x86_sse2_storeu_dq:
9168 case Intrinsic::x86_sse2_storel_dq:
9169 // Turn X86 storeu -> store if the pointer is known aligned.
9170 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9171 const Type *OpPtrTy =
9172 PointerType::getUnqual(II->getOperand(2)->getType());
9173 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9174 return new StoreInst(II->getOperand(2), Ptr);
9178 case Intrinsic::x86_sse_cvttss2si: {
9179 // These intrinsics only demands the 0th element of its input vector. If
9180 // we can simplify the input based on that, do so now.
9182 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
9184 II->setOperand(1, V);
9190 case Intrinsic::ppc_altivec_vperm:
9191 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9192 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9193 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9195 // Check that all of the elements are integer constants or undefs.
9196 bool AllEltsOk = true;
9197 for (unsigned i = 0; i != 16; ++i) {
9198 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9199 !isa<UndefValue>(Mask->getOperand(i))) {
9206 // Cast the input vectors to byte vectors.
9207 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9208 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9209 Value *Result = UndefValue::get(Op0->getType());
9211 // Only extract each element once.
9212 Value *ExtractedElts[32];
9213 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9215 for (unsigned i = 0; i != 16; ++i) {
9216 if (isa<UndefValue>(Mask->getOperand(i)))
9218 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9219 Idx &= 31; // Match the hardware behavior.
9221 if (ExtractedElts[Idx] == 0) {
9223 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9224 InsertNewInstBefore(Elt, CI);
9225 ExtractedElts[Idx] = Elt;
9228 // Insert this value into the result vector.
9229 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9231 InsertNewInstBefore(cast<Instruction>(Result), CI);
9233 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9238 case Intrinsic::stackrestore: {
9239 // If the save is right next to the restore, remove the restore. This can
9240 // happen when variable allocas are DCE'd.
9241 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9242 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9243 BasicBlock::iterator BI = SS;
9245 return EraseInstFromFunction(CI);
9249 // Scan down this block to see if there is another stack restore in the
9250 // same block without an intervening call/alloca.
9251 BasicBlock::iterator BI = II;
9252 TerminatorInst *TI = II->getParent()->getTerminator();
9253 bool CannotRemove = false;
9254 for (++BI; &*BI != TI; ++BI) {
9255 if (isa<AllocaInst>(BI)) {
9256 CannotRemove = true;
9259 if (isa<CallInst>(BI)) {
9260 if (!isa<IntrinsicInst>(BI)) {
9261 CannotRemove = true;
9264 // If there is a stackrestore below this one, remove this one.
9265 return EraseInstFromFunction(CI);
9269 // If the stack restore is in a return/unwind block and if there are no
9270 // allocas or calls between the restore and the return, nuke the restore.
9271 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9272 return EraseInstFromFunction(CI);
9278 return visitCallSite(II);
9281 // InvokeInst simplification
9283 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9284 return visitCallSite(&II);
9287 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
9288 /// passed through the varargs area, we can eliminate the use of the cast.
9289 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9290 const CastInst * const CI,
9291 const TargetData * const TD,
9293 if (!CI->isLosslessCast())
9296 // The size of ByVal arguments is derived from the type, so we
9297 // can't change to a type with a different size. If the size were
9298 // passed explicitly we could avoid this check.
9299 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
9303 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9304 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9305 if (!SrcTy->isSized() || !DstTy->isSized())
9307 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9312 // visitCallSite - Improvements for call and invoke instructions.
9314 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9315 bool Changed = false;
9317 // If the callee is a constexpr cast of a function, attempt to move the cast
9318 // to the arguments of the call/invoke.
9319 if (transformConstExprCastCall(CS)) return 0;
9321 Value *Callee = CS.getCalledValue();
9323 if (Function *CalleeF = dyn_cast<Function>(Callee))
9324 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9325 Instruction *OldCall = CS.getInstruction();
9326 // If the call and callee calling conventions don't match, this call must
9327 // be unreachable, as the call is undefined.
9328 new StoreInst(ConstantInt::getTrue(),
9329 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9331 if (!OldCall->use_empty())
9332 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9333 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9334 return EraseInstFromFunction(*OldCall);
9338 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9339 // This instruction is not reachable, just remove it. We insert a store to
9340 // undef so that we know that this code is not reachable, despite the fact
9341 // that we can't modify the CFG here.
9342 new StoreInst(ConstantInt::getTrue(),
9343 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9344 CS.getInstruction());
9346 if (!CS.getInstruction()->use_empty())
9347 CS.getInstruction()->
9348 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9350 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9351 // Don't break the CFG, insert a dummy cond branch.
9352 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9353 ConstantInt::getTrue(), II);
9355 return EraseInstFromFunction(*CS.getInstruction());
9358 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9359 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9360 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9361 return transformCallThroughTrampoline(CS);
9363 const PointerType *PTy = cast<PointerType>(Callee->getType());
9364 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9365 if (FTy->isVarArg()) {
9366 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9367 // See if we can optimize any arguments passed through the varargs area of
9369 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9370 E = CS.arg_end(); I != E; ++I, ++ix) {
9371 CastInst *CI = dyn_cast<CastInst>(*I);
9372 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9373 *I = CI->getOperand(0);
9379 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9380 // Inline asm calls cannot throw - mark them 'nounwind'.
9381 CS.setDoesNotThrow();
9385 return Changed ? CS.getInstruction() : 0;
9388 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9389 // attempt to move the cast to the arguments of the call/invoke.
9391 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9392 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9393 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9394 if (CE->getOpcode() != Instruction::BitCast ||
9395 !isa<Function>(CE->getOperand(0)))
9397 Function *Callee = cast<Function>(CE->getOperand(0));
9398 Instruction *Caller = CS.getInstruction();
9399 const PAListPtr &CallerPAL = CS.getParamAttrs();
9401 // Okay, this is a cast from a function to a different type. Unless doing so
9402 // would cause a type conversion of one of our arguments, change this call to
9403 // be a direct call with arguments casted to the appropriate types.
9405 const FunctionType *FT = Callee->getFunctionType();
9406 const Type *OldRetTy = Caller->getType();
9408 if (isa<StructType>(FT->getReturnType()))
9409 return false; // TODO: Handle multiple return values.
9411 // Check to see if we are changing the return type...
9412 if (OldRetTy != FT->getReturnType()) {
9413 if (Callee->isDeclaration() &&
9414 // Conversion is ok if changing from pointer to int of same size.
9415 !(isa<PointerType>(FT->getReturnType()) &&
9416 TD->getIntPtrType() == OldRetTy))
9417 return false; // Cannot transform this return value.
9419 if (!Caller->use_empty() &&
9420 // void -> non-void is handled specially
9421 FT->getReturnType() != Type::VoidTy &&
9422 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
9423 return false; // Cannot transform this return value.
9425 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9426 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
9427 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
9428 return false; // Attribute not compatible with transformed value.
9431 // If the callsite is an invoke instruction, and the return value is used by
9432 // a PHI node in a successor, we cannot change the return type of the call
9433 // because there is no place to put the cast instruction (without breaking
9434 // the critical edge). Bail out in this case.
9435 if (!Caller->use_empty())
9436 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9437 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9439 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9440 if (PN->getParent() == II->getNormalDest() ||
9441 PN->getParent() == II->getUnwindDest())
9445 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9446 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9448 CallSite::arg_iterator AI = CS.arg_begin();
9449 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9450 const Type *ParamTy = FT->getParamType(i);
9451 const Type *ActTy = (*AI)->getType();
9453 if (!CastInst::isCastable(ActTy, ParamTy))
9454 return false; // Cannot transform this parameter value.
9456 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
9457 return false; // Attribute not compatible with transformed value.
9459 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
9460 // Some conversions are safe even if we do not have a body.
9461 // Either we can cast directly, or we can upconvert the argument
9462 bool isConvertible = ActTy == ParamTy ||
9463 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
9464 (ParamTy->isInteger() && ActTy->isInteger() &&
9465 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
9466 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
9467 && c->getValue().isStrictlyPositive());
9468 if (Callee->isDeclaration() && !isConvertible) return false;
9471 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9472 Callee->isDeclaration())
9473 return false; // Do not delete arguments unless we have a function body.
9475 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9476 !CallerPAL.isEmpty())
9477 // In this case we have more arguments than the new function type, but we
9478 // won't be dropping them. Check that these extra arguments have attributes
9479 // that are compatible with being a vararg call argument.
9480 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9481 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9483 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9484 if (PAttrs & ParamAttr::VarArgsIncompatible)
9488 // Okay, we decided that this is a safe thing to do: go ahead and start
9489 // inserting cast instructions as necessary...
9490 std::vector<Value*> Args;
9491 Args.reserve(NumActualArgs);
9492 SmallVector<ParamAttrsWithIndex, 8> attrVec;
9493 attrVec.reserve(NumCommonArgs);
9495 // Get any return attributes.
9496 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
9498 // If the return value is not being used, the type may not be compatible
9499 // with the existing attributes. Wipe out any problematic attributes.
9500 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
9502 // Add the new return attributes.
9504 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
9506 AI = CS.arg_begin();
9507 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9508 const Type *ParamTy = FT->getParamType(i);
9509 if ((*AI)->getType() == ParamTy) {
9510 Args.push_back(*AI);
9512 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9513 false, ParamTy, false);
9514 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9515 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9518 // Add any parameter attributes.
9519 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9520 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9523 // If the function takes more arguments than the call was taking, add them
9525 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9526 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9528 // If we are removing arguments to the function, emit an obnoxious warning...
9529 if (FT->getNumParams() < NumActualArgs) {
9530 if (!FT->isVarArg()) {
9531 cerr << "WARNING: While resolving call to function '"
9532 << Callee->getName() << "' arguments were dropped!\n";
9534 // Add all of the arguments in their promoted form to the arg list...
9535 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9536 const Type *PTy = getPromotedType((*AI)->getType());
9537 if (PTy != (*AI)->getType()) {
9538 // Must promote to pass through va_arg area!
9539 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9541 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9542 InsertNewInstBefore(Cast, *Caller);
9543 Args.push_back(Cast);
9545 Args.push_back(*AI);
9548 // Add any parameter attributes.
9549 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9550 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9555 if (FT->getReturnType() == Type::VoidTy)
9556 Caller->setName(""); // Void type should not have a name.
9558 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
9561 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9562 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9563 Args.begin(), Args.end(),
9564 Caller->getName(), Caller);
9565 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9566 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
9568 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9569 Caller->getName(), Caller);
9570 CallInst *CI = cast<CallInst>(Caller);
9571 if (CI->isTailCall())
9572 cast<CallInst>(NC)->setTailCall();
9573 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9574 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
9577 // Insert a cast of the return type as necessary.
9579 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9580 if (NV->getType() != Type::VoidTy) {
9581 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
9583 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9585 // If this is an invoke instruction, we should insert it after the first
9586 // non-phi, instruction in the normal successor block.
9587 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9588 BasicBlock::iterator I = II->getNormalDest()->begin();
9589 while (isa<PHINode>(I)) ++I;
9590 InsertNewInstBefore(NC, *I);
9592 // Otherwise, it's a call, just insert cast right after the call instr
9593 InsertNewInstBefore(NC, *Caller);
9595 AddUsersToWorkList(*Caller);
9597 NV = UndefValue::get(Caller->getType());
9601 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9602 Caller->replaceAllUsesWith(NV);
9603 Caller->eraseFromParent();
9604 RemoveFromWorkList(Caller);
9608 // transformCallThroughTrampoline - Turn a call to a function created by the
9609 // init_trampoline intrinsic into a direct call to the underlying function.
9611 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9612 Value *Callee = CS.getCalledValue();
9613 const PointerType *PTy = cast<PointerType>(Callee->getType());
9614 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9615 const PAListPtr &Attrs = CS.getParamAttrs();
9617 // If the call already has the 'nest' attribute somewhere then give up -
9618 // otherwise 'nest' would occur twice after splicing in the chain.
9619 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
9622 IntrinsicInst *Tramp =
9623 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9625 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9626 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9627 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9629 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9630 if (!NestAttrs.isEmpty()) {
9631 unsigned NestIdx = 1;
9632 const Type *NestTy = 0;
9633 ParameterAttributes NestAttr = ParamAttr::None;
9635 // Look for a parameter marked with the 'nest' attribute.
9636 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9637 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9638 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
9639 // Record the parameter type and any other attributes.
9641 NestAttr = NestAttrs.getParamAttrs(NestIdx);
9646 Instruction *Caller = CS.getInstruction();
9647 std::vector<Value*> NewArgs;
9648 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9650 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9651 NewAttrs.reserve(Attrs.getNumSlots() + 1);
9653 // Insert the nest argument into the call argument list, which may
9654 // mean appending it. Likewise for attributes.
9656 // Add any function result attributes.
9657 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9658 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
9662 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9664 if (Idx == NestIdx) {
9665 // Add the chain argument and attributes.
9666 Value *NestVal = Tramp->getOperand(3);
9667 if (NestVal->getType() != NestTy)
9668 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9669 NewArgs.push_back(NestVal);
9670 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
9676 // Add the original argument and attributes.
9677 NewArgs.push_back(*I);
9678 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
9680 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9686 // The trampoline may have been bitcast to a bogus type (FTy).
9687 // Handle this by synthesizing a new function type, equal to FTy
9688 // with the chain parameter inserted.
9690 std::vector<const Type*> NewTypes;
9691 NewTypes.reserve(FTy->getNumParams()+1);
9693 // Insert the chain's type into the list of parameter types, which may
9694 // mean appending it.
9697 FunctionType::param_iterator I = FTy->param_begin(),
9698 E = FTy->param_end();
9702 // Add the chain's type.
9703 NewTypes.push_back(NestTy);
9708 // Add the original type.
9709 NewTypes.push_back(*I);
9715 // Replace the trampoline call with a direct call. Let the generic
9716 // code sort out any function type mismatches.
9717 FunctionType *NewFTy =
9718 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9719 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9720 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9721 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
9723 Instruction *NewCaller;
9724 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9725 NewCaller = InvokeInst::Create(NewCallee,
9726 II->getNormalDest(), II->getUnwindDest(),
9727 NewArgs.begin(), NewArgs.end(),
9728 Caller->getName(), Caller);
9729 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9730 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
9732 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9733 Caller->getName(), Caller);
9734 if (cast<CallInst>(Caller)->isTailCall())
9735 cast<CallInst>(NewCaller)->setTailCall();
9736 cast<CallInst>(NewCaller)->
9737 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9738 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
9740 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9741 Caller->replaceAllUsesWith(NewCaller);
9742 Caller->eraseFromParent();
9743 RemoveFromWorkList(Caller);
9748 // Replace the trampoline call with a direct call. Since there is no 'nest'
9749 // parameter, there is no need to adjust the argument list. Let the generic
9750 // code sort out any function type mismatches.
9751 Constant *NewCallee =
9752 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9753 CS.setCalledFunction(NewCallee);
9754 return CS.getInstruction();
9757 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9758 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9759 /// and a single binop.
9760 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9761 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9762 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9763 isa<CmpInst>(FirstInst));
9764 unsigned Opc = FirstInst->getOpcode();
9765 Value *LHSVal = FirstInst->getOperand(0);
9766 Value *RHSVal = FirstInst->getOperand(1);
9768 const Type *LHSType = LHSVal->getType();
9769 const Type *RHSType = RHSVal->getType();
9771 // Scan to see if all operands are the same opcode, all have one use, and all
9772 // kill their operands (i.e. the operands have one use).
9773 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9774 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9775 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9776 // Verify type of the LHS matches so we don't fold cmp's of different
9777 // types or GEP's with different index types.
9778 I->getOperand(0)->getType() != LHSType ||
9779 I->getOperand(1)->getType() != RHSType)
9782 // If they are CmpInst instructions, check their predicates
9783 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9784 if (cast<CmpInst>(I)->getPredicate() !=
9785 cast<CmpInst>(FirstInst)->getPredicate())
9788 // Keep track of which operand needs a phi node.
9789 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9790 if (I->getOperand(1) != RHSVal) RHSVal = 0;
9793 // Otherwise, this is safe to transform, determine if it is profitable.
9795 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9796 // Indexes are often folded into load/store instructions, so we don't want to
9797 // hide them behind a phi.
9798 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9801 Value *InLHS = FirstInst->getOperand(0);
9802 Value *InRHS = FirstInst->getOperand(1);
9803 PHINode *NewLHS = 0, *NewRHS = 0;
9805 NewLHS = PHINode::Create(LHSType,
9806 FirstInst->getOperand(0)->getName() + ".pn");
9807 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9808 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9809 InsertNewInstBefore(NewLHS, PN);
9814 NewRHS = PHINode::Create(RHSType,
9815 FirstInst->getOperand(1)->getName() + ".pn");
9816 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9817 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9818 InsertNewInstBefore(NewRHS, PN);
9822 // Add all operands to the new PHIs.
9823 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9825 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9826 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9829 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9830 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9834 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9835 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
9836 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9837 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
9840 assert(isa<GetElementPtrInst>(FirstInst));
9841 return GetElementPtrInst::Create(LHSVal, RHSVal);
9845 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9846 /// of the block that defines it. This means that it must be obvious the value
9847 /// of the load is not changed from the point of the load to the end of the
9850 /// Finally, it is safe, but not profitable, to sink a load targetting a
9851 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
9853 static bool isSafeToSinkLoad(LoadInst *L) {
9854 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9856 for (++BBI; BBI != E; ++BBI)
9857 if (BBI->mayWriteToMemory())
9860 // Check for non-address taken alloca. If not address-taken already, it isn't
9861 // profitable to do this xform.
9862 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9863 bool isAddressTaken = false;
9864 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9866 if (isa<LoadInst>(UI)) continue;
9867 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9868 // If storing TO the alloca, then the address isn't taken.
9869 if (SI->getOperand(1) == AI) continue;
9871 isAddressTaken = true;
9875 if (!isAddressTaken)
9883 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9884 // operator and they all are only used by the PHI, PHI together their
9885 // inputs, and do the operation once, to the result of the PHI.
9886 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9887 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9889 // Scan the instruction, looking for input operations that can be folded away.
9890 // If all input operands to the phi are the same instruction (e.g. a cast from
9891 // the same type or "+42") we can pull the operation through the PHI, reducing
9892 // code size and simplifying code.
9893 Constant *ConstantOp = 0;
9894 const Type *CastSrcTy = 0;
9895 bool isVolatile = false;
9896 if (isa<CastInst>(FirstInst)) {
9897 CastSrcTy = FirstInst->getOperand(0)->getType();
9898 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9899 // Can fold binop, compare or shift here if the RHS is a constant,
9900 // otherwise call FoldPHIArgBinOpIntoPHI.
9901 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9902 if (ConstantOp == 0)
9903 return FoldPHIArgBinOpIntoPHI(PN);
9904 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9905 isVolatile = LI->isVolatile();
9906 // We can't sink the load if the loaded value could be modified between the
9907 // load and the PHI.
9908 if (LI->getParent() != PN.getIncomingBlock(0) ||
9909 !isSafeToSinkLoad(LI))
9911 } else if (isa<GetElementPtrInst>(FirstInst)) {
9912 if (FirstInst->getNumOperands() == 2)
9913 return FoldPHIArgBinOpIntoPHI(PN);
9914 // Can't handle general GEPs yet.
9917 return 0; // Cannot fold this operation.
9920 // Check to see if all arguments are the same operation.
9921 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9922 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9923 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9924 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9927 if (I->getOperand(0)->getType() != CastSrcTy)
9928 return 0; // Cast operation must match.
9929 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9930 // We can't sink the load if the loaded value could be modified between
9931 // the load and the PHI.
9932 if (LI->isVolatile() != isVolatile ||
9933 LI->getParent() != PN.getIncomingBlock(i) ||
9934 !isSafeToSinkLoad(LI))
9937 // If the PHI is volatile and its block has multiple successors, sinking
9938 // it would remove a load of the volatile value from the path through the
9941 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9945 } else if (I->getOperand(1) != ConstantOp) {
9950 // Okay, they are all the same operation. Create a new PHI node of the
9951 // correct type, and PHI together all of the LHS's of the instructions.
9952 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9953 PN.getName()+".in");
9954 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9956 Value *InVal = FirstInst->getOperand(0);
9957 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9959 // Add all operands to the new PHI.
9960 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9961 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9962 if (NewInVal != InVal)
9964 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9969 // The new PHI unions all of the same values together. This is really
9970 // common, so we handle it intelligently here for compile-time speed.
9974 InsertNewInstBefore(NewPN, PN);
9978 // Insert and return the new operation.
9979 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9980 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
9981 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9982 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
9983 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9984 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
9985 PhiVal, ConstantOp);
9986 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9988 // If this was a volatile load that we are merging, make sure to loop through
9989 // and mark all the input loads as non-volatile. If we don't do this, we will
9990 // insert a new volatile load and the old ones will not be deletable.
9992 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9993 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9995 return new LoadInst(PhiVal, "", isVolatile);
9998 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10000 static bool DeadPHICycle(PHINode *PN,
10001 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10002 if (PN->use_empty()) return true;
10003 if (!PN->hasOneUse()) return false;
10005 // Remember this node, and if we find the cycle, return.
10006 if (!PotentiallyDeadPHIs.insert(PN))
10009 // Don't scan crazily complex things.
10010 if (PotentiallyDeadPHIs.size() == 16)
10013 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10014 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10019 /// PHIsEqualValue - Return true if this phi node is always equal to
10020 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10021 /// z = some value; x = phi (y, z); y = phi (x, z)
10022 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10023 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10024 // See if we already saw this PHI node.
10025 if (!ValueEqualPHIs.insert(PN))
10028 // Don't scan crazily complex things.
10029 if (ValueEqualPHIs.size() == 16)
10032 // Scan the operands to see if they are either phi nodes or are equal to
10034 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10035 Value *Op = PN->getIncomingValue(i);
10036 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10037 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10039 } else if (Op != NonPhiInVal)
10047 // PHINode simplification
10049 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10050 // If LCSSA is around, don't mess with Phi nodes
10051 if (MustPreserveLCSSA) return 0;
10053 if (Value *V = PN.hasConstantValue())
10054 return ReplaceInstUsesWith(PN, V);
10056 // If all PHI operands are the same operation, pull them through the PHI,
10057 // reducing code size.
10058 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10059 PN.getIncomingValue(0)->hasOneUse())
10060 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10063 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10064 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10065 // PHI)... break the cycle.
10066 if (PN.hasOneUse()) {
10067 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10068 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10069 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10070 PotentiallyDeadPHIs.insert(&PN);
10071 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10072 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10075 // If this phi has a single use, and if that use just computes a value for
10076 // the next iteration of a loop, delete the phi. This occurs with unused
10077 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10078 // common case here is good because the only other things that catch this
10079 // are induction variable analysis (sometimes) and ADCE, which is only run
10081 if (PHIUser->hasOneUse() &&
10082 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10083 PHIUser->use_back() == &PN) {
10084 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10088 // We sometimes end up with phi cycles that non-obviously end up being the
10089 // same value, for example:
10090 // z = some value; x = phi (y, z); y = phi (x, z)
10091 // where the phi nodes don't necessarily need to be in the same block. Do a
10092 // quick check to see if the PHI node only contains a single non-phi value, if
10093 // so, scan to see if the phi cycle is actually equal to that value.
10095 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10096 // Scan for the first non-phi operand.
10097 while (InValNo != NumOperandVals &&
10098 isa<PHINode>(PN.getIncomingValue(InValNo)))
10101 if (InValNo != NumOperandVals) {
10102 Value *NonPhiInVal = PN.getOperand(InValNo);
10104 // Scan the rest of the operands to see if there are any conflicts, if so
10105 // there is no need to recursively scan other phis.
10106 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10107 Value *OpVal = PN.getIncomingValue(InValNo);
10108 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10112 // If we scanned over all operands, then we have one unique value plus
10113 // phi values. Scan PHI nodes to see if they all merge in each other or
10115 if (InValNo == NumOperandVals) {
10116 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10117 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10118 return ReplaceInstUsesWith(PN, NonPhiInVal);
10125 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10126 Instruction *InsertPoint,
10127 InstCombiner *IC) {
10128 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10129 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10130 // We must cast correctly to the pointer type. Ensure that we
10131 // sign extend the integer value if it is smaller as this is
10132 // used for address computation.
10133 Instruction::CastOps opcode =
10134 (VTySize < PtrSize ? Instruction::SExt :
10135 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10136 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10140 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10141 Value *PtrOp = GEP.getOperand(0);
10142 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
10143 // If so, eliminate the noop.
10144 if (GEP.getNumOperands() == 1)
10145 return ReplaceInstUsesWith(GEP, PtrOp);
10147 if (isa<UndefValue>(GEP.getOperand(0)))
10148 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10150 bool HasZeroPointerIndex = false;
10151 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10152 HasZeroPointerIndex = C->isNullValue();
10154 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10155 return ReplaceInstUsesWith(GEP, PtrOp);
10157 // Eliminate unneeded casts for indices.
10158 bool MadeChange = false;
10160 gep_type_iterator GTI = gep_type_begin(GEP);
10161 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
10162 if (isa<SequentialType>(*GTI)) {
10163 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
10164 if (CI->getOpcode() == Instruction::ZExt ||
10165 CI->getOpcode() == Instruction::SExt) {
10166 const Type *SrcTy = CI->getOperand(0)->getType();
10167 // We can eliminate a cast from i32 to i64 iff the target
10168 // is a 32-bit pointer target.
10169 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10171 GEP.setOperand(i, CI->getOperand(0));
10175 // If we are using a wider index than needed for this platform, shrink it
10176 // to what we need. If the incoming value needs a cast instruction,
10177 // insert it. This explicit cast can make subsequent optimizations more
10179 Value *Op = GEP.getOperand(i);
10180 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10181 if (Constant *C = dyn_cast<Constant>(Op)) {
10182 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
10185 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10187 GEP.setOperand(i, Op);
10193 if (MadeChange) return &GEP;
10195 // If this GEP instruction doesn't move the pointer, and if the input operand
10196 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
10197 // real input to the dest type.
10198 if (GEP.hasAllZeroIndices()) {
10199 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
10200 // If the bitcast is of an allocation, and the allocation will be
10201 // converted to match the type of the cast, don't touch this.
10202 if (isa<AllocationInst>(BCI->getOperand(0))) {
10203 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10204 if (Instruction *I = visitBitCast(*BCI)) {
10207 BCI->getParent()->getInstList().insert(BCI, I);
10208 ReplaceInstUsesWith(*BCI, I);
10213 return new BitCastInst(BCI->getOperand(0), GEP.getType());
10217 // Combine Indices - If the source pointer to this getelementptr instruction
10218 // is a getelementptr instruction, combine the indices of the two
10219 // getelementptr instructions into a single instruction.
10221 SmallVector<Value*, 8> SrcGEPOperands;
10222 if (User *Src = dyn_castGetElementPtr(PtrOp))
10223 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10225 if (!SrcGEPOperands.empty()) {
10226 // Note that if our source is a gep chain itself that we wait for that
10227 // chain to be resolved before we perform this transformation. This
10228 // avoids us creating a TON of code in some cases.
10230 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10231 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10232 return 0; // Wait until our source is folded to completion.
10234 SmallVector<Value*, 8> Indices;
10236 // Find out whether the last index in the source GEP is a sequential idx.
10237 bool EndsWithSequential = false;
10238 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10239 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10240 EndsWithSequential = !isa<StructType>(*I);
10242 // Can we combine the two pointer arithmetics offsets?
10243 if (EndsWithSequential) {
10244 // Replace: gep (gep %P, long B), long A, ...
10245 // With: T = long A+B; gep %P, T, ...
10247 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10248 if (SO1 == Constant::getNullValue(SO1->getType())) {
10250 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10253 // If they aren't the same type, convert both to an integer of the
10254 // target's pointer size.
10255 if (SO1->getType() != GO1->getType()) {
10256 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10257 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10258 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10259 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10261 unsigned PS = TD->getPointerSizeInBits();
10262 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10263 // Convert GO1 to SO1's type.
10264 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10266 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10267 // Convert SO1 to GO1's type.
10268 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10270 const Type *PT = TD->getIntPtrType();
10271 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10272 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10276 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10277 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10279 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10280 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10284 // Recycle the GEP we already have if possible.
10285 if (SrcGEPOperands.size() == 2) {
10286 GEP.setOperand(0, SrcGEPOperands[0]);
10287 GEP.setOperand(1, Sum);
10290 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10291 SrcGEPOperands.end()-1);
10292 Indices.push_back(Sum);
10293 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10295 } else if (isa<Constant>(*GEP.idx_begin()) &&
10296 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10297 SrcGEPOperands.size() != 1) {
10298 // Otherwise we can do the fold if the first index of the GEP is a zero
10299 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10300 SrcGEPOperands.end());
10301 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10304 if (!Indices.empty())
10305 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10306 Indices.end(), GEP.getName());
10308 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10309 // GEP of global variable. If all of the indices for this GEP are
10310 // constants, we can promote this to a constexpr instead of an instruction.
10312 // Scan for nonconstants...
10313 SmallVector<Constant*, 8> Indices;
10314 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10315 for (; I != E && isa<Constant>(*I); ++I)
10316 Indices.push_back(cast<Constant>(*I));
10318 if (I == E) { // If they are all constants...
10319 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10320 &Indices[0],Indices.size());
10322 // Replace all uses of the GEP with the new constexpr...
10323 return ReplaceInstUsesWith(GEP, CE);
10325 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
10326 if (!isa<PointerType>(X->getType())) {
10327 // Not interesting. Source pointer must be a cast from pointer.
10328 } else if (HasZeroPointerIndex) {
10329 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10330 // into : GEP [10 x i8]* X, i32 0, ...
10332 // This occurs when the program declares an array extern like "int X[];"
10334 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10335 const PointerType *XTy = cast<PointerType>(X->getType());
10336 if (const ArrayType *XATy =
10337 dyn_cast<ArrayType>(XTy->getElementType()))
10338 if (const ArrayType *CATy =
10339 dyn_cast<ArrayType>(CPTy->getElementType()))
10340 if (CATy->getElementType() == XATy->getElementType()) {
10341 // At this point, we know that the cast source type is a pointer
10342 // to an array of the same type as the destination pointer
10343 // array. Because the array type is never stepped over (there
10344 // is a leading zero) we can fold the cast into this GEP.
10345 GEP.setOperand(0, X);
10348 } else if (GEP.getNumOperands() == 2) {
10349 // Transform things like:
10350 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10351 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10352 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10353 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10354 if (isa<ArrayType>(SrcElTy) &&
10355 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10356 TD->getABITypeSize(ResElTy)) {
10358 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10359 Idx[1] = GEP.getOperand(1);
10360 Value *V = InsertNewInstBefore(
10361 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10362 // V and GEP are both pointer types --> BitCast
10363 return new BitCastInst(V, GEP.getType());
10366 // Transform things like:
10367 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10368 // (where tmp = 8*tmp2) into:
10369 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10371 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
10372 uint64_t ArrayEltSize =
10373 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
10375 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10376 // allow either a mul, shift, or constant here.
10378 ConstantInt *Scale = 0;
10379 if (ArrayEltSize == 1) {
10380 NewIdx = GEP.getOperand(1);
10381 Scale = ConstantInt::get(NewIdx->getType(), 1);
10382 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10383 NewIdx = ConstantInt::get(CI->getType(), 1);
10385 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10386 if (Inst->getOpcode() == Instruction::Shl &&
10387 isa<ConstantInt>(Inst->getOperand(1))) {
10388 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10389 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10390 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10391 NewIdx = Inst->getOperand(0);
10392 } else if (Inst->getOpcode() == Instruction::Mul &&
10393 isa<ConstantInt>(Inst->getOperand(1))) {
10394 Scale = cast<ConstantInt>(Inst->getOperand(1));
10395 NewIdx = Inst->getOperand(0);
10399 // If the index will be to exactly the right offset with the scale taken
10400 // out, perform the transformation. Note, we don't know whether Scale is
10401 // signed or not. We'll use unsigned version of division/modulo
10402 // operation after making sure Scale doesn't have the sign bit set.
10403 if (Scale && Scale->getSExtValue() >= 0LL &&
10404 Scale->getZExtValue() % ArrayEltSize == 0) {
10405 Scale = ConstantInt::get(Scale->getType(),
10406 Scale->getZExtValue() / ArrayEltSize);
10407 if (Scale->getZExtValue() != 1) {
10408 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
10410 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
10411 NewIdx = InsertNewInstBefore(Sc, GEP);
10414 // Insert the new GEP instruction.
10416 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10418 Instruction *NewGEP =
10419 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
10420 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10421 // The NewGEP must be pointer typed, so must the old one -> BitCast
10422 return new BitCastInst(NewGEP, GEP.getType());
10431 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10432 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
10433 if (AI.isArrayAllocation()) { // Check C != 1
10434 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10435 const Type *NewTy =
10436 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10437 AllocationInst *New = 0;
10439 // Create and insert the replacement instruction...
10440 if (isa<MallocInst>(AI))
10441 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10443 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10444 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10447 InsertNewInstBefore(New, AI);
10449 // Scan to the end of the allocation instructions, to skip over a block of
10450 // allocas if possible...
10452 BasicBlock::iterator It = New;
10453 while (isa<AllocationInst>(*It)) ++It;
10455 // Now that I is pointing to the first non-allocation-inst in the block,
10456 // insert our getelementptr instruction...
10458 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
10462 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10463 New->getName()+".sub", It);
10465 // Now make everything use the getelementptr instead of the original
10467 return ReplaceInstUsesWith(AI, V);
10468 } else if (isa<UndefValue>(AI.getArraySize())) {
10469 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10473 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10474 // Note that we only do this for alloca's, because malloc should allocate and
10475 // return a unique pointer, even for a zero byte allocation.
10476 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
10477 TD->getABITypeSize(AI.getAllocatedType()) == 0)
10478 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10483 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10484 Value *Op = FI.getOperand(0);
10486 // free undef -> unreachable.
10487 if (isa<UndefValue>(Op)) {
10488 // Insert a new store to null because we cannot modify the CFG here.
10489 new StoreInst(ConstantInt::getTrue(),
10490 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
10491 return EraseInstFromFunction(FI);
10494 // If we have 'free null' delete the instruction. This can happen in stl code
10495 // when lots of inlining happens.
10496 if (isa<ConstantPointerNull>(Op))
10497 return EraseInstFromFunction(FI);
10499 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10500 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10501 FI.setOperand(0, CI->getOperand(0));
10505 // Change free (gep X, 0,0,0,0) into free(X)
10506 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10507 if (GEPI->hasAllZeroIndices()) {
10508 AddToWorkList(GEPI);
10509 FI.setOperand(0, GEPI->getOperand(0));
10514 // Change free(malloc) into nothing, if the malloc has a single use.
10515 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10516 if (MI->hasOneUse()) {
10517 EraseInstFromFunction(FI);
10518 return EraseInstFromFunction(*MI);
10525 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10526 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10527 const TargetData *TD) {
10528 User *CI = cast<User>(LI.getOperand(0));
10529 Value *CastOp = CI->getOperand(0);
10531 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10532 // Instead of loading constant c string, use corresponding integer value
10533 // directly if string length is small enough.
10534 const std::string &Str = CE->getOperand(0)->getStringValue();
10535 if (!Str.empty()) {
10536 unsigned len = Str.length();
10537 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10538 unsigned numBits = Ty->getPrimitiveSizeInBits();
10539 // Replace LI with immediate integer store.
10540 if ((numBits >> 3) == len + 1) {
10541 APInt StrVal(numBits, 0);
10542 APInt SingleChar(numBits, 0);
10543 if (TD->isLittleEndian()) {
10544 for (signed i = len-1; i >= 0; i--) {
10545 SingleChar = (uint64_t) Str[i];
10546 StrVal = (StrVal << 8) | SingleChar;
10549 for (unsigned i = 0; i < len; i++) {
10550 SingleChar = (uint64_t) Str[i];
10551 StrVal = (StrVal << 8) | SingleChar;
10553 // Append NULL at the end.
10555 StrVal = (StrVal << 8) | SingleChar;
10557 Value *NL = ConstantInt::get(StrVal);
10558 return IC.ReplaceInstUsesWith(LI, NL);
10563 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10564 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10565 const Type *SrcPTy = SrcTy->getElementType();
10567 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
10568 isa<VectorType>(DestPTy)) {
10569 // If the source is an array, the code below will not succeed. Check to
10570 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10572 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10573 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10574 if (ASrcTy->getNumElements() != 0) {
10576 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10577 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10578 SrcTy = cast<PointerType>(CastOp->getType());
10579 SrcPTy = SrcTy->getElementType();
10582 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
10583 isa<VectorType>(SrcPTy)) &&
10584 // Do not allow turning this into a load of an integer, which is then
10585 // casted to a pointer, this pessimizes pointer analysis a lot.
10586 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10587 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10588 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10590 // Okay, we are casting from one integer or pointer type to another of
10591 // the same size. Instead of casting the pointer before the load, cast
10592 // the result of the loaded value.
10593 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10595 LI.isVolatile()),LI);
10596 // Now cast the result of the load.
10597 return new BitCastInst(NewLoad, LI.getType());
10604 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10605 /// from this value cannot trap. If it is not obviously safe to load from the
10606 /// specified pointer, we do a quick local scan of the basic block containing
10607 /// ScanFrom, to determine if the address is already accessed.
10608 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10609 // If it is an alloca it is always safe to load from.
10610 if (isa<AllocaInst>(V)) return true;
10612 // If it is a global variable it is mostly safe to load from.
10613 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10614 // Don't try to evaluate aliases. External weak GV can be null.
10615 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10617 // Otherwise, be a little bit agressive by scanning the local block where we
10618 // want to check to see if the pointer is already being loaded or stored
10619 // from/to. If so, the previous load or store would have already trapped,
10620 // so there is no harm doing an extra load (also, CSE will later eliminate
10621 // the load entirely).
10622 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10627 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10628 if (LI->getOperand(0) == V) return true;
10629 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10630 if (SI->getOperand(1) == V) return true;
10636 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10637 /// until we find the underlying object a pointer is referring to or something
10638 /// we don't understand. Note that the returned pointer may be offset from the
10639 /// input, because we ignore GEP indices.
10640 static Value *GetUnderlyingObject(Value *Ptr) {
10642 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10643 if (CE->getOpcode() == Instruction::BitCast ||
10644 CE->getOpcode() == Instruction::GetElementPtr)
10645 Ptr = CE->getOperand(0);
10648 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10649 Ptr = BCI->getOperand(0);
10650 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10651 Ptr = GEP->getOperand(0);
10658 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10659 Value *Op = LI.getOperand(0);
10661 // Attempt to improve the alignment.
10662 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10664 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10665 LI.getAlignment()))
10666 LI.setAlignment(KnownAlign);
10668 // load (cast X) --> cast (load X) iff safe
10669 if (isa<CastInst>(Op))
10670 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10673 // None of the following transforms are legal for volatile loads.
10674 if (LI.isVolatile()) return 0;
10676 if (&LI.getParent()->front() != &LI) {
10677 BasicBlock::iterator BBI = &LI; --BBI;
10678 // If the instruction immediately before this is a store to the same
10679 // address, do a simple form of store->load forwarding.
10680 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10681 if (SI->getOperand(1) == LI.getOperand(0))
10682 return ReplaceInstUsesWith(LI, SI->getOperand(0));
10683 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10684 if (LIB->getOperand(0) == LI.getOperand(0))
10685 return ReplaceInstUsesWith(LI, LIB);
10688 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10689 const Value *GEPI0 = GEPI->getOperand(0);
10690 // TODO: Consider a target hook for valid address spaces for this xform.
10691 if (isa<ConstantPointerNull>(GEPI0) &&
10692 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10693 // Insert a new store to null instruction before the load to indicate
10694 // that this code is not reachable. We do this instead of inserting
10695 // an unreachable instruction directly because we cannot modify the
10697 new StoreInst(UndefValue::get(LI.getType()),
10698 Constant::getNullValue(Op->getType()), &LI);
10699 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10703 if (Constant *C = dyn_cast<Constant>(Op)) {
10704 // load null/undef -> undef
10705 // TODO: Consider a target hook for valid address spaces for this xform.
10706 if (isa<UndefValue>(C) || (C->isNullValue() &&
10707 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10708 // Insert a new store to null instruction before the load to indicate that
10709 // this code is not reachable. We do this instead of inserting an
10710 // unreachable instruction directly because we cannot modify the CFG.
10711 new StoreInst(UndefValue::get(LI.getType()),
10712 Constant::getNullValue(Op->getType()), &LI);
10713 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10716 // Instcombine load (constant global) into the value loaded.
10717 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10718 if (GV->isConstant() && !GV->isDeclaration())
10719 return ReplaceInstUsesWith(LI, GV->getInitializer());
10721 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10722 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10723 if (CE->getOpcode() == Instruction::GetElementPtr) {
10724 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10725 if (GV->isConstant() && !GV->isDeclaration())
10727 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10728 return ReplaceInstUsesWith(LI, V);
10729 if (CE->getOperand(0)->isNullValue()) {
10730 // Insert a new store to null instruction before the load to indicate
10731 // that this code is not reachable. We do this instead of inserting
10732 // an unreachable instruction directly because we cannot modify the
10734 new StoreInst(UndefValue::get(LI.getType()),
10735 Constant::getNullValue(Op->getType()), &LI);
10736 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10739 } else if (CE->isCast()) {
10740 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10746 // If this load comes from anywhere in a constant global, and if the global
10747 // is all undef or zero, we know what it loads.
10748 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10749 if (GV->isConstant() && GV->hasInitializer()) {
10750 if (GV->getInitializer()->isNullValue())
10751 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10752 else if (isa<UndefValue>(GV->getInitializer()))
10753 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10757 if (Op->hasOneUse()) {
10758 // Change select and PHI nodes to select values instead of addresses: this
10759 // helps alias analysis out a lot, allows many others simplifications, and
10760 // exposes redundancy in the code.
10762 // Note that we cannot do the transformation unless we know that the
10763 // introduced loads cannot trap! Something like this is valid as long as
10764 // the condition is always false: load (select bool %C, int* null, int* %G),
10765 // but it would not be valid if we transformed it to load from null
10766 // unconditionally.
10768 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10769 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
10770 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10771 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10772 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10773 SI->getOperand(1)->getName()+".val"), LI);
10774 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10775 SI->getOperand(2)->getName()+".val"), LI);
10776 return SelectInst::Create(SI->getCondition(), V1, V2);
10779 // load (select (cond, null, P)) -> load P
10780 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10781 if (C->isNullValue()) {
10782 LI.setOperand(0, SI->getOperand(2));
10786 // load (select (cond, P, null)) -> load P
10787 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10788 if (C->isNullValue()) {
10789 LI.setOperand(0, SI->getOperand(1));
10797 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10799 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10800 User *CI = cast<User>(SI.getOperand(1));
10801 Value *CastOp = CI->getOperand(0);
10803 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10804 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10805 const Type *SrcPTy = SrcTy->getElementType();
10807 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10808 // If the source is an array, the code below will not succeed. Check to
10809 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10811 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10812 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10813 if (ASrcTy->getNumElements() != 0) {
10815 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10816 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10817 SrcTy = cast<PointerType>(CastOp->getType());
10818 SrcPTy = SrcTy->getElementType();
10821 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10822 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10823 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10825 // Okay, we are casting from one integer or pointer type to another of
10826 // the same size. Instead of casting the pointer before
10827 // the store, cast the value to be stored.
10829 Value *SIOp0 = SI.getOperand(0);
10830 Instruction::CastOps opcode = Instruction::BitCast;
10831 const Type* CastSrcTy = SIOp0->getType();
10832 const Type* CastDstTy = SrcPTy;
10833 if (isa<PointerType>(CastDstTy)) {
10834 if (CastSrcTy->isInteger())
10835 opcode = Instruction::IntToPtr;
10836 } else if (isa<IntegerType>(CastDstTy)) {
10837 if (isa<PointerType>(SIOp0->getType()))
10838 opcode = Instruction::PtrToInt;
10840 if (Constant *C = dyn_cast<Constant>(SIOp0))
10841 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10843 NewCast = IC.InsertNewInstBefore(
10844 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
10846 return new StoreInst(NewCast, CastOp);
10853 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10854 Value *Val = SI.getOperand(0);
10855 Value *Ptr = SI.getOperand(1);
10857 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
10858 EraseInstFromFunction(SI);
10863 // If the RHS is an alloca with a single use, zapify the store, making the
10865 if (Ptr->hasOneUse() && !SI.isVolatile()) {
10866 if (isa<AllocaInst>(Ptr)) {
10867 EraseInstFromFunction(SI);
10872 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10873 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10874 GEP->getOperand(0)->hasOneUse()) {
10875 EraseInstFromFunction(SI);
10881 // Attempt to improve the alignment.
10882 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10884 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10885 SI.getAlignment()))
10886 SI.setAlignment(KnownAlign);
10888 // Do really simple DSE, to catch cases where there are several consequtive
10889 // stores to the same location, separated by a few arithmetic operations. This
10890 // situation often occurs with bitfield accesses.
10891 BasicBlock::iterator BBI = &SI;
10892 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10896 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10897 // Prev store isn't volatile, and stores to the same location?
10898 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10901 EraseInstFromFunction(*PrevSI);
10907 // If this is a load, we have to stop. However, if the loaded value is from
10908 // the pointer we're loading and is producing the pointer we're storing,
10909 // then *this* store is dead (X = load P; store X -> P).
10910 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10911 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
10912 EraseInstFromFunction(SI);
10916 // Otherwise, this is a load from some other location. Stores before it
10917 // may not be dead.
10921 // Don't skip over loads or things that can modify memory.
10922 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
10927 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
10929 // store X, null -> turns into 'unreachable' in SimplifyCFG
10930 if (isa<ConstantPointerNull>(Ptr)) {
10931 if (!isa<UndefValue>(Val)) {
10932 SI.setOperand(0, UndefValue::get(Val->getType()));
10933 if (Instruction *U = dyn_cast<Instruction>(Val))
10934 AddToWorkList(U); // Dropped a use.
10937 return 0; // Do not modify these!
10940 // store undef, Ptr -> noop
10941 if (isa<UndefValue>(Val)) {
10942 EraseInstFromFunction(SI);
10947 // If the pointer destination is a cast, see if we can fold the cast into the
10949 if (isa<CastInst>(Ptr))
10950 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10952 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10954 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10958 // If this store is the last instruction in the basic block, and if the block
10959 // ends with an unconditional branch, try to move it to the successor block.
10961 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10962 if (BI->isUnconditional())
10963 if (SimplifyStoreAtEndOfBlock(SI))
10964 return 0; // xform done!
10969 /// SimplifyStoreAtEndOfBlock - Turn things like:
10970 /// if () { *P = v1; } else { *P = v2 }
10971 /// into a phi node with a store in the successor.
10973 /// Simplify things like:
10974 /// *P = v1; if () { *P = v2; }
10975 /// into a phi node with a store in the successor.
10977 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10978 BasicBlock *StoreBB = SI.getParent();
10980 // Check to see if the successor block has exactly two incoming edges. If
10981 // so, see if the other predecessor contains a store to the same location.
10982 // if so, insert a PHI node (if needed) and move the stores down.
10983 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10985 // Determine whether Dest has exactly two predecessors and, if so, compute
10986 // the other predecessor.
10987 pred_iterator PI = pred_begin(DestBB);
10988 BasicBlock *OtherBB = 0;
10989 if (*PI != StoreBB)
10992 if (PI == pred_end(DestBB))
10995 if (*PI != StoreBB) {
11000 if (++PI != pred_end(DestBB))
11004 // Verify that the other block ends in a branch and is not otherwise empty.
11005 BasicBlock::iterator BBI = OtherBB->getTerminator();
11006 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11007 if (!OtherBr || BBI == OtherBB->begin())
11010 // If the other block ends in an unconditional branch, check for the 'if then
11011 // else' case. there is an instruction before the branch.
11012 StoreInst *OtherStore = 0;
11013 if (OtherBr->isUnconditional()) {
11014 // If this isn't a store, or isn't a store to the same location, bail out.
11016 OtherStore = dyn_cast<StoreInst>(BBI);
11017 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11020 // Otherwise, the other block ended with a conditional branch. If one of the
11021 // destinations is StoreBB, then we have the if/then case.
11022 if (OtherBr->getSuccessor(0) != StoreBB &&
11023 OtherBr->getSuccessor(1) != StoreBB)
11026 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11027 // if/then triangle. See if there is a store to the same ptr as SI that
11028 // lives in OtherBB.
11030 // Check to see if we find the matching store.
11031 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11032 if (OtherStore->getOperand(1) != SI.getOperand(1))
11036 // If we find something that may be using the stored value, or if we run
11037 // out of instructions, we can't do the xform.
11038 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
11039 BBI == OtherBB->begin())
11043 // In order to eliminate the store in OtherBr, we have to
11044 // make sure nothing reads the stored value in StoreBB.
11045 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11046 // FIXME: This should really be AA driven.
11047 if (isa<LoadInst>(I) || I->mayWriteToMemory())
11052 // Insert a PHI node now if we need it.
11053 Value *MergedVal = OtherStore->getOperand(0);
11054 if (MergedVal != SI.getOperand(0)) {
11055 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11056 PN->reserveOperandSpace(2);
11057 PN->addIncoming(SI.getOperand(0), SI.getParent());
11058 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11059 MergedVal = InsertNewInstBefore(PN, DestBB->front());
11062 // Advance to a place where it is safe to insert the new store and
11064 BBI = DestBB->begin();
11065 while (isa<PHINode>(BBI)) ++BBI;
11066 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11067 OtherStore->isVolatile()), *BBI);
11069 // Nuke the old stores.
11070 EraseInstFromFunction(SI);
11071 EraseInstFromFunction(*OtherStore);
11077 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11078 // Change br (not X), label True, label False to: br X, label False, True
11080 BasicBlock *TrueDest;
11081 BasicBlock *FalseDest;
11082 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11083 !isa<Constant>(X)) {
11084 // Swap Destinations and condition...
11085 BI.setCondition(X);
11086 BI.setSuccessor(0, FalseDest);
11087 BI.setSuccessor(1, TrueDest);
11091 // Cannonicalize fcmp_one -> fcmp_oeq
11092 FCmpInst::Predicate FPred; Value *Y;
11093 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11094 TrueDest, FalseDest)))
11095 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11096 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11097 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11098 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11099 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11100 NewSCC->takeName(I);
11101 // Swap Destinations and condition...
11102 BI.setCondition(NewSCC);
11103 BI.setSuccessor(0, FalseDest);
11104 BI.setSuccessor(1, TrueDest);
11105 RemoveFromWorkList(I);
11106 I->eraseFromParent();
11107 AddToWorkList(NewSCC);
11111 // Cannonicalize icmp_ne -> icmp_eq
11112 ICmpInst::Predicate IPred;
11113 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11114 TrueDest, FalseDest)))
11115 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11116 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11117 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11118 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11119 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11120 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11121 NewSCC->takeName(I);
11122 // Swap Destinations and condition...
11123 BI.setCondition(NewSCC);
11124 BI.setSuccessor(0, FalseDest);
11125 BI.setSuccessor(1, TrueDest);
11126 RemoveFromWorkList(I);
11127 I->eraseFromParent();;
11128 AddToWorkList(NewSCC);
11135 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11136 Value *Cond = SI.getCondition();
11137 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11138 if (I->getOpcode() == Instruction::Add)
11139 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11140 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11141 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11142 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11144 SI.setOperand(0, I->getOperand(0));
11152 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11153 /// is to leave as a vector operation.
11154 static bool CheapToScalarize(Value *V, bool isConstant) {
11155 if (isa<ConstantAggregateZero>(V))
11157 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11158 if (isConstant) return true;
11159 // If all elts are the same, we can extract.
11160 Constant *Op0 = C->getOperand(0);
11161 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11162 if (C->getOperand(i) != Op0)
11166 Instruction *I = dyn_cast<Instruction>(V);
11167 if (!I) return false;
11169 // Insert element gets simplified to the inserted element or is deleted if
11170 // this is constant idx extract element and its a constant idx insertelt.
11171 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11172 isa<ConstantInt>(I->getOperand(2)))
11174 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11176 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11177 if (BO->hasOneUse() &&
11178 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11179 CheapToScalarize(BO->getOperand(1), isConstant)))
11181 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11182 if (CI->hasOneUse() &&
11183 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11184 CheapToScalarize(CI->getOperand(1), isConstant)))
11190 /// Read and decode a shufflevector mask.
11192 /// It turns undef elements into values that are larger than the number of
11193 /// elements in the input.
11194 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11195 unsigned NElts = SVI->getType()->getNumElements();
11196 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11197 return std::vector<unsigned>(NElts, 0);
11198 if (isa<UndefValue>(SVI->getOperand(2)))
11199 return std::vector<unsigned>(NElts, 2*NElts);
11201 std::vector<unsigned> Result;
11202 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
11203 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
11204 if (isa<UndefValue>(CP->getOperand(i)))
11205 Result.push_back(NElts*2); // undef -> 8
11207 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
11211 /// FindScalarElement - Given a vector and an element number, see if the scalar
11212 /// value is already around as a register, for example if it were inserted then
11213 /// extracted from the vector.
11214 static Value *FindScalarElement(Value *V, unsigned EltNo) {
11215 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11216 const VectorType *PTy = cast<VectorType>(V->getType());
11217 unsigned Width = PTy->getNumElements();
11218 if (EltNo >= Width) // Out of range access.
11219 return UndefValue::get(PTy->getElementType());
11221 if (isa<UndefValue>(V))
11222 return UndefValue::get(PTy->getElementType());
11223 else if (isa<ConstantAggregateZero>(V))
11224 return Constant::getNullValue(PTy->getElementType());
11225 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11226 return CP->getOperand(EltNo);
11227 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11228 // If this is an insert to a variable element, we don't know what it is.
11229 if (!isa<ConstantInt>(III->getOperand(2)))
11231 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11233 // If this is an insert to the element we are looking for, return the
11235 if (EltNo == IIElt)
11236 return III->getOperand(1);
11238 // Otherwise, the insertelement doesn't modify the value, recurse on its
11240 return FindScalarElement(III->getOperand(0), EltNo);
11241 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
11242 unsigned InEl = getShuffleMask(SVI)[EltNo];
11244 return FindScalarElement(SVI->getOperand(0), InEl);
11245 else if (InEl < Width*2)
11246 return FindScalarElement(SVI->getOperand(1), InEl - Width);
11248 return UndefValue::get(PTy->getElementType());
11251 // Otherwise, we don't know.
11255 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
11257 // If vector val is undef, replace extract with scalar undef.
11258 if (isa<UndefValue>(EI.getOperand(0)))
11259 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11261 // If vector val is constant 0, replace extract with scalar 0.
11262 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11263 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11265 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
11266 // If vector val is constant with uniform operands, replace EI
11267 // with that operand
11268 Constant *op0 = C->getOperand(0);
11269 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11270 if (C->getOperand(i) != op0) {
11275 return ReplaceInstUsesWith(EI, op0);
11278 // If extracting a specified index from the vector, see if we can recursively
11279 // find a previously computed scalar that was inserted into the vector.
11280 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11281 unsigned IndexVal = IdxC->getZExtValue();
11282 unsigned VectorWidth =
11283 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11285 // If this is extracting an invalid index, turn this into undef, to avoid
11286 // crashing the code below.
11287 if (IndexVal >= VectorWidth)
11288 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11290 // This instruction only demands the single element from the input vector.
11291 // If the input vector has a single use, simplify it based on this use
11293 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11294 uint64_t UndefElts;
11295 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11298 EI.setOperand(0, V);
11303 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11304 return ReplaceInstUsesWith(EI, Elt);
11306 // If the this extractelement is directly using a bitcast from a vector of
11307 // the same number of elements, see if we can find the source element from
11308 // it. In this case, we will end up needing to bitcast the scalars.
11309 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11310 if (const VectorType *VT =
11311 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11312 if (VT->getNumElements() == VectorWidth)
11313 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11314 return new BitCastInst(Elt, EI.getType());
11318 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11319 if (I->hasOneUse()) {
11320 // Push extractelement into predecessor operation if legal and
11321 // profitable to do so
11322 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11323 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11324 if (CheapToScalarize(BO, isConstantElt)) {
11325 ExtractElementInst *newEI0 =
11326 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11327 EI.getName()+".lhs");
11328 ExtractElementInst *newEI1 =
11329 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11330 EI.getName()+".rhs");
11331 InsertNewInstBefore(newEI0, EI);
11332 InsertNewInstBefore(newEI1, EI);
11333 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
11335 } else if (isa<LoadInst>(I)) {
11337 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
11338 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11339 PointerType::get(EI.getType(), AS),EI);
11340 GetElementPtrInst *GEP =
11341 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
11342 InsertNewInstBefore(GEP, EI);
11343 return new LoadInst(GEP);
11346 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11347 // Extracting the inserted element?
11348 if (IE->getOperand(2) == EI.getOperand(1))
11349 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11350 // If the inserted and extracted elements are constants, they must not
11351 // be the same value, extract from the pre-inserted value instead.
11352 if (isa<Constant>(IE->getOperand(2)) &&
11353 isa<Constant>(EI.getOperand(1))) {
11354 AddUsesToWorkList(EI);
11355 EI.setOperand(0, IE->getOperand(0));
11358 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11359 // If this is extracting an element from a shufflevector, figure out where
11360 // it came from and extract from the appropriate input element instead.
11361 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11362 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11364 if (SrcIdx < SVI->getType()->getNumElements())
11365 Src = SVI->getOperand(0);
11366 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
11367 SrcIdx -= SVI->getType()->getNumElements();
11368 Src = SVI->getOperand(1);
11370 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11372 return new ExtractElementInst(Src, SrcIdx);
11379 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11380 /// elements from either LHS or RHS, return the shuffle mask and true.
11381 /// Otherwise, return false.
11382 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11383 std::vector<Constant*> &Mask) {
11384 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11385 "Invalid CollectSingleShuffleElements");
11386 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11388 if (isa<UndefValue>(V)) {
11389 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11391 } else if (V == LHS) {
11392 for (unsigned i = 0; i != NumElts; ++i)
11393 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11395 } else if (V == RHS) {
11396 for (unsigned i = 0; i != NumElts; ++i)
11397 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11399 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11400 // If this is an insert of an extract from some other vector, include it.
11401 Value *VecOp = IEI->getOperand(0);
11402 Value *ScalarOp = IEI->getOperand(1);
11403 Value *IdxOp = IEI->getOperand(2);
11405 if (!isa<ConstantInt>(IdxOp))
11407 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11409 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11410 // Okay, we can handle this if the vector we are insertinting into is
11411 // transitively ok.
11412 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11413 // If so, update the mask to reflect the inserted undef.
11414 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11417 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11418 if (isa<ConstantInt>(EI->getOperand(1)) &&
11419 EI->getOperand(0)->getType() == V->getType()) {
11420 unsigned ExtractedIdx =
11421 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11423 // This must be extracting from either LHS or RHS.
11424 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11425 // Okay, we can handle this if the vector we are insertinting into is
11426 // transitively ok.
11427 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11428 // If so, update the mask to reflect the inserted value.
11429 if (EI->getOperand(0) == LHS) {
11430 Mask[InsertedIdx & (NumElts-1)] =
11431 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11433 assert(EI->getOperand(0) == RHS);
11434 Mask[InsertedIdx & (NumElts-1)] =
11435 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11444 // TODO: Handle shufflevector here!
11449 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11450 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11451 /// that computes V and the LHS value of the shuffle.
11452 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11454 assert(isa<VectorType>(V->getType()) &&
11455 (RHS == 0 || V->getType() == RHS->getType()) &&
11456 "Invalid shuffle!");
11457 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11459 if (isa<UndefValue>(V)) {
11460 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11462 } else if (isa<ConstantAggregateZero>(V)) {
11463 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11465 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11466 // If this is an insert of an extract from some other vector, include it.
11467 Value *VecOp = IEI->getOperand(0);
11468 Value *ScalarOp = IEI->getOperand(1);
11469 Value *IdxOp = IEI->getOperand(2);
11471 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11472 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11473 EI->getOperand(0)->getType() == V->getType()) {
11474 unsigned ExtractedIdx =
11475 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11476 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11478 // Either the extracted from or inserted into vector must be RHSVec,
11479 // otherwise we'd end up with a shuffle of three inputs.
11480 if (EI->getOperand(0) == RHS || RHS == 0) {
11481 RHS = EI->getOperand(0);
11482 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11483 Mask[InsertedIdx & (NumElts-1)] =
11484 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11488 if (VecOp == RHS) {
11489 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11490 // Everything but the extracted element is replaced with the RHS.
11491 for (unsigned i = 0; i != NumElts; ++i) {
11492 if (i != InsertedIdx)
11493 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11498 // If this insertelement is a chain that comes from exactly these two
11499 // vectors, return the vector and the effective shuffle.
11500 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11501 return EI->getOperand(0);
11506 // TODO: Handle shufflevector here!
11508 // Otherwise, can't do anything fancy. Return an identity vector.
11509 for (unsigned i = 0; i != NumElts; ++i)
11510 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11514 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11515 Value *VecOp = IE.getOperand(0);
11516 Value *ScalarOp = IE.getOperand(1);
11517 Value *IdxOp = IE.getOperand(2);
11519 // Inserting an undef or into an undefined place, remove this.
11520 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11521 ReplaceInstUsesWith(IE, VecOp);
11523 // If the inserted element was extracted from some other vector, and if the
11524 // indexes are constant, try to turn this into a shufflevector operation.
11525 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11526 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11527 EI->getOperand(0)->getType() == IE.getType()) {
11528 unsigned NumVectorElts = IE.getType()->getNumElements();
11529 unsigned ExtractedIdx =
11530 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11531 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11533 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11534 return ReplaceInstUsesWith(IE, VecOp);
11536 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11537 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11539 // If we are extracting a value from a vector, then inserting it right
11540 // back into the same place, just use the input vector.
11541 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11542 return ReplaceInstUsesWith(IE, VecOp);
11544 // We could theoretically do this for ANY input. However, doing so could
11545 // turn chains of insertelement instructions into a chain of shufflevector
11546 // instructions, and right now we do not merge shufflevectors. As such,
11547 // only do this in a situation where it is clear that there is benefit.
11548 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11549 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11550 // the values of VecOp, except then one read from EIOp0.
11551 // Build a new shuffle mask.
11552 std::vector<Constant*> Mask;
11553 if (isa<UndefValue>(VecOp))
11554 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11556 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11557 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11560 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11561 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11562 ConstantVector::get(Mask));
11565 // If this insertelement isn't used by some other insertelement, turn it
11566 // (and any insertelements it points to), into one big shuffle.
11567 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11568 std::vector<Constant*> Mask;
11570 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11571 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11572 // We now have a shuffle of LHS, RHS, Mask.
11573 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11582 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11583 Value *LHS = SVI.getOperand(0);
11584 Value *RHS = SVI.getOperand(1);
11585 std::vector<unsigned> Mask = getShuffleMask(&SVI);
11587 bool MadeChange = false;
11589 // Undefined shuffle mask -> undefined value.
11590 if (isa<UndefValue>(SVI.getOperand(2)))
11591 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11593 // If we have shuffle(x, undef, mask) and any elements of mask refer to
11594 // the undef, change them to undefs.
11595 if (isa<UndefValue>(SVI.getOperand(1))) {
11596 // Scan to see if there are any references to the RHS. If so, replace them
11597 // with undef element refs and set MadeChange to true.
11598 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11599 if (Mask[i] >= e && Mask[i] != 2*e) {
11606 // Remap any references to RHS to use LHS.
11607 std::vector<Constant*> Elts;
11608 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11609 if (Mask[i] == 2*e)
11610 Elts.push_back(UndefValue::get(Type::Int32Ty));
11612 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11614 SVI.setOperand(2, ConstantVector::get(Elts));
11618 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11619 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11620 if (LHS == RHS || isa<UndefValue>(LHS)) {
11621 if (isa<UndefValue>(LHS) && LHS == RHS) {
11622 // shuffle(undef,undef,mask) -> undef.
11623 return ReplaceInstUsesWith(SVI, LHS);
11626 // Remap any references to RHS to use LHS.
11627 std::vector<Constant*> Elts;
11628 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11629 if (Mask[i] >= 2*e)
11630 Elts.push_back(UndefValue::get(Type::Int32Ty));
11632 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11633 (Mask[i] < e && isa<UndefValue>(LHS)))
11634 Mask[i] = 2*e; // Turn into undef.
11636 Mask[i] &= (e-1); // Force to LHS.
11637 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11640 SVI.setOperand(0, SVI.getOperand(1));
11641 SVI.setOperand(1, UndefValue::get(RHS->getType()));
11642 SVI.setOperand(2, ConstantVector::get(Elts));
11643 LHS = SVI.getOperand(0);
11644 RHS = SVI.getOperand(1);
11648 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11649 bool isLHSID = true, isRHSID = true;
11651 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11652 if (Mask[i] >= e*2) continue; // Ignore undef values.
11653 // Is this an identity shuffle of the LHS value?
11654 isLHSID &= (Mask[i] == i);
11656 // Is this an identity shuffle of the RHS value?
11657 isRHSID &= (Mask[i]-e == i);
11660 // Eliminate identity shuffles.
11661 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11662 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11664 // If the LHS is a shufflevector itself, see if we can combine it with this
11665 // one without producing an unusual shuffle. Here we are really conservative:
11666 // we are absolutely afraid of producing a shuffle mask not in the input
11667 // program, because the code gen may not be smart enough to turn a merged
11668 // shuffle into two specific shuffles: it may produce worse code. As such,
11669 // we only merge two shuffles if the result is one of the two input shuffle
11670 // masks. In this case, merging the shuffles just removes one instruction,
11671 // which we know is safe. This is good for things like turning:
11672 // (splat(splat)) -> splat.
11673 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11674 if (isa<UndefValue>(RHS)) {
11675 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11677 std::vector<unsigned> NewMask;
11678 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11679 if (Mask[i] >= 2*e)
11680 NewMask.push_back(2*e);
11682 NewMask.push_back(LHSMask[Mask[i]]);
11684 // If the result mask is equal to the src shuffle or this shuffle mask, do
11685 // the replacement.
11686 if (NewMask == LHSMask || NewMask == Mask) {
11687 std::vector<Constant*> Elts;
11688 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11689 if (NewMask[i] >= e*2) {
11690 Elts.push_back(UndefValue::get(Type::Int32Ty));
11692 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11695 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11696 LHSSVI->getOperand(1),
11697 ConstantVector::get(Elts));
11702 return MadeChange ? &SVI : 0;
11708 /// TryToSinkInstruction - Try to move the specified instruction from its
11709 /// current block into the beginning of DestBlock, which can only happen if it's
11710 /// safe to move the instruction past all of the instructions between it and the
11711 /// end of its block.
11712 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11713 assert(I->hasOneUse() && "Invariants didn't hold!");
11715 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11716 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11719 // Do not sink alloca instructions out of the entry block.
11720 if (isa<AllocaInst>(I) && I->getParent() ==
11721 &DestBlock->getParent()->getEntryBlock())
11724 // We can only sink load instructions if there is nothing between the load and
11725 // the end of block that could change the value.
11726 if (I->mayReadFromMemory()) {
11727 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
11729 if (Scan->mayWriteToMemory())
11733 BasicBlock::iterator InsertPos = DestBlock->begin();
11734 while (isa<PHINode>(InsertPos)) ++InsertPos;
11736 I->moveBefore(InsertPos);
11742 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11743 /// all reachable code to the worklist.
11745 /// This has a couple of tricks to make the code faster and more powerful. In
11746 /// particular, we constant fold and DCE instructions as we go, to avoid adding
11747 /// them to the worklist (this significantly speeds up instcombine on code where
11748 /// many instructions are dead or constant). Additionally, if we find a branch
11749 /// whose condition is a known constant, we only visit the reachable successors.
11751 static void AddReachableCodeToWorklist(BasicBlock *BB,
11752 SmallPtrSet<BasicBlock*, 64> &Visited,
11754 const TargetData *TD) {
11755 std::vector<BasicBlock*> Worklist;
11756 Worklist.push_back(BB);
11758 while (!Worklist.empty()) {
11759 BB = Worklist.back();
11760 Worklist.pop_back();
11762 // We have now visited this block! If we've already been here, ignore it.
11763 if (!Visited.insert(BB)) continue;
11765 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11766 Instruction *Inst = BBI++;
11768 // DCE instruction if trivially dead.
11769 if (isInstructionTriviallyDead(Inst)) {
11771 DOUT << "IC: DCE: " << *Inst;
11772 Inst->eraseFromParent();
11776 // ConstantProp instruction if trivially constant.
11777 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11778 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11779 Inst->replaceAllUsesWith(C);
11781 Inst->eraseFromParent();
11785 IC.AddToWorkList(Inst);
11788 // Recursively visit successors. If this is a branch or switch on a
11789 // constant, only visit the reachable successor.
11790 TerminatorInst *TI = BB->getTerminator();
11791 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11792 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11793 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
11794 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11795 Worklist.push_back(ReachableBB);
11798 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11799 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11800 // See if this is an explicit destination.
11801 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11802 if (SI->getCaseValue(i) == Cond) {
11803 BasicBlock *ReachableBB = SI->getSuccessor(i);
11804 Worklist.push_back(ReachableBB);
11808 // Otherwise it is the default destination.
11809 Worklist.push_back(SI->getSuccessor(0));
11814 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11815 Worklist.push_back(TI->getSuccessor(i));
11819 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11820 bool Changed = false;
11821 TD = &getAnalysis<TargetData>();
11823 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11824 << F.getNameStr() << "\n");
11827 // Do a depth-first traversal of the function, populate the worklist with
11828 // the reachable instructions. Ignore blocks that are not reachable. Keep
11829 // track of which blocks we visit.
11830 SmallPtrSet<BasicBlock*, 64> Visited;
11831 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11833 // Do a quick scan over the function. If we find any blocks that are
11834 // unreachable, remove any instructions inside of them. This prevents
11835 // the instcombine code from having to deal with some bad special cases.
11836 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11837 if (!Visited.count(BB)) {
11838 Instruction *Term = BB->getTerminator();
11839 while (Term != BB->begin()) { // Remove instrs bottom-up
11840 BasicBlock::iterator I = Term; --I;
11842 DOUT << "IC: DCE: " << *I;
11845 if (!I->use_empty())
11846 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11847 I->eraseFromParent();
11852 while (!Worklist.empty()) {
11853 Instruction *I = RemoveOneFromWorkList();
11854 if (I == 0) continue; // skip null values.
11856 // Check to see if we can DCE the instruction.
11857 if (isInstructionTriviallyDead(I)) {
11858 // Add operands to the worklist.
11859 if (I->getNumOperands() < 4)
11860 AddUsesToWorkList(*I);
11863 DOUT << "IC: DCE: " << *I;
11865 I->eraseFromParent();
11866 RemoveFromWorkList(I);
11870 // Instruction isn't dead, see if we can constant propagate it.
11871 if (Constant *C = ConstantFoldInstruction(I, TD)) {
11872 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11874 // Add operands to the worklist.
11875 AddUsesToWorkList(*I);
11876 ReplaceInstUsesWith(*I, C);
11879 I->eraseFromParent();
11880 RemoveFromWorkList(I);
11884 // See if we can trivially sink this instruction to a successor basic block.
11885 // FIXME: Remove GetResultInst test when first class support for aggregates
11887 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
11888 BasicBlock *BB = I->getParent();
11889 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11890 if (UserParent != BB) {
11891 bool UserIsSuccessor = false;
11892 // See if the user is one of our successors.
11893 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11894 if (*SI == UserParent) {
11895 UserIsSuccessor = true;
11899 // If the user is one of our immediate successors, and if that successor
11900 // only has us as a predecessors (we'd have to split the critical edge
11901 // otherwise), we can keep going.
11902 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11903 next(pred_begin(UserParent)) == pred_end(UserParent))
11904 // Okay, the CFG is simple enough, try to sink this instruction.
11905 Changed |= TryToSinkInstruction(I, UserParent);
11909 // Now that we have an instruction, try combining it to simplify it...
11913 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11914 if (Instruction *Result = visit(*I)) {
11916 // Should we replace the old instruction with a new one?
11918 DOUT << "IC: Old = " << *I
11919 << " New = " << *Result;
11921 // Everything uses the new instruction now.
11922 I->replaceAllUsesWith(Result);
11924 // Push the new instruction and any users onto the worklist.
11925 AddToWorkList(Result);
11926 AddUsersToWorkList(*Result);
11928 // Move the name to the new instruction first.
11929 Result->takeName(I);
11931 // Insert the new instruction into the basic block...
11932 BasicBlock *InstParent = I->getParent();
11933 BasicBlock::iterator InsertPos = I;
11935 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11936 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11939 InstParent->getInstList().insert(InsertPos, Result);
11941 // Make sure that we reprocess all operands now that we reduced their
11943 AddUsesToWorkList(*I);
11945 // Instructions can end up on the worklist more than once. Make sure
11946 // we do not process an instruction that has been deleted.
11947 RemoveFromWorkList(I);
11949 // Erase the old instruction.
11950 InstParent->getInstList().erase(I);
11953 DOUT << "IC: Mod = " << OrigI
11954 << " New = " << *I;
11957 // If the instruction was modified, it's possible that it is now dead.
11958 // if so, remove it.
11959 if (isInstructionTriviallyDead(I)) {
11960 // Make sure we process all operands now that we are reducing their
11962 AddUsesToWorkList(*I);
11964 // Instructions may end up in the worklist more than once. Erase all
11965 // occurrences of this instruction.
11966 RemoveFromWorkList(I);
11967 I->eraseFromParent();
11970 AddUsersToWorkList(*I);
11977 assert(WorklistMap.empty() && "Worklist empty, but map not?");
11979 // Do an explicit clear, this shrinks the map if needed.
11980 WorklistMap.clear();
11985 bool InstCombiner::runOnFunction(Function &F) {
11986 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11988 bool EverMadeChange = false;
11990 // Iterate while there is work to do.
11991 unsigned Iteration = 0;
11992 while (DoOneIteration(F, Iteration++))
11993 EverMadeChange = true;
11994 return EverMadeChange;
11997 FunctionPass *llvm::createInstructionCombiningPass() {
11998 return new InstCombiner();