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 algebraic
12 // simplification happens.
14 // This pass combines things like:
20 // This is a simple worklist driven algorithm.
22 // This pass guarantees that the following canonicalizations are performed on
24 // 1. If a binary operator has a constant operand, it is moved to the RHS
25 // 2. Bitwise operators with constant operands are always grouped so that
26 // shifts are performed first, then or's, then and's, then xor's.
27 // 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All cmp instructions on boolean values are replaced with logical ops
29 // 5. add X, X is represented as (X*2) => (X << 1)
30 // 6. Multiplies with a power-of-two constant argument are transformed into
34 //===----------------------------------------------------------------------===//
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Analysis/ConstantFolding.h"
43 #include "llvm/Target/TargetData.h"
44 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
45 #include "llvm/Transforms/Utils/Local.h"
46 #include "llvm/Support/CallSite.h"
47 #include "llvm/Support/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"
62 using namespace llvm::PatternMatch;
64 STATISTIC(NumCombined , "Number of insts combined");
65 STATISTIC(NumConstProp, "Number of constant folds");
66 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
67 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
68 STATISTIC(NumSunkInst , "Number of instructions sunk");
71 class VISIBILITY_HIDDEN InstCombiner
72 : public FunctionPass,
73 public InstVisitor<InstCombiner, Instruction*> {
74 // Worklist of all of the instructions that need to be simplified.
75 std::vector<Instruction*> Worklist;
76 DenseMap<Instruction*, unsigned> WorklistMap;
78 bool MustPreserveLCSSA;
80 static char ID; // Pass identification, replacement for typeid
81 InstCombiner() : FunctionPass((intptr_t)&ID) {}
83 /// AddToWorkList - Add the specified instruction to the worklist if it
84 /// isn't already in it.
85 void AddToWorkList(Instruction *I) {
86 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
87 Worklist.push_back(I);
90 // RemoveFromWorkList - remove I from the worklist if it exists.
91 void RemoveFromWorkList(Instruction *I) {
92 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
93 if (It == WorklistMap.end()) return; // Not in worklist.
95 // Don't bother moving everything down, just null out the slot.
96 Worklist[It->second] = 0;
98 WorklistMap.erase(It);
101 Instruction *RemoveOneFromWorkList() {
102 Instruction *I = Worklist.back();
104 WorklistMap.erase(I);
109 /// AddUsersToWorkList - When an instruction is simplified, add all users of
110 /// the instruction to the work lists because they might get more simplified
113 void AddUsersToWorkList(Value &I) {
114 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
116 AddToWorkList(cast<Instruction>(*UI));
119 /// AddUsesToWorkList - When an instruction is simplified, add operands to
120 /// the work lists because they might get more simplified now.
122 void AddUsesToWorkList(Instruction &I) {
123 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
124 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
128 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
129 /// dead. Add all of its operands to the worklist, turning them into
130 /// undef's to reduce the number of uses of those instructions.
132 /// Return the specified operand before it is turned into an undef.
134 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
135 Value *R = I.getOperand(op);
137 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
138 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
140 // Set the operand to undef to drop the use.
141 I.setOperand(i, UndefValue::get(Op->getType()));
148 virtual bool runOnFunction(Function &F);
150 bool DoOneIteration(Function &F, unsigned ItNum);
152 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
153 AU.addRequired<TargetData>();
154 AU.addPreservedID(LCSSAID);
155 AU.setPreservesCFG();
158 TargetData &getTargetData() const { return *TD; }
160 // Visitation implementation - Implement instruction combining for different
161 // instruction types. The semantics are as follows:
163 // null - No change was made
164 // I - Change was made, I is still valid, I may be dead though
165 // otherwise - Change was made, replace I with returned instruction
167 Instruction *visitAdd(BinaryOperator &I);
168 Instruction *visitSub(BinaryOperator &I);
169 Instruction *visitMul(BinaryOperator &I);
170 Instruction *visitURem(BinaryOperator &I);
171 Instruction *visitSRem(BinaryOperator &I);
172 Instruction *visitFRem(BinaryOperator &I);
173 Instruction *commonRemTransforms(BinaryOperator &I);
174 Instruction *commonIRemTransforms(BinaryOperator &I);
175 Instruction *commonDivTransforms(BinaryOperator &I);
176 Instruction *commonIDivTransforms(BinaryOperator &I);
177 Instruction *visitUDiv(BinaryOperator &I);
178 Instruction *visitSDiv(BinaryOperator &I);
179 Instruction *visitFDiv(BinaryOperator &I);
180 Instruction *visitAnd(BinaryOperator &I);
181 Instruction *visitOr (BinaryOperator &I);
182 Instruction *visitXor(BinaryOperator &I);
183 Instruction *visitShl(BinaryOperator &I);
184 Instruction *visitAShr(BinaryOperator &I);
185 Instruction *visitLShr(BinaryOperator &I);
186 Instruction *commonShiftTransforms(BinaryOperator &I);
187 Instruction *visitFCmpInst(FCmpInst &I);
188 Instruction *visitICmpInst(ICmpInst &I);
189 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
190 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
193 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
194 ConstantInt *DivRHS);
196 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
197 ICmpInst::Predicate Cond, Instruction &I);
198 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
200 Instruction *commonCastTransforms(CastInst &CI);
201 Instruction *commonIntCastTransforms(CastInst &CI);
202 Instruction *commonPointerCastTransforms(CastInst &CI);
203 Instruction *visitTrunc(TruncInst &CI);
204 Instruction *visitZExt(ZExtInst &CI);
205 Instruction *visitSExt(SExtInst &CI);
206 Instruction *visitFPTrunc(FPTruncInst &CI);
207 Instruction *visitFPExt(CastInst &CI);
208 Instruction *visitFPToUI(CastInst &CI);
209 Instruction *visitFPToSI(CastInst &CI);
210 Instruction *visitUIToFP(CastInst &CI);
211 Instruction *visitSIToFP(CastInst &CI);
212 Instruction *visitPtrToInt(CastInst &CI);
213 Instruction *visitIntToPtr(IntToPtrInst &CI);
214 Instruction *visitBitCast(BitCastInst &CI);
215 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
217 Instruction *visitSelectInst(SelectInst &CI);
218 Instruction *visitCallInst(CallInst &CI);
219 Instruction *visitInvokeInst(InvokeInst &II);
220 Instruction *visitPHINode(PHINode &PN);
221 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
222 Instruction *visitAllocationInst(AllocationInst &AI);
223 Instruction *visitFreeInst(FreeInst &FI);
224 Instruction *visitLoadInst(LoadInst &LI);
225 Instruction *visitStoreInst(StoreInst &SI);
226 Instruction *visitBranchInst(BranchInst &BI);
227 Instruction *visitSwitchInst(SwitchInst &SI);
228 Instruction *visitInsertElementInst(InsertElementInst &IE);
229 Instruction *visitExtractElementInst(ExtractElementInst &EI);
230 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
232 // visitInstruction - Specify what to return for unhandled instructions...
233 Instruction *visitInstruction(Instruction &I) { return 0; }
236 Instruction *visitCallSite(CallSite CS);
237 bool transformConstExprCastCall(CallSite CS);
238 Instruction *transformCallThroughTrampoline(CallSite CS);
239 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
240 bool DoXform = true);
243 // InsertNewInstBefore - insert an instruction New before instruction Old
244 // in the program. Add the new instruction to the worklist.
246 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
247 assert(New && New->getParent() == 0 &&
248 "New instruction already inserted into a basic block!");
249 BasicBlock *BB = Old.getParent();
250 BB->getInstList().insert(&Old, New); // Insert inst
255 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
256 /// This also adds the cast to the worklist. Finally, this returns the
258 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
260 if (V->getType() == Ty) return V;
262 if (Constant *CV = dyn_cast<Constant>(V))
263 return ConstantExpr::getCast(opc, CV, Ty);
265 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
270 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
271 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
275 // ReplaceInstUsesWith - This method is to be used when an instruction is
276 // found to be dead, replacable with another preexisting expression. Here
277 // we add all uses of I to the worklist, replace all uses of I with the new
278 // value, then return I, so that the inst combiner will know that I was
281 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
282 AddUsersToWorkList(I); // Add all modified instrs to worklist
284 I.replaceAllUsesWith(V);
287 // If we are replacing the instruction with itself, this must be in a
288 // segment of unreachable code, so just clobber the instruction.
289 I.replaceAllUsesWith(UndefValue::get(I.getType()));
294 // UpdateValueUsesWith - This method is to be used when an value is
295 // found to be replacable with another preexisting expression or was
296 // updated. Here we add all uses of I to the worklist, replace all uses of
297 // I with the new value (unless the instruction was just updated), then
298 // return true, so that the inst combiner will know that I was modified.
300 bool UpdateValueUsesWith(Value *Old, Value *New) {
301 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
303 Old->replaceAllUsesWith(New);
304 if (Instruction *I = dyn_cast<Instruction>(Old))
306 if (Instruction *I = dyn_cast<Instruction>(New))
311 // EraseInstFromFunction - When dealing with an instruction that has side
312 // effects or produces a void value, we can't rely on DCE to delete the
313 // instruction. Instead, visit methods should return the value returned by
315 Instruction *EraseInstFromFunction(Instruction &I) {
316 assert(I.use_empty() && "Cannot erase instruction that is used!");
317 AddUsesToWorkList(I);
318 RemoveFromWorkList(&I);
320 return 0; // Don't do anything with FI
324 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
325 /// InsertBefore instruction. This is specialized a bit to avoid inserting
326 /// casts that are known to not do anything...
328 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
329 Value *V, const Type *DestTy,
330 Instruction *InsertBefore);
332 /// SimplifyCommutative - This performs a few simplifications for
333 /// commutative operators.
334 bool SimplifyCommutative(BinaryOperator &I);
336 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
337 /// most-complex to least-complex order.
338 bool SimplifyCompare(CmpInst &I);
340 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
341 /// on the demanded bits.
342 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
343 APInt& KnownZero, APInt& KnownOne,
346 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
347 uint64_t &UndefElts, unsigned Depth = 0);
349 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
350 // PHI node as operand #0, see if we can fold the instruction into the PHI
351 // (which is only possible if all operands to the PHI are constants).
352 Instruction *FoldOpIntoPhi(Instruction &I);
354 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
355 // operator and they all are only used by the PHI, PHI together their
356 // inputs, and do the operation once, to the result of the PHI.
357 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
358 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
361 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
362 ConstantInt *AndRHS, BinaryOperator &TheAnd);
364 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
365 bool isSub, Instruction &I);
366 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
367 bool isSigned, bool Inside, Instruction &IB);
368 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
369 Instruction *MatchBSwap(BinaryOperator &I);
370 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
371 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
374 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
377 char InstCombiner::ID = 0;
378 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
381 // getComplexity: Assign a complexity or rank value to LLVM Values...
382 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
383 static unsigned getComplexity(Value *V) {
384 if (isa<Instruction>(V)) {
385 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
389 if (isa<Argument>(V)) return 3;
390 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
393 // isOnlyUse - Return true if this instruction will be deleted if we stop using
395 static bool isOnlyUse(Value *V) {
396 return V->hasOneUse() || isa<Constant>(V);
399 // getPromotedType - Return the specified type promoted as it would be to pass
400 // though a va_arg area...
401 static const Type *getPromotedType(const Type *Ty) {
402 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
403 if (ITy->getBitWidth() < 32)
404 return Type::Int32Ty;
409 /// getBitCastOperand - If the specified operand is a CastInst or a constant
410 /// expression bitcast, return the operand value, otherwise return null.
411 static Value *getBitCastOperand(Value *V) {
412 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
413 return I->getOperand(0);
414 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
415 if (CE->getOpcode() == Instruction::BitCast)
416 return CE->getOperand(0);
420 /// This function is a wrapper around CastInst::isEliminableCastPair. It
421 /// simply extracts arguments and returns what that function returns.
422 static Instruction::CastOps
423 isEliminableCastPair(
424 const CastInst *CI, ///< The first cast instruction
425 unsigned opcode, ///< The opcode of the second cast instruction
426 const Type *DstTy, ///< The target type for the second cast instruction
427 TargetData *TD ///< The target data for pointer size
430 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
431 const Type *MidTy = CI->getType(); // B from above
433 // Get the opcodes of the two Cast instructions
434 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
435 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
437 return Instruction::CastOps(
438 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
439 DstTy, TD->getIntPtrType()));
442 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
443 /// in any code being generated. It does not require codegen if V is simple
444 /// enough or if the cast can be folded into other casts.
445 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
446 const Type *Ty, TargetData *TD) {
447 if (V->getType() == Ty || isa<Constant>(V)) return false;
449 // If this is another cast that can be eliminated, it isn't codegen either.
450 if (const CastInst *CI = dyn_cast<CastInst>(V))
451 if (isEliminableCastPair(CI, opcode, Ty, TD))
456 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
457 /// InsertBefore instruction. This is specialized a bit to avoid inserting
458 /// casts that are known to not do anything...
460 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
461 Value *V, const Type *DestTy,
462 Instruction *InsertBefore) {
463 if (V->getType() == DestTy) return V;
464 if (Constant *C = dyn_cast<Constant>(V))
465 return ConstantExpr::getCast(opcode, C, DestTy);
467 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
470 // SimplifyCommutative - This performs a few simplifications for commutative
473 // 1. Order operands such that they are listed from right (least complex) to
474 // left (most complex). This puts constants before unary operators before
477 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
478 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
480 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
481 bool Changed = false;
482 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
483 Changed = !I.swapOperands();
485 if (!I.isAssociative()) return Changed;
486 Instruction::BinaryOps Opcode = I.getOpcode();
487 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
488 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
489 if (isa<Constant>(I.getOperand(1))) {
490 Constant *Folded = ConstantExpr::get(I.getOpcode(),
491 cast<Constant>(I.getOperand(1)),
492 cast<Constant>(Op->getOperand(1)));
493 I.setOperand(0, Op->getOperand(0));
494 I.setOperand(1, Folded);
496 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
497 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
498 isOnlyUse(Op) && isOnlyUse(Op1)) {
499 Constant *C1 = cast<Constant>(Op->getOperand(1));
500 Constant *C2 = cast<Constant>(Op1->getOperand(1));
502 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
503 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
504 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
508 I.setOperand(0, New);
509 I.setOperand(1, Folded);
516 /// SimplifyCompare - For a CmpInst this function just orders the operands
517 /// so that theyare listed from right (least complex) to left (most complex).
518 /// This puts constants before unary operators before binary operators.
519 bool InstCombiner::SimplifyCompare(CmpInst &I) {
520 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
523 // Compare instructions are not associative so there's nothing else we can do.
527 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
528 // if the LHS is a constant zero (which is the 'negate' form).
530 static inline Value *dyn_castNegVal(Value *V) {
531 if (BinaryOperator::isNeg(V))
532 return BinaryOperator::getNegArgument(V);
534 // Constants can be considered to be negated values if they can be folded.
535 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
536 return ConstantExpr::getNeg(C);
540 static inline Value *dyn_castNotVal(Value *V) {
541 if (BinaryOperator::isNot(V))
542 return BinaryOperator::getNotArgument(V);
544 // Constants can be considered to be not'ed values...
545 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
546 return ConstantInt::get(~C->getValue());
550 // dyn_castFoldableMul - If this value is a multiply that can be folded into
551 // other computations (because it has a constant operand), return the
552 // non-constant operand of the multiply, and set CST to point to the multiplier.
553 // Otherwise, return null.
555 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
556 if (V->hasOneUse() && V->getType()->isInteger())
557 if (Instruction *I = dyn_cast<Instruction>(V)) {
558 if (I->getOpcode() == Instruction::Mul)
559 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
560 return I->getOperand(0);
561 if (I->getOpcode() == Instruction::Shl)
562 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
563 // The multiplier is really 1 << CST.
564 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
565 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
566 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
567 return I->getOperand(0);
573 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
574 /// expression, return it.
575 static User *dyn_castGetElementPtr(Value *V) {
576 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
577 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
578 if (CE->getOpcode() == Instruction::GetElementPtr)
579 return cast<User>(V);
583 /// AddOne - Add one to a ConstantInt
584 static ConstantInt *AddOne(ConstantInt *C) {
585 APInt Val(C->getValue());
586 return ConstantInt::get(++Val);
588 /// SubOne - Subtract one from a ConstantInt
589 static ConstantInt *SubOne(ConstantInt *C) {
590 APInt Val(C->getValue());
591 return ConstantInt::get(--Val);
593 /// Add - Add two ConstantInts together
594 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
595 return ConstantInt::get(C1->getValue() + C2->getValue());
597 /// And - Bitwise AND two ConstantInts together
598 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
599 return ConstantInt::get(C1->getValue() & C2->getValue());
601 /// Subtract - Subtract one ConstantInt from another
602 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
603 return ConstantInt::get(C1->getValue() - C2->getValue());
605 /// Multiply - Multiply two ConstantInts together
606 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
607 return ConstantInt::get(C1->getValue() * C2->getValue());
609 /// MultiplyOverflows - True if the multiply can not be expressed in an int
611 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
612 uint32_t W = C1->getBitWidth();
613 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
622 APInt MulExt = LHSExt * RHSExt;
625 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
626 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
627 return MulExt.slt(Min) || MulExt.sgt(Max);
629 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
632 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
633 /// known to be either zero or one and return them in the KnownZero/KnownOne
634 /// bit sets. This code only analyzes bits in Mask, in order to short-circuit
636 /// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
637 /// we cannot optimize based on the assumption that it is zero without changing
638 /// it to be an explicit zero. If we don't change it to zero, other code could
639 /// optimized based on the contradictory assumption that it is non-zero.
640 /// Because instcombine aggressively folds operations with undef args anyway,
641 /// this won't lose us code quality.
642 static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
643 APInt& KnownOne, unsigned Depth = 0) {
644 assert(V && "No Value?");
645 assert(Depth <= 6 && "Limit Search Depth");
646 uint32_t BitWidth = Mask.getBitWidth();
647 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
648 KnownZero.getBitWidth() == BitWidth &&
649 KnownOne.getBitWidth() == BitWidth &&
650 "V, Mask, KnownOne and KnownZero should have same BitWidth");
651 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
652 // We know all of the bits for a constant!
653 KnownOne = CI->getValue() & Mask;
654 KnownZero = ~KnownOne & Mask;
658 if (Depth == 6 || Mask == 0)
659 return; // Limit search depth.
661 Instruction *I = dyn_cast<Instruction>(V);
664 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
665 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
667 switch (I->getOpcode()) {
668 case Instruction::And: {
669 // If either the LHS or the RHS are Zero, the result is zero.
670 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
671 APInt Mask2(Mask & ~KnownZero);
672 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
673 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
674 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
676 // Output known-1 bits are only known if set in both the LHS & RHS.
677 KnownOne &= KnownOne2;
678 // Output known-0 are known to be clear if zero in either the LHS | RHS.
679 KnownZero |= KnownZero2;
682 case Instruction::Or: {
683 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
684 APInt Mask2(Mask & ~KnownOne);
685 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
686 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
687 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
689 // Output known-0 bits are only known if clear in both the LHS & RHS.
690 KnownZero &= KnownZero2;
691 // Output known-1 are known to be set if set in either the LHS | RHS.
692 KnownOne |= KnownOne2;
695 case Instruction::Xor: {
696 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
697 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
698 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
699 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
701 // Output known-0 bits are known if clear or set in both the LHS & RHS.
702 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
703 // Output known-1 are known to be set if set in only one of the LHS, RHS.
704 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
705 KnownZero = KnownZeroOut;
708 case Instruction::Select:
709 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
710 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
711 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
712 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
714 // Only known if known in both the LHS and RHS.
715 KnownOne &= KnownOne2;
716 KnownZero &= KnownZero2;
718 case Instruction::FPTrunc:
719 case Instruction::FPExt:
720 case Instruction::FPToUI:
721 case Instruction::FPToSI:
722 case Instruction::SIToFP:
723 case Instruction::PtrToInt:
724 case Instruction::UIToFP:
725 case Instruction::IntToPtr:
726 return; // Can't work with floating point or pointers
727 case Instruction::Trunc: {
728 // All these have integer operands
729 uint32_t SrcBitWidth =
730 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
732 MaskIn.zext(SrcBitWidth);
733 KnownZero.zext(SrcBitWidth);
734 KnownOne.zext(SrcBitWidth);
735 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
736 KnownZero.trunc(BitWidth);
737 KnownOne.trunc(BitWidth);
740 case Instruction::BitCast: {
741 const Type *SrcTy = I->getOperand(0)->getType();
742 if (SrcTy->isInteger()) {
743 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
748 case Instruction::ZExt: {
749 // Compute the bits in the result that are not present in the input.
750 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
751 uint32_t SrcBitWidth = SrcTy->getBitWidth();
754 MaskIn.trunc(SrcBitWidth);
755 KnownZero.trunc(SrcBitWidth);
756 KnownOne.trunc(SrcBitWidth);
757 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
758 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
759 // The top bits are known to be zero.
760 KnownZero.zext(BitWidth);
761 KnownOne.zext(BitWidth);
762 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
765 case Instruction::SExt: {
766 // Compute the bits in the result that are not present in the input.
767 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
768 uint32_t SrcBitWidth = SrcTy->getBitWidth();
771 MaskIn.trunc(SrcBitWidth);
772 KnownZero.trunc(SrcBitWidth);
773 KnownOne.trunc(SrcBitWidth);
774 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
775 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
776 KnownZero.zext(BitWidth);
777 KnownOne.zext(BitWidth);
779 // If the sign bit of the input is known set or clear, then we know the
780 // top bits of the result.
781 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
782 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
783 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
784 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
787 case Instruction::Shl:
788 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
789 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
790 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
791 APInt Mask2(Mask.lshr(ShiftAmt));
792 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
793 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
794 KnownZero <<= ShiftAmt;
795 KnownOne <<= ShiftAmt;
796 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
800 case Instruction::LShr:
801 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
802 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
803 // Compute the new bits that are at the top now.
804 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
806 // Unsigned shift right.
807 APInt Mask2(Mask.shl(ShiftAmt));
808 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
809 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
810 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
811 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
812 // high bits known zero.
813 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
817 case Instruction::AShr:
818 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
819 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
820 // Compute the new bits that are at the top now.
821 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
823 // Signed shift right.
824 APInt Mask2(Mask.shl(ShiftAmt));
825 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
826 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
827 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
828 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
830 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
831 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
832 KnownZero |= HighBits;
833 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
834 KnownOne |= HighBits;
838 case Instruction::Add: {
839 // If either the LHS or the RHS are Zero, the result is zero.
840 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
841 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
842 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
843 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
845 // Output known-0 bits are known if clear or set in both the low clear bits
846 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
848 unsigned KnownZeroOut = std::min(KnownZero.countTrailingOnes(),
849 KnownZero2.countTrailingOnes());
851 KnownZero = APInt::getLowBitsSet(BitWidth, KnownZeroOut);
852 KnownOne = APInt(BitWidth, 0);
855 case Instruction::Sub: {
856 ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0));
859 // We know that the top bits of C-X are clear if X contains less bits
860 // than C (i.e. no wrap-around can happen). For example, 20-X is
861 // positive if we can prove that X is >= 0 and < 16.
862 if (CLHS->getValue().isNegative())
865 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
866 // NLZ can't be BitWidth with no sign bit
867 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
868 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero, KnownOne, Depth+1);
870 // If all of the MaskV bits are known to be zero, then we know the output
871 // top bits are zero, because we now know that the output is from [0-C].
872 if ((KnownZero & MaskV) == MaskV) {
873 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
874 // Top bits known zero.
875 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
876 KnownOne = APInt(BitWidth, 0); // No one bits known.
878 KnownZero = KnownOne = APInt(BitWidth, 0); // Otherwise, nothing known.
882 case Instruction::SRem:
883 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
884 APInt RA = Rem->getValue();
885 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
886 APInt LowBits = RA.isStrictlyPositive() ? ((RA - 1) | RA) : ~RA;
887 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
888 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
890 // The sign of a remainder is equal to the sign of the first
891 // operand (zero being positive).
892 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
893 KnownZero2 |= ~LowBits;
894 else if (KnownOne2[BitWidth-1])
895 KnownOne2 |= ~LowBits;
897 KnownZero |= KnownZero2 & Mask;
898 KnownOne |= KnownOne2 & Mask;
900 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
904 case Instruction::URem:
905 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
906 APInt RA = Rem->getValue();
907 if (RA.isStrictlyPositive() && RA.isPowerOf2()) {
908 APInt LowBits = (RA - 1) | RA;
909 APInt Mask2 = LowBits & Mask;
910 KnownZero |= ~LowBits & Mask;
911 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
912 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
915 // Since the result is less than or equal to RHS, any leading zero bits
916 // in RHS must also exist in the result.
917 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
918 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
921 uint32_t Leaders = KnownZero2.countLeadingOnes();
922 KnownZero |= APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
923 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
929 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
930 /// this predicate to simplify operations downstream. Mask is known to be zero
931 /// for bits that V cannot have.
932 static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
933 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
934 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
935 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
936 return (KnownZero & Mask) == Mask;
939 /// ShrinkDemandedConstant - Check to see if the specified operand of the
940 /// specified instruction is a constant integer. If so, check to see if there
941 /// are any bits set in the constant that are not demanded. If so, shrink the
942 /// constant and return true.
943 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
945 assert(I && "No instruction?");
946 assert(OpNo < I->getNumOperands() && "Operand index too large");
948 // If the operand is not a constant integer, nothing to do.
949 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
950 if (!OpC) return false;
952 // If there are no bits set that aren't demanded, nothing to do.
953 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
954 if ((~Demanded & OpC->getValue()) == 0)
957 // This instruction is producing bits that are not demanded. Shrink the RHS.
958 Demanded &= OpC->getValue();
959 I->setOperand(OpNo, ConstantInt::get(Demanded));
963 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
964 // set of known zero and one bits, compute the maximum and minimum values that
965 // could have the specified known zero and known one bits, returning them in
967 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
968 const APInt& KnownZero,
969 const APInt& KnownOne,
970 APInt& Min, APInt& Max) {
971 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
972 assert(KnownZero.getBitWidth() == BitWidth &&
973 KnownOne.getBitWidth() == BitWidth &&
974 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
975 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
976 APInt UnknownBits = ~(KnownZero|KnownOne);
978 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
979 // bit if it is unknown.
981 Max = KnownOne|UnknownBits;
983 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
985 Max.clear(BitWidth-1);
989 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
990 // a set of known zero and one bits, compute the maximum and minimum values that
991 // could have the specified known zero and known one bits, returning them in
993 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
994 const APInt &KnownZero,
995 const APInt &KnownOne,
996 APInt &Min, APInt &Max) {
997 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
998 assert(KnownZero.getBitWidth() == BitWidth &&
999 KnownOne.getBitWidth() == BitWidth &&
1000 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1001 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1002 APInt UnknownBits = ~(KnownZero|KnownOne);
1004 // The minimum value is when the unknown bits are all zeros.
1006 // The maximum value is when the unknown bits are all ones.
1007 Max = KnownOne|UnknownBits;
1010 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
1011 /// value based on the demanded bits. When this function is called, it is known
1012 /// that only the bits set in DemandedMask of the result of V are ever used
1013 /// downstream. Consequently, depending on the mask and V, it may be possible
1014 /// to replace V with a constant or one of its operands. In such cases, this
1015 /// function does the replacement and returns true. In all other cases, it
1016 /// returns false after analyzing the expression and setting KnownOne and known
1017 /// to be one in the expression. KnownZero contains all the bits that are known
1018 /// to be zero in the expression. These are provided to potentially allow the
1019 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1020 /// the expression. KnownOne and KnownZero always follow the invariant that
1021 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1022 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
1023 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1024 /// and KnownOne must all be the same.
1025 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1026 APInt& KnownZero, APInt& KnownOne,
1028 assert(V != 0 && "Null pointer of Value???");
1029 assert(Depth <= 6 && "Limit Search Depth");
1030 uint32_t BitWidth = DemandedMask.getBitWidth();
1031 const IntegerType *VTy = cast<IntegerType>(V->getType());
1032 assert(VTy->getBitWidth() == BitWidth &&
1033 KnownZero.getBitWidth() == BitWidth &&
1034 KnownOne.getBitWidth() == BitWidth &&
1035 "Value *V, DemandedMask, KnownZero and KnownOne \
1036 must have same BitWidth");
1037 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1038 // We know all of the bits for a constant!
1039 KnownOne = CI->getValue() & DemandedMask;
1040 KnownZero = ~KnownOne & DemandedMask;
1046 if (!V->hasOneUse()) { // Other users may use these bits.
1047 if (Depth != 0) { // Not at the root.
1048 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1049 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1052 // If this is the root being simplified, allow it to have multiple uses,
1053 // just set the DemandedMask to all bits.
1054 DemandedMask = APInt::getAllOnesValue(BitWidth);
1055 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1056 if (V != UndefValue::get(VTy))
1057 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1059 } else if (Depth == 6) { // Limit search depth.
1063 Instruction *I = dyn_cast<Instruction>(V);
1064 if (!I) return false; // Only analyze instructions.
1066 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1067 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1068 switch (I->getOpcode()) {
1070 case Instruction::And:
1071 // If either the LHS or the RHS are Zero, the result is zero.
1072 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1073 RHSKnownZero, RHSKnownOne, Depth+1))
1075 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1076 "Bits known to be one AND zero?");
1078 // If something is known zero on the RHS, the bits aren't demanded on the
1080 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1081 LHSKnownZero, LHSKnownOne, Depth+1))
1083 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1084 "Bits known to be one AND zero?");
1086 // If all of the demanded bits are known 1 on one side, return the other.
1087 // These bits cannot contribute to the result of the 'and'.
1088 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1089 (DemandedMask & ~LHSKnownZero))
1090 return UpdateValueUsesWith(I, I->getOperand(0));
1091 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1092 (DemandedMask & ~RHSKnownZero))
1093 return UpdateValueUsesWith(I, I->getOperand(1));
1095 // If all of the demanded bits in the inputs are known zeros, return zero.
1096 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1097 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1099 // If the RHS is a constant, see if we can simplify it.
1100 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1101 return UpdateValueUsesWith(I, I);
1103 // Output known-1 bits are only known if set in both the LHS & RHS.
1104 RHSKnownOne &= LHSKnownOne;
1105 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1106 RHSKnownZero |= LHSKnownZero;
1108 case Instruction::Or:
1109 // If either the LHS or the RHS are One, the result is One.
1110 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1111 RHSKnownZero, RHSKnownOne, Depth+1))
1113 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1114 "Bits known to be one AND zero?");
1115 // If something is known one on the RHS, the bits aren't demanded on the
1117 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1118 LHSKnownZero, LHSKnownOne, Depth+1))
1120 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1121 "Bits known to be one AND zero?");
1123 // If all of the demanded bits are known zero on one side, return the other.
1124 // These bits cannot contribute to the result of the 'or'.
1125 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1126 (DemandedMask & ~LHSKnownOne))
1127 return UpdateValueUsesWith(I, I->getOperand(0));
1128 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1129 (DemandedMask & ~RHSKnownOne))
1130 return UpdateValueUsesWith(I, I->getOperand(1));
1132 // If all of the potentially set bits on one side are known to be set on
1133 // the other side, just use the 'other' side.
1134 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1135 (DemandedMask & (~RHSKnownZero)))
1136 return UpdateValueUsesWith(I, I->getOperand(0));
1137 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1138 (DemandedMask & (~LHSKnownZero)))
1139 return UpdateValueUsesWith(I, I->getOperand(1));
1141 // If the RHS is a constant, see if we can simplify it.
1142 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1143 return UpdateValueUsesWith(I, I);
1145 // Output known-0 bits are only known if clear in both the LHS & RHS.
1146 RHSKnownZero &= LHSKnownZero;
1147 // Output known-1 are known to be set if set in either the LHS | RHS.
1148 RHSKnownOne |= LHSKnownOne;
1150 case Instruction::Xor: {
1151 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1152 RHSKnownZero, RHSKnownOne, Depth+1))
1154 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1155 "Bits known to be one AND zero?");
1156 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1157 LHSKnownZero, LHSKnownOne, Depth+1))
1159 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1160 "Bits known to be one AND zero?");
1162 // If all of the demanded bits are known zero on one side, return the other.
1163 // These bits cannot contribute to the result of the 'xor'.
1164 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1165 return UpdateValueUsesWith(I, I->getOperand(0));
1166 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1167 return UpdateValueUsesWith(I, I->getOperand(1));
1169 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1170 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1171 (RHSKnownOne & LHSKnownOne);
1172 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1173 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1174 (RHSKnownOne & LHSKnownZero);
1176 // If all of the demanded bits are known to be zero on one side or the
1177 // other, turn this into an *inclusive* or.
1178 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1179 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1181 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1183 InsertNewInstBefore(Or, *I);
1184 return UpdateValueUsesWith(I, Or);
1187 // If all of the demanded bits on one side are known, and all of the set
1188 // bits on that side are also known to be set on the other side, turn this
1189 // into an AND, as we know the bits will be cleared.
1190 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1191 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1193 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1194 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1196 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1197 InsertNewInstBefore(And, *I);
1198 return UpdateValueUsesWith(I, And);
1202 // If the RHS is a constant, see if we can simplify it.
1203 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1204 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1205 return UpdateValueUsesWith(I, I);
1207 RHSKnownZero = KnownZeroOut;
1208 RHSKnownOne = KnownOneOut;
1211 case Instruction::Select:
1212 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1213 RHSKnownZero, RHSKnownOne, Depth+1))
1215 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1216 LHSKnownZero, LHSKnownOne, Depth+1))
1218 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1219 "Bits known to be one AND zero?");
1220 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1221 "Bits known to be one AND zero?");
1223 // If the operands are constants, see if we can simplify them.
1224 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1225 return UpdateValueUsesWith(I, I);
1226 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1227 return UpdateValueUsesWith(I, I);
1229 // Only known if known in both the LHS and RHS.
1230 RHSKnownOne &= LHSKnownOne;
1231 RHSKnownZero &= LHSKnownZero;
1233 case Instruction::Trunc: {
1235 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1236 DemandedMask.zext(truncBf);
1237 RHSKnownZero.zext(truncBf);
1238 RHSKnownOne.zext(truncBf);
1239 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1240 RHSKnownZero, RHSKnownOne, Depth+1))
1242 DemandedMask.trunc(BitWidth);
1243 RHSKnownZero.trunc(BitWidth);
1244 RHSKnownOne.trunc(BitWidth);
1245 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1246 "Bits known to be one AND zero?");
1249 case Instruction::BitCast:
1250 if (!I->getOperand(0)->getType()->isInteger())
1253 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1254 RHSKnownZero, RHSKnownOne, Depth+1))
1256 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1257 "Bits known to be one AND zero?");
1259 case Instruction::ZExt: {
1260 // Compute the bits in the result that are not present in the input.
1261 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1262 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1264 DemandedMask.trunc(SrcBitWidth);
1265 RHSKnownZero.trunc(SrcBitWidth);
1266 RHSKnownOne.trunc(SrcBitWidth);
1267 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1268 RHSKnownZero, RHSKnownOne, Depth+1))
1270 DemandedMask.zext(BitWidth);
1271 RHSKnownZero.zext(BitWidth);
1272 RHSKnownOne.zext(BitWidth);
1273 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1274 "Bits known to be one AND zero?");
1275 // The top bits are known to be zero.
1276 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1279 case Instruction::SExt: {
1280 // Compute the bits in the result that are not present in the input.
1281 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1282 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1284 APInt InputDemandedBits = DemandedMask &
1285 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1287 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1288 // If any of the sign extended bits are demanded, we know that the sign
1290 if ((NewBits & DemandedMask) != 0)
1291 InputDemandedBits.set(SrcBitWidth-1);
1293 InputDemandedBits.trunc(SrcBitWidth);
1294 RHSKnownZero.trunc(SrcBitWidth);
1295 RHSKnownOne.trunc(SrcBitWidth);
1296 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1297 RHSKnownZero, RHSKnownOne, Depth+1))
1299 InputDemandedBits.zext(BitWidth);
1300 RHSKnownZero.zext(BitWidth);
1301 RHSKnownOne.zext(BitWidth);
1302 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1303 "Bits known to be one AND zero?");
1305 // If the sign bit of the input is known set or clear, then we know the
1306 // top bits of the result.
1308 // If the input sign bit is known zero, or if the NewBits are not demanded
1309 // convert this into a zero extension.
1310 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1312 // Convert to ZExt cast
1313 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1314 return UpdateValueUsesWith(I, NewCast);
1315 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1316 RHSKnownOne |= NewBits;
1320 case Instruction::Add: {
1321 // Figure out what the input bits are. If the top bits of the and result
1322 // are not demanded, then the add doesn't demand them from its input
1324 uint32_t NLZ = DemandedMask.countLeadingZeros();
1326 // If there is a constant on the RHS, there are a variety of xformations
1328 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1329 // If null, this should be simplified elsewhere. Some of the xforms here
1330 // won't work if the RHS is zero.
1334 // If the top bit of the output is demanded, demand everything from the
1335 // input. Otherwise, we demand all the input bits except NLZ top bits.
1336 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1338 // Find information about known zero/one bits in the input.
1339 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1340 LHSKnownZero, LHSKnownOne, Depth+1))
1343 // If the RHS of the add has bits set that can't affect the input, reduce
1345 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1346 return UpdateValueUsesWith(I, I);
1348 // Avoid excess work.
1349 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1352 // Turn it into OR if input bits are zero.
1353 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1355 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1357 InsertNewInstBefore(Or, *I);
1358 return UpdateValueUsesWith(I, Or);
1361 // We can say something about the output known-zero and known-one bits,
1362 // depending on potential carries from the input constant and the
1363 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1364 // bits set and the RHS constant is 0x01001, then we know we have a known
1365 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1367 // To compute this, we first compute the potential carry bits. These are
1368 // the bits which may be modified. I'm not aware of a better way to do
1370 const APInt& RHSVal = RHS->getValue();
1371 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1373 // Now that we know which bits have carries, compute the known-1/0 sets.
1375 // Bits are known one if they are known zero in one operand and one in the
1376 // other, and there is no input carry.
1377 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1378 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1380 // Bits are known zero if they are known zero in both operands and there
1381 // is no input carry.
1382 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1384 // If the high-bits of this ADD are not demanded, then it does not demand
1385 // the high bits of its LHS or RHS.
1386 if (DemandedMask[BitWidth-1] == 0) {
1387 // Right fill the mask of bits for this ADD to demand the most
1388 // significant bit and all those below it.
1389 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1390 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1391 LHSKnownZero, LHSKnownOne, Depth+1))
1393 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1394 LHSKnownZero, LHSKnownOne, Depth+1))
1400 case Instruction::Sub:
1401 // If the high-bits of this SUB are not demanded, then it does not demand
1402 // the high bits of its LHS or RHS.
1403 if (DemandedMask[BitWidth-1] == 0) {
1404 // Right fill the mask of bits for this SUB to demand the most
1405 // significant bit and all those below it.
1406 uint32_t NLZ = DemandedMask.countLeadingZeros();
1407 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1408 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1409 LHSKnownZero, LHSKnownOne, Depth+1))
1411 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1412 LHSKnownZero, LHSKnownOne, Depth+1))
1416 case Instruction::Shl:
1417 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1418 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1419 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1420 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1421 RHSKnownZero, RHSKnownOne, Depth+1))
1423 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1424 "Bits known to be one AND zero?");
1425 RHSKnownZero <<= ShiftAmt;
1426 RHSKnownOne <<= ShiftAmt;
1427 // low bits known zero.
1429 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1432 case Instruction::LShr:
1433 // For a logical shift right
1434 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1435 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1437 // Unsigned shift right.
1438 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1439 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1440 RHSKnownZero, RHSKnownOne, Depth+1))
1442 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1443 "Bits known to be one AND zero?");
1444 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1445 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1447 // Compute the new bits that are at the top now.
1448 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1449 RHSKnownZero |= HighBits; // high bits known zero.
1453 case Instruction::AShr:
1454 // If this is an arithmetic shift right and only the low-bit is set, we can
1455 // always convert this into a logical shr, even if the shift amount is
1456 // variable. The low bit of the shift cannot be an input sign bit unless
1457 // the shift amount is >= the size of the datatype, which is undefined.
1458 if (DemandedMask == 1) {
1459 // Perform the logical shift right.
1460 Value *NewVal = BinaryOperator::createLShr(
1461 I->getOperand(0), I->getOperand(1), I->getName());
1462 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1463 return UpdateValueUsesWith(I, NewVal);
1466 // If the sign bit is the only bit demanded by this ashr, then there is no
1467 // need to do it, the shift doesn't change the high bit.
1468 if (DemandedMask.isSignBit())
1469 return UpdateValueUsesWith(I, I->getOperand(0));
1471 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1472 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1474 // Signed shift right.
1475 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1476 // If any of the "high bits" are demanded, we should set the sign bit as
1478 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1479 DemandedMaskIn.set(BitWidth-1);
1480 if (SimplifyDemandedBits(I->getOperand(0),
1482 RHSKnownZero, RHSKnownOne, Depth+1))
1484 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1485 "Bits known to be one AND zero?");
1486 // Compute the new bits that are at the top now.
1487 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1488 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1489 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1491 // Handle the sign bits.
1492 APInt SignBit(APInt::getSignBit(BitWidth));
1493 // Adjust to where it is now in the mask.
1494 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1496 // If the input sign bit is known to be zero, or if none of the top bits
1497 // are demanded, turn this into an unsigned shift right.
1498 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
1499 (HighBits & ~DemandedMask) == HighBits) {
1500 // Perform the logical shift right.
1501 Value *NewVal = BinaryOperator::createLShr(
1502 I->getOperand(0), SA, I->getName());
1503 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1504 return UpdateValueUsesWith(I, NewVal);
1505 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1506 RHSKnownOne |= HighBits;
1510 case Instruction::SRem:
1511 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1512 APInt RA = Rem->getValue();
1513 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1514 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) | RA : ~RA;
1515 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1516 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1517 LHSKnownZero, LHSKnownOne, Depth+1))
1520 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1521 LHSKnownZero |= ~LowBits;
1522 else if (LHSKnownOne[BitWidth-1])
1523 LHSKnownOne |= ~LowBits;
1525 KnownZero |= LHSKnownZero & DemandedMask;
1526 KnownOne |= LHSKnownOne & DemandedMask;
1528 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1532 case Instruction::URem:
1533 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1534 APInt RA = Rem->getValue();
1535 if (RA.isPowerOf2()) {
1536 APInt LowBits = (RA - 1) | RA;
1537 APInt Mask2 = LowBits & DemandedMask;
1538 KnownZero |= ~LowBits & DemandedMask;
1539 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1540 KnownZero, KnownOne, Depth+1))
1543 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1546 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1547 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1548 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1549 KnownZero2, KnownOne2, Depth+1))
1552 uint32_t Leaders = KnownZero2.countLeadingOnes();
1553 KnownZero |= APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1558 // If the client is only demanding bits that we know, return the known
1560 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1561 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1566 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1567 /// 64 or fewer elements. DemandedElts contains the set of elements that are
1568 /// actually used by the caller. This method analyzes which elements of the
1569 /// operand are undef and returns that information in UndefElts.
1571 /// If the information about demanded elements can be used to simplify the
1572 /// operation, the operation is simplified, then the resultant value is
1573 /// returned. This returns null if no change was made.
1574 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1575 uint64_t &UndefElts,
1577 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1578 assert(VWidth <= 64 && "Vector too wide to analyze!");
1579 uint64_t EltMask = ~0ULL >> (64-VWidth);
1580 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1581 "Invalid DemandedElts!");
1583 if (isa<UndefValue>(V)) {
1584 // If the entire vector is undefined, just return this info.
1585 UndefElts = EltMask;
1587 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1588 UndefElts = EltMask;
1589 return UndefValue::get(V->getType());
1593 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1594 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1595 Constant *Undef = UndefValue::get(EltTy);
1597 std::vector<Constant*> Elts;
1598 for (unsigned i = 0; i != VWidth; ++i)
1599 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1600 Elts.push_back(Undef);
1601 UndefElts |= (1ULL << i);
1602 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1603 Elts.push_back(Undef);
1604 UndefElts |= (1ULL << i);
1605 } else { // Otherwise, defined.
1606 Elts.push_back(CP->getOperand(i));
1609 // If we changed the constant, return it.
1610 Constant *NewCP = ConstantVector::get(Elts);
1611 return NewCP != CP ? NewCP : 0;
1612 } else if (isa<ConstantAggregateZero>(V)) {
1613 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1615 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1616 Constant *Zero = Constant::getNullValue(EltTy);
1617 Constant *Undef = UndefValue::get(EltTy);
1618 std::vector<Constant*> Elts;
1619 for (unsigned i = 0; i != VWidth; ++i)
1620 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1621 UndefElts = DemandedElts ^ EltMask;
1622 return ConstantVector::get(Elts);
1625 if (!V->hasOneUse()) { // Other users may use these bits.
1626 if (Depth != 0) { // Not at the root.
1627 // TODO: Just compute the UndefElts information recursively.
1631 } else if (Depth == 10) { // Limit search depth.
1635 Instruction *I = dyn_cast<Instruction>(V);
1636 if (!I) return false; // Only analyze instructions.
1638 bool MadeChange = false;
1639 uint64_t UndefElts2;
1641 switch (I->getOpcode()) {
1644 case Instruction::InsertElement: {
1645 // If this is a variable index, we don't know which element it overwrites.
1646 // demand exactly the same input as we produce.
1647 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1649 // Note that we can't propagate undef elt info, because we don't know
1650 // which elt is getting updated.
1651 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1652 UndefElts2, Depth+1);
1653 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1657 // If this is inserting an element that isn't demanded, remove this
1659 unsigned IdxNo = Idx->getZExtValue();
1660 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1661 return AddSoonDeadInstToWorklist(*I, 0);
1663 // Otherwise, the element inserted overwrites whatever was there, so the
1664 // input demanded set is simpler than the output set.
1665 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1666 DemandedElts & ~(1ULL << IdxNo),
1667 UndefElts, Depth+1);
1668 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1670 // The inserted element is defined.
1671 UndefElts |= 1ULL << IdxNo;
1674 case Instruction::BitCast: {
1675 // Vector->vector casts only.
1676 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1678 unsigned InVWidth = VTy->getNumElements();
1679 uint64_t InputDemandedElts = 0;
1682 if (VWidth == InVWidth) {
1683 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1684 // elements as are demanded of us.
1686 InputDemandedElts = DemandedElts;
1687 } else if (VWidth > InVWidth) {
1691 // If there are more elements in the result than there are in the source,
1692 // then an input element is live if any of the corresponding output
1693 // elements are live.
1694 Ratio = VWidth/InVWidth;
1695 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1696 if (DemandedElts & (1ULL << OutIdx))
1697 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1703 // If there are more elements in the source than there are in the result,
1704 // then an input element is live if the corresponding output element is
1706 Ratio = InVWidth/VWidth;
1707 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1708 if (DemandedElts & (1ULL << InIdx/Ratio))
1709 InputDemandedElts |= 1ULL << InIdx;
1712 // div/rem demand all inputs, because they don't want divide by zero.
1713 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1714 UndefElts2, Depth+1);
1716 I->setOperand(0, TmpV);
1720 UndefElts = UndefElts2;
1721 if (VWidth > InVWidth) {
1722 assert(0 && "Unimp");
1723 // If there are more elements in the result than there are in the source,
1724 // then an output element is undef if the corresponding input element is
1726 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1727 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1728 UndefElts |= 1ULL << OutIdx;
1729 } else if (VWidth < InVWidth) {
1730 assert(0 && "Unimp");
1731 // If there are more elements in the source than there are in the result,
1732 // then a result element is undef if all of the corresponding input
1733 // elements are undef.
1734 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1735 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1736 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1737 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1741 case Instruction::And:
1742 case Instruction::Or:
1743 case Instruction::Xor:
1744 case Instruction::Add:
1745 case Instruction::Sub:
1746 case Instruction::Mul:
1747 // div/rem demand all inputs, because they don't want divide by zero.
1748 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1749 UndefElts, Depth+1);
1750 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1751 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1752 UndefElts2, Depth+1);
1753 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1755 // Output elements are undefined if both are undefined. Consider things
1756 // like undef&0. The result is known zero, not undef.
1757 UndefElts &= UndefElts2;
1760 case Instruction::Call: {
1761 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1763 switch (II->getIntrinsicID()) {
1766 // Binary vector operations that work column-wise. A dest element is a
1767 // function of the corresponding input elements from the two inputs.
1768 case Intrinsic::x86_sse_sub_ss:
1769 case Intrinsic::x86_sse_mul_ss:
1770 case Intrinsic::x86_sse_min_ss:
1771 case Intrinsic::x86_sse_max_ss:
1772 case Intrinsic::x86_sse2_sub_sd:
1773 case Intrinsic::x86_sse2_mul_sd:
1774 case Intrinsic::x86_sse2_min_sd:
1775 case Intrinsic::x86_sse2_max_sd:
1776 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1777 UndefElts, Depth+1);
1778 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1779 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1780 UndefElts2, Depth+1);
1781 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1783 // If only the low elt is demanded and this is a scalarizable intrinsic,
1784 // scalarize it now.
1785 if (DemandedElts == 1) {
1786 switch (II->getIntrinsicID()) {
1788 case Intrinsic::x86_sse_sub_ss:
1789 case Intrinsic::x86_sse_mul_ss:
1790 case Intrinsic::x86_sse2_sub_sd:
1791 case Intrinsic::x86_sse2_mul_sd:
1792 // TODO: Lower MIN/MAX/ABS/etc
1793 Value *LHS = II->getOperand(1);
1794 Value *RHS = II->getOperand(2);
1795 // Extract the element as scalars.
1796 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1797 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1799 switch (II->getIntrinsicID()) {
1800 default: assert(0 && "Case stmts out of sync!");
1801 case Intrinsic::x86_sse_sub_ss:
1802 case Intrinsic::x86_sse2_sub_sd:
1803 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1804 II->getName()), *II);
1806 case Intrinsic::x86_sse_mul_ss:
1807 case Intrinsic::x86_sse2_mul_sd:
1808 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1809 II->getName()), *II);
1814 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1816 InsertNewInstBefore(New, *II);
1817 AddSoonDeadInstToWorklist(*II, 0);
1822 // Output elements are undefined if both are undefined. Consider things
1823 // like undef&0. The result is known zero, not undef.
1824 UndefElts &= UndefElts2;
1830 return MadeChange ? I : 0;
1833 /// @returns true if the specified compare predicate is
1834 /// true when both operands are equal...
1835 /// @brief Determine if the icmp Predicate is true when both operands are equal
1836 static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
1837 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1838 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1839 pred == ICmpInst::ICMP_SLE;
1842 /// @returns true if the specified compare instruction is
1843 /// true when both operands are equal...
1844 /// @brief Determine if the ICmpInst returns true when both operands are equal
1845 static bool isTrueWhenEqual(ICmpInst &ICI) {
1846 return isTrueWhenEqual(ICI.getPredicate());
1849 /// AssociativeOpt - Perform an optimization on an associative operator. This
1850 /// function is designed to check a chain of associative operators for a
1851 /// potential to apply a certain optimization. Since the optimization may be
1852 /// applicable if the expression was reassociated, this checks the chain, then
1853 /// reassociates the expression as necessary to expose the optimization
1854 /// opportunity. This makes use of a special Functor, which must define
1855 /// 'shouldApply' and 'apply' methods.
1857 template<typename Functor>
1858 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1859 unsigned Opcode = Root.getOpcode();
1860 Value *LHS = Root.getOperand(0);
1862 // Quick check, see if the immediate LHS matches...
1863 if (F.shouldApply(LHS))
1864 return F.apply(Root);
1866 // Otherwise, if the LHS is not of the same opcode as the root, return.
1867 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1868 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1869 // Should we apply this transform to the RHS?
1870 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1872 // If not to the RHS, check to see if we should apply to the LHS...
1873 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1874 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1878 // If the functor wants to apply the optimization to the RHS of LHSI,
1879 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1881 BasicBlock *BB = Root.getParent();
1883 // Now all of the instructions are in the current basic block, go ahead
1884 // and perform the reassociation.
1885 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1887 // First move the selected RHS to the LHS of the root...
1888 Root.setOperand(0, LHSI->getOperand(1));
1890 // Make what used to be the LHS of the root be the user of the root...
1891 Value *ExtraOperand = TmpLHSI->getOperand(1);
1892 if (&Root == TmpLHSI) {
1893 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1896 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1897 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1898 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1899 BasicBlock::iterator ARI = &Root; ++ARI;
1900 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1903 // Now propagate the ExtraOperand down the chain of instructions until we
1905 while (TmpLHSI != LHSI) {
1906 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1907 // Move the instruction to immediately before the chain we are
1908 // constructing to avoid breaking dominance properties.
1909 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1910 BB->getInstList().insert(ARI, NextLHSI);
1913 Value *NextOp = NextLHSI->getOperand(1);
1914 NextLHSI->setOperand(1, ExtraOperand);
1916 ExtraOperand = NextOp;
1919 // Now that the instructions are reassociated, have the functor perform
1920 // the transformation...
1921 return F.apply(Root);
1924 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1930 // AddRHS - Implements: X + X --> X << 1
1933 AddRHS(Value *rhs) : RHS(rhs) {}
1934 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1935 Instruction *apply(BinaryOperator &Add) const {
1936 return BinaryOperator::createShl(Add.getOperand(0),
1937 ConstantInt::get(Add.getType(), 1));
1941 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1943 struct AddMaskingAnd {
1945 AddMaskingAnd(Constant *c) : C2(c) {}
1946 bool shouldApply(Value *LHS) const {
1948 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1949 ConstantExpr::getAnd(C1, C2)->isNullValue();
1951 Instruction *apply(BinaryOperator &Add) const {
1952 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1956 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1958 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1959 if (Constant *SOC = dyn_cast<Constant>(SO))
1960 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1962 return IC->InsertNewInstBefore(CastInst::create(
1963 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1966 // Figure out if the constant is the left or the right argument.
1967 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1968 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1970 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1972 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1973 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1976 Value *Op0 = SO, *Op1 = ConstOperand;
1978 std::swap(Op0, Op1);
1980 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1981 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1982 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1983 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1984 SO->getName()+".cmp");
1986 assert(0 && "Unknown binary instruction type!");
1989 return IC->InsertNewInstBefore(New, I);
1992 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1993 // constant as the other operand, try to fold the binary operator into the
1994 // select arguments. This also works for Cast instructions, which obviously do
1995 // not have a second operand.
1996 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1998 // Don't modify shared select instructions
1999 if (!SI->hasOneUse()) return 0;
2000 Value *TV = SI->getOperand(1);
2001 Value *FV = SI->getOperand(2);
2003 if (isa<Constant>(TV) || isa<Constant>(FV)) {
2004 // Bool selects with constant operands can be folded to logical ops.
2005 if (SI->getType() == Type::Int1Ty) return 0;
2007 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2008 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2010 return new SelectInst(SI->getCondition(), SelectTrueVal,
2017 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2018 /// node as operand #0, see if we can fold the instruction into the PHI (which
2019 /// is only possible if all operands to the PHI are constants).
2020 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2021 PHINode *PN = cast<PHINode>(I.getOperand(0));
2022 unsigned NumPHIValues = PN->getNumIncomingValues();
2023 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
2025 // Check to see if all of the operands of the PHI are constants. If there is
2026 // one non-constant value, remember the BB it is. If there is more than one
2027 // or if *it* is a PHI, bail out.
2028 BasicBlock *NonConstBB = 0;
2029 for (unsigned i = 0; i != NumPHIValues; ++i)
2030 if (!isa<Constant>(PN->getIncomingValue(i))) {
2031 if (NonConstBB) return 0; // More than one non-const value.
2032 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
2033 NonConstBB = PN->getIncomingBlock(i);
2035 // If the incoming non-constant value is in I's block, we have an infinite
2037 if (NonConstBB == I.getParent())
2041 // If there is exactly one non-constant value, we can insert a copy of the
2042 // operation in that block. However, if this is a critical edge, we would be
2043 // inserting the computation one some other paths (e.g. inside a loop). Only
2044 // do this if the pred block is unconditionally branching into the phi block.
2046 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2047 if (!BI || !BI->isUnconditional()) return 0;
2050 // Okay, we can do the transformation: create the new PHI node.
2051 PHINode *NewPN = new PHINode(I.getType(), "");
2052 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2053 InsertNewInstBefore(NewPN, *PN);
2054 NewPN->takeName(PN);
2056 // Next, add all of the operands to the PHI.
2057 if (I.getNumOperands() == 2) {
2058 Constant *C = cast<Constant>(I.getOperand(1));
2059 for (unsigned i = 0; i != NumPHIValues; ++i) {
2061 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2062 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2063 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2065 InV = ConstantExpr::get(I.getOpcode(), InC, C);
2067 assert(PN->getIncomingBlock(i) == NonConstBB);
2068 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2069 InV = BinaryOperator::create(BO->getOpcode(),
2070 PN->getIncomingValue(i), C, "phitmp",
2071 NonConstBB->getTerminator());
2072 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2073 InV = CmpInst::create(CI->getOpcode(),
2075 PN->getIncomingValue(i), C, "phitmp",
2076 NonConstBB->getTerminator());
2078 assert(0 && "Unknown binop!");
2080 AddToWorkList(cast<Instruction>(InV));
2082 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2085 CastInst *CI = cast<CastInst>(&I);
2086 const Type *RetTy = CI->getType();
2087 for (unsigned i = 0; i != NumPHIValues; ++i) {
2089 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2090 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2092 assert(PN->getIncomingBlock(i) == NonConstBB);
2093 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
2094 I.getType(), "phitmp",
2095 NonConstBB->getTerminator());
2096 AddToWorkList(cast<Instruction>(InV));
2098 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2101 return ReplaceInstUsesWith(I, NewPN);
2105 /// CannotBeNegativeZero - Return true if we can prove that the specified FP
2106 /// value is never equal to -0.0.
2108 /// Note that this function will need to be revisited when we support nondefault
2111 static bool CannotBeNegativeZero(const Value *V) {
2112 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2113 return !CFP->getValueAPF().isNegZero();
2115 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2116 if (const Instruction *I = dyn_cast<Instruction>(V)) {
2117 if (I->getOpcode() == Instruction::Add &&
2118 isa<ConstantFP>(I->getOperand(1)) &&
2119 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2122 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2123 if (II->getIntrinsicID() == Intrinsic::sqrt)
2124 return CannotBeNegativeZero(II->getOperand(1));
2126 if (const CallInst *CI = dyn_cast<CallInst>(I))
2127 if (const Function *F = CI->getCalledFunction()) {
2128 if (F->isDeclaration()) {
2129 switch (F->getNameLen()) {
2130 case 3: // abs(x) != -0.0
2131 if (!strcmp(F->getNameStart(), "abs")) return true;
2133 case 4: // abs[lf](x) != -0.0
2134 if (!strcmp(F->getNameStart(), "absf")) return true;
2135 if (!strcmp(F->getNameStart(), "absl")) return true;
2146 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2147 bool Changed = SimplifyCommutative(I);
2148 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2150 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2151 // X + undef -> undef
2152 if (isa<UndefValue>(RHS))
2153 return ReplaceInstUsesWith(I, RHS);
2156 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2157 if (RHSC->isNullValue())
2158 return ReplaceInstUsesWith(I, LHS);
2159 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2160 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2161 (I.getType())->getValueAPF()))
2162 return ReplaceInstUsesWith(I, LHS);
2165 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2166 // X + (signbit) --> X ^ signbit
2167 const APInt& Val = CI->getValue();
2168 uint32_t BitWidth = Val.getBitWidth();
2169 if (Val == APInt::getSignBit(BitWidth))
2170 return BinaryOperator::createXor(LHS, RHS);
2172 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2173 // (X & 254)+1 -> (X&254)|1
2174 if (!isa<VectorType>(I.getType())) {
2175 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2176 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2177 KnownZero, KnownOne))
2182 if (isa<PHINode>(LHS))
2183 if (Instruction *NV = FoldOpIntoPhi(I))
2186 ConstantInt *XorRHS = 0;
2188 if (isa<ConstantInt>(RHSC) &&
2189 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2190 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2191 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2193 uint32_t Size = TySizeBits / 2;
2194 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2195 APInt CFF80Val(-C0080Val);
2197 if (TySizeBits > Size) {
2198 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2199 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2200 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2201 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2202 // This is a sign extend if the top bits are known zero.
2203 if (!MaskedValueIsZero(XorLHS,
2204 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2205 Size = 0; // Not a sign ext, but can't be any others either.
2210 C0080Val = APIntOps::lshr(C0080Val, Size);
2211 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2212 } while (Size >= 1);
2214 // FIXME: This shouldn't be necessary. When the backends can handle types
2215 // with funny bit widths then this whole cascade of if statements should
2216 // be removed. It is just here to get the size of the "middle" type back
2217 // up to something that the back ends can handle.
2218 const Type *MiddleType = 0;
2221 case 32: MiddleType = Type::Int32Ty; break;
2222 case 16: MiddleType = Type::Int16Ty; break;
2223 case 8: MiddleType = Type::Int8Ty; break;
2226 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2227 InsertNewInstBefore(NewTrunc, I);
2228 return new SExtInst(NewTrunc, I.getType(), I.getName());
2234 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2235 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2237 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2238 if (RHSI->getOpcode() == Instruction::Sub)
2239 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2240 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2242 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2243 if (LHSI->getOpcode() == Instruction::Sub)
2244 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2245 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2250 // -A + -B --> -(A + B)
2251 if (Value *LHSV = dyn_castNegVal(LHS)) {
2252 if (LHS->getType()->isIntOrIntVector()) {
2253 if (Value *RHSV = dyn_castNegVal(RHS)) {
2254 Instruction *NewAdd = BinaryOperator::createAdd(LHSV, RHSV, "sum");
2255 InsertNewInstBefore(NewAdd, I);
2256 return BinaryOperator::createNeg(NewAdd);
2260 return BinaryOperator::createSub(RHS, LHSV);
2264 if (!isa<Constant>(RHS))
2265 if (Value *V = dyn_castNegVal(RHS))
2266 return BinaryOperator::createSub(LHS, V);
2270 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2271 if (X == RHS) // X*C + X --> X * (C+1)
2272 return BinaryOperator::createMul(RHS, AddOne(C2));
2274 // X*C1 + X*C2 --> X * (C1+C2)
2276 if (X == dyn_castFoldableMul(RHS, C1))
2277 return BinaryOperator::createMul(X, Add(C1, C2));
2280 // X + X*C --> X * (C+1)
2281 if (dyn_castFoldableMul(RHS, C2) == LHS)
2282 return BinaryOperator::createMul(LHS, AddOne(C2));
2284 // X + ~X --> -1 since ~X = -X-1
2285 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2286 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2289 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2290 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2291 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2294 // W*X + Y*Z --> W * (X+Z) iff W == Y
2295 if (I.getType()->isIntOrIntVector()) {
2296 Value *W, *X, *Y, *Z;
2297 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2298 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2302 } else if (Y == X) {
2304 } else if (X == Z) {
2311 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, Z,
2312 LHS->getName()), I);
2313 return BinaryOperator::createMul(W, NewAdd);
2318 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2320 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2321 return BinaryOperator::createSub(SubOne(CRHS), X);
2323 // (X & FF00) + xx00 -> (X+xx00) & FF00
2324 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2325 Constant *Anded = And(CRHS, C2);
2326 if (Anded == CRHS) {
2327 // See if all bits from the first bit set in the Add RHS up are included
2328 // in the mask. First, get the rightmost bit.
2329 const APInt& AddRHSV = CRHS->getValue();
2331 // Form a mask of all bits from the lowest bit added through the top.
2332 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2334 // See if the and mask includes all of these bits.
2335 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2337 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2338 // Okay, the xform is safe. Insert the new add pronto.
2339 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2340 LHS->getName()), I);
2341 return BinaryOperator::createAnd(NewAdd, C2);
2346 // Try to fold constant add into select arguments.
2347 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2348 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2352 // add (cast *A to intptrtype) B ->
2353 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
2355 CastInst *CI = dyn_cast<CastInst>(LHS);
2358 CI = dyn_cast<CastInst>(RHS);
2361 if (CI && CI->getType()->isSized() &&
2362 (CI->getType()->getPrimitiveSizeInBits() ==
2363 TD->getIntPtrType()->getPrimitiveSizeInBits())
2364 && isa<PointerType>(CI->getOperand(0)->getType())) {
2366 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2367 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2368 PointerType::get(Type::Int8Ty, AS), I);
2369 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
2370 return new PtrToIntInst(I2, CI->getType());
2374 // add (select X 0 (sub n A)) A --> select X A n
2376 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2379 SI = dyn_cast<SelectInst>(RHS);
2382 if (SI && SI->hasOneUse()) {
2383 Value *TV = SI->getTrueValue();
2384 Value *FV = SI->getFalseValue();
2387 // Can we fold the add into the argument of the select?
2388 // We check both true and false select arguments for a matching subtract.
2389 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2390 A == Other) // Fold the add into the true select value.
2391 return new SelectInst(SI->getCondition(), N, A);
2392 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2393 A == Other) // Fold the add into the false select value.
2394 return new SelectInst(SI->getCondition(), A, N);
2398 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2399 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2400 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2401 return ReplaceInstUsesWith(I, LHS);
2403 return Changed ? &I : 0;
2406 // isSignBit - Return true if the value represented by the constant only has the
2407 // highest order bit set.
2408 static bool isSignBit(ConstantInt *CI) {
2409 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2410 return CI->getValue() == APInt::getSignBit(NumBits);
2413 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2414 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2416 if (Op0 == Op1) // sub X, X -> 0
2417 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2419 // If this is a 'B = x-(-A)', change to B = x+A...
2420 if (Value *V = dyn_castNegVal(Op1))
2421 return BinaryOperator::createAdd(Op0, V);
2423 if (isa<UndefValue>(Op0))
2424 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2425 if (isa<UndefValue>(Op1))
2426 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2428 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2429 // Replace (-1 - A) with (~A)...
2430 if (C->isAllOnesValue())
2431 return BinaryOperator::createNot(Op1);
2433 // C - ~X == X + (1+C)
2435 if (match(Op1, m_Not(m_Value(X))))
2436 return BinaryOperator::createAdd(X, AddOne(C));
2438 // -(X >>u 31) -> (X >>s 31)
2439 // -(X >>s 31) -> (X >>u 31)
2441 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2442 if (SI->getOpcode() == Instruction::LShr) {
2443 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2444 // Check to see if we are shifting out everything but the sign bit.
2445 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2446 SI->getType()->getPrimitiveSizeInBits()-1) {
2447 // Ok, the transformation is safe. Insert AShr.
2448 return BinaryOperator::create(Instruction::AShr,
2449 SI->getOperand(0), CU, SI->getName());
2453 else if (SI->getOpcode() == Instruction::AShr) {
2454 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2455 // Check to see if we are shifting out everything but the sign bit.
2456 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2457 SI->getType()->getPrimitiveSizeInBits()-1) {
2458 // Ok, the transformation is safe. Insert LShr.
2459 return BinaryOperator::createLShr(
2460 SI->getOperand(0), CU, SI->getName());
2467 // Try to fold constant sub into select arguments.
2468 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2469 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2472 if (isa<PHINode>(Op0))
2473 if (Instruction *NV = FoldOpIntoPhi(I))
2477 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2478 if (Op1I->getOpcode() == Instruction::Add &&
2479 !Op0->getType()->isFPOrFPVector()) {
2480 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2481 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2482 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2483 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2484 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2485 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2486 // C1-(X+C2) --> (C1-C2)-X
2487 return BinaryOperator::createSub(Subtract(CI1, CI2),
2488 Op1I->getOperand(0));
2492 if (Op1I->hasOneUse()) {
2493 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2494 // is not used by anyone else...
2496 if (Op1I->getOpcode() == Instruction::Sub &&
2497 !Op1I->getType()->isFPOrFPVector()) {
2498 // Swap the two operands of the subexpr...
2499 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2500 Op1I->setOperand(0, IIOp1);
2501 Op1I->setOperand(1, IIOp0);
2503 // Create the new top level add instruction...
2504 return BinaryOperator::createAdd(Op0, Op1);
2507 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2509 if (Op1I->getOpcode() == Instruction::And &&
2510 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2511 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2514 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2515 return BinaryOperator::createAnd(Op0, NewNot);
2518 // 0 - (X sdiv C) -> (X sdiv -C)
2519 if (Op1I->getOpcode() == Instruction::SDiv)
2520 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2522 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2523 return BinaryOperator::createSDiv(Op1I->getOperand(0),
2524 ConstantExpr::getNeg(DivRHS));
2526 // X - X*C --> X * (1-C)
2527 ConstantInt *C2 = 0;
2528 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2529 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2530 return BinaryOperator::createMul(Op0, CP1);
2533 // X - ((X / Y) * Y) --> X % Y
2534 if (Op1I->getOpcode() == Instruction::Mul)
2535 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2536 if (Op0 == I->getOperand(0) &&
2537 Op1I->getOperand(1) == I->getOperand(1)) {
2538 if (I->getOpcode() == Instruction::SDiv)
2539 return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2540 if (I->getOpcode() == Instruction::UDiv)
2541 return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2546 if (!Op0->getType()->isFPOrFPVector())
2547 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2548 if (Op0I->getOpcode() == Instruction::Add) {
2549 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2550 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2551 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2552 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2553 } else if (Op0I->getOpcode() == Instruction::Sub) {
2554 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2555 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2560 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2561 if (X == Op1) // X*C - X --> X * (C-1)
2562 return BinaryOperator::createMul(Op1, SubOne(C1));
2564 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2565 if (X == dyn_castFoldableMul(Op1, C2))
2566 return BinaryOperator::createMul(X, Subtract(C1, C2));
2571 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2572 /// comparison only checks the sign bit. If it only checks the sign bit, set
2573 /// TrueIfSigned if the result of the comparison is true when the input value is
2575 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2576 bool &TrueIfSigned) {
2578 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2579 TrueIfSigned = true;
2580 return RHS->isZero();
2581 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2582 TrueIfSigned = true;
2583 return RHS->isAllOnesValue();
2584 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2585 TrueIfSigned = false;
2586 return RHS->isAllOnesValue();
2587 case ICmpInst::ICMP_UGT:
2588 // True if LHS u> RHS and RHS == high-bit-mask - 1
2589 TrueIfSigned = true;
2590 return RHS->getValue() ==
2591 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2592 case ICmpInst::ICMP_UGE:
2593 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2594 TrueIfSigned = true;
2595 return RHS->getValue() ==
2596 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
2602 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2603 bool Changed = SimplifyCommutative(I);
2604 Value *Op0 = I.getOperand(0);
2606 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2607 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2609 // Simplify mul instructions with a constant RHS...
2610 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2611 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2613 // ((X << C1)*C2) == (X * (C2 << C1))
2614 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2615 if (SI->getOpcode() == Instruction::Shl)
2616 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2617 return BinaryOperator::createMul(SI->getOperand(0),
2618 ConstantExpr::getShl(CI, ShOp));
2621 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2622 if (CI->equalsInt(1)) // X * 1 == X
2623 return ReplaceInstUsesWith(I, Op0);
2624 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2625 return BinaryOperator::createNeg(Op0, I.getName());
2627 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2628 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2629 return BinaryOperator::createShl(Op0,
2630 ConstantInt::get(Op0->getType(), Val.logBase2()));
2632 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2633 if (Op1F->isNullValue())
2634 return ReplaceInstUsesWith(I, Op1);
2636 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2637 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2638 // We need a better interface for long double here.
2639 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2640 if (Op1F->isExactlyValue(1.0))
2641 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2644 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2645 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2646 isa<ConstantInt>(Op0I->getOperand(1))) {
2647 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2648 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2650 InsertNewInstBefore(Add, I);
2651 Value *C1C2 = ConstantExpr::getMul(Op1,
2652 cast<Constant>(Op0I->getOperand(1)));
2653 return BinaryOperator::createAdd(Add, C1C2);
2657 // Try to fold constant mul into select arguments.
2658 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2659 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2662 if (isa<PHINode>(Op0))
2663 if (Instruction *NV = FoldOpIntoPhi(I))
2667 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2668 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2669 return BinaryOperator::createMul(Op0v, Op1v);
2671 // If one of the operands of the multiply is a cast from a boolean value, then
2672 // we know the bool is either zero or one, so this is a 'masking' multiply.
2673 // See if we can simplify things based on how the boolean was originally
2675 CastInst *BoolCast = 0;
2676 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2677 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2680 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2681 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2684 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2685 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2686 const Type *SCOpTy = SCIOp0->getType();
2689 // If the icmp is true iff the sign bit of X is set, then convert this
2690 // multiply into a shift/and combination.
2691 if (isa<ConstantInt>(SCIOp1) &&
2692 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2694 // Shift the X value right to turn it into "all signbits".
2695 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2696 SCOpTy->getPrimitiveSizeInBits()-1);
2698 InsertNewInstBefore(
2699 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
2700 BoolCast->getOperand(0)->getName()+
2703 // If the multiply type is not the same as the source type, sign extend
2704 // or truncate to the multiply type.
2705 if (I.getType() != V->getType()) {
2706 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2707 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2708 Instruction::CastOps opcode =
2709 (SrcBits == DstBits ? Instruction::BitCast :
2710 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2711 V = InsertCastBefore(opcode, V, I.getType(), I);
2714 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2715 return BinaryOperator::createAnd(V, OtherOp);
2720 return Changed ? &I : 0;
2723 /// This function implements the transforms on div instructions that work
2724 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2725 /// used by the visitors to those instructions.
2726 /// @brief Transforms common to all three div instructions
2727 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2728 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2730 // undef / X -> 0 for integer.
2731 // undef / X -> undef for FP (the undef could be a snan).
2732 if (isa<UndefValue>(Op0)) {
2733 if (Op0->getType()->isFPOrFPVector())
2734 return ReplaceInstUsesWith(I, Op0);
2735 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2738 // X / undef -> undef
2739 if (isa<UndefValue>(Op1))
2740 return ReplaceInstUsesWith(I, Op1);
2742 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2743 // This does not apply for fdiv.
2744 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2745 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2746 // the same basic block, then we replace the select with Y, and the
2747 // condition of the select with false (if the cond value is in the same BB).
2748 // If the select has uses other than the div, this allows them to be
2749 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2750 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
2751 if (ST->isNullValue()) {
2752 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2753 if (CondI && CondI->getParent() == I.getParent())
2754 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2755 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2756 I.setOperand(1, SI->getOperand(2));
2758 UpdateValueUsesWith(SI, SI->getOperand(2));
2762 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2763 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
2764 if (ST->isNullValue()) {
2765 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2766 if (CondI && CondI->getParent() == I.getParent())
2767 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2768 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2769 I.setOperand(1, SI->getOperand(1));
2771 UpdateValueUsesWith(SI, SI->getOperand(1));
2779 /// This function implements the transforms common to both integer division
2780 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2781 /// division instructions.
2782 /// @brief Common integer divide transforms
2783 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2784 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2786 if (Instruction *Common = commonDivTransforms(I))
2789 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2791 if (RHS->equalsInt(1))
2792 return ReplaceInstUsesWith(I, Op0);
2794 // (X / C1) / C2 -> X / (C1*C2)
2795 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2796 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2797 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2798 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2799 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2801 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2802 Multiply(RHS, LHSRHS));
2805 if (!RHS->isZero()) { // avoid X udiv 0
2806 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2807 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2809 if (isa<PHINode>(Op0))
2810 if (Instruction *NV = FoldOpIntoPhi(I))
2815 // 0 / X == 0, we don't need to preserve faults!
2816 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2817 if (LHS->equalsInt(0))
2818 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2823 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2824 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2826 // Handle the integer div common cases
2827 if (Instruction *Common = commonIDivTransforms(I))
2830 // X udiv C^2 -> X >> C
2831 // Check to see if this is an unsigned division with an exact power of 2,
2832 // if so, convert to a right shift.
2833 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2834 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
2835 return BinaryOperator::createLShr(Op0,
2836 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2839 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2840 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2841 if (RHSI->getOpcode() == Instruction::Shl &&
2842 isa<ConstantInt>(RHSI->getOperand(0))) {
2843 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2844 if (C1.isPowerOf2()) {
2845 Value *N = RHSI->getOperand(1);
2846 const Type *NTy = N->getType();
2847 if (uint32_t C2 = C1.logBase2()) {
2848 Constant *C2V = ConstantInt::get(NTy, C2);
2849 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2851 return BinaryOperator::createLShr(Op0, N);
2856 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2857 // where C1&C2 are powers of two.
2858 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2859 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2860 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2861 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2862 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2863 // Compute the shift amounts
2864 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2865 // Construct the "on true" case of the select
2866 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2867 Instruction *TSI = BinaryOperator::createLShr(
2868 Op0, TC, SI->getName()+".t");
2869 TSI = InsertNewInstBefore(TSI, I);
2871 // Construct the "on false" case of the select
2872 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2873 Instruction *FSI = BinaryOperator::createLShr(
2874 Op0, FC, SI->getName()+".f");
2875 FSI = InsertNewInstBefore(FSI, I);
2877 // construct the select instruction and return it.
2878 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2884 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2885 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2887 // Handle the integer div common cases
2888 if (Instruction *Common = commonIDivTransforms(I))
2891 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2893 if (RHS->isAllOnesValue())
2894 return BinaryOperator::createNeg(Op0);
2897 if (Value *LHSNeg = dyn_castNegVal(Op0))
2898 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2901 // If the sign bits of both operands are zero (i.e. we can prove they are
2902 // unsigned inputs), turn this into a udiv.
2903 if (I.getType()->isInteger()) {
2904 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2905 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2906 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2907 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2914 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2915 return commonDivTransforms(I);
2918 /// This function implements the transforms on rem instructions that work
2919 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2920 /// is used by the visitors to those instructions.
2921 /// @brief Transforms common to all three rem instructions
2922 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2923 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2925 // 0 % X == 0 for integer, we don't need to preserve faults!
2926 if (Constant *LHS = dyn_cast<Constant>(Op0))
2927 if (LHS->isNullValue())
2928 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2930 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2931 if (I.getType()->isFPOrFPVector())
2932 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
2933 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2935 if (isa<UndefValue>(Op1))
2936 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2938 // Handle cases involving: rem X, (select Cond, Y, Z)
2939 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2940 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2941 // the same basic block, then we replace the select with Y, and the
2942 // condition of the select with false (if the cond value is in the same
2943 // BB). If the select has uses other than the div, this allows them to be
2945 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2946 if (ST->isNullValue()) {
2947 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2948 if (CondI && CondI->getParent() == I.getParent())
2949 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2950 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2951 I.setOperand(1, SI->getOperand(2));
2953 UpdateValueUsesWith(SI, SI->getOperand(2));
2956 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2957 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2958 if (ST->isNullValue()) {
2959 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2960 if (CondI && CondI->getParent() == I.getParent())
2961 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2962 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2963 I.setOperand(1, SI->getOperand(1));
2965 UpdateValueUsesWith(SI, SI->getOperand(1));
2973 /// This function implements the transforms common to both integer remainder
2974 /// instructions (urem and srem). It is called by the visitors to those integer
2975 /// remainder instructions.
2976 /// @brief Common integer remainder transforms
2977 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2978 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2980 if (Instruction *common = commonRemTransforms(I))
2983 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2984 // X % 0 == undef, we don't need to preserve faults!
2985 if (RHS->equalsInt(0))
2986 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2988 if (RHS->equalsInt(1)) // X % 1 == 0
2989 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2991 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2992 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2993 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2995 } else if (isa<PHINode>(Op0I)) {
2996 if (Instruction *NV = FoldOpIntoPhi(I))
3000 // See if we can fold away this rem instruction.
3001 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3002 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3003 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3004 KnownZero, KnownOne))
3012 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3013 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3015 if (Instruction *common = commonIRemTransforms(I))
3018 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3019 // X urem C^2 -> X and C
3020 // Check to see if this is an unsigned remainder with an exact power of 2,
3021 // if so, convert to a bitwise and.
3022 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3023 if (C->getValue().isPowerOf2())
3024 return BinaryOperator::createAnd(Op0, SubOne(C));
3027 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3028 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3029 if (RHSI->getOpcode() == Instruction::Shl &&
3030 isa<ConstantInt>(RHSI->getOperand(0))) {
3031 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3032 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3033 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
3035 return BinaryOperator::createAnd(Op0, Add);
3040 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3041 // where C1&C2 are powers of two.
3042 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3043 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3044 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3045 // STO == 0 and SFO == 0 handled above.
3046 if ((STO->getValue().isPowerOf2()) &&
3047 (SFO->getValue().isPowerOf2())) {
3048 Value *TrueAnd = InsertNewInstBefore(
3049 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3050 Value *FalseAnd = InsertNewInstBefore(
3051 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3052 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
3060 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3061 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3063 // Handle the integer rem common cases
3064 if (Instruction *common = commonIRemTransforms(I))
3067 if (Value *RHSNeg = dyn_castNegVal(Op1))
3068 if (!isa<ConstantInt>(RHSNeg) ||
3069 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
3071 AddUsesToWorkList(I);
3072 I.setOperand(1, RHSNeg);
3076 // If the sign bits of both operands are zero (i.e. we can prove they are
3077 // unsigned inputs), turn this into a urem.
3078 if (I.getType()->isInteger()) {
3079 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3080 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3081 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3082 return BinaryOperator::createURem(Op0, Op1, I.getName());
3089 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3090 return commonRemTransforms(I);
3093 // isMaxValueMinusOne - return true if this is Max-1
3094 static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
3095 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3097 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3098 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
3101 // isMinValuePlusOne - return true if this is Min+1
3102 static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
3104 return C->getValue() == 1; // unsigned
3106 // Calculate 1111111111000000000000
3107 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3108 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
3111 // isOneBitSet - Return true if there is exactly one bit set in the specified
3113 static bool isOneBitSet(const ConstantInt *CI) {
3114 return CI->getValue().isPowerOf2();
3117 // isHighOnes - Return true if the constant is of the form 1+0+.
3118 // This is the same as lowones(~X).
3119 static bool isHighOnes(const ConstantInt *CI) {
3120 return (~CI->getValue() + 1).isPowerOf2();
3123 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3124 /// are carefully arranged to allow folding of expressions such as:
3126 /// (A < B) | (A > B) --> (A != B)
3128 /// Note that this is only valid if the first and second predicates have the
3129 /// same sign. Is illegal to do: (A u< B) | (A s> B)
3131 /// Three bits are used to represent the condition, as follows:
3136 /// <=> Value Definition
3137 /// 000 0 Always false
3144 /// 111 7 Always true
3146 static unsigned getICmpCode(const ICmpInst *ICI) {
3147 switch (ICI->getPredicate()) {
3149 case ICmpInst::ICMP_UGT: return 1; // 001
3150 case ICmpInst::ICMP_SGT: return 1; // 001
3151 case ICmpInst::ICMP_EQ: return 2; // 010
3152 case ICmpInst::ICMP_UGE: return 3; // 011
3153 case ICmpInst::ICMP_SGE: return 3; // 011
3154 case ICmpInst::ICMP_ULT: return 4; // 100
3155 case ICmpInst::ICMP_SLT: return 4; // 100
3156 case ICmpInst::ICMP_NE: return 5; // 101
3157 case ICmpInst::ICMP_ULE: return 6; // 110
3158 case ICmpInst::ICMP_SLE: return 6; // 110
3161 assert(0 && "Invalid ICmp predicate!");
3166 /// getICmpValue - This is the complement of getICmpCode, which turns an
3167 /// opcode and two operands into either a constant true or false, or a brand
3168 /// new ICmp instruction. The sign is passed in to determine which kind
3169 /// of predicate to use in new icmp instructions.
3170 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3172 default: assert(0 && "Illegal ICmp code!");
3173 case 0: return ConstantInt::getFalse();
3176 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3178 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3179 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3182 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3184 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3187 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3189 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3190 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3193 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3195 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3196 case 7: return ConstantInt::getTrue();
3200 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3201 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3202 (ICmpInst::isSignedPredicate(p1) &&
3203 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3204 (ICmpInst::isSignedPredicate(p2) &&
3205 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3209 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3210 struct FoldICmpLogical {
3213 ICmpInst::Predicate pred;
3214 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3215 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3216 pred(ICI->getPredicate()) {}
3217 bool shouldApply(Value *V) const {
3218 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3219 if (PredicatesFoldable(pred, ICI->getPredicate()))
3220 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3221 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3224 Instruction *apply(Instruction &Log) const {
3225 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3226 if (ICI->getOperand(0) != LHS) {
3227 assert(ICI->getOperand(1) == LHS);
3228 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3231 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3232 unsigned LHSCode = getICmpCode(ICI);
3233 unsigned RHSCode = getICmpCode(RHSICI);
3235 switch (Log.getOpcode()) {
3236 case Instruction::And: Code = LHSCode & RHSCode; break;
3237 case Instruction::Or: Code = LHSCode | RHSCode; break;
3238 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3239 default: assert(0 && "Illegal logical opcode!"); return 0;
3242 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3243 ICmpInst::isSignedPredicate(ICI->getPredicate());
3245 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3246 if (Instruction *I = dyn_cast<Instruction>(RV))
3248 // Otherwise, it's a constant boolean value...
3249 return IC.ReplaceInstUsesWith(Log, RV);
3252 } // end anonymous namespace
3254 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3255 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3256 // guaranteed to be a binary operator.
3257 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3259 ConstantInt *AndRHS,
3260 BinaryOperator &TheAnd) {
3261 Value *X = Op->getOperand(0);
3262 Constant *Together = 0;
3264 Together = And(AndRHS, OpRHS);
3266 switch (Op->getOpcode()) {
3267 case Instruction::Xor:
3268 if (Op->hasOneUse()) {
3269 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3270 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
3271 InsertNewInstBefore(And, TheAnd);
3273 return BinaryOperator::createXor(And, Together);
3276 case Instruction::Or:
3277 if (Together == AndRHS) // (X | C) & C --> C
3278 return ReplaceInstUsesWith(TheAnd, AndRHS);
3280 if (Op->hasOneUse() && Together != OpRHS) {
3281 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3282 Instruction *Or = BinaryOperator::createOr(X, Together);
3283 InsertNewInstBefore(Or, TheAnd);
3285 return BinaryOperator::createAnd(Or, AndRHS);
3288 case Instruction::Add:
3289 if (Op->hasOneUse()) {
3290 // Adding a one to a single bit bit-field should be turned into an XOR
3291 // of the bit. First thing to check is to see if this AND is with a
3292 // single bit constant.
3293 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3295 // If there is only one bit set...
3296 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3297 // Ok, at this point, we know that we are masking the result of the
3298 // ADD down to exactly one bit. If the constant we are adding has
3299 // no bits set below this bit, then we can eliminate the ADD.
3300 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3302 // Check to see if any bits below the one bit set in AndRHSV are set.
3303 if ((AddRHS & (AndRHSV-1)) == 0) {
3304 // If not, the only thing that can effect the output of the AND is
3305 // the bit specified by AndRHSV. If that bit is set, the effect of
3306 // the XOR is to toggle the bit. If it is clear, then the ADD has
3308 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3309 TheAnd.setOperand(0, X);
3312 // Pull the XOR out of the AND.
3313 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
3314 InsertNewInstBefore(NewAnd, TheAnd);
3315 NewAnd->takeName(Op);
3316 return BinaryOperator::createXor(NewAnd, AndRHS);
3323 case Instruction::Shl: {
3324 // We know that the AND will not produce any of the bits shifted in, so if
3325 // the anded constant includes them, clear them now!
3327 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3328 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3329 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3330 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3332 if (CI->getValue() == ShlMask) {
3333 // Masking out bits that the shift already masks
3334 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3335 } else if (CI != AndRHS) { // Reducing bits set in and.
3336 TheAnd.setOperand(1, CI);
3341 case Instruction::LShr:
3343 // We know that the AND will not produce any of the bits shifted in, so if
3344 // the anded constant includes them, clear them now! This only applies to
3345 // unsigned shifts, because a signed shr may bring in set bits!
3347 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3348 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3349 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3350 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3352 if (CI->getValue() == ShrMask) {
3353 // Masking out bits that the shift already masks.
3354 return ReplaceInstUsesWith(TheAnd, Op);
3355 } else if (CI != AndRHS) {
3356 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3361 case Instruction::AShr:
3363 // See if this is shifting in some sign extension, then masking it out
3365 if (Op->hasOneUse()) {
3366 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3367 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3368 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3369 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3370 if (C == AndRHS) { // Masking out bits shifted in.
3371 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3372 // Make the argument unsigned.
3373 Value *ShVal = Op->getOperand(0);
3374 ShVal = InsertNewInstBefore(
3375 BinaryOperator::createLShr(ShVal, OpRHS,
3376 Op->getName()), TheAnd);
3377 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
3386 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3387 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3388 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3389 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3390 /// insert new instructions.
3391 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3392 bool isSigned, bool Inside,
3394 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3395 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3396 "Lo is not <= Hi in range emission code!");
3399 if (Lo == Hi) // Trivially false.
3400 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3402 // V >= Min && V < Hi --> V < Hi
3403 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3404 ICmpInst::Predicate pred = (isSigned ?
3405 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3406 return new ICmpInst(pred, V, Hi);
3409 // Emit V-Lo <u Hi-Lo
3410 Constant *NegLo = ConstantExpr::getNeg(Lo);
3411 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3412 InsertNewInstBefore(Add, IB);
3413 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3414 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3417 if (Lo == Hi) // Trivially true.
3418 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3420 // V < Min || V >= Hi -> V > Hi-1
3421 Hi = SubOne(cast<ConstantInt>(Hi));
3422 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3423 ICmpInst::Predicate pred = (isSigned ?
3424 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3425 return new ICmpInst(pred, V, Hi);
3428 // Emit V-Lo >u Hi-1-Lo
3429 // Note that Hi has already had one subtracted from it, above.
3430 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3431 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3432 InsertNewInstBefore(Add, IB);
3433 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3434 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3437 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3438 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3439 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3440 // not, since all 1s are not contiguous.
3441 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3442 const APInt& V = Val->getValue();
3443 uint32_t BitWidth = Val->getType()->getBitWidth();
3444 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3446 // look for the first zero bit after the run of ones
3447 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3448 // look for the first non-zero bit
3449 ME = V.getActiveBits();
3453 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3454 /// where isSub determines whether the operator is a sub. If we can fold one of
3455 /// the following xforms:
3457 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3458 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3459 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3461 /// return (A +/- B).
3463 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3464 ConstantInt *Mask, bool isSub,
3466 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3467 if (!LHSI || LHSI->getNumOperands() != 2 ||
3468 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3470 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3472 switch (LHSI->getOpcode()) {
3474 case Instruction::And:
3475 if (And(N, Mask) == Mask) {
3476 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3477 if ((Mask->getValue().countLeadingZeros() +
3478 Mask->getValue().countPopulation()) ==
3479 Mask->getValue().getBitWidth())
3482 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3483 // part, we don't need any explicit masks to take them out of A. If that
3484 // is all N is, ignore it.
3485 uint32_t MB = 0, ME = 0;
3486 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3487 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3488 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3489 if (MaskedValueIsZero(RHS, Mask))
3494 case Instruction::Or:
3495 case Instruction::Xor:
3496 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3497 if ((Mask->getValue().countLeadingZeros() +
3498 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3499 && And(N, Mask)->isZero())
3506 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3508 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3509 return InsertNewInstBefore(New, I);
3512 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3513 bool Changed = SimplifyCommutative(I);
3514 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3516 if (isa<UndefValue>(Op1)) // X & undef -> 0
3517 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3521 return ReplaceInstUsesWith(I, Op1);
3523 // See if we can simplify any instructions used by the instruction whose sole
3524 // purpose is to compute bits we don't care about.
3525 if (!isa<VectorType>(I.getType())) {
3526 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3527 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3528 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3529 KnownZero, KnownOne))
3532 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3533 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3534 return ReplaceInstUsesWith(I, I.getOperand(0));
3535 } else if (isa<ConstantAggregateZero>(Op1)) {
3536 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3540 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3541 const APInt& AndRHSMask = AndRHS->getValue();
3542 APInt NotAndRHS(~AndRHSMask);
3544 // Optimize a variety of ((val OP C1) & C2) combinations...
3545 if (isa<BinaryOperator>(Op0)) {
3546 Instruction *Op0I = cast<Instruction>(Op0);
3547 Value *Op0LHS = Op0I->getOperand(0);
3548 Value *Op0RHS = Op0I->getOperand(1);
3549 switch (Op0I->getOpcode()) {
3550 case Instruction::Xor:
3551 case Instruction::Or:
3552 // If the mask is only needed on one incoming arm, push it up.
3553 if (Op0I->hasOneUse()) {
3554 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3555 // Not masking anything out for the LHS, move to RHS.
3556 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3557 Op0RHS->getName()+".masked");
3558 InsertNewInstBefore(NewRHS, I);
3559 return BinaryOperator::create(
3560 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3562 if (!isa<Constant>(Op0RHS) &&
3563 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3564 // Not masking anything out for the RHS, move to LHS.
3565 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3566 Op0LHS->getName()+".masked");
3567 InsertNewInstBefore(NewLHS, I);
3568 return BinaryOperator::create(
3569 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3574 case Instruction::Add:
3575 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3576 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3577 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3578 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3579 return BinaryOperator::createAnd(V, AndRHS);
3580 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3581 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
3584 case Instruction::Sub:
3585 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3586 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3587 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3588 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3589 return BinaryOperator::createAnd(V, AndRHS);
3593 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3594 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3596 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3597 // If this is an integer truncation or change from signed-to-unsigned, and
3598 // if the source is an and/or with immediate, transform it. This
3599 // frequently occurs for bitfield accesses.
3600 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3601 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3602 CastOp->getNumOperands() == 2)
3603 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3604 if (CastOp->getOpcode() == Instruction::And) {
3605 // Change: and (cast (and X, C1) to T), C2
3606 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3607 // This will fold the two constants together, which may allow
3608 // other simplifications.
3609 Instruction *NewCast = CastInst::createTruncOrBitCast(
3610 CastOp->getOperand(0), I.getType(),
3611 CastOp->getName()+".shrunk");
3612 NewCast = InsertNewInstBefore(NewCast, I);
3613 // trunc_or_bitcast(C1)&C2
3614 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3615 C3 = ConstantExpr::getAnd(C3, AndRHS);
3616 return BinaryOperator::createAnd(NewCast, C3);
3617 } else if (CastOp->getOpcode() == Instruction::Or) {
3618 // Change: and (cast (or X, C1) to T), C2
3619 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3620 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3621 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3622 return ReplaceInstUsesWith(I, AndRHS);
3628 // Try to fold constant and into select arguments.
3629 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3630 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3632 if (isa<PHINode>(Op0))
3633 if (Instruction *NV = FoldOpIntoPhi(I))
3637 Value *Op0NotVal = dyn_castNotVal(Op0);
3638 Value *Op1NotVal = dyn_castNotVal(Op1);
3640 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3641 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3643 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3644 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3645 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3646 I.getName()+".demorgan");
3647 InsertNewInstBefore(Or, I);
3648 return BinaryOperator::createNot(Or);
3652 Value *A = 0, *B = 0, *C = 0, *D = 0;
3653 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3654 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3655 return ReplaceInstUsesWith(I, Op1);
3657 // (A|B) & ~(A&B) -> A^B
3658 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3659 if ((A == C && B == D) || (A == D && B == C))
3660 return BinaryOperator::createXor(A, B);
3664 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3665 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3666 return ReplaceInstUsesWith(I, Op0);
3668 // ~(A&B) & (A|B) -> A^B
3669 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3670 if ((A == C && B == D) || (A == D && B == C))
3671 return BinaryOperator::createXor(A, B);
3675 if (Op0->hasOneUse() &&
3676 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3677 if (A == Op1) { // (A^B)&A -> A&(A^B)
3678 I.swapOperands(); // Simplify below
3679 std::swap(Op0, Op1);
3680 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3681 cast<BinaryOperator>(Op0)->swapOperands();
3682 I.swapOperands(); // Simplify below
3683 std::swap(Op0, Op1);
3686 if (Op1->hasOneUse() &&
3687 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3688 if (B == Op0) { // B&(A^B) -> B&(B^A)
3689 cast<BinaryOperator>(Op1)->swapOperands();
3692 if (A == Op0) { // A&(A^B) -> A & ~B
3693 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3694 InsertNewInstBefore(NotB, I);
3695 return BinaryOperator::createAnd(A, NotB);
3700 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3701 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3702 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3705 Value *LHSVal, *RHSVal;
3706 ConstantInt *LHSCst, *RHSCst;
3707 ICmpInst::Predicate LHSCC, RHSCC;
3708 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3709 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3710 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3711 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3712 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3713 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3714 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3715 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3717 // Don't try to fold ICMP_SLT + ICMP_ULT.
3718 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3719 ICmpInst::isSignedPredicate(LHSCC) ==
3720 ICmpInst::isSignedPredicate(RHSCC))) {
3721 // Ensure that the larger constant is on the RHS.
3722 ICmpInst::Predicate GT;
3723 if (ICmpInst::isSignedPredicate(LHSCC) ||
3724 (ICmpInst::isEquality(LHSCC) &&
3725 ICmpInst::isSignedPredicate(RHSCC)))
3726 GT = ICmpInst::ICMP_SGT;
3728 GT = ICmpInst::ICMP_UGT;
3730 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3731 ICmpInst *LHS = cast<ICmpInst>(Op0);
3732 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3733 std::swap(LHS, RHS);
3734 std::swap(LHSCst, RHSCst);
3735 std::swap(LHSCC, RHSCC);
3738 // At this point, we know we have have two icmp instructions
3739 // comparing a value against two constants and and'ing the result
3740 // together. Because of the above check, we know that we only have
3741 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3742 // (from the FoldICmpLogical check above), that the two constants
3743 // are not equal and that the larger constant is on the RHS
3744 assert(LHSCst != RHSCst && "Compares not folded above?");
3747 default: assert(0 && "Unknown integer condition code!");
3748 case ICmpInst::ICMP_EQ:
3750 default: assert(0 && "Unknown integer condition code!");
3751 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3752 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3753 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3754 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3755 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3756 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3757 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3758 return ReplaceInstUsesWith(I, LHS);
3760 case ICmpInst::ICMP_NE:
3762 default: assert(0 && "Unknown integer condition code!");
3763 case ICmpInst::ICMP_ULT:
3764 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3765 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3766 break; // (X != 13 & X u< 15) -> no change
3767 case ICmpInst::ICMP_SLT:
3768 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3769 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3770 break; // (X != 13 & X s< 15) -> no change
3771 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3772 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3773 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3774 return ReplaceInstUsesWith(I, RHS);
3775 case ICmpInst::ICMP_NE:
3776 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3777 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3778 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3779 LHSVal->getName()+".off");
3780 InsertNewInstBefore(Add, I);
3781 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3782 ConstantInt::get(Add->getType(), 1));
3784 break; // (X != 13 & X != 15) -> no change
3787 case ICmpInst::ICMP_ULT:
3789 default: assert(0 && "Unknown integer condition code!");
3790 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3791 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3792 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3793 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3795 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3796 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3797 return ReplaceInstUsesWith(I, LHS);
3798 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3802 case ICmpInst::ICMP_SLT:
3804 default: assert(0 && "Unknown integer condition code!");
3805 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3806 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3807 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3808 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3810 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3811 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3812 return ReplaceInstUsesWith(I, LHS);
3813 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3817 case ICmpInst::ICMP_UGT:
3819 default: assert(0 && "Unknown integer condition code!");
3820 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3821 return ReplaceInstUsesWith(I, LHS);
3822 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3823 return ReplaceInstUsesWith(I, RHS);
3824 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3826 case ICmpInst::ICMP_NE:
3827 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3828 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3829 break; // (X u> 13 & X != 15) -> no change
3830 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3831 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3833 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3837 case ICmpInst::ICMP_SGT:
3839 default: assert(0 && "Unknown integer condition code!");
3840 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3841 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3842 return ReplaceInstUsesWith(I, RHS);
3843 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3845 case ICmpInst::ICMP_NE:
3846 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3847 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3848 break; // (X s> 13 & X != 15) -> no change
3849 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3850 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3852 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3860 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3861 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3862 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3863 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3864 const Type *SrcTy = Op0C->getOperand(0)->getType();
3865 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3866 // Only do this if the casts both really cause code to be generated.
3867 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3869 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3871 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3872 Op1C->getOperand(0),
3874 InsertNewInstBefore(NewOp, I);
3875 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3879 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3880 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3881 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3882 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
3883 SI0->getOperand(1) == SI1->getOperand(1) &&
3884 (SI0->hasOneUse() || SI1->hasOneUse())) {
3885 Instruction *NewOp =
3886 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3888 SI0->getName()), I);
3889 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3890 SI1->getOperand(1));
3894 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3895 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3896 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3897 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3898 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3899 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3900 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3901 // If either of the constants are nans, then the whole thing returns
3903 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3904 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3905 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3906 RHS->getOperand(0));
3911 return Changed ? &I : 0;
3914 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3915 /// in the result. If it does, and if the specified byte hasn't been filled in
3916 /// yet, fill it in and return false.
3917 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3918 Instruction *I = dyn_cast<Instruction>(V);
3919 if (I == 0) return true;
3921 // If this is an or instruction, it is an inner node of the bswap.
3922 if (I->getOpcode() == Instruction::Or)
3923 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3924 CollectBSwapParts(I->getOperand(1), ByteValues);
3926 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3927 // If this is a shift by a constant int, and it is "24", then its operand
3928 // defines a byte. We only handle unsigned types here.
3929 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3930 // Not shifting the entire input by N-1 bytes?
3931 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3932 8*(ByteValues.size()-1))
3936 if (I->getOpcode() == Instruction::Shl) {
3937 // X << 24 defines the top byte with the lowest of the input bytes.
3938 DestNo = ByteValues.size()-1;
3940 // X >>u 24 defines the low byte with the highest of the input bytes.
3944 // If the destination byte value is already defined, the values are or'd
3945 // together, which isn't a bswap (unless it's an or of the same bits).
3946 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3948 ByteValues[DestNo] = I->getOperand(0);
3952 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3954 Value *Shift = 0, *ShiftLHS = 0;
3955 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3956 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3957 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3959 Instruction *SI = cast<Instruction>(Shift);
3961 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3962 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3963 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3966 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3968 if (AndAmt->getValue().getActiveBits() > 64)
3970 uint64_t AndAmtVal = AndAmt->getZExtValue();
3971 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3972 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3974 // Unknown mask for bswap.
3975 if (DestByte == ByteValues.size()) return true;
3977 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3979 if (SI->getOpcode() == Instruction::Shl)
3980 SrcByte = DestByte - ShiftBytes;
3982 SrcByte = DestByte + ShiftBytes;
3984 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3985 if (SrcByte != ByteValues.size()-DestByte-1)
3988 // If the destination byte value is already defined, the values are or'd
3989 // together, which isn't a bswap (unless it's an or of the same bits).
3990 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3992 ByteValues[DestByte] = SI->getOperand(0);
3996 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3997 /// If so, insert the new bswap intrinsic and return it.
3998 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3999 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4000 if (!ITy || ITy->getBitWidth() % 16)
4001 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4003 /// ByteValues - For each byte of the result, we keep track of which value
4004 /// defines each byte.
4005 SmallVector<Value*, 8> ByteValues;
4006 ByteValues.resize(ITy->getBitWidth()/8);
4008 // Try to find all the pieces corresponding to the bswap.
4009 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4010 CollectBSwapParts(I.getOperand(1), ByteValues))
4013 // Check to see if all of the bytes come from the same value.
4014 Value *V = ByteValues[0];
4015 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4017 // Check to make sure that all of the bytes come from the same value.
4018 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4019 if (ByteValues[i] != V)
4021 const Type *Tys[] = { ITy };
4022 Module *M = I.getParent()->getParent()->getParent();
4023 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4024 return new CallInst(F, V);
4028 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4029 bool Changed = SimplifyCommutative(I);
4030 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4032 if (isa<UndefValue>(Op1)) // X | undef -> -1
4033 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4037 return ReplaceInstUsesWith(I, Op0);
4039 // See if we can simplify any instructions used by the instruction whose sole
4040 // purpose is to compute bits we don't care about.
4041 if (!isa<VectorType>(I.getType())) {
4042 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4043 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4044 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4045 KnownZero, KnownOne))
4047 } else if (isa<ConstantAggregateZero>(Op1)) {
4048 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4049 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4050 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4051 return ReplaceInstUsesWith(I, I.getOperand(1));
4057 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4058 ConstantInt *C1 = 0; Value *X = 0;
4059 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4060 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4061 Instruction *Or = BinaryOperator::createOr(X, RHS);
4062 InsertNewInstBefore(Or, I);
4064 return BinaryOperator::createAnd(Or,
4065 ConstantInt::get(RHS->getValue() | C1->getValue()));
4068 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4069 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4070 Instruction *Or = BinaryOperator::createOr(X, RHS);
4071 InsertNewInstBefore(Or, I);
4073 return BinaryOperator::createXor(Or,
4074 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4077 // Try to fold constant and into select arguments.
4078 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4079 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4081 if (isa<PHINode>(Op0))
4082 if (Instruction *NV = FoldOpIntoPhi(I))
4086 Value *A = 0, *B = 0;
4087 ConstantInt *C1 = 0, *C2 = 0;
4089 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4090 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4091 return ReplaceInstUsesWith(I, Op1);
4092 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4093 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4094 return ReplaceInstUsesWith(I, Op0);
4096 // (A | B) | C and A | (B | C) -> bswap if possible.
4097 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4098 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4099 match(Op1, m_Or(m_Value(), m_Value())) ||
4100 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4101 match(Op1, m_Shift(m_Value(), m_Value())))) {
4102 if (Instruction *BSwap = MatchBSwap(I))
4106 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4107 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4108 MaskedValueIsZero(Op1, C1->getValue())) {
4109 Instruction *NOr = BinaryOperator::createOr(A, Op1);
4110 InsertNewInstBefore(NOr, I);
4112 return BinaryOperator::createXor(NOr, C1);
4115 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4116 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4117 MaskedValueIsZero(Op0, C1->getValue())) {
4118 Instruction *NOr = BinaryOperator::createOr(A, Op0);
4119 InsertNewInstBefore(NOr, I);
4121 return BinaryOperator::createXor(NOr, C1);
4125 Value *C = 0, *D = 0;
4126 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4127 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4128 Value *V1 = 0, *V2 = 0, *V3 = 0;
4129 C1 = dyn_cast<ConstantInt>(C);
4130 C2 = dyn_cast<ConstantInt>(D);
4131 if (C1 && C2) { // (A & C1)|(B & C2)
4132 // If we have: ((V + N) & C1) | (V & C2)
4133 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4134 // replace with V+N.
4135 if (C1->getValue() == ~C2->getValue()) {
4136 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4137 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4138 // Add commutes, try both ways.
4139 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4140 return ReplaceInstUsesWith(I, A);
4141 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4142 return ReplaceInstUsesWith(I, A);
4144 // Or commutes, try both ways.
4145 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4146 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4147 // Add commutes, try both ways.
4148 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4149 return ReplaceInstUsesWith(I, B);
4150 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4151 return ReplaceInstUsesWith(I, B);
4154 V1 = 0; V2 = 0; V3 = 0;
4157 // Check to see if we have any common things being and'ed. If so, find the
4158 // terms for V1 & (V2|V3).
4159 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4160 if (A == B) // (A & C)|(A & D) == A & (C|D)
4161 V1 = A, V2 = C, V3 = D;
4162 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4163 V1 = A, V2 = B, V3 = C;
4164 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4165 V1 = C, V2 = A, V3 = D;
4166 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4167 V1 = C, V2 = A, V3 = B;
4171 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
4172 return BinaryOperator::createAnd(V1, Or);
4177 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4178 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4179 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4180 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4181 SI0->getOperand(1) == SI1->getOperand(1) &&
4182 (SI0->hasOneUse() || SI1->hasOneUse())) {
4183 Instruction *NewOp =
4184 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4186 SI0->getName()), I);
4187 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4188 SI1->getOperand(1));
4192 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4193 if (A == Op1) // ~A | A == -1
4194 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4198 // Note, A is still live here!
4199 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4201 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4203 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4204 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4205 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4206 I.getName()+".demorgan"), I);
4207 return BinaryOperator::createNot(And);
4211 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4212 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4213 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4216 Value *LHSVal, *RHSVal;
4217 ConstantInt *LHSCst, *RHSCst;
4218 ICmpInst::Predicate LHSCC, RHSCC;
4219 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4220 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4221 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4222 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4223 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4224 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4225 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4226 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4227 // We can't fold (ugt x, C) | (sgt x, C2).
4228 PredicatesFoldable(LHSCC, RHSCC)) {
4229 // Ensure that the larger constant is on the RHS.
4230 ICmpInst *LHS = cast<ICmpInst>(Op0);
4232 if (ICmpInst::isSignedPredicate(LHSCC))
4233 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4235 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4238 std::swap(LHS, RHS);
4239 std::swap(LHSCst, RHSCst);
4240 std::swap(LHSCC, RHSCC);
4243 // At this point, we know we have have two icmp instructions
4244 // comparing a value against two constants and or'ing the result
4245 // together. Because of the above check, we know that we only have
4246 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4247 // FoldICmpLogical check above), that the two constants are not
4249 assert(LHSCst != RHSCst && "Compares not folded above?");
4252 default: assert(0 && "Unknown integer condition code!");
4253 case ICmpInst::ICMP_EQ:
4255 default: assert(0 && "Unknown integer condition code!");
4256 case ICmpInst::ICMP_EQ:
4257 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4258 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4259 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4260 LHSVal->getName()+".off");
4261 InsertNewInstBefore(Add, I);
4262 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4263 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4265 break; // (X == 13 | X == 15) -> no change
4266 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4267 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4269 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4270 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4271 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4272 return ReplaceInstUsesWith(I, RHS);
4275 case ICmpInst::ICMP_NE:
4277 default: assert(0 && "Unknown integer condition code!");
4278 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4279 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4280 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4281 return ReplaceInstUsesWith(I, LHS);
4282 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4283 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4284 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4285 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4288 case ICmpInst::ICMP_ULT:
4290 default: assert(0 && "Unknown integer condition code!");
4291 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4293 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
4294 // If RHSCst is [us]MAXINT, it is always false. Not handling
4295 // this can cause overflow.
4296 if (RHSCst->isMaxValue(false))
4297 return ReplaceInstUsesWith(I, LHS);
4298 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4300 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4302 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4303 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4304 return ReplaceInstUsesWith(I, RHS);
4305 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4309 case ICmpInst::ICMP_SLT:
4311 default: assert(0 && "Unknown integer condition code!");
4312 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4314 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
4315 // If RHSCst is [us]MAXINT, it is always false. Not handling
4316 // this can cause overflow.
4317 if (RHSCst->isMaxValue(true))
4318 return ReplaceInstUsesWith(I, LHS);
4319 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4321 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4323 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4324 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4325 return ReplaceInstUsesWith(I, RHS);
4326 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4330 case ICmpInst::ICMP_UGT:
4332 default: assert(0 && "Unknown integer condition code!");
4333 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4334 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4335 return ReplaceInstUsesWith(I, LHS);
4336 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4338 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4339 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4340 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4341 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4345 case ICmpInst::ICMP_SGT:
4347 default: assert(0 && "Unknown integer condition code!");
4348 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4349 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4350 return ReplaceInstUsesWith(I, LHS);
4351 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4353 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4354 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4355 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4356 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4364 // fold (or (cast A), (cast B)) -> (cast (or A, B))
4365 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4366 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4367 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4368 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4369 !isa<ICmpInst>(Op1C->getOperand(0))) {
4370 const Type *SrcTy = Op0C->getOperand(0)->getType();
4371 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4372 // Only do this if the casts both really cause code to be
4374 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4376 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4378 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4379 Op1C->getOperand(0),
4381 InsertNewInstBefore(NewOp, I);
4382 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4389 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4390 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4391 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4392 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4393 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4394 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
4395 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4396 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4397 // If either of the constants are nans, then the whole thing returns
4399 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4400 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4402 // Otherwise, no need to compare the two constants, compare the
4404 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4405 RHS->getOperand(0));
4410 return Changed ? &I : 0;
4413 // XorSelf - Implements: X ^ X --> 0
4416 XorSelf(Value *rhs) : RHS(rhs) {}
4417 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4418 Instruction *apply(BinaryOperator &Xor) const {
4424 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4425 bool Changed = SimplifyCommutative(I);
4426 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4428 if (isa<UndefValue>(Op1)) {
4429 if (isa<UndefValue>(Op0))
4430 // Handle undef ^ undef -> 0 special case. This is a common
4432 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4433 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4436 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4437 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4438 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4439 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4442 // See if we can simplify any instructions used by the instruction whose sole
4443 // purpose is to compute bits we don't care about.
4444 if (!isa<VectorType>(I.getType())) {
4445 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4446 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4447 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4448 KnownZero, KnownOne))
4450 } else if (isa<ConstantAggregateZero>(Op1)) {
4451 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4454 // Is this a ~ operation?
4455 if (Value *NotOp = dyn_castNotVal(&I)) {
4456 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4457 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4458 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4459 if (Op0I->getOpcode() == Instruction::And ||
4460 Op0I->getOpcode() == Instruction::Or) {
4461 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4462 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4464 BinaryOperator::createNot(Op0I->getOperand(1),
4465 Op0I->getOperand(1)->getName()+".not");
4466 InsertNewInstBefore(NotY, I);
4467 if (Op0I->getOpcode() == Instruction::And)
4468 return BinaryOperator::createOr(Op0NotVal, NotY);
4470 return BinaryOperator::createAnd(Op0NotVal, NotY);
4477 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4478 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4479 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4480 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4481 return new ICmpInst(ICI->getInversePredicate(),
4482 ICI->getOperand(0), ICI->getOperand(1));
4484 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4485 return new FCmpInst(FCI->getInversePredicate(),
4486 FCI->getOperand(0), FCI->getOperand(1));
4489 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4490 // ~(c-X) == X-c-1 == X+(-c-1)
4491 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4492 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4493 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4494 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4495 ConstantInt::get(I.getType(), 1));
4496 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
4499 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4500 if (Op0I->getOpcode() == Instruction::Add) {
4501 // ~(X-c) --> (-c-1)-X
4502 if (RHS->isAllOnesValue()) {
4503 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4504 return BinaryOperator::createSub(
4505 ConstantExpr::getSub(NegOp0CI,
4506 ConstantInt::get(I.getType(), 1)),
4507 Op0I->getOperand(0));
4508 } else if (RHS->getValue().isSignBit()) {
4509 // (X + C) ^ signbit -> (X + C + signbit)
4510 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4511 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
4514 } else if (Op0I->getOpcode() == Instruction::Or) {
4515 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4516 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4517 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4518 // Anything in both C1 and C2 is known to be zero, remove it from
4520 Constant *CommonBits = And(Op0CI, RHS);
4521 NewRHS = ConstantExpr::getAnd(NewRHS,
4522 ConstantExpr::getNot(CommonBits));
4523 AddToWorkList(Op0I);
4524 I.setOperand(0, Op0I->getOperand(0));
4525 I.setOperand(1, NewRHS);
4532 // Try to fold constant and into select arguments.
4533 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4534 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4536 if (isa<PHINode>(Op0))
4537 if (Instruction *NV = FoldOpIntoPhi(I))
4541 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4543 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4545 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4547 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4550 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4553 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4554 if (A == Op0) { // B^(B|A) == (A|B)^B
4555 Op1I->swapOperands();
4557 std::swap(Op0, Op1);
4558 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4559 I.swapOperands(); // Simplified below.
4560 std::swap(Op0, Op1);
4562 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4563 if (Op0 == A) // A^(A^B) == B
4564 return ReplaceInstUsesWith(I, B);
4565 else if (Op0 == B) // A^(B^A) == B
4566 return ReplaceInstUsesWith(I, A);
4567 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4568 if (A == Op0) { // A^(A&B) -> A^(B&A)
4569 Op1I->swapOperands();
4572 if (B == Op0) { // A^(B&A) -> (B&A)^A
4573 I.swapOperands(); // Simplified below.
4574 std::swap(Op0, Op1);
4579 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4582 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4583 if (A == Op1) // (B|A)^B == (A|B)^B
4585 if (B == Op1) { // (A|B)^B == A & ~B
4587 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4588 return BinaryOperator::createAnd(A, NotB);
4590 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4591 if (Op1 == A) // (A^B)^A == B
4592 return ReplaceInstUsesWith(I, B);
4593 else if (Op1 == B) // (B^A)^A == B
4594 return ReplaceInstUsesWith(I, A);
4595 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4596 if (A == Op1) // (A&B)^A -> (B&A)^A
4598 if (B == Op1 && // (B&A)^A == ~B & A
4599 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
4601 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
4602 return BinaryOperator::createAnd(N, Op1);
4607 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4608 if (Op0I && Op1I && Op0I->isShift() &&
4609 Op0I->getOpcode() == Op1I->getOpcode() &&
4610 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4611 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4612 Instruction *NewOp =
4613 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4614 Op1I->getOperand(0),
4615 Op0I->getName()), I);
4616 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4617 Op1I->getOperand(1));
4621 Value *A, *B, *C, *D;
4622 // (A & B)^(A | B) -> A ^ B
4623 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4624 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4625 if ((A == C && B == D) || (A == D && B == C))
4626 return BinaryOperator::createXor(A, B);
4628 // (A | B)^(A & B) -> A ^ B
4629 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4630 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4631 if ((A == C && B == D) || (A == D && B == C))
4632 return BinaryOperator::createXor(A, B);
4636 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4637 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4638 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4639 // (X & Y)^(X & Y) -> (Y^Z) & X
4640 Value *X = 0, *Y = 0, *Z = 0;
4642 X = A, Y = B, Z = D;
4644 X = A, Y = B, Z = C;
4646 X = B, Y = A, Z = D;
4648 X = B, Y = A, Z = C;
4651 Instruction *NewOp =
4652 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4653 return BinaryOperator::createAnd(NewOp, X);
4658 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4659 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4660 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4663 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4664 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4665 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4666 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4667 const Type *SrcTy = Op0C->getOperand(0)->getType();
4668 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4669 // Only do this if the casts both really cause code to be generated.
4670 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4672 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4674 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4675 Op1C->getOperand(0),
4677 InsertNewInstBefore(NewOp, I);
4678 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4682 return Changed ? &I : 0;
4685 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4686 /// overflowed for this type.
4687 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4688 ConstantInt *In2, bool IsSigned = false) {
4689 Result = cast<ConstantInt>(Add(In1, In2));
4692 if (In2->getValue().isNegative())
4693 return Result->getValue().sgt(In1->getValue());
4695 return Result->getValue().slt(In1->getValue());
4697 return Result->getValue().ult(In1->getValue());
4700 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4701 /// code necessary to compute the offset from the base pointer (without adding
4702 /// in the base pointer). Return the result as a signed integer of intptr size.
4703 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4704 TargetData &TD = IC.getTargetData();
4705 gep_type_iterator GTI = gep_type_begin(GEP);
4706 const Type *IntPtrTy = TD.getIntPtrType();
4707 Value *Result = Constant::getNullValue(IntPtrTy);
4709 // Build a mask for high order bits.
4710 unsigned IntPtrWidth = TD.getPointerSize()*8;
4711 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4713 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4714 Value *Op = GEP->getOperand(i);
4715 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
4716 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4717 if (OpC->isZero()) continue;
4719 // Handle a struct index, which adds its field offset to the pointer.
4720 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4721 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4723 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4724 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4726 Result = IC.InsertNewInstBefore(
4727 BinaryOperator::createAdd(Result,
4728 ConstantInt::get(IntPtrTy, Size),
4729 GEP->getName()+".offs"), I);
4733 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4734 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4735 Scale = ConstantExpr::getMul(OC, Scale);
4736 if (Constant *RC = dyn_cast<Constant>(Result))
4737 Result = ConstantExpr::getAdd(RC, Scale);
4739 // Emit an add instruction.
4740 Result = IC.InsertNewInstBefore(
4741 BinaryOperator::createAdd(Result, Scale,
4742 GEP->getName()+".offs"), I);
4746 // Convert to correct type.
4747 if (Op->getType() != IntPtrTy) {
4748 if (Constant *OpC = dyn_cast<Constant>(Op))
4749 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4751 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4752 Op->getName()+".c"), I);
4755 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4756 if (Constant *OpC = dyn_cast<Constant>(Op))
4757 Op = ConstantExpr::getMul(OpC, Scale);
4758 else // We'll let instcombine(mul) convert this to a shl if possible.
4759 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4760 GEP->getName()+".idx"), I);
4763 // Emit an add instruction.
4764 if (isa<Constant>(Op) && isa<Constant>(Result))
4765 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4766 cast<Constant>(Result));
4768 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4769 GEP->getName()+".offs"), I);
4774 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4775 /// else. At this point we know that the GEP is on the LHS of the comparison.
4776 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4777 ICmpInst::Predicate Cond,
4779 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4781 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4782 if (isa<PointerType>(CI->getOperand(0)->getType()))
4783 RHS = CI->getOperand(0);
4785 Value *PtrBase = GEPLHS->getOperand(0);
4786 if (PtrBase == RHS) {
4787 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4788 // This transformation is valid because we know pointers can't overflow.
4789 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4790 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4791 Constant::getNullValue(Offset->getType()));
4792 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4793 // If the base pointers are different, but the indices are the same, just
4794 // compare the base pointer.
4795 if (PtrBase != GEPRHS->getOperand(0)) {
4796 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4797 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4798 GEPRHS->getOperand(0)->getType();
4800 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4801 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4802 IndicesTheSame = false;
4806 // If all indices are the same, just compare the base pointers.
4808 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4809 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4811 // Otherwise, the base pointers are different and the indices are
4812 // different, bail out.
4816 // If one of the GEPs has all zero indices, recurse.
4817 bool AllZeros = true;
4818 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4819 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4820 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4825 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4826 ICmpInst::getSwappedPredicate(Cond), I);
4828 // If the other GEP has all zero indices, recurse.
4830 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4831 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4832 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4837 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4839 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4840 // If the GEPs only differ by one index, compare it.
4841 unsigned NumDifferences = 0; // Keep track of # differences.
4842 unsigned DiffOperand = 0; // The operand that differs.
4843 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4844 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4845 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4846 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4847 // Irreconcilable differences.
4851 if (NumDifferences++) break;
4856 if (NumDifferences == 0) // SAME GEP?
4857 return ReplaceInstUsesWith(I, // No comparison is needed here.
4858 ConstantInt::get(Type::Int1Ty,
4859 isTrueWhenEqual(Cond)));
4861 else if (NumDifferences == 1) {
4862 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4863 Value *RHSV = GEPRHS->getOperand(DiffOperand);
4864 // Make sure we do a signed comparison here.
4865 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4869 // Only lower this if the icmp is the only user of the GEP or if we expect
4870 // the result to fold to a constant!
4871 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4872 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4873 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4874 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4875 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4876 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4882 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4883 bool Changed = SimplifyCompare(I);
4884 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4886 // Fold trivial predicates.
4887 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4888 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4889 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4890 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4892 // Simplify 'fcmp pred X, X'
4894 switch (I.getPredicate()) {
4895 default: assert(0 && "Unknown predicate!");
4896 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4897 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4898 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4899 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4900 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4901 case FCmpInst::FCMP_OLT: // True if ordered and less than
4902 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4903 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4905 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4906 case FCmpInst::FCMP_ULT: // True if unordered or less than
4907 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4908 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4909 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4910 I.setPredicate(FCmpInst::FCMP_UNO);
4911 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4914 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4915 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4916 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4917 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4918 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4919 I.setPredicate(FCmpInst::FCMP_ORD);
4920 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4925 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
4926 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4928 // Handle fcmp with constant RHS
4929 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4930 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4931 switch (LHSI->getOpcode()) {
4932 case Instruction::PHI:
4933 if (Instruction *NV = FoldOpIntoPhi(I))
4936 case Instruction::Select:
4937 // If either operand of the select is a constant, we can fold the
4938 // comparison into the select arms, which will cause one to be
4939 // constant folded and the select turned into a bitwise or.
4940 Value *Op1 = 0, *Op2 = 0;
4941 if (LHSI->hasOneUse()) {
4942 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4943 // Fold the known value into the constant operand.
4944 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4945 // Insert a new FCmp of the other select operand.
4946 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4947 LHSI->getOperand(2), RHSC,
4949 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4950 // Fold the known value into the constant operand.
4951 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4952 // Insert a new FCmp of the other select operand.
4953 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4954 LHSI->getOperand(1), RHSC,
4960 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4965 return Changed ? &I : 0;
4968 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4969 bool Changed = SimplifyCompare(I);
4970 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4971 const Type *Ty = Op0->getType();
4975 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4976 isTrueWhenEqual(I)));
4978 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
4979 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4981 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4982 // addresses never equal each other! We already know that Op0 != Op1.
4983 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4984 isa<ConstantPointerNull>(Op0)) &&
4985 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4986 isa<ConstantPointerNull>(Op1)))
4987 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4988 !isTrueWhenEqual(I)));
4990 // icmp's with boolean values can always be turned into bitwise operations
4991 if (Ty == Type::Int1Ty) {
4992 switch (I.getPredicate()) {
4993 default: assert(0 && "Invalid icmp instruction!");
4994 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
4995 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4996 InsertNewInstBefore(Xor, I);
4997 return BinaryOperator::createNot(Xor);
4999 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
5000 return BinaryOperator::createXor(Op0, Op1);
5002 case ICmpInst::ICMP_UGT:
5003 case ICmpInst::ICMP_SGT:
5004 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
5006 case ICmpInst::ICMP_ULT:
5007 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
5008 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5009 InsertNewInstBefore(Not, I);
5010 return BinaryOperator::createAnd(Not, Op1);
5012 case ICmpInst::ICMP_UGE:
5013 case ICmpInst::ICMP_SGE:
5014 std::swap(Op0, Op1); // Change icmp ge -> icmp le
5016 case ICmpInst::ICMP_ULE:
5017 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
5018 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
5019 InsertNewInstBefore(Not, I);
5020 return BinaryOperator::createOr(Not, Op1);
5025 // See if we are doing a comparison between a constant and an instruction that
5026 // can be folded into the comparison.
5027 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5030 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5031 if (I.isEquality() && CI->isNullValue() &&
5032 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5033 // (icmp cond A B) if cond is equality
5034 return new ICmpInst(I.getPredicate(), A, B);
5037 switch (I.getPredicate()) {
5039 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5040 if (CI->isMinValue(false))
5041 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5042 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5043 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5044 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5045 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5046 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5047 if (CI->isMinValue(true))
5048 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5049 ConstantInt::getAllOnesValue(Op0->getType()));
5053 case ICmpInst::ICMP_SLT:
5054 if (CI->isMinValue(true)) // A <s MIN -> FALSE
5055 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5056 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5057 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5058 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5059 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5062 case ICmpInst::ICMP_UGT:
5063 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
5064 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5065 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5066 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5067 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5068 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5070 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5071 if (CI->isMaxValue(true))
5072 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5073 ConstantInt::getNullValue(Op0->getType()));
5076 case ICmpInst::ICMP_SGT:
5077 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
5078 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5079 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5080 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5081 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5082 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5085 case ICmpInst::ICMP_ULE:
5086 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5087 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5088 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5089 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5090 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5091 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5094 case ICmpInst::ICMP_SLE:
5095 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5096 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5097 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5098 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5099 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5100 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5103 case ICmpInst::ICMP_UGE:
5104 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5105 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5106 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5107 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5108 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5109 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5112 case ICmpInst::ICMP_SGE:
5113 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5114 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5115 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5116 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5117 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5118 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5122 // If we still have a icmp le or icmp ge instruction, turn it into the
5123 // appropriate icmp lt or icmp gt instruction. Since the border cases have
5124 // already been handled above, this requires little checking.
5126 switch (I.getPredicate()) {
5128 case ICmpInst::ICMP_ULE:
5129 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5130 case ICmpInst::ICMP_SLE:
5131 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5132 case ICmpInst::ICMP_UGE:
5133 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5134 case ICmpInst::ICMP_SGE:
5135 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5138 // See if we can fold the comparison based on bits known to be zero or one
5139 // in the input. If this comparison is a normal comparison, it demands all
5140 // bits, if it is a sign bit comparison, it only demands the sign bit.
5143 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5145 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5146 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5147 if (SimplifyDemandedBits(Op0,
5148 isSignBit ? APInt::getSignBit(BitWidth)
5149 : APInt::getAllOnesValue(BitWidth),
5150 KnownZero, KnownOne, 0))
5153 // Given the known and unknown bits, compute a range that the LHS could be
5155 if ((KnownOne | KnownZero) != 0) {
5156 // Compute the Min, Max and RHS values based on the known bits. For the
5157 // EQ and NE we use unsigned values.
5158 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5159 const APInt& RHSVal = CI->getValue();
5160 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5161 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5164 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5167 switch (I.getPredicate()) { // LE/GE have been folded already.
5168 default: assert(0 && "Unknown icmp opcode!");
5169 case ICmpInst::ICMP_EQ:
5170 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5171 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5173 case ICmpInst::ICMP_NE:
5174 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5175 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5177 case ICmpInst::ICMP_ULT:
5178 if (Max.ult(RHSVal))
5179 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5180 if (Min.uge(RHSVal))
5181 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5183 case ICmpInst::ICMP_UGT:
5184 if (Min.ugt(RHSVal))
5185 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5186 if (Max.ule(RHSVal))
5187 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5189 case ICmpInst::ICMP_SLT:
5190 if (Max.slt(RHSVal))
5191 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5192 if (Min.sgt(RHSVal))
5193 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5195 case ICmpInst::ICMP_SGT:
5196 if (Min.sgt(RHSVal))
5197 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5198 if (Max.sle(RHSVal))
5199 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5204 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5205 // instruction, see if that instruction also has constants so that the
5206 // instruction can be folded into the icmp
5207 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5208 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5212 // Handle icmp with constant (but not simple integer constant) RHS
5213 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5214 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5215 switch (LHSI->getOpcode()) {
5216 case Instruction::GetElementPtr:
5217 if (RHSC->isNullValue()) {
5218 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5219 bool isAllZeros = true;
5220 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5221 if (!isa<Constant>(LHSI->getOperand(i)) ||
5222 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5227 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5228 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5232 case Instruction::PHI:
5233 if (Instruction *NV = FoldOpIntoPhi(I))
5236 case Instruction::Select: {
5237 // If either operand of the select is a constant, we can fold the
5238 // comparison into the select arms, which will cause one to be
5239 // constant folded and the select turned into a bitwise or.
5240 Value *Op1 = 0, *Op2 = 0;
5241 if (LHSI->hasOneUse()) {
5242 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5243 // Fold the known value into the constant operand.
5244 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5245 // Insert a new ICmp of the other select operand.
5246 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5247 LHSI->getOperand(2), RHSC,
5249 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5250 // Fold the known value into the constant operand.
5251 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5252 // Insert a new ICmp of the other select operand.
5253 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5254 LHSI->getOperand(1), RHSC,
5260 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5263 case Instruction::Malloc:
5264 // If we have (malloc != null), and if the malloc has a single use, we
5265 // can assume it is successful and remove the malloc.
5266 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5267 AddToWorkList(LHSI);
5268 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5269 !isTrueWhenEqual(I)));
5275 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5276 if (User *GEP = dyn_castGetElementPtr(Op0))
5277 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5279 if (User *GEP = dyn_castGetElementPtr(Op1))
5280 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5281 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5284 // Test to see if the operands of the icmp are casted versions of other
5285 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5287 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5288 if (isa<PointerType>(Op0->getType()) &&
5289 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
5290 // We keep moving the cast from the left operand over to the right
5291 // operand, where it can often be eliminated completely.
5292 Op0 = CI->getOperand(0);
5294 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5295 // so eliminate it as well.
5296 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5297 Op1 = CI2->getOperand(0);
5299 // If Op1 is a constant, we can fold the cast into the constant.
5300 if (Op0->getType() != Op1->getType()) {
5301 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5302 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5304 // Otherwise, cast the RHS right before the icmp
5305 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5308 return new ICmpInst(I.getPredicate(), Op0, Op1);
5312 if (isa<CastInst>(Op0)) {
5313 // Handle the special case of: icmp (cast bool to X), <cst>
5314 // This comes up when you have code like
5317 // For generality, we handle any zero-extension of any operand comparison
5318 // with a constant or another cast from the same type.
5319 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5320 if (Instruction *R = visitICmpInstWithCastAndCast(I))
5324 if (I.isEquality()) {
5325 Value *A, *B, *C, *D;
5326 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5327 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5328 Value *OtherVal = A == Op1 ? B : A;
5329 return new ICmpInst(I.getPredicate(), OtherVal,
5330 Constant::getNullValue(A->getType()));
5333 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5334 // A^c1 == C^c2 --> A == C^(c1^c2)
5335 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5336 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5337 if (Op1->hasOneUse()) {
5338 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5339 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5340 return new ICmpInst(I.getPredicate(), A,
5341 InsertNewInstBefore(Xor, I));
5344 // A^B == A^D -> B == D
5345 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5346 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5347 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5348 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5352 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5353 (A == Op0 || B == Op0)) {
5354 // A == (A^B) -> B == 0
5355 Value *OtherVal = A == Op0 ? B : A;
5356 return new ICmpInst(I.getPredicate(), OtherVal,
5357 Constant::getNullValue(A->getType()));
5359 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5360 // (A-B) == A -> B == 0
5361 return new ICmpInst(I.getPredicate(), B,
5362 Constant::getNullValue(B->getType()));
5364 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5365 // A == (A-B) -> B == 0
5366 return new ICmpInst(I.getPredicate(), B,
5367 Constant::getNullValue(B->getType()));
5370 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5371 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5372 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5373 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5374 Value *X = 0, *Y = 0, *Z = 0;
5377 X = B; Y = D; Z = A;
5378 } else if (A == D) {
5379 X = B; Y = C; Z = A;
5380 } else if (B == C) {
5381 X = A; Y = D; Z = B;
5382 } else if (B == D) {
5383 X = A; Y = C; Z = B;
5386 if (X) { // Build (X^Y) & Z
5387 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5388 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5389 I.setOperand(0, Op1);
5390 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5395 return Changed ? &I : 0;
5399 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5400 /// and CmpRHS are both known to be integer constants.
5401 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5402 ConstantInt *DivRHS) {
5403 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5404 const APInt &CmpRHSV = CmpRHS->getValue();
5406 // FIXME: If the operand types don't match the type of the divide
5407 // then don't attempt this transform. The code below doesn't have the
5408 // logic to deal with a signed divide and an unsigned compare (and
5409 // vice versa). This is because (x /s C1) <s C2 produces different
5410 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5411 // (x /u C1) <u C2. Simply casting the operands and result won't
5412 // work. :( The if statement below tests that condition and bails
5414 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5415 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5417 if (DivRHS->isZero())
5418 return 0; // The ProdOV computation fails on divide by zero.
5420 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5421 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5422 // C2 (CI). By solving for X we can turn this into a range check
5423 // instead of computing a divide.
5424 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5426 // Determine if the product overflows by seeing if the product is
5427 // not equal to the divide. Make sure we do the same kind of divide
5428 // as in the LHS instruction that we're folding.
5429 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5430 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5432 // Get the ICmp opcode
5433 ICmpInst::Predicate Pred = ICI.getPredicate();
5435 // Figure out the interval that is being checked. For example, a comparison
5436 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5437 // Compute this interval based on the constants involved and the signedness of
5438 // the compare/divide. This computes a half-open interval, keeping track of
5439 // whether either value in the interval overflows. After analysis each
5440 // overflow variable is set to 0 if it's corresponding bound variable is valid
5441 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5442 int LoOverflow = 0, HiOverflow = 0;
5443 ConstantInt *LoBound = 0, *HiBound = 0;
5446 if (!DivIsSigned) { // udiv
5447 // e.g. X/5 op 3 --> [15, 20)
5449 HiOverflow = LoOverflow = ProdOV;
5451 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5452 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
5453 if (CmpRHSV == 0) { // (X / pos) op 0
5454 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
5455 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5457 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
5458 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5459 HiOverflow = LoOverflow = ProdOV;
5461 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5462 } else { // (X / pos) op neg
5463 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
5464 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5465 LoOverflow = AddWithOverflow(LoBound, Prod,
5466 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5467 HiBound = AddOne(Prod);
5468 HiOverflow = ProdOV ? -1 : 0;
5470 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
5471 if (CmpRHSV == 0) { // (X / neg) op 0
5472 // e.g. X/-5 op 0 --> [-4, 5)
5473 LoBound = AddOne(DivRHS);
5474 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5475 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5476 HiOverflow = 1; // [INTMIN+1, overflow)
5477 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5479 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
5480 // e.g. X/-5 op 3 --> [-19, -14)
5481 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5483 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5484 HiBound = AddOne(Prod);
5485 } else { // (X / neg) op neg
5486 // e.g. X/-5 op -3 --> [15, 20)
5488 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5489 HiBound = Subtract(Prod, DivRHS);
5492 // Dividing by a negative swaps the condition. LT <-> GT
5493 Pred = ICmpInst::getSwappedPredicate(Pred);
5496 Value *X = DivI->getOperand(0);
5498 default: assert(0 && "Unhandled icmp opcode!");
5499 case ICmpInst::ICMP_EQ:
5500 if (LoOverflow && HiOverflow)
5501 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5502 else if (HiOverflow)
5503 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5504 ICmpInst::ICMP_UGE, X, LoBound);
5505 else if (LoOverflow)
5506 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5507 ICmpInst::ICMP_ULT, X, HiBound);
5509 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5510 case ICmpInst::ICMP_NE:
5511 if (LoOverflow && HiOverflow)
5512 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5513 else if (HiOverflow)
5514 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5515 ICmpInst::ICMP_ULT, X, LoBound);
5516 else if (LoOverflow)
5517 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5518 ICmpInst::ICMP_UGE, X, HiBound);
5520 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5521 case ICmpInst::ICMP_ULT:
5522 case ICmpInst::ICMP_SLT:
5523 if (LoOverflow == +1) // Low bound is greater than input range.
5524 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5525 if (LoOverflow == -1) // Low bound is less than input range.
5526 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5527 return new ICmpInst(Pred, X, LoBound);
5528 case ICmpInst::ICMP_UGT:
5529 case ICmpInst::ICMP_SGT:
5530 if (HiOverflow == +1) // High bound greater than input range.
5531 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5532 else if (HiOverflow == -1) // High bound less than input range.
5533 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5534 if (Pred == ICmpInst::ICMP_UGT)
5535 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5537 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5542 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5544 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5547 const APInt &RHSV = RHS->getValue();
5549 switch (LHSI->getOpcode()) {
5550 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
5551 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5552 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5554 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5555 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
5556 Value *CompareVal = LHSI->getOperand(0);
5558 // If the sign bit of the XorCST is not set, there is no change to
5559 // the operation, just stop using the Xor.
5560 if (!XorCST->getValue().isNegative()) {
5561 ICI.setOperand(0, CompareVal);
5562 AddToWorkList(LHSI);
5566 // Was the old condition true if the operand is positive?
5567 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5569 // If so, the new one isn't.
5570 isTrueIfPositive ^= true;
5572 if (isTrueIfPositive)
5573 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5575 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5579 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5580 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5581 LHSI->getOperand(0)->hasOneUse()) {
5582 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5584 // If the LHS is an AND of a truncating cast, we can widen the
5585 // and/compare to be the input width without changing the value
5586 // produced, eliminating a cast.
5587 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5588 // We can do this transformation if either the AND constant does not
5589 // have its sign bit set or if it is an equality comparison.
5590 // Extending a relational comparison when we're checking the sign
5591 // bit would not work.
5592 if (Cast->hasOneUse() &&
5593 (ICI.isEquality() ||
5594 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
5596 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5597 APInt NewCST = AndCST->getValue();
5598 NewCST.zext(BitWidth);
5600 NewCI.zext(BitWidth);
5601 Instruction *NewAnd =
5602 BinaryOperator::createAnd(Cast->getOperand(0),
5603 ConstantInt::get(NewCST),LHSI->getName());
5604 InsertNewInstBefore(NewAnd, ICI);
5605 return new ICmpInst(ICI.getPredicate(), NewAnd,
5606 ConstantInt::get(NewCI));
5610 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5611 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5612 // happens a LOT in code produced by the C front-end, for bitfield
5614 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5615 if (Shift && !Shift->isShift())
5619 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5620 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5621 const Type *AndTy = AndCST->getType(); // Type of the and.
5623 // We can fold this as long as we can't shift unknown bits
5624 // into the mask. This can only happen with signed shift
5625 // rights, as they sign-extend.
5627 bool CanFold = Shift->isLogicalShift();
5629 // To test for the bad case of the signed shr, see if any
5630 // of the bits shifted in could be tested after the mask.
5631 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5632 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5634 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5635 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5636 AndCST->getValue()) == 0)
5642 if (Shift->getOpcode() == Instruction::Shl)
5643 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5645 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5647 // Check to see if we are shifting out any of the bits being
5649 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5650 // If we shifted bits out, the fold is not going to work out.
5651 // As a special case, check to see if this means that the
5652 // result is always true or false now.
5653 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5654 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5655 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5656 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5658 ICI.setOperand(1, NewCst);
5659 Constant *NewAndCST;
5660 if (Shift->getOpcode() == Instruction::Shl)
5661 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5663 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5664 LHSI->setOperand(1, NewAndCST);
5665 LHSI->setOperand(0, Shift->getOperand(0));
5666 AddToWorkList(Shift); // Shift is dead.
5667 AddUsesToWorkList(ICI);
5673 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5674 // preferable because it allows the C<<Y expression to be hoisted out
5675 // of a loop if Y is invariant and X is not.
5676 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5677 ICI.isEquality() && !Shift->isArithmeticShift() &&
5678 isa<Instruction>(Shift->getOperand(0))) {
5681 if (Shift->getOpcode() == Instruction::LShr) {
5682 NS = BinaryOperator::createShl(AndCST,
5683 Shift->getOperand(1), "tmp");
5685 // Insert a logical shift.
5686 NS = BinaryOperator::createLShr(AndCST,
5687 Shift->getOperand(1), "tmp");
5689 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5691 // Compute X & (C << Y).
5692 Instruction *NewAnd =
5693 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5694 InsertNewInstBefore(NewAnd, ICI);
5696 ICI.setOperand(0, NewAnd);
5702 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5703 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5706 uint32_t TypeBits = RHSV.getBitWidth();
5708 // Check that the shift amount is in range. If not, don't perform
5709 // undefined shifts. When the shift is visited it will be
5711 if (ShAmt->uge(TypeBits))
5714 if (ICI.isEquality()) {
5715 // If we are comparing against bits always shifted out, the
5716 // comparison cannot succeed.
5718 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5719 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5720 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5721 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5722 return ReplaceInstUsesWith(ICI, Cst);
5725 if (LHSI->hasOneUse()) {
5726 // Otherwise strength reduce the shift into an and.
5727 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5729 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5732 BinaryOperator::createAnd(LHSI->getOperand(0),
5733 Mask, LHSI->getName()+".mask");
5734 Value *And = InsertNewInstBefore(AndI, ICI);
5735 return new ICmpInst(ICI.getPredicate(), And,
5736 ConstantInt::get(RHSV.lshr(ShAmtVal)));
5740 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5741 bool TrueIfSigned = false;
5742 if (LHSI->hasOneUse() &&
5743 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5744 // (X << 31) <s 0 --> (X&1) != 0
5745 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5746 (TypeBits-ShAmt->getZExtValue()-1));
5748 BinaryOperator::createAnd(LHSI->getOperand(0),
5749 Mask, LHSI->getName()+".mask");
5750 Value *And = InsertNewInstBefore(AndI, ICI);
5752 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5753 And, Constant::getNullValue(And->getType()));
5758 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
5759 case Instruction::AShr: {
5760 // Only handle equality comparisons of shift-by-constant.
5761 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5762 if (!ShAmt || !ICI.isEquality()) break;
5764 // Check that the shift amount is in range. If not, don't perform
5765 // undefined shifts. When the shift is visited it will be
5767 uint32_t TypeBits = RHSV.getBitWidth();
5768 if (ShAmt->uge(TypeBits))
5771 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5773 // If we are comparing against bits always shifted out, the
5774 // comparison cannot succeed.
5775 APInt Comp = RHSV << ShAmtVal;
5776 if (LHSI->getOpcode() == Instruction::LShr)
5777 Comp = Comp.lshr(ShAmtVal);
5779 Comp = Comp.ashr(ShAmtVal);
5781 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5782 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5783 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5784 return ReplaceInstUsesWith(ICI, Cst);
5787 // Otherwise, check to see if the bits shifted out are known to be zero.
5788 // If so, we can compare against the unshifted value:
5789 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
5790 if (MaskedValueIsZero(LHSI->getOperand(0),
5791 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5792 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5793 ConstantExpr::getShl(RHS, ShAmt));
5796 if (LHSI->hasOneUse() || RHSV == 0) {
5797 // Otherwise strength reduce the shift into an and.
5798 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5799 Constant *Mask = ConstantInt::get(Val);
5802 BinaryOperator::createAnd(LHSI->getOperand(0),
5803 Mask, LHSI->getName()+".mask");
5804 Value *And = InsertNewInstBefore(AndI, ICI);
5805 return new ICmpInst(ICI.getPredicate(), And,
5806 ConstantExpr::getShl(RHS, ShAmt));
5811 case Instruction::SDiv:
5812 case Instruction::UDiv:
5813 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5814 // Fold this div into the comparison, producing a range check.
5815 // Determine, based on the divide type, what the range is being
5816 // checked. If there is an overflow on the low or high side, remember
5817 // it, otherwise compute the range [low, hi) bounding the new value.
5818 // See: InsertRangeTest above for the kinds of replacements possible.
5819 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5820 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5825 case Instruction::Add:
5826 // Fold: icmp pred (add, X, C1), C2
5828 if (!ICI.isEquality()) {
5829 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5831 const APInt &LHSV = LHSC->getValue();
5833 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5836 if (ICI.isSignedPredicate()) {
5837 if (CR.getLower().isSignBit()) {
5838 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
5839 ConstantInt::get(CR.getUpper()));
5840 } else if (CR.getUpper().isSignBit()) {
5841 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
5842 ConstantInt::get(CR.getLower()));
5845 if (CR.getLower().isMinValue()) {
5846 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
5847 ConstantInt::get(CR.getUpper()));
5848 } else if (CR.getUpper().isMinValue()) {
5849 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
5850 ConstantInt::get(CR.getLower()));
5857 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5858 if (ICI.isEquality()) {
5859 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5861 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5862 // the second operand is a constant, simplify a bit.
5863 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5864 switch (BO->getOpcode()) {
5865 case Instruction::SRem:
5866 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5867 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5868 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5869 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5870 Instruction *NewRem =
5871 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5873 InsertNewInstBefore(NewRem, ICI);
5874 return new ICmpInst(ICI.getPredicate(), NewRem,
5875 Constant::getNullValue(BO->getType()));
5879 case Instruction::Add:
5880 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5881 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5882 if (BO->hasOneUse())
5883 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5884 Subtract(RHS, BOp1C));
5885 } else if (RHSV == 0) {
5886 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5887 // efficiently invertible, or if the add has just this one use.
5888 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5890 if (Value *NegVal = dyn_castNegVal(BOp1))
5891 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5892 else if (Value *NegVal = dyn_castNegVal(BOp0))
5893 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5894 else if (BO->hasOneUse()) {
5895 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5896 InsertNewInstBefore(Neg, ICI);
5898 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5902 case Instruction::Xor:
5903 // For the xor case, we can xor two constants together, eliminating
5904 // the explicit xor.
5905 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5906 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5907 ConstantExpr::getXor(RHS, BOC));
5910 case Instruction::Sub:
5911 // Replace (([sub|xor] A, B) != 0) with (A != B)
5913 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5917 case Instruction::Or:
5918 // If bits are being or'd in that are not present in the constant we
5919 // are comparing against, then the comparison could never succeed!
5920 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5921 Constant *NotCI = ConstantExpr::getNot(RHS);
5922 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5923 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5928 case Instruction::And:
5929 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5930 // If bits are being compared against that are and'd out, then the
5931 // comparison can never succeed!
5932 if ((RHSV & ~BOC->getValue()) != 0)
5933 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5936 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5937 if (RHS == BOC && RHSV.isPowerOf2())
5938 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5939 ICmpInst::ICMP_NE, LHSI,
5940 Constant::getNullValue(RHS->getType()));
5942 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5943 if (isSignBit(BOC)) {
5944 Value *X = BO->getOperand(0);
5945 Constant *Zero = Constant::getNullValue(X->getType());
5946 ICmpInst::Predicate pred = isICMP_NE ?
5947 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5948 return new ICmpInst(pred, X, Zero);
5951 // ((X & ~7) == 0) --> X < 8
5952 if (RHSV == 0 && isHighOnes(BOC)) {
5953 Value *X = BO->getOperand(0);
5954 Constant *NegX = ConstantExpr::getNeg(BOC);
5955 ICmpInst::Predicate pred = isICMP_NE ?
5956 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5957 return new ICmpInst(pred, X, NegX);
5962 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5963 // Handle icmp {eq|ne} <intrinsic>, intcst.
5964 if (II->getIntrinsicID() == Intrinsic::bswap) {
5966 ICI.setOperand(0, II->getOperand(1));
5967 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5971 } else { // Not a ICMP_EQ/ICMP_NE
5972 // If the LHS is a cast from an integral value of the same size,
5973 // then since we know the RHS is a constant, try to simlify.
5974 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5975 Value *CastOp = Cast->getOperand(0);
5976 const Type *SrcTy = CastOp->getType();
5977 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5978 if (SrcTy->isInteger() &&
5979 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5980 // If this is an unsigned comparison, try to make the comparison use
5981 // smaller constant values.
5982 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5983 // X u< 128 => X s> -1
5984 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5985 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5986 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5987 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5988 // X u> 127 => X s< 0
5989 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5990 Constant::getNullValue(SrcTy));
5998 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5999 /// We only handle extending casts so far.
6001 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6002 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6003 Value *LHSCIOp = LHSCI->getOperand(0);
6004 const Type *SrcTy = LHSCIOp->getType();
6005 const Type *DestTy = LHSCI->getType();
6008 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6009 // integer type is the same size as the pointer type.
6010 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6011 getTargetData().getPointerSizeInBits() ==
6012 cast<IntegerType>(DestTy)->getBitWidth()) {
6014 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6015 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6016 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6017 RHSOp = RHSC->getOperand(0);
6018 // If the pointer types don't match, insert a bitcast.
6019 if (LHSCIOp->getType() != RHSOp->getType())
6020 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6024 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6027 // The code below only handles extension cast instructions, so far.
6029 if (LHSCI->getOpcode() != Instruction::ZExt &&
6030 LHSCI->getOpcode() != Instruction::SExt)
6033 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6034 bool isSignedCmp = ICI.isSignedPredicate();
6036 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6037 // Not an extension from the same type?
6038 RHSCIOp = CI->getOperand(0);
6039 if (RHSCIOp->getType() != LHSCIOp->getType())
6042 // If the signedness of the two casts doesn't agree (i.e. one is a sext
6043 // and the other is a zext), then we can't handle this.
6044 if (CI->getOpcode() != LHSCI->getOpcode())
6047 // Deal with equality cases early.
6048 if (ICI.isEquality())
6049 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6051 // A signed comparison of sign extended values simplifies into a
6052 // signed comparison.
6053 if (isSignedCmp && isSignedExt)
6054 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6056 // The other three cases all fold into an unsigned comparison.
6057 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6060 // If we aren't dealing with a constant on the RHS, exit early
6061 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6065 // Compute the constant that would happen if we truncated to SrcTy then
6066 // reextended to DestTy.
6067 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6068 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6070 // If the re-extended constant didn't change...
6072 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6073 // For example, we might have:
6074 // %A = sext short %X to uint
6075 // %B = icmp ugt uint %A, 1330
6076 // It is incorrect to transform this into
6077 // %B = icmp ugt short %X, 1330
6078 // because %A may have negative value.
6080 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6081 // OR operation is EQ/NE.
6082 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6083 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6088 // The re-extended constant changed so the constant cannot be represented
6089 // in the shorter type. Consequently, we cannot emit a simple comparison.
6091 // First, handle some easy cases. We know the result cannot be equal at this
6092 // point so handle the ICI.isEquality() cases
6093 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6094 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6095 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6096 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6098 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6099 // should have been folded away previously and not enter in here.
6102 // We're performing a signed comparison.
6103 if (cast<ConstantInt>(CI)->getValue().isNegative())
6104 Result = ConstantInt::getFalse(); // X < (small) --> false
6106 Result = ConstantInt::getTrue(); // X < (large) --> true
6108 // We're performing an unsigned comparison.
6110 // We're performing an unsigned comp with a sign extended value.
6111 // This is true if the input is >= 0. [aka >s -1]
6112 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6113 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6114 NegOne, ICI.getName()), ICI);
6116 // Unsigned extend & unsigned compare -> always true.
6117 Result = ConstantInt::getTrue();
6121 // Finally, return the value computed.
6122 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6123 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6124 return ReplaceInstUsesWith(ICI, Result);
6126 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6127 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6128 "ICmp should be folded!");
6129 if (Constant *CI = dyn_cast<Constant>(Result))
6130 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6132 return BinaryOperator::createNot(Result);
6136 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6137 return commonShiftTransforms(I);
6140 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6141 return commonShiftTransforms(I);
6144 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6145 if (Instruction *R = commonShiftTransforms(I))
6148 Value *Op0 = I.getOperand(0);
6150 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6151 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6152 if (CSI->isAllOnesValue())
6153 return ReplaceInstUsesWith(I, CSI);
6155 // See if we can turn a signed shr into an unsigned shr.
6156 if (MaskedValueIsZero(Op0,
6157 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6158 return BinaryOperator::createLShr(Op0, I.getOperand(1));
6163 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6164 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6165 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6167 // shl X, 0 == X and shr X, 0 == X
6168 // shl 0, X == 0 and shr 0, X == 0
6169 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6170 Op0 == Constant::getNullValue(Op0->getType()))
6171 return ReplaceInstUsesWith(I, Op0);
6173 if (isa<UndefValue>(Op0)) {
6174 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6175 return ReplaceInstUsesWith(I, Op0);
6176 else // undef << X -> 0, undef >>u X -> 0
6177 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6179 if (isa<UndefValue>(Op1)) {
6180 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6181 return ReplaceInstUsesWith(I, Op0);
6182 else // X << undef, X >>u undef -> 0
6183 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6186 // Try to fold constant and into select arguments.
6187 if (isa<Constant>(Op0))
6188 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6189 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6192 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6193 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6198 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6199 BinaryOperator &I) {
6200 bool isLeftShift = I.getOpcode() == Instruction::Shl;
6202 // See if we can simplify any instructions used by the instruction whose sole
6203 // purpose is to compute bits we don't care about.
6204 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6205 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6206 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6207 KnownZero, KnownOne))
6210 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6211 // of a signed value.
6213 if (Op1->uge(TypeBits)) {
6214 if (I.getOpcode() != Instruction::AShr)
6215 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6217 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6222 // ((X*C1) << C2) == (X * (C1 << C2))
6223 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6224 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6225 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6226 return BinaryOperator::createMul(BO->getOperand(0),
6227 ConstantExpr::getShl(BOOp, Op1));
6229 // Try to fold constant and into select arguments.
6230 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6231 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6233 if (isa<PHINode>(Op0))
6234 if (Instruction *NV = FoldOpIntoPhi(I))
6237 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6238 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6239 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6240 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6241 // place. Don't try to do this transformation in this case. Also, we
6242 // require that the input operand is a shift-by-constant so that we have
6243 // confidence that the shifts will get folded together. We could do this
6244 // xform in more cases, but it is unlikely to be profitable.
6245 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6246 isa<ConstantInt>(TrOp->getOperand(1))) {
6247 // Okay, we'll do this xform. Make the shift of shift.
6248 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6249 Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6251 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6253 // For logical shifts, the truncation has the effect of making the high
6254 // part of the register be zeros. Emulate this by inserting an AND to
6255 // clear the top bits as needed. This 'and' will usually be zapped by
6256 // other xforms later if dead.
6257 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6258 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6259 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6261 // The mask we constructed says what the trunc would do if occurring
6262 // between the shifts. We want to know the effect *after* the second
6263 // shift. We know that it is a logical shift by a constant, so adjust the
6264 // mask as appropriate.
6265 if (I.getOpcode() == Instruction::Shl)
6266 MaskV <<= Op1->getZExtValue();
6268 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6269 MaskV = MaskV.lshr(Op1->getZExtValue());
6272 Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6274 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6276 // Return the value truncated to the interesting size.
6277 return new TruncInst(And, I.getType());
6281 if (Op0->hasOneUse()) {
6282 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6283 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6286 switch (Op0BO->getOpcode()) {
6288 case Instruction::Add:
6289 case Instruction::And:
6290 case Instruction::Or:
6291 case Instruction::Xor: {
6292 // These operators commute.
6293 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
6294 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6295 match(Op0BO->getOperand(1),
6296 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6297 Instruction *YS = BinaryOperator::createShl(
6298 Op0BO->getOperand(0), Op1,
6300 InsertNewInstBefore(YS, I); // (Y << C)
6302 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6303 Op0BO->getOperand(1)->getName());
6304 InsertNewInstBefore(X, I); // (X + (Y << C))
6305 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6306 return BinaryOperator::createAnd(X, ConstantInt::get(
6307 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6310 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
6311 Value *Op0BOOp1 = Op0BO->getOperand(1);
6312 if (isLeftShift && Op0BOOp1->hasOneUse() &&
6314 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6315 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6317 Instruction *YS = BinaryOperator::createShl(
6318 Op0BO->getOperand(0), Op1,
6320 InsertNewInstBefore(YS, I); // (Y << C)
6322 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6323 V1->getName()+".mask");
6324 InsertNewInstBefore(XM, I); // X & (CC << C)
6326 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6331 case Instruction::Sub: {
6332 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6333 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6334 match(Op0BO->getOperand(0),
6335 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6336 Instruction *YS = BinaryOperator::createShl(
6337 Op0BO->getOperand(1), Op1,
6339 InsertNewInstBefore(YS, I); // (Y << C)
6341 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
6342 Op0BO->getOperand(0)->getName());
6343 InsertNewInstBefore(X, I); // (X + (Y << C))
6344 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6345 return BinaryOperator::createAnd(X, ConstantInt::get(
6346 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6349 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
6350 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6351 match(Op0BO->getOperand(0),
6352 m_And(m_Shr(m_Value(V1), m_Value(V2)),
6353 m_ConstantInt(CC))) && V2 == Op1 &&
6354 cast<BinaryOperator>(Op0BO->getOperand(0))
6355 ->getOperand(0)->hasOneUse()) {
6356 Instruction *YS = BinaryOperator::createShl(
6357 Op0BO->getOperand(1), Op1,
6359 InsertNewInstBefore(YS, I); // (Y << C)
6361 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6362 V1->getName()+".mask");
6363 InsertNewInstBefore(XM, I); // X & (CC << C)
6365 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
6373 // If the operand is an bitwise operator with a constant RHS, and the
6374 // shift is the only use, we can pull it out of the shift.
6375 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6376 bool isValid = true; // Valid only for And, Or, Xor
6377 bool highBitSet = false; // Transform if high bit of constant set?
6379 switch (Op0BO->getOpcode()) {
6380 default: isValid = false; break; // Do not perform transform!
6381 case Instruction::Add:
6382 isValid = isLeftShift;
6384 case Instruction::Or:
6385 case Instruction::Xor:
6388 case Instruction::And:
6393 // If this is a signed shift right, and the high bit is modified
6394 // by the logical operation, do not perform the transformation.
6395 // The highBitSet boolean indicates the value of the high bit of
6396 // the constant which would cause it to be modified for this
6399 if (isValid && I.getOpcode() == Instruction::AShr)
6400 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6403 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6405 Instruction *NewShift =
6406 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6407 InsertNewInstBefore(NewShift, I);
6408 NewShift->takeName(Op0BO);
6410 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6417 // Find out if this is a shift of a shift by a constant.
6418 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6419 if (ShiftOp && !ShiftOp->isShift())
6422 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6423 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6424 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6425 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6426 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6427 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6428 Value *X = ShiftOp->getOperand(0);
6430 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
6431 if (AmtSum > TypeBits)
6434 const IntegerType *Ty = cast<IntegerType>(I.getType());
6436 // Check for (X << c1) << c2 and (X >> c1) >> c2
6437 if (I.getOpcode() == ShiftOp->getOpcode()) {
6438 return BinaryOperator::create(I.getOpcode(), X,
6439 ConstantInt::get(Ty, AmtSum));
6440 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6441 I.getOpcode() == Instruction::AShr) {
6442 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6443 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6444 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6445 I.getOpcode() == Instruction::LShr) {
6446 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6447 Instruction *Shift =
6448 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6449 InsertNewInstBefore(Shift, I);
6451 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6452 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6455 // Okay, if we get here, one shift must be left, and the other shift must be
6456 // right. See if the amounts are equal.
6457 if (ShiftAmt1 == ShiftAmt2) {
6458 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6459 if (I.getOpcode() == Instruction::Shl) {
6460 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6461 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6463 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6464 if (I.getOpcode() == Instruction::LShr) {
6465 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6466 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6468 // We can simplify ((X << C) >>s C) into a trunc + sext.
6469 // NOTE: we could do this for any C, but that would make 'unusual' integer
6470 // types. For now, just stick to ones well-supported by the code
6472 const Type *SExtType = 0;
6473 switch (Ty->getBitWidth() - ShiftAmt1) {
6480 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6485 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6486 InsertNewInstBefore(NewTrunc, I);
6487 return new SExtInst(NewTrunc, Ty);
6489 // Otherwise, we can't handle it yet.
6490 } else if (ShiftAmt1 < ShiftAmt2) {
6491 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6493 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6494 if (I.getOpcode() == Instruction::Shl) {
6495 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6496 ShiftOp->getOpcode() == Instruction::AShr);
6497 Instruction *Shift =
6498 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6499 InsertNewInstBefore(Shift, I);
6501 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6502 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6505 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
6506 if (I.getOpcode() == Instruction::LShr) {
6507 assert(ShiftOp->getOpcode() == Instruction::Shl);
6508 Instruction *Shift =
6509 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6510 InsertNewInstBefore(Shift, I);
6512 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6513 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6516 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6518 assert(ShiftAmt2 < ShiftAmt1);
6519 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6521 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6522 if (I.getOpcode() == Instruction::Shl) {
6523 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6524 ShiftOp->getOpcode() == Instruction::AShr);
6525 Instruction *Shift =
6526 BinaryOperator::create(ShiftOp->getOpcode(), X,
6527 ConstantInt::get(Ty, ShiftDiff));
6528 InsertNewInstBefore(Shift, I);
6530 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6531 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6534 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
6535 if (I.getOpcode() == Instruction::LShr) {
6536 assert(ShiftOp->getOpcode() == Instruction::Shl);
6537 Instruction *Shift =
6538 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6539 InsertNewInstBefore(Shift, I);
6541 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6542 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6545 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6552 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6553 /// expression. If so, decompose it, returning some value X, such that Val is
6556 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6558 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6559 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6560 Offset = CI->getZExtValue();
6562 return ConstantInt::get(Type::Int32Ty, 0);
6563 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6564 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6565 if (I->getOpcode() == Instruction::Shl) {
6566 // This is a value scaled by '1 << the shift amt'.
6567 Scale = 1U << RHS->getZExtValue();
6569 return I->getOperand(0);
6570 } else if (I->getOpcode() == Instruction::Mul) {
6571 // This value is scaled by 'RHS'.
6572 Scale = RHS->getZExtValue();
6574 return I->getOperand(0);
6575 } else if (I->getOpcode() == Instruction::Add) {
6576 // We have X+C. Check to see if we really have (X*C2)+C1,
6577 // where C1 is divisible by C2.
6580 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6581 Offset += RHS->getZExtValue();
6588 // Otherwise, we can't look past this.
6595 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6596 /// try to eliminate the cast by moving the type information into the alloc.
6597 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6598 AllocationInst &AI) {
6599 const PointerType *PTy = cast<PointerType>(CI.getType());
6601 // Remove any uses of AI that are dead.
6602 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6604 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6605 Instruction *User = cast<Instruction>(*UI++);
6606 if (isInstructionTriviallyDead(User)) {
6607 while (UI != E && *UI == User)
6608 ++UI; // If this instruction uses AI more than once, don't break UI.
6611 DOUT << "IC: DCE: " << *User;
6612 EraseInstFromFunction(*User);
6616 // Get the type really allocated and the type casted to.
6617 const Type *AllocElTy = AI.getAllocatedType();
6618 const Type *CastElTy = PTy->getElementType();
6619 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6621 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6622 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6623 if (CastElTyAlign < AllocElTyAlign) return 0;
6625 // If the allocation has multiple uses, only promote it if we are strictly
6626 // increasing the alignment of the resultant allocation. If we keep it the
6627 // same, we open the door to infinite loops of various kinds.
6628 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6630 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6631 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
6632 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6634 // See if we can satisfy the modulus by pulling a scale out of the array
6636 unsigned ArraySizeScale;
6638 Value *NumElements = // See if the array size is a decomposable linear expr.
6639 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6641 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6643 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6644 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
6646 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6651 // If the allocation size is constant, form a constant mul expression
6652 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6653 if (isa<ConstantInt>(NumElements))
6654 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6655 // otherwise multiply the amount and the number of elements
6656 else if (Scale != 1) {
6657 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6658 Amt = InsertNewInstBefore(Tmp, AI);
6662 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6663 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6664 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6665 Amt = InsertNewInstBefore(Tmp, AI);
6668 AllocationInst *New;
6669 if (isa<MallocInst>(AI))
6670 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6672 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6673 InsertNewInstBefore(New, AI);
6676 // If the allocation has multiple uses, insert a cast and change all things
6677 // that used it to use the new cast. This will also hack on CI, but it will
6679 if (!AI.hasOneUse()) {
6680 AddUsesToWorkList(AI);
6681 // New is the allocation instruction, pointer typed. AI is the original
6682 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6683 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6684 InsertNewInstBefore(NewCast, AI);
6685 AI.replaceAllUsesWith(NewCast);
6687 return ReplaceInstUsesWith(CI, New);
6690 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6691 /// and return it as type Ty without inserting any new casts and without
6692 /// changing the computed value. This is used by code that tries to decide
6693 /// whether promoting or shrinking integer operations to wider or smaller types
6694 /// will allow us to eliminate a truncate or extend.
6696 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6697 /// extension operation if Ty is larger.
6698 static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6699 unsigned CastOpc, int &NumCastsRemoved) {
6700 // We can always evaluate constants in another type.
6701 if (isa<ConstantInt>(V))
6704 Instruction *I = dyn_cast<Instruction>(V);
6705 if (!I) return false;
6707 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6709 // If this is an extension or truncate, we can often eliminate it.
6710 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6711 // If this is a cast from the destination type, we can trivially eliminate
6712 // it, and this will remove a cast overall.
6713 if (I->getOperand(0)->getType() == Ty) {
6714 // If the first operand is itself a cast, and is eliminable, do not count
6715 // this as an eliminable cast. We would prefer to eliminate those two
6717 if (!isa<CastInst>(I->getOperand(0)))
6723 // We can't extend or shrink something that has multiple uses: doing so would
6724 // require duplicating the instruction in general, which isn't profitable.
6725 if (!I->hasOneUse()) return false;
6727 switch (I->getOpcode()) {
6728 case Instruction::Add:
6729 case Instruction::Sub:
6730 case Instruction::And:
6731 case Instruction::Or:
6732 case Instruction::Xor:
6733 // These operators can all arbitrarily be extended or truncated.
6734 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6736 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6739 case Instruction::Mul:
6740 // A multiply can be truncated by truncating its operands.
6741 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6742 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6744 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6747 case Instruction::Shl:
6748 // If we are truncating the result of this SHL, and if it's a shift of a
6749 // constant amount, we can always perform a SHL in a smaller type.
6750 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6751 uint32_t BitWidth = Ty->getBitWidth();
6752 if (BitWidth < OrigTy->getBitWidth() &&
6753 CI->getLimitedValue(BitWidth) < BitWidth)
6754 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6758 case Instruction::LShr:
6759 // If this is a truncate of a logical shr, we can truncate it to a smaller
6760 // lshr iff we know that the bits we would otherwise be shifting in are
6762 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6763 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6764 uint32_t BitWidth = Ty->getBitWidth();
6765 if (BitWidth < OrigBitWidth &&
6766 MaskedValueIsZero(I->getOperand(0),
6767 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6768 CI->getLimitedValue(BitWidth) < BitWidth) {
6769 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6774 case Instruction::ZExt:
6775 case Instruction::SExt:
6776 case Instruction::Trunc:
6777 // If this is the same kind of case as our original (e.g. zext+zext), we
6778 // can safely replace it. Note that replacing it does not reduce the number
6779 // of casts in the input.
6780 if (I->getOpcode() == CastOpc)
6785 // TODO: Can handle more cases here.
6792 /// EvaluateInDifferentType - Given an expression that
6793 /// CanEvaluateInDifferentType returns true for, actually insert the code to
6794 /// evaluate the expression.
6795 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
6797 if (Constant *C = dyn_cast<Constant>(V))
6798 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6800 // Otherwise, it must be an instruction.
6801 Instruction *I = cast<Instruction>(V);
6802 Instruction *Res = 0;
6803 switch (I->getOpcode()) {
6804 case Instruction::Add:
6805 case Instruction::Sub:
6806 case Instruction::Mul:
6807 case Instruction::And:
6808 case Instruction::Or:
6809 case Instruction::Xor:
6810 case Instruction::AShr:
6811 case Instruction::LShr:
6812 case Instruction::Shl: {
6813 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6814 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6815 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6816 LHS, RHS, I->getName());
6819 case Instruction::Trunc:
6820 case Instruction::ZExt:
6821 case Instruction::SExt:
6822 // If the source type of the cast is the type we're trying for then we can
6823 // just return the source. There's no need to insert it because it is not
6825 if (I->getOperand(0)->getType() == Ty)
6826 return I->getOperand(0);
6828 // Otherwise, must be the same type of case, so just reinsert a new one.
6829 Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6833 // TODO: Can handle more cases here.
6834 assert(0 && "Unreachable!");
6838 return InsertNewInstBefore(Res, *I);
6841 /// @brief Implement the transforms common to all CastInst visitors.
6842 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6843 Value *Src = CI.getOperand(0);
6845 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
6846 // eliminate it now.
6847 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
6848 if (Instruction::CastOps opc =
6849 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6850 // The first cast (CSrc) is eliminable so we need to fix up or replace
6851 // the second cast (CI). CSrc will then have a good chance of being dead.
6852 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
6856 // If we are casting a select then fold the cast into the select
6857 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6858 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6861 // If we are casting a PHI then fold the cast into the PHI
6862 if (isa<PHINode>(Src))
6863 if (Instruction *NV = FoldOpIntoPhi(CI))
6869 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6870 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6871 Value *Src = CI.getOperand(0);
6873 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6874 // If casting the result of a getelementptr instruction with no offset, turn
6875 // this into a cast of the original pointer!
6876 if (GEP->hasAllZeroIndices()) {
6877 // Changing the cast operand is usually not a good idea but it is safe
6878 // here because the pointer operand is being replaced with another
6879 // pointer operand so the opcode doesn't need to change.
6881 CI.setOperand(0, GEP->getOperand(0));
6885 // If the GEP has a single use, and the base pointer is a bitcast, and the
6886 // GEP computes a constant offset, see if we can convert these three
6887 // instructions into fewer. This typically happens with unions and other
6888 // non-type-safe code.
6889 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6890 if (GEP->hasAllConstantIndices()) {
6891 // We are guaranteed to get a constant from EmitGEPOffset.
6892 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6893 int64_t Offset = OffsetV->getSExtValue();
6895 // Get the base pointer input of the bitcast, and the type it points to.
6896 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6897 const Type *GEPIdxTy =
6898 cast<PointerType>(OrigBase->getType())->getElementType();
6899 if (GEPIdxTy->isSized()) {
6900 SmallVector<Value*, 8> NewIndices;
6902 // Start with the index over the outer type. Note that the type size
6903 // might be zero (even if the offset isn't zero) if the indexed type
6904 // is something like [0 x {int, int}]
6905 const Type *IntPtrTy = TD->getIntPtrType();
6906 int64_t FirstIdx = 0;
6907 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
6908 FirstIdx = Offset/TySize;
6911 // Handle silly modulus not returning values values [0..TySize).
6915 assert(Offset >= 0);
6917 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
6920 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
6922 // Index into the types. If we fail, set OrigBase to null.
6924 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6925 const StructLayout *SL = TD->getStructLayout(STy);
6926 if (Offset < (int64_t)SL->getSizeInBytes()) {
6927 unsigned Elt = SL->getElementContainingOffset(Offset);
6928 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
6930 Offset -= SL->getElementOffset(Elt);
6931 GEPIdxTy = STy->getElementType(Elt);
6933 // Otherwise, we can't index into this, bail out.
6937 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6938 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
6939 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
6940 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6943 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6945 GEPIdxTy = STy->getElementType();
6947 // Otherwise, we can't index into this, bail out.
6953 // If we were able to index down into an element, create the GEP
6954 // and bitcast the result. This eliminates one bitcast, potentially
6956 Instruction *NGEP = new GetElementPtrInst(OrigBase,
6958 NewIndices.end(), "");
6959 InsertNewInstBefore(NGEP, CI);
6960 NGEP->takeName(GEP);
6962 if (isa<BitCastInst>(CI))
6963 return new BitCastInst(NGEP, CI.getType());
6964 assert(isa<PtrToIntInst>(CI));
6965 return new PtrToIntInst(NGEP, CI.getType());
6972 return commonCastTransforms(CI);
6977 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6978 /// integer types. This function implements the common transforms for all those
6980 /// @brief Implement the transforms common to CastInst with integer operands
6981 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6982 if (Instruction *Result = commonCastTransforms(CI))
6985 Value *Src = CI.getOperand(0);
6986 const Type *SrcTy = Src->getType();
6987 const Type *DestTy = CI.getType();
6988 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6989 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
6991 // See if we can simplify any instructions used by the LHS whose sole
6992 // purpose is to compute bits we don't care about.
6993 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6994 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
6995 KnownZero, KnownOne))
6998 // If the source isn't an instruction or has more than one use then we
6999 // can't do anything more.
7000 Instruction *SrcI = dyn_cast<Instruction>(Src);
7001 if (!SrcI || !Src->hasOneUse())
7004 // Attempt to propagate the cast into the instruction for int->int casts.
7005 int NumCastsRemoved = 0;
7006 if (!isa<BitCastInst>(CI) &&
7007 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7008 CI.getOpcode(), NumCastsRemoved)) {
7009 // If this cast is a truncate, evaluting in a different type always
7010 // eliminates the cast, so it is always a win. If this is a zero-extension,
7011 // we need to do an AND to maintain the clear top-part of the computation,
7012 // so we require that the input have eliminated at least one cast. If this
7013 // is a sign extension, we insert two new casts (to do the extension) so we
7014 // require that two casts have been eliminated.
7016 switch (CI.getOpcode()) {
7018 // All the others use floating point so we shouldn't actually
7019 // get here because of the check above.
7020 assert(0 && "Unknown cast type");
7021 case Instruction::Trunc:
7024 case Instruction::ZExt:
7025 DoXForm = NumCastsRemoved >= 1;
7027 case Instruction::SExt:
7028 DoXForm = NumCastsRemoved >= 2;
7033 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7034 CI.getOpcode() == Instruction::SExt);
7035 assert(Res->getType() == DestTy);
7036 switch (CI.getOpcode()) {
7037 default: assert(0 && "Unknown cast type!");
7038 case Instruction::Trunc:
7039 case Instruction::BitCast:
7040 // Just replace this cast with the result.
7041 return ReplaceInstUsesWith(CI, Res);
7042 case Instruction::ZExt: {
7043 // We need to emit an AND to clear the high bits.
7044 assert(SrcBitSize < DestBitSize && "Not a zext?");
7045 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7047 return BinaryOperator::createAnd(Res, C);
7049 case Instruction::SExt:
7050 // We need to emit a cast to truncate, then a cast to sext.
7051 return CastInst::create(Instruction::SExt,
7052 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7058 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7059 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7061 switch (SrcI->getOpcode()) {
7062 case Instruction::Add:
7063 case Instruction::Mul:
7064 case Instruction::And:
7065 case Instruction::Or:
7066 case Instruction::Xor:
7067 // If we are discarding information, rewrite.
7068 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7069 // Don't insert two casts if they cannot be eliminated. We allow
7070 // two casts to be inserted if the sizes are the same. This could
7071 // only be converting signedness, which is a noop.
7072 if (DestBitSize == SrcBitSize ||
7073 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7074 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7075 Instruction::CastOps opcode = CI.getOpcode();
7076 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7077 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7078 return BinaryOperator::create(
7079 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7083 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7084 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7085 SrcI->getOpcode() == Instruction::Xor &&
7086 Op1 == ConstantInt::getTrue() &&
7087 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7088 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7089 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
7092 case Instruction::SDiv:
7093 case Instruction::UDiv:
7094 case Instruction::SRem:
7095 case Instruction::URem:
7096 // If we are just changing the sign, rewrite.
7097 if (DestBitSize == SrcBitSize) {
7098 // Don't insert two casts if they cannot be eliminated. We allow
7099 // two casts to be inserted if the sizes are the same. This could
7100 // only be converting signedness, which is a noop.
7101 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7102 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7103 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7105 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7107 return BinaryOperator::create(
7108 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7113 case Instruction::Shl:
7114 // Allow changing the sign of the source operand. Do not allow
7115 // changing the size of the shift, UNLESS the shift amount is a
7116 // constant. We must not change variable sized shifts to a smaller
7117 // size, because it is undefined to shift more bits out than exist
7119 if (DestBitSize == SrcBitSize ||
7120 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7121 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7122 Instruction::BitCast : Instruction::Trunc);
7123 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7124 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7125 return BinaryOperator::createShl(Op0c, Op1c);
7128 case Instruction::AShr:
7129 // If this is a signed shr, and if all bits shifted in are about to be
7130 // truncated off, turn it into an unsigned shr to allow greater
7132 if (DestBitSize < SrcBitSize &&
7133 isa<ConstantInt>(Op1)) {
7134 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7135 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7136 // Insert the new logical shift right.
7137 return BinaryOperator::createLShr(Op0, Op1);
7145 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7146 if (Instruction *Result = commonIntCastTransforms(CI))
7149 Value *Src = CI.getOperand(0);
7150 const Type *Ty = CI.getType();
7151 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7152 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7154 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7155 switch (SrcI->getOpcode()) {
7157 case Instruction::LShr:
7158 // We can shrink lshr to something smaller if we know the bits shifted in
7159 // are already zeros.
7160 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7161 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7163 // Get a mask for the bits shifting in.
7164 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7165 Value* SrcIOp0 = SrcI->getOperand(0);
7166 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7167 if (ShAmt >= DestBitWidth) // All zeros.
7168 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7170 // Okay, we can shrink this. Truncate the input, then return a new
7172 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7173 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7175 return BinaryOperator::createLShr(V1, V2);
7177 } else { // This is a variable shr.
7179 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7180 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7181 // loop-invariant and CSE'd.
7182 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7183 Value *One = ConstantInt::get(SrcI->getType(), 1);
7185 Value *V = InsertNewInstBefore(
7186 BinaryOperator::createShl(One, SrcI->getOperand(1),
7188 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7189 SrcI->getOperand(0),
7191 Value *Zero = Constant::getNullValue(V->getType());
7192 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7202 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7203 /// in order to eliminate the icmp.
7204 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7206 // If we are just checking for a icmp eq of a single bit and zext'ing it
7207 // to an integer, then shift the bit to the appropriate place and then
7208 // cast to integer to avoid the comparison.
7209 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7210 const APInt &Op1CV = Op1C->getValue();
7212 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7213 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7214 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7215 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7216 if (!DoXform) return ICI;
7218 Value *In = ICI->getOperand(0);
7219 Value *Sh = ConstantInt::get(In->getType(),
7220 In->getType()->getPrimitiveSizeInBits()-1);
7221 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
7222 In->getName()+".lobit"),
7224 if (In->getType() != CI.getType())
7225 In = CastInst::createIntegerCast(In, CI.getType(),
7226 false/*ZExt*/, "tmp", &CI);
7228 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7229 Constant *One = ConstantInt::get(In->getType(), 1);
7230 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
7231 In->getName()+".not"),
7235 return ReplaceInstUsesWith(CI, In);
7240 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7241 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7242 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7243 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7244 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7245 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7246 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7247 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7248 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7249 // This only works for EQ and NE
7250 ICI->isEquality()) {
7251 // If Op1C some other power of two, convert:
7252 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7253 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7254 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7255 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7257 APInt KnownZeroMask(~KnownZero);
7258 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7259 if (!DoXform) return ICI;
7261 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7262 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7263 // (X&4) == 2 --> false
7264 // (X&4) != 2 --> true
7265 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7266 Res = ConstantExpr::getZExt(Res, CI.getType());
7267 return ReplaceInstUsesWith(CI, Res);
7270 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7271 Value *In = ICI->getOperand(0);
7273 // Perform a logical shr by shiftamt.
7274 // Insert the shift to put the result in the low bit.
7275 In = InsertNewInstBefore(BinaryOperator::createLShr(In,
7276 ConstantInt::get(In->getType(), ShiftAmt),
7277 In->getName()+".lobit"), CI);
7280 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7281 Constant *One = ConstantInt::get(In->getType(), 1);
7282 In = BinaryOperator::createXor(In, One, "tmp");
7283 InsertNewInstBefore(cast<Instruction>(In), CI);
7286 if (CI.getType() == In->getType())
7287 return ReplaceInstUsesWith(CI, In);
7289 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7297 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7298 // If one of the common conversion will work ..
7299 if (Instruction *Result = commonIntCastTransforms(CI))
7302 Value *Src = CI.getOperand(0);
7304 // If this is a cast of a cast
7305 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7306 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7307 // types and if the sizes are just right we can convert this into a logical
7308 // 'and' which will be much cheaper than the pair of casts.
7309 if (isa<TruncInst>(CSrc)) {
7310 // Get the sizes of the types involved
7311 Value *A = CSrc->getOperand(0);
7312 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7313 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7314 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7315 // If we're actually extending zero bits and the trunc is a no-op
7316 if (MidSize < DstSize && SrcSize == DstSize) {
7317 // Replace both of the casts with an And of the type mask.
7318 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7319 Constant *AndConst = ConstantInt::get(AndValue);
7321 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7322 // Unfortunately, if the type changed, we need to cast it back.
7323 if (And->getType() != CI.getType()) {
7324 And->setName(CSrc->getName()+".mask");
7325 InsertNewInstBefore(And, CI);
7326 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
7333 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7334 return transformZExtICmp(ICI, CI);
7336 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7337 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7338 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7339 // of the (zext icmp) will be transformed.
7340 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7341 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7342 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7343 (transformZExtICmp(LHS, CI, false) ||
7344 transformZExtICmp(RHS, CI, false))) {
7345 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7346 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7347 return BinaryOperator::create(Instruction::Or, LCast, RCast);
7354 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7355 if (Instruction *I = commonIntCastTransforms(CI))
7358 Value *Src = CI.getOperand(0);
7360 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7361 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7362 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7363 // If we are just checking for a icmp eq of a single bit and zext'ing it
7364 // to an integer, then shift the bit to the appropriate place and then
7365 // cast to integer to avoid the comparison.
7366 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7367 const APInt &Op1CV = Op1C->getValue();
7369 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7370 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7371 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7372 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7373 Value *In = ICI->getOperand(0);
7374 Value *Sh = ConstantInt::get(In->getType(),
7375 In->getType()->getPrimitiveSizeInBits()-1);
7376 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
7377 In->getName()+".lobit"),
7379 if (In->getType() != CI.getType())
7380 In = CastInst::createIntegerCast(In, CI.getType(),
7381 true/*SExt*/, "tmp", &CI);
7383 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7384 In = InsertNewInstBefore(BinaryOperator::createNot(In,
7385 In->getName()+".not"), CI);
7387 return ReplaceInstUsesWith(CI, In);
7395 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7396 /// in the specified FP type without changing its value.
7397 static Constant *FitsInFPType(ConstantFP *CFP, const Type *FPTy,
7398 const fltSemantics &Sem) {
7399 APFloat F = CFP->getValueAPF();
7400 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7401 return ConstantFP::get(FPTy, F);
7405 /// LookThroughFPExtensions - If this is an fp extension instruction, look
7406 /// through it until we get the source value.
7407 static Value *LookThroughFPExtensions(Value *V) {
7408 if (Instruction *I = dyn_cast<Instruction>(V))
7409 if (I->getOpcode() == Instruction::FPExt)
7410 return LookThroughFPExtensions(I->getOperand(0));
7412 // If this value is a constant, return the constant in the smallest FP type
7413 // that can accurately represent it. This allows us to turn
7414 // (float)((double)X+2.0) into x+2.0f.
7415 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7416 if (CFP->getType() == Type::PPC_FP128Ty)
7417 return V; // No constant folding of this.
7418 // See if the value can be truncated to float and then reextended.
7419 if (Value *V = FitsInFPType(CFP, Type::FloatTy, APFloat::IEEEsingle))
7421 if (CFP->getType() == Type::DoubleTy)
7422 return V; // Won't shrink.
7423 if (Value *V = FitsInFPType(CFP, Type::DoubleTy, APFloat::IEEEdouble))
7425 // Don't try to shrink to various long double types.
7431 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7432 if (Instruction *I = commonCastTransforms(CI))
7435 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7436 // smaller than the destination type, we can eliminate the truncate by doing
7437 // the add as the smaller type. This applies to add/sub/mul/div as well as
7438 // many builtins (sqrt, etc).
7439 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7440 if (OpI && OpI->hasOneUse()) {
7441 switch (OpI->getOpcode()) {
7443 case Instruction::Add:
7444 case Instruction::Sub:
7445 case Instruction::Mul:
7446 case Instruction::FDiv:
7447 case Instruction::FRem:
7448 const Type *SrcTy = OpI->getType();
7449 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7450 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7451 if (LHSTrunc->getType() != SrcTy &&
7452 RHSTrunc->getType() != SrcTy) {
7453 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7454 // If the source types were both smaller than the destination type of
7455 // the cast, do this xform.
7456 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7457 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7458 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7460 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7462 return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7471 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7472 return commonCastTransforms(CI);
7475 Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
7476 return commonCastTransforms(CI);
7479 Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
7480 return commonCastTransforms(CI);
7483 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7484 return commonCastTransforms(CI);
7487 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7488 return commonCastTransforms(CI);
7491 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7492 return commonPointerCastTransforms(CI);
7495 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7496 if (Instruction *I = commonCastTransforms(CI))
7499 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7500 if (!DestPointee->isSized()) return 0;
7502 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7505 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7506 m_ConstantInt(Cst)))) {
7507 // If the source and destination operands have the same type, see if this
7508 // is a single-index GEP.
7509 if (X->getType() == CI.getType()) {
7510 // Get the size of the pointee type.
7511 uint64_t Size = TD->getABITypeSize(DestPointee);
7513 // Convert the constant to intptr type.
7514 APInt Offset = Cst->getValue();
7515 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7517 // If Offset is evenly divisible by Size, we can do this xform.
7518 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7519 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7520 return new GetElementPtrInst(X, ConstantInt::get(Offset));
7523 // TODO: Could handle other cases, e.g. where add is indexing into field of
7525 } else if (CI.getOperand(0)->hasOneUse() &&
7526 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7527 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7528 // "inttoptr+GEP" instead of "add+intptr".
7530 // Get the size of the pointee type.
7531 uint64_t Size = TD->getABITypeSize(DestPointee);
7533 // Convert the constant to intptr type.
7534 APInt Offset = Cst->getValue();
7535 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7537 // If Offset is evenly divisible by Size, we can do this xform.
7538 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7539 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7541 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7543 return new GetElementPtrInst(P, ConstantInt::get(Offset), "tmp");
7549 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7550 // If the operands are integer typed then apply the integer transforms,
7551 // otherwise just apply the common ones.
7552 Value *Src = CI.getOperand(0);
7553 const Type *SrcTy = Src->getType();
7554 const Type *DestTy = CI.getType();
7556 if (SrcTy->isInteger() && DestTy->isInteger()) {
7557 if (Instruction *Result = commonIntCastTransforms(CI))
7559 } else if (isa<PointerType>(SrcTy)) {
7560 if (Instruction *I = commonPointerCastTransforms(CI))
7563 if (Instruction *Result = commonCastTransforms(CI))
7568 // Get rid of casts from one type to the same type. These are useless and can
7569 // be replaced by the operand.
7570 if (DestTy == Src->getType())
7571 return ReplaceInstUsesWith(CI, Src);
7573 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7574 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7575 const Type *DstElTy = DstPTy->getElementType();
7576 const Type *SrcElTy = SrcPTy->getElementType();
7578 // If we are casting a malloc or alloca to a pointer to a type of the same
7579 // size, rewrite the allocation instruction to allocate the "right" type.
7580 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7581 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7584 // If the source and destination are pointers, and this cast is equivalent
7585 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
7586 // This can enhance SROA and other transforms that want type-safe pointers.
7587 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7588 unsigned NumZeros = 0;
7589 while (SrcElTy != DstElTy &&
7590 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7591 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7592 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7596 // If we found a path from the src to dest, create the getelementptr now.
7597 if (SrcElTy == DstElTy) {
7598 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7599 return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "",
7600 ((Instruction*) NULL));
7604 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7605 if (SVI->hasOneUse()) {
7606 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7607 // a bitconvert to a vector with the same # elts.
7608 if (isa<VectorType>(DestTy) &&
7609 cast<VectorType>(DestTy)->getNumElements() ==
7610 SVI->getType()->getNumElements()) {
7612 // If either of the operands is a cast from CI.getType(), then
7613 // evaluating the shuffle in the casted destination's type will allow
7614 // us to eliminate at least one cast.
7615 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7616 Tmp->getOperand(0)->getType() == DestTy) ||
7617 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7618 Tmp->getOperand(0)->getType() == DestTy)) {
7619 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7620 SVI->getOperand(0), DestTy, &CI);
7621 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7622 SVI->getOperand(1), DestTy, &CI);
7623 // Return a new shuffle vector. Use the same element ID's, as we
7624 // know the vector types match #elts.
7625 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7633 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7635 /// %D = select %cond, %C, %A
7637 /// %C = select %cond, %B, 0
7640 /// Assuming that the specified instruction is an operand to the select, return
7641 /// a bitmask indicating which operands of this instruction are foldable if they
7642 /// equal the other incoming value of the select.
7644 static unsigned GetSelectFoldableOperands(Instruction *I) {
7645 switch (I->getOpcode()) {
7646 case Instruction::Add:
7647 case Instruction::Mul:
7648 case Instruction::And:
7649 case Instruction::Or:
7650 case Instruction::Xor:
7651 return 3; // Can fold through either operand.
7652 case Instruction::Sub: // Can only fold on the amount subtracted.
7653 case Instruction::Shl: // Can only fold on the shift amount.
7654 case Instruction::LShr:
7655 case Instruction::AShr:
7658 return 0; // Cannot fold
7662 /// GetSelectFoldableConstant - For the same transformation as the previous
7663 /// function, return the identity constant that goes into the select.
7664 static Constant *GetSelectFoldableConstant(Instruction *I) {
7665 switch (I->getOpcode()) {
7666 default: assert(0 && "This cannot happen!"); abort();
7667 case Instruction::Add:
7668 case Instruction::Sub:
7669 case Instruction::Or:
7670 case Instruction::Xor:
7671 case Instruction::Shl:
7672 case Instruction::LShr:
7673 case Instruction::AShr:
7674 return Constant::getNullValue(I->getType());
7675 case Instruction::And:
7676 return Constant::getAllOnesValue(I->getType());
7677 case Instruction::Mul:
7678 return ConstantInt::get(I->getType(), 1);
7682 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7683 /// have the same opcode and only one use each. Try to simplify this.
7684 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7686 if (TI->getNumOperands() == 1) {
7687 // If this is a non-volatile load or a cast from the same type,
7690 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7693 return 0; // unknown unary op.
7696 // Fold this by inserting a select from the input values.
7697 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7698 FI->getOperand(0), SI.getName()+".v");
7699 InsertNewInstBefore(NewSI, SI);
7700 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7704 // Only handle binary operators here.
7705 if (!isa<BinaryOperator>(TI))
7708 // Figure out if the operations have any operands in common.
7709 Value *MatchOp, *OtherOpT, *OtherOpF;
7711 if (TI->getOperand(0) == FI->getOperand(0)) {
7712 MatchOp = TI->getOperand(0);
7713 OtherOpT = TI->getOperand(1);
7714 OtherOpF = FI->getOperand(1);
7715 MatchIsOpZero = true;
7716 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7717 MatchOp = TI->getOperand(1);
7718 OtherOpT = TI->getOperand(0);
7719 OtherOpF = FI->getOperand(0);
7720 MatchIsOpZero = false;
7721 } else if (!TI->isCommutative()) {
7723 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7724 MatchOp = TI->getOperand(0);
7725 OtherOpT = TI->getOperand(1);
7726 OtherOpF = FI->getOperand(0);
7727 MatchIsOpZero = true;
7728 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7729 MatchOp = TI->getOperand(1);
7730 OtherOpT = TI->getOperand(0);
7731 OtherOpF = FI->getOperand(1);
7732 MatchIsOpZero = true;
7737 // If we reach here, they do have operations in common.
7738 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7739 OtherOpF, SI.getName()+".v");
7740 InsertNewInstBefore(NewSI, SI);
7742 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7744 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7746 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
7748 assert(0 && "Shouldn't get here");
7752 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7753 Value *CondVal = SI.getCondition();
7754 Value *TrueVal = SI.getTrueValue();
7755 Value *FalseVal = SI.getFalseValue();
7757 // select true, X, Y -> X
7758 // select false, X, Y -> Y
7759 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7760 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7762 // select C, X, X -> X
7763 if (TrueVal == FalseVal)
7764 return ReplaceInstUsesWith(SI, TrueVal);
7766 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7767 return ReplaceInstUsesWith(SI, FalseVal);
7768 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7769 return ReplaceInstUsesWith(SI, TrueVal);
7770 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7771 if (isa<Constant>(TrueVal))
7772 return ReplaceInstUsesWith(SI, TrueVal);
7774 return ReplaceInstUsesWith(SI, FalseVal);
7777 if (SI.getType() == Type::Int1Ty) {
7778 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7779 if (C->getZExtValue()) {
7780 // Change: A = select B, true, C --> A = or B, C
7781 return BinaryOperator::createOr(CondVal, FalseVal);
7783 // Change: A = select B, false, C --> A = and !B, C
7785 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7786 "not."+CondVal->getName()), SI);
7787 return BinaryOperator::createAnd(NotCond, FalseVal);
7789 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7790 if (C->getZExtValue() == false) {
7791 // Change: A = select B, C, false --> A = and B, C
7792 return BinaryOperator::createAnd(CondVal, TrueVal);
7794 // Change: A = select B, C, true --> A = or !B, C
7796 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7797 "not."+CondVal->getName()), SI);
7798 return BinaryOperator::createOr(NotCond, TrueVal);
7802 // select a, b, a -> a&b
7803 // select a, a, b -> a|b
7804 if (CondVal == TrueVal)
7805 return BinaryOperator::createOr(CondVal, FalseVal);
7806 else if (CondVal == FalseVal)
7807 return BinaryOperator::createAnd(CondVal, TrueVal);
7810 // Selecting between two integer constants?
7811 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7812 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7813 // select C, 1, 0 -> zext C to int
7814 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
7815 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
7816 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
7817 // select C, 0, 1 -> zext !C to int
7819 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7820 "not."+CondVal->getName()), SI);
7821 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
7824 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
7826 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
7828 // (x <s 0) ? -1 : 0 -> ashr x, 31
7829 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
7830 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
7831 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
7832 // The comparison constant and the result are not neccessarily the
7833 // same width. Make an all-ones value by inserting a AShr.
7834 Value *X = IC->getOperand(0);
7835 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
7836 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7837 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7839 InsertNewInstBefore(SRA, SI);
7841 // Finally, convert to the type of the select RHS. We figure out
7842 // if this requires a SExt, Trunc or BitCast based on the sizes.
7843 Instruction::CastOps opc = Instruction::BitCast;
7844 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7845 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
7846 if (SRASize < SISize)
7847 opc = Instruction::SExt;
7848 else if (SRASize > SISize)
7849 opc = Instruction::Trunc;
7850 return CastInst::create(opc, SRA, SI.getType());
7855 // If one of the constants is zero (we know they can't both be) and we
7856 // have an icmp instruction with zero, and we have an 'and' with the
7857 // non-constant value, eliminate this whole mess. This corresponds to
7858 // cases like this: ((X & 27) ? 27 : 0)
7859 if (TrueValC->isZero() || FalseValC->isZero())
7860 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
7861 cast<Constant>(IC->getOperand(1))->isNullValue())
7862 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7863 if (ICA->getOpcode() == Instruction::And &&
7864 isa<ConstantInt>(ICA->getOperand(1)) &&
7865 (ICA->getOperand(1) == TrueValC ||
7866 ICA->getOperand(1) == FalseValC) &&
7867 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7868 // Okay, now we know that everything is set up, we just don't
7869 // know whether we have a icmp_ne or icmp_eq and whether the
7870 // true or false val is the zero.
7871 bool ShouldNotVal = !TrueValC->isZero();
7872 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
7875 V = InsertNewInstBefore(BinaryOperator::create(
7876 Instruction::Xor, V, ICA->getOperand(1)), SI);
7877 return ReplaceInstUsesWith(SI, V);
7882 // See if we are selecting two values based on a comparison of the two values.
7883 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7884 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
7885 // Transform (X == Y) ? X : Y -> Y
7886 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7887 // This is not safe in general for floating point:
7888 // consider X== -0, Y== +0.
7889 // It becomes safe if either operand is a nonzero constant.
7890 ConstantFP *CFPt, *CFPf;
7891 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7892 !CFPt->getValueAPF().isZero()) ||
7893 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7894 !CFPf->getValueAPF().isZero()))
7895 return ReplaceInstUsesWith(SI, FalseVal);
7897 // Transform (X != Y) ? X : Y -> X
7898 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7899 return ReplaceInstUsesWith(SI, TrueVal);
7900 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7902 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
7903 // Transform (X == Y) ? Y : X -> X
7904 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7905 // This is not safe in general for floating point:
7906 // consider X== -0, Y== +0.
7907 // It becomes safe if either operand is a nonzero constant.
7908 ConstantFP *CFPt, *CFPf;
7909 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7910 !CFPt->getValueAPF().isZero()) ||
7911 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7912 !CFPf->getValueAPF().isZero()))
7913 return ReplaceInstUsesWith(SI, FalseVal);
7915 // Transform (X != Y) ? Y : X -> Y
7916 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7917 return ReplaceInstUsesWith(SI, TrueVal);
7918 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7922 // See if we are selecting two values based on a comparison of the two values.
7923 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7924 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7925 // Transform (X == Y) ? X : Y -> Y
7926 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7927 return ReplaceInstUsesWith(SI, FalseVal);
7928 // Transform (X != Y) ? X : Y -> X
7929 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7930 return ReplaceInstUsesWith(SI, TrueVal);
7931 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7933 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7934 // Transform (X == Y) ? Y : X -> X
7935 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7936 return ReplaceInstUsesWith(SI, FalseVal);
7937 // Transform (X != Y) ? Y : X -> Y
7938 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7939 return ReplaceInstUsesWith(SI, TrueVal);
7940 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7944 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7945 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7946 if (TI->hasOneUse() && FI->hasOneUse()) {
7947 Instruction *AddOp = 0, *SubOp = 0;
7949 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7950 if (TI->getOpcode() == FI->getOpcode())
7951 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7954 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7955 // even legal for FP.
7956 if (TI->getOpcode() == Instruction::Sub &&
7957 FI->getOpcode() == Instruction::Add) {
7958 AddOp = FI; SubOp = TI;
7959 } else if (FI->getOpcode() == Instruction::Sub &&
7960 TI->getOpcode() == Instruction::Add) {
7961 AddOp = TI; SubOp = FI;
7965 Value *OtherAddOp = 0;
7966 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7967 OtherAddOp = AddOp->getOperand(1);
7968 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7969 OtherAddOp = AddOp->getOperand(0);
7973 // So at this point we know we have (Y -> OtherAddOp):
7974 // select C, (add X, Y), (sub X, Z)
7975 Value *NegVal; // Compute -Z
7976 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7977 NegVal = ConstantExpr::getNeg(C);
7979 NegVal = InsertNewInstBefore(
7980 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
7983 Value *NewTrueOp = OtherAddOp;
7984 Value *NewFalseOp = NegVal;
7986 std::swap(NewTrueOp, NewFalseOp);
7987 Instruction *NewSel =
7988 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7990 NewSel = InsertNewInstBefore(NewSel, SI);
7991 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
7996 // See if we can fold the select into one of our operands.
7997 if (SI.getType()->isInteger()) {
7998 // See the comment above GetSelectFoldableOperands for a description of the
7999 // transformation we are doing here.
8000 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8001 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8002 !isa<Constant>(FalseVal))
8003 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8004 unsigned OpToFold = 0;
8005 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8007 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8012 Constant *C = GetSelectFoldableConstant(TVI);
8013 Instruction *NewSel =
8014 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
8015 InsertNewInstBefore(NewSel, SI);
8016 NewSel->takeName(TVI);
8017 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8018 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
8020 assert(0 && "Unknown instruction!!");
8025 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8026 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8027 !isa<Constant>(TrueVal))
8028 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8029 unsigned OpToFold = 0;
8030 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8032 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8037 Constant *C = GetSelectFoldableConstant(FVI);
8038 Instruction *NewSel =
8039 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
8040 InsertNewInstBefore(NewSel, SI);
8041 NewSel->takeName(FVI);
8042 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8043 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
8045 assert(0 && "Unknown instruction!!");
8050 if (BinaryOperator::isNot(CondVal)) {
8051 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8052 SI.setOperand(1, FalseVal);
8053 SI.setOperand(2, TrueVal);
8060 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8061 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8062 /// and it is more than the alignment of the ultimate object, see if we can
8063 /// increase the alignment of the ultimate object, making this check succeed.
8064 static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
8065 unsigned PrefAlign = 0) {
8066 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
8067 unsigned Align = GV->getAlignment();
8068 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
8069 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
8071 // If there is a large requested alignment and we can, bump up the alignment
8073 if (PrefAlign > Align && GV->hasInitializer()) {
8074 GV->setAlignment(PrefAlign);
8078 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8079 unsigned Align = AI->getAlignment();
8080 if (Align == 0 && TD) {
8081 if (isa<AllocaInst>(AI))
8082 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
8083 else if (isa<MallocInst>(AI)) {
8084 // Malloc returns maximally aligned memory.
8085 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
8088 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
8091 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
8095 // If there is a requested alignment and if this is an alloca, round up. We
8096 // don't do this for malloc, because some systems can't respect the request.
8097 if (PrefAlign > Align && isa<AllocaInst>(AI)) {
8098 AI->setAlignment(PrefAlign);
8102 } else if (isa<BitCastInst>(V) ||
8103 (isa<ConstantExpr>(V) &&
8104 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
8105 return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
8107 } else if (User *GEPI = dyn_castGetElementPtr(V)) {
8108 // If all indexes are zero, it is just the alignment of the base pointer.
8109 bool AllZeroOperands = true;
8110 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
8111 if (!isa<Constant>(GEPI->getOperand(i)) ||
8112 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
8113 AllZeroOperands = false;
8117 if (AllZeroOperands) {
8118 // Treat this like a bitcast.
8119 return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
8122 unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
8123 if (BaseAlignment == 0) return 0;
8125 // Otherwise, if the base alignment is >= the alignment we expect for the
8126 // base pointer type, then we know that the resultant pointer is aligned at
8127 // least as much as its type requires.
8130 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
8131 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
8132 unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
8133 if (Align <= BaseAlignment) {
8134 const Type *GEPTy = GEPI->getType();
8135 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
8136 Align = std::min(Align, (unsigned)
8137 TD->getABITypeAlignment(GEPPtrTy->getElementType()));
8145 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8146 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
8147 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
8148 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8149 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8151 if (CopyAlign < MinAlign) {
8152 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8156 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8158 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8159 if (MemOpLength == 0) return 0;
8161 // Source and destination pointer types are always "i8*" for intrinsic. See
8162 // if the size is something we can handle with a single primitive load/store.
8163 // A single load+store correctly handles overlapping memory in the memmove
8165 unsigned Size = MemOpLength->getZExtValue();
8166 if (Size == 0 || Size > 8 || (Size&(Size-1)))
8167 return 0; // If not 1/2/4/8 bytes, exit.
8169 // Use an integer load+store unless we can find something better.
8170 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
8172 // Memcpy forces the use of i8* for the source and destination. That means
8173 // that if you're using memcpy to move one double around, you'll get a cast
8174 // from double* to i8*. We'd much rather use a double load+store rather than
8175 // an i64 load+store, here because this improves the odds that the source or
8176 // dest address will be promotable. See if we can find a better type than the
8177 // integer datatype.
8178 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8179 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8180 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8181 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8182 // down through these levels if so.
8183 while (!SrcETy->isFirstClassType()) {
8184 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8185 if (STy->getNumElements() == 1)
8186 SrcETy = STy->getElementType(0);
8189 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8190 if (ATy->getNumElements() == 1)
8191 SrcETy = ATy->getElementType();
8198 if (SrcETy->isFirstClassType())
8199 NewPtrTy = PointerType::getUnqual(SrcETy);
8204 // If the memcpy/memmove provides better alignment info than we can
8206 SrcAlign = std::max(SrcAlign, CopyAlign);
8207 DstAlign = std::max(DstAlign, CopyAlign);
8209 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8210 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
8211 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8212 InsertNewInstBefore(L, *MI);
8213 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8215 // Set the size of the copy to 0, it will be deleted on the next iteration.
8216 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8220 /// visitCallInst - CallInst simplification. This mostly only handles folding
8221 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8222 /// the heavy lifting.
8224 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8225 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8226 if (!II) return visitCallSite(&CI);
8228 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8230 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8231 bool Changed = false;
8233 // memmove/cpy/set of zero bytes is a noop.
8234 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8235 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8237 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8238 if (CI->getZExtValue() == 1) {
8239 // Replace the instruction with just byte operations. We would
8240 // transform other cases to loads/stores, but we don't know if
8241 // alignment is sufficient.
8245 // If we have a memmove and the source operation is a constant global,
8246 // then the source and dest pointers can't alias, so we can change this
8247 // into a call to memcpy.
8248 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
8249 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8250 if (GVSrc->isConstant()) {
8251 Module *M = CI.getParent()->getParent()->getParent();
8252 Intrinsic::ID MemCpyID;
8253 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8254 MemCpyID = Intrinsic::memcpy_i32;
8256 MemCpyID = Intrinsic::memcpy_i64;
8257 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
8262 // If we can determine a pointer alignment that is bigger than currently
8263 // set, update the alignment.
8264 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
8265 if (Instruction *I = SimplifyMemTransfer(MI))
8267 } else if (isa<MemSetInst>(MI)) {
8268 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
8269 if (MI->getAlignment()->getZExtValue() < Alignment) {
8270 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8275 if (Changed) return II;
8277 switch (II->getIntrinsicID()) {
8279 case Intrinsic::ppc_altivec_lvx:
8280 case Intrinsic::ppc_altivec_lvxl:
8281 case Intrinsic::x86_sse_loadu_ps:
8282 case Intrinsic::x86_sse2_loadu_pd:
8283 case Intrinsic::x86_sse2_loadu_dq:
8284 // Turn PPC lvx -> load if the pointer is known aligned.
8285 // Turn X86 loadups -> load if the pointer is known aligned.
8286 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
8287 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8288 PointerType::getUnqual(II->getType()),
8290 return new LoadInst(Ptr);
8293 case Intrinsic::ppc_altivec_stvx:
8294 case Intrinsic::ppc_altivec_stvxl:
8295 // Turn stvx -> store if the pointer is known aligned.
8296 if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
8297 const Type *OpPtrTy =
8298 PointerType::getUnqual(II->getOperand(1)->getType());
8299 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8300 return new StoreInst(II->getOperand(1), Ptr);
8303 case Intrinsic::x86_sse_storeu_ps:
8304 case Intrinsic::x86_sse2_storeu_pd:
8305 case Intrinsic::x86_sse2_storeu_dq:
8306 case Intrinsic::x86_sse2_storel_dq:
8307 // Turn X86 storeu -> store if the pointer is known aligned.
8308 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
8309 const Type *OpPtrTy =
8310 PointerType::getUnqual(II->getOperand(2)->getType());
8311 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8312 return new StoreInst(II->getOperand(2), Ptr);
8316 case Intrinsic::x86_sse_cvttss2si: {
8317 // These intrinsics only demands the 0th element of its input vector. If
8318 // we can simplify the input based on that, do so now.
8320 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8322 II->setOperand(1, V);
8328 case Intrinsic::ppc_altivec_vperm:
8329 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8330 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8331 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8333 // Check that all of the elements are integer constants or undefs.
8334 bool AllEltsOk = true;
8335 for (unsigned i = 0; i != 16; ++i) {
8336 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8337 !isa<UndefValue>(Mask->getOperand(i))) {
8344 // Cast the input vectors to byte vectors.
8345 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8346 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8347 Value *Result = UndefValue::get(Op0->getType());
8349 // Only extract each element once.
8350 Value *ExtractedElts[32];
8351 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8353 for (unsigned i = 0; i != 16; ++i) {
8354 if (isa<UndefValue>(Mask->getOperand(i)))
8356 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8357 Idx &= 31; // Match the hardware behavior.
8359 if (ExtractedElts[Idx] == 0) {
8361 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8362 InsertNewInstBefore(Elt, CI);
8363 ExtractedElts[Idx] = Elt;
8366 // Insert this value into the result vector.
8367 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
8368 InsertNewInstBefore(cast<Instruction>(Result), CI);
8370 return CastInst::create(Instruction::BitCast, Result, CI.getType());
8375 case Intrinsic::stackrestore: {
8376 // If the save is right next to the restore, remove the restore. This can
8377 // happen when variable allocas are DCE'd.
8378 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8379 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8380 BasicBlock::iterator BI = SS;
8382 return EraseInstFromFunction(CI);
8386 // Scan down this block to see if there is another stack restore in the
8387 // same block without an intervening call/alloca.
8388 BasicBlock::iterator BI = II;
8389 TerminatorInst *TI = II->getParent()->getTerminator();
8390 bool CannotRemove = false;
8391 for (++BI; &*BI != TI; ++BI) {
8392 if (isa<AllocaInst>(BI)) {
8393 CannotRemove = true;
8396 if (isa<CallInst>(BI)) {
8397 if (!isa<IntrinsicInst>(BI)) {
8398 CannotRemove = true;
8401 // If there is a stackrestore below this one, remove this one.
8402 return EraseInstFromFunction(CI);
8406 // If the stack restore is in a return/unwind block and if there are no
8407 // allocas or calls between the restore and the return, nuke the restore.
8408 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8409 return EraseInstFromFunction(CI);
8415 return visitCallSite(II);
8418 // InvokeInst simplification
8420 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8421 return visitCallSite(&II);
8424 // visitCallSite - Improvements for call and invoke instructions.
8426 Instruction *InstCombiner::visitCallSite(CallSite CS) {
8427 bool Changed = false;
8429 // If the callee is a constexpr cast of a function, attempt to move the cast
8430 // to the arguments of the call/invoke.
8431 if (transformConstExprCastCall(CS)) return 0;
8433 Value *Callee = CS.getCalledValue();
8435 if (Function *CalleeF = dyn_cast<Function>(Callee))
8436 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8437 Instruction *OldCall = CS.getInstruction();
8438 // If the call and callee calling conventions don't match, this call must
8439 // be unreachable, as the call is undefined.
8440 new StoreInst(ConstantInt::getTrue(),
8441 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8443 if (!OldCall->use_empty())
8444 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8445 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8446 return EraseInstFromFunction(*OldCall);
8450 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8451 // This instruction is not reachable, just remove it. We insert a store to
8452 // undef so that we know that this code is not reachable, despite the fact
8453 // that we can't modify the CFG here.
8454 new StoreInst(ConstantInt::getTrue(),
8455 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8456 CS.getInstruction());
8458 if (!CS.getInstruction()->use_empty())
8459 CS.getInstruction()->
8460 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8462 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8463 // Don't break the CFG, insert a dummy cond branch.
8464 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
8465 ConstantInt::getTrue(), II);
8467 return EraseInstFromFunction(*CS.getInstruction());
8470 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8471 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8472 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8473 return transformCallThroughTrampoline(CS);
8475 const PointerType *PTy = cast<PointerType>(Callee->getType());
8476 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8477 if (FTy->isVarArg()) {
8478 // See if we can optimize any arguments passed through the varargs area of
8480 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8481 E = CS.arg_end(); I != E; ++I)
8482 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8483 // If this cast does not effect the value passed through the varargs
8484 // area, we can eliminate the use of the cast.
8485 Value *Op = CI->getOperand(0);
8486 if (CI->isLosslessCast()) {
8493 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
8494 // Inline asm calls cannot throw - mark them 'nounwind'.
8495 CS.setDoesNotThrow();
8499 return Changed ? CS.getInstruction() : 0;
8502 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8503 // attempt to move the cast to the arguments of the call/invoke.
8505 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8506 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8507 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8508 if (CE->getOpcode() != Instruction::BitCast ||
8509 !isa<Function>(CE->getOperand(0)))
8511 Function *Callee = cast<Function>(CE->getOperand(0));
8512 Instruction *Caller = CS.getInstruction();
8513 const PAListPtr &CallerPAL = CS.getParamAttrs();
8515 // Okay, this is a cast from a function to a different type. Unless doing so
8516 // would cause a type conversion of one of our arguments, change this call to
8517 // be a direct call with arguments casted to the appropriate types.
8519 const FunctionType *FT = Callee->getFunctionType();
8520 const Type *OldRetTy = Caller->getType();
8522 if (isa<StructType>(FT->getReturnType()))
8523 return false; // TODO: Handle multiple return values.
8525 // Check to see if we are changing the return type...
8526 if (OldRetTy != FT->getReturnType()) {
8527 if (Callee->isDeclaration() && !Caller->use_empty() &&
8528 // Conversion is ok if changing from pointer to int of same size.
8529 !(isa<PointerType>(FT->getReturnType()) &&
8530 TD->getIntPtrType() == OldRetTy))
8531 return false; // Cannot transform this return value.
8533 if (!Caller->use_empty() &&
8534 // void -> non-void is handled specially
8535 FT->getReturnType() != Type::VoidTy &&
8536 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
8537 return false; // Cannot transform this return value.
8539 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8540 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8541 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8542 return false; // Attribute not compatible with transformed value.
8545 // If the callsite is an invoke instruction, and the return value is used by
8546 // a PHI node in a successor, we cannot change the return type of the call
8547 // because there is no place to put the cast instruction (without breaking
8548 // the critical edge). Bail out in this case.
8549 if (!Caller->use_empty())
8550 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8551 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8553 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8554 if (PN->getParent() == II->getNormalDest() ||
8555 PN->getParent() == II->getUnwindDest())
8559 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8560 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8562 CallSite::arg_iterator AI = CS.arg_begin();
8563 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8564 const Type *ParamTy = FT->getParamType(i);
8565 const Type *ActTy = (*AI)->getType();
8567 if (!CastInst::isCastable(ActTy, ParamTy))
8568 return false; // Cannot transform this parameter value.
8570 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8571 return false; // Attribute not compatible with transformed value.
8573 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
8574 // Some conversions are safe even if we do not have a body.
8575 // Either we can cast directly, or we can upconvert the argument
8576 bool isConvertible = ActTy == ParamTy ||
8577 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
8578 (ParamTy->isInteger() && ActTy->isInteger() &&
8579 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8580 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
8581 && c->getValue().isStrictlyPositive());
8582 if (Callee->isDeclaration() && !isConvertible) return false;
8585 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8586 Callee->isDeclaration())
8587 return false; // Do not delete arguments unless we have a function body.
8589 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8590 !CallerPAL.isEmpty())
8591 // In this case we have more arguments than the new function type, but we
8592 // won't be dropping them. Check that these extra arguments have attributes
8593 // that are compatible with being a vararg call argument.
8594 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8595 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
8597 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
8598 if (PAttrs & ParamAttr::VarArgsIncompatible)
8602 // Okay, we decided that this is a safe thing to do: go ahead and start
8603 // inserting cast instructions as necessary...
8604 std::vector<Value*> Args;
8605 Args.reserve(NumActualArgs);
8606 SmallVector<ParamAttrsWithIndex, 8> attrVec;
8607 attrVec.reserve(NumCommonArgs);
8609 // Get any return attributes.
8610 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8612 // If the return value is not being used, the type may not be compatible
8613 // with the existing attributes. Wipe out any problematic attributes.
8614 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
8616 // Add the new return attributes.
8618 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
8620 AI = CS.arg_begin();
8621 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8622 const Type *ParamTy = FT->getParamType(i);
8623 if ((*AI)->getType() == ParamTy) {
8624 Args.push_back(*AI);
8626 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8627 false, ParamTy, false);
8628 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
8629 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8632 // Add any parameter attributes.
8633 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
8634 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8637 // If the function takes more arguments than the call was taking, add them
8639 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8640 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8642 // If we are removing arguments to the function, emit an obnoxious warning...
8643 if (FT->getNumParams() < NumActualArgs) {
8644 if (!FT->isVarArg()) {
8645 cerr << "WARNING: While resolving call to function '"
8646 << Callee->getName() << "' arguments were dropped!\n";
8648 // Add all of the arguments in their promoted form to the arg list...
8649 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8650 const Type *PTy = getPromotedType((*AI)->getType());
8651 if (PTy != (*AI)->getType()) {
8652 // Must promote to pass through va_arg area!
8653 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8655 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
8656 InsertNewInstBefore(Cast, *Caller);
8657 Args.push_back(Cast);
8659 Args.push_back(*AI);
8662 // Add any parameter attributes.
8663 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
8664 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8669 if (FT->getReturnType() == Type::VoidTy)
8670 Caller->setName(""); // Void type should not have a name.
8672 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
8675 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8676 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
8677 Args.begin(), Args.end(), Caller->getName(), Caller);
8678 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
8679 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
8681 NC = new CallInst(Callee, Args.begin(), Args.end(),
8682 Caller->getName(), Caller);
8683 CallInst *CI = cast<CallInst>(Caller);
8684 if (CI->isTailCall())
8685 cast<CallInst>(NC)->setTailCall();
8686 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
8687 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
8690 // Insert a cast of the return type as necessary.
8692 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
8693 if (NV->getType() != Type::VoidTy) {
8694 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
8696 NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
8698 // If this is an invoke instruction, we should insert it after the first
8699 // non-phi, instruction in the normal successor block.
8700 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8701 BasicBlock::iterator I = II->getNormalDest()->begin();
8702 while (isa<PHINode>(I)) ++I;
8703 InsertNewInstBefore(NC, *I);
8705 // Otherwise, it's a call, just insert cast right after the call instr
8706 InsertNewInstBefore(NC, *Caller);
8708 AddUsersToWorkList(*Caller);
8710 NV = UndefValue::get(Caller->getType());
8714 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8715 Caller->replaceAllUsesWith(NV);
8716 Caller->eraseFromParent();
8717 RemoveFromWorkList(Caller);
8721 // transformCallThroughTrampoline - Turn a call to a function created by the
8722 // init_trampoline intrinsic into a direct call to the underlying function.
8724 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8725 Value *Callee = CS.getCalledValue();
8726 const PointerType *PTy = cast<PointerType>(Callee->getType());
8727 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8728 const PAListPtr &Attrs = CS.getParamAttrs();
8730 // If the call already has the 'nest' attribute somewhere then give up -
8731 // otherwise 'nest' would occur twice after splicing in the chain.
8732 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
8735 IntrinsicInst *Tramp =
8736 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8739 cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8740 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8741 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8743 const PAListPtr &NestAttrs = NestF->getParamAttrs();
8744 if (!NestAttrs.isEmpty()) {
8745 unsigned NestIdx = 1;
8746 const Type *NestTy = 0;
8747 ParameterAttributes NestAttr = ParamAttr::None;
8749 // Look for a parameter marked with the 'nest' attribute.
8750 for (FunctionType::param_iterator I = NestFTy->param_begin(),
8751 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
8752 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
8753 // Record the parameter type and any other attributes.
8755 NestAttr = NestAttrs.getParamAttrs(NestIdx);
8760 Instruction *Caller = CS.getInstruction();
8761 std::vector<Value*> NewArgs;
8762 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8764 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
8765 NewAttrs.reserve(Attrs.getNumSlots() + 1);
8767 // Insert the nest argument into the call argument list, which may
8768 // mean appending it. Likewise for attributes.
8770 // Add any function result attributes.
8771 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
8772 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
8776 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8778 if (Idx == NestIdx) {
8779 // Add the chain argument and attributes.
8780 Value *NestVal = Tramp->getOperand(3);
8781 if (NestVal->getType() != NestTy)
8782 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8783 NewArgs.push_back(NestVal);
8784 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
8790 // Add the original argument and attributes.
8791 NewArgs.push_back(*I);
8792 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
8794 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
8800 // The trampoline may have been bitcast to a bogus type (FTy).
8801 // Handle this by synthesizing a new function type, equal to FTy
8802 // with the chain parameter inserted.
8804 std::vector<const Type*> NewTypes;
8805 NewTypes.reserve(FTy->getNumParams()+1);
8807 // Insert the chain's type into the list of parameter types, which may
8808 // mean appending it.
8811 FunctionType::param_iterator I = FTy->param_begin(),
8812 E = FTy->param_end();
8816 // Add the chain's type.
8817 NewTypes.push_back(NestTy);
8822 // Add the original type.
8823 NewTypes.push_back(*I);
8829 // Replace the trampoline call with a direct call. Let the generic
8830 // code sort out any function type mismatches.
8831 FunctionType *NewFTy =
8832 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
8833 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8834 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
8835 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
8837 Instruction *NewCaller;
8838 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8839 NewCaller = new InvokeInst(NewCallee,
8840 II->getNormalDest(), II->getUnwindDest(),
8841 NewArgs.begin(), NewArgs.end(),
8842 Caller->getName(), Caller);
8843 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
8844 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
8846 NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8847 Caller->getName(), Caller);
8848 if (cast<CallInst>(Caller)->isTailCall())
8849 cast<CallInst>(NewCaller)->setTailCall();
8850 cast<CallInst>(NewCaller)->
8851 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
8852 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
8854 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8855 Caller->replaceAllUsesWith(NewCaller);
8856 Caller->eraseFromParent();
8857 RemoveFromWorkList(Caller);
8862 // Replace the trampoline call with a direct call. Since there is no 'nest'
8863 // parameter, there is no need to adjust the argument list. Let the generic
8864 // code sort out any function type mismatches.
8865 Constant *NewCallee =
8866 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8867 CS.setCalledFunction(NewCallee);
8868 return CS.getInstruction();
8871 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8872 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8873 /// and a single binop.
8874 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8875 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8876 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8877 isa<CmpInst>(FirstInst));
8878 unsigned Opc = FirstInst->getOpcode();
8879 Value *LHSVal = FirstInst->getOperand(0);
8880 Value *RHSVal = FirstInst->getOperand(1);
8882 const Type *LHSType = LHSVal->getType();
8883 const Type *RHSType = RHSVal->getType();
8885 // Scan to see if all operands are the same opcode, all have one use, and all
8886 // kill their operands (i.e. the operands have one use).
8887 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
8888 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
8889 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
8890 // Verify type of the LHS matches so we don't fold cmp's of different
8891 // types or GEP's with different index types.
8892 I->getOperand(0)->getType() != LHSType ||
8893 I->getOperand(1)->getType() != RHSType)
8896 // If they are CmpInst instructions, check their predicates
8897 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8898 if (cast<CmpInst>(I)->getPredicate() !=
8899 cast<CmpInst>(FirstInst)->getPredicate())
8902 // Keep track of which operand needs a phi node.
8903 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8904 if (I->getOperand(1) != RHSVal) RHSVal = 0;
8907 // Otherwise, this is safe to transform, determine if it is profitable.
8909 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8910 // Indexes are often folded into load/store instructions, so we don't want to
8911 // hide them behind a phi.
8912 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8915 Value *InLHS = FirstInst->getOperand(0);
8916 Value *InRHS = FirstInst->getOperand(1);
8917 PHINode *NewLHS = 0, *NewRHS = 0;
8919 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8920 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8921 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
8922 InsertNewInstBefore(NewLHS, PN);
8927 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8928 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8929 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
8930 InsertNewInstBefore(NewRHS, PN);
8934 // Add all operands to the new PHIs.
8935 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8937 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8938 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8941 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8942 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8946 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8947 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
8948 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8949 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8952 assert(isa<GetElementPtrInst>(FirstInst));
8953 return new GetElementPtrInst(LHSVal, RHSVal);
8957 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8958 /// of the block that defines it. This means that it must be obvious the value
8959 /// of the load is not changed from the point of the load to the end of the
8962 /// Finally, it is safe, but not profitable, to sink a load targetting a
8963 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
8965 static bool isSafeToSinkLoad(LoadInst *L) {
8966 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8968 for (++BBI; BBI != E; ++BBI)
8969 if (BBI->mayWriteToMemory())
8972 // Check for non-address taken alloca. If not address-taken already, it isn't
8973 // profitable to do this xform.
8974 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8975 bool isAddressTaken = false;
8976 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8978 if (isa<LoadInst>(UI)) continue;
8979 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8980 // If storing TO the alloca, then the address isn't taken.
8981 if (SI->getOperand(1) == AI) continue;
8983 isAddressTaken = true;
8987 if (!isAddressTaken)
8995 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8996 // operator and they all are only used by the PHI, PHI together their
8997 // inputs, and do the operation once, to the result of the PHI.
8998 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8999 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9001 // Scan the instruction, looking for input operations that can be folded away.
9002 // If all input operands to the phi are the same instruction (e.g. a cast from
9003 // the same type or "+42") we can pull the operation through the PHI, reducing
9004 // code size and simplifying code.
9005 Constant *ConstantOp = 0;
9006 const Type *CastSrcTy = 0;
9007 bool isVolatile = false;
9008 if (isa<CastInst>(FirstInst)) {
9009 CastSrcTy = FirstInst->getOperand(0)->getType();
9010 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9011 // Can fold binop, compare or shift here if the RHS is a constant,
9012 // otherwise call FoldPHIArgBinOpIntoPHI.
9013 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9014 if (ConstantOp == 0)
9015 return FoldPHIArgBinOpIntoPHI(PN);
9016 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9017 isVolatile = LI->isVolatile();
9018 // We can't sink the load if the loaded value could be modified between the
9019 // load and the PHI.
9020 if (LI->getParent() != PN.getIncomingBlock(0) ||
9021 !isSafeToSinkLoad(LI))
9023 } else if (isa<GetElementPtrInst>(FirstInst)) {
9024 if (FirstInst->getNumOperands() == 2)
9025 return FoldPHIArgBinOpIntoPHI(PN);
9026 // Can't handle general GEPs yet.
9029 return 0; // Cannot fold this operation.
9032 // Check to see if all arguments are the same operation.
9033 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9034 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9035 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9036 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9039 if (I->getOperand(0)->getType() != CastSrcTy)
9040 return 0; // Cast operation must match.
9041 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9042 // We can't sink the load if the loaded value could be modified between
9043 // the load and the PHI.
9044 if (LI->isVolatile() != isVolatile ||
9045 LI->getParent() != PN.getIncomingBlock(i) ||
9046 !isSafeToSinkLoad(LI))
9048 } else if (I->getOperand(1) != ConstantOp) {
9053 // Okay, they are all the same operation. Create a new PHI node of the
9054 // correct type, and PHI together all of the LHS's of the instructions.
9055 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
9056 PN.getName()+".in");
9057 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9059 Value *InVal = FirstInst->getOperand(0);
9060 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9062 // Add all operands to the new PHI.
9063 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9064 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9065 if (NewInVal != InVal)
9067 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9072 // The new PHI unions all of the same values together. This is really
9073 // common, so we handle it intelligently here for compile-time speed.
9077 InsertNewInstBefore(NewPN, PN);
9081 // Insert and return the new operation.
9082 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9083 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
9084 else if (isa<LoadInst>(FirstInst))
9085 return new LoadInst(PhiVal, "", isVolatile);
9086 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9087 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
9088 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9089 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
9090 PhiVal, ConstantOp);
9092 assert(0 && "Unknown operation");
9096 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9098 static bool DeadPHICycle(PHINode *PN,
9099 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9100 if (PN->use_empty()) return true;
9101 if (!PN->hasOneUse()) return false;
9103 // Remember this node, and if we find the cycle, return.
9104 if (!PotentiallyDeadPHIs.insert(PN))
9107 // Don't scan crazily complex things.
9108 if (PotentiallyDeadPHIs.size() == 16)
9111 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9112 return DeadPHICycle(PU, PotentiallyDeadPHIs);
9117 /// PHIsEqualValue - Return true if this phi node is always equal to
9118 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9119 /// z = some value; x = phi (y, z); y = phi (x, z)
9120 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9121 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9122 // See if we already saw this PHI node.
9123 if (!ValueEqualPHIs.insert(PN))
9126 // Don't scan crazily complex things.
9127 if (ValueEqualPHIs.size() == 16)
9130 // Scan the operands to see if they are either phi nodes or are equal to
9132 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9133 Value *Op = PN->getIncomingValue(i);
9134 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9135 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9137 } else if (Op != NonPhiInVal)
9145 // PHINode simplification
9147 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9148 // If LCSSA is around, don't mess with Phi nodes
9149 if (MustPreserveLCSSA) return 0;
9151 if (Value *V = PN.hasConstantValue())
9152 return ReplaceInstUsesWith(PN, V);
9154 // If all PHI operands are the same operation, pull them through the PHI,
9155 // reducing code size.
9156 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9157 PN.getIncomingValue(0)->hasOneUse())
9158 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9161 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9162 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9163 // PHI)... break the cycle.
9164 if (PN.hasOneUse()) {
9165 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9166 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9167 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9168 PotentiallyDeadPHIs.insert(&PN);
9169 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9170 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9173 // If this phi has a single use, and if that use just computes a value for
9174 // the next iteration of a loop, delete the phi. This occurs with unused
9175 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9176 // common case here is good because the only other things that catch this
9177 // are induction variable analysis (sometimes) and ADCE, which is only run
9179 if (PHIUser->hasOneUse() &&
9180 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9181 PHIUser->use_back() == &PN) {
9182 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9186 // We sometimes end up with phi cycles that non-obviously end up being the
9187 // same value, for example:
9188 // z = some value; x = phi (y, z); y = phi (x, z)
9189 // where the phi nodes don't necessarily need to be in the same block. Do a
9190 // quick check to see if the PHI node only contains a single non-phi value, if
9191 // so, scan to see if the phi cycle is actually equal to that value.
9193 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9194 // Scan for the first non-phi operand.
9195 while (InValNo != NumOperandVals &&
9196 isa<PHINode>(PN.getIncomingValue(InValNo)))
9199 if (InValNo != NumOperandVals) {
9200 Value *NonPhiInVal = PN.getOperand(InValNo);
9202 // Scan the rest of the operands to see if there are any conflicts, if so
9203 // there is no need to recursively scan other phis.
9204 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9205 Value *OpVal = PN.getIncomingValue(InValNo);
9206 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9210 // If we scanned over all operands, then we have one unique value plus
9211 // phi values. Scan PHI nodes to see if they all merge in each other or
9213 if (InValNo == NumOperandVals) {
9214 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9215 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9216 return ReplaceInstUsesWith(PN, NonPhiInVal);
9223 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9224 Instruction *InsertPoint,
9226 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9227 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9228 // We must cast correctly to the pointer type. Ensure that we
9229 // sign extend the integer value if it is smaller as this is
9230 // used for address computation.
9231 Instruction::CastOps opcode =
9232 (VTySize < PtrSize ? Instruction::SExt :
9233 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9234 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9238 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9239 Value *PtrOp = GEP.getOperand(0);
9240 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
9241 // If so, eliminate the noop.
9242 if (GEP.getNumOperands() == 1)
9243 return ReplaceInstUsesWith(GEP, PtrOp);
9245 if (isa<UndefValue>(GEP.getOperand(0)))
9246 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9248 bool HasZeroPointerIndex = false;
9249 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9250 HasZeroPointerIndex = C->isNullValue();
9252 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9253 return ReplaceInstUsesWith(GEP, PtrOp);
9255 // Eliminate unneeded casts for indices.
9256 bool MadeChange = false;
9258 gep_type_iterator GTI = gep_type_begin(GEP);
9259 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
9260 if (isa<SequentialType>(*GTI)) {
9261 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
9262 if (CI->getOpcode() == Instruction::ZExt ||
9263 CI->getOpcode() == Instruction::SExt) {
9264 const Type *SrcTy = CI->getOperand(0)->getType();
9265 // We can eliminate a cast from i32 to i64 iff the target
9266 // is a 32-bit pointer target.
9267 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9269 GEP.setOperand(i, CI->getOperand(0));
9273 // If we are using a wider index than needed for this platform, shrink it
9274 // to what we need. If the incoming value needs a cast instruction,
9275 // insert it. This explicit cast can make subsequent optimizations more
9277 Value *Op = GEP.getOperand(i);
9278 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
9279 if (Constant *C = dyn_cast<Constant>(Op)) {
9280 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
9283 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9285 GEP.setOperand(i, Op);
9291 if (MadeChange) return &GEP;
9293 // If this GEP instruction doesn't move the pointer, and if the input operand
9294 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9295 // real input to the dest type.
9296 if (GEP.hasAllZeroIndices()) {
9297 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9298 // If the bitcast is of an allocation, and the allocation will be
9299 // converted to match the type of the cast, don't touch this.
9300 if (isa<AllocationInst>(BCI->getOperand(0))) {
9301 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
9302 if (Instruction *I = visitBitCast(*BCI)) {
9305 BCI->getParent()->getInstList().insert(BCI, I);
9306 ReplaceInstUsesWith(*BCI, I);
9311 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9315 // Combine Indices - If the source pointer to this getelementptr instruction
9316 // is a getelementptr instruction, combine the indices of the two
9317 // getelementptr instructions into a single instruction.
9319 SmallVector<Value*, 8> SrcGEPOperands;
9320 if (User *Src = dyn_castGetElementPtr(PtrOp))
9321 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9323 if (!SrcGEPOperands.empty()) {
9324 // Note that if our source is a gep chain itself that we wait for that
9325 // chain to be resolved before we perform this transformation. This
9326 // avoids us creating a TON of code in some cases.
9328 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9329 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9330 return 0; // Wait until our source is folded to completion.
9332 SmallVector<Value*, 8> Indices;
9334 // Find out whether the last index in the source GEP is a sequential idx.
9335 bool EndsWithSequential = false;
9336 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9337 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9338 EndsWithSequential = !isa<StructType>(*I);
9340 // Can we combine the two pointer arithmetics offsets?
9341 if (EndsWithSequential) {
9342 // Replace: gep (gep %P, long B), long A, ...
9343 // With: T = long A+B; gep %P, T, ...
9345 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9346 if (SO1 == Constant::getNullValue(SO1->getType())) {
9348 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9351 // If they aren't the same type, convert both to an integer of the
9352 // target's pointer size.
9353 if (SO1->getType() != GO1->getType()) {
9354 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9355 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9356 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9357 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9359 unsigned PS = TD->getPointerSizeInBits();
9360 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
9361 // Convert GO1 to SO1's type.
9362 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9364 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
9365 // Convert SO1 to GO1's type.
9366 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9368 const Type *PT = TD->getIntPtrType();
9369 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9370 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9374 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9375 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9377 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9378 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9382 // Recycle the GEP we already have if possible.
9383 if (SrcGEPOperands.size() == 2) {
9384 GEP.setOperand(0, SrcGEPOperands[0]);
9385 GEP.setOperand(1, Sum);
9388 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9389 SrcGEPOperands.end()-1);
9390 Indices.push_back(Sum);
9391 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9393 } else if (isa<Constant>(*GEP.idx_begin()) &&
9394 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9395 SrcGEPOperands.size() != 1) {
9396 // Otherwise we can do the fold if the first index of the GEP is a zero
9397 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9398 SrcGEPOperands.end());
9399 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9402 if (!Indices.empty())
9403 return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
9404 Indices.end(), GEP.getName());
9406 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9407 // GEP of global variable. If all of the indices for this GEP are
9408 // constants, we can promote this to a constexpr instead of an instruction.
9410 // Scan for nonconstants...
9411 SmallVector<Constant*, 8> Indices;
9412 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9413 for (; I != E && isa<Constant>(*I); ++I)
9414 Indices.push_back(cast<Constant>(*I));
9416 if (I == E) { // If they are all constants...
9417 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9418 &Indices[0],Indices.size());
9420 // Replace all uses of the GEP with the new constexpr...
9421 return ReplaceInstUsesWith(GEP, CE);
9423 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
9424 if (!isa<PointerType>(X->getType())) {
9425 // Not interesting. Source pointer must be a cast from pointer.
9426 } else if (HasZeroPointerIndex) {
9427 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9428 // into : GEP [10 x i8]* X, i32 0, ...
9430 // This occurs when the program declares an array extern like "int X[];"
9432 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9433 const PointerType *XTy = cast<PointerType>(X->getType());
9434 if (const ArrayType *XATy =
9435 dyn_cast<ArrayType>(XTy->getElementType()))
9436 if (const ArrayType *CATy =
9437 dyn_cast<ArrayType>(CPTy->getElementType()))
9438 if (CATy->getElementType() == XATy->getElementType()) {
9439 // At this point, we know that the cast source type is a pointer
9440 // to an array of the same type as the destination pointer
9441 // array. Because the array type is never stepped over (there
9442 // is a leading zero) we can fold the cast into this GEP.
9443 GEP.setOperand(0, X);
9446 } else if (GEP.getNumOperands() == 2) {
9447 // Transform things like:
9448 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9449 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
9450 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9451 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9452 if (isa<ArrayType>(SrcElTy) &&
9453 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9454 TD->getABITypeSize(ResElTy)) {
9456 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9457 Idx[1] = GEP.getOperand(1);
9458 Value *V = InsertNewInstBefore(
9459 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
9460 // V and GEP are both pointer types --> BitCast
9461 return new BitCastInst(V, GEP.getType());
9464 // Transform things like:
9465 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
9466 // (where tmp = 8*tmp2) into:
9467 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
9469 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
9470 uint64_t ArrayEltSize =
9471 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
9473 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9474 // allow either a mul, shift, or constant here.
9476 ConstantInt *Scale = 0;
9477 if (ArrayEltSize == 1) {
9478 NewIdx = GEP.getOperand(1);
9479 Scale = ConstantInt::get(NewIdx->getType(), 1);
9480 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9481 NewIdx = ConstantInt::get(CI->getType(), 1);
9483 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9484 if (Inst->getOpcode() == Instruction::Shl &&
9485 isa<ConstantInt>(Inst->getOperand(1))) {
9486 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9487 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9488 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9489 NewIdx = Inst->getOperand(0);
9490 } else if (Inst->getOpcode() == Instruction::Mul &&
9491 isa<ConstantInt>(Inst->getOperand(1))) {
9492 Scale = cast<ConstantInt>(Inst->getOperand(1));
9493 NewIdx = Inst->getOperand(0);
9497 // If the index will be to exactly the right offset with the scale taken
9498 // out, perform the transformation. Note, we don't know whether Scale is
9499 // signed or not. We'll use unsigned version of division/modulo
9500 // operation after making sure Scale doesn't have the sign bit set.
9501 if (Scale && Scale->getSExtValue() >= 0LL &&
9502 Scale->getZExtValue() % ArrayEltSize == 0) {
9503 Scale = ConstantInt::get(Scale->getType(),
9504 Scale->getZExtValue() / ArrayEltSize);
9505 if (Scale->getZExtValue() != 1) {
9506 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
9508 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9509 NewIdx = InsertNewInstBefore(Sc, GEP);
9512 // Insert the new GEP instruction.
9514 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9516 Instruction *NewGEP =
9517 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
9518 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9519 // The NewGEP must be pointer typed, so must the old one -> BitCast
9520 return new BitCastInst(NewGEP, GEP.getType());
9529 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9530 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9531 if (AI.isArrayAllocation()) { // Check C != 1
9532 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9534 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9535 AllocationInst *New = 0;
9537 // Create and insert the replacement instruction...
9538 if (isa<MallocInst>(AI))
9539 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9541 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9542 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9545 InsertNewInstBefore(New, AI);
9547 // Scan to the end of the allocation instructions, to skip over a block of
9548 // allocas if possible...
9550 BasicBlock::iterator It = New;
9551 while (isa<AllocationInst>(*It)) ++It;
9553 // Now that I is pointing to the first non-allocation-inst in the block,
9554 // insert our getelementptr instruction...
9556 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
9560 Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
9561 New->getName()+".sub", It);
9563 // Now make everything use the getelementptr instead of the original
9565 return ReplaceInstUsesWith(AI, V);
9566 } else if (isa<UndefValue>(AI.getArraySize())) {
9567 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9571 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9572 // Note that we only do this for alloca's, because malloc should allocate and
9573 // return a unique pointer, even for a zero byte allocation.
9574 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
9575 TD->getABITypeSize(AI.getAllocatedType()) == 0)
9576 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9581 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9582 Value *Op = FI.getOperand(0);
9584 // free undef -> unreachable.
9585 if (isa<UndefValue>(Op)) {
9586 // Insert a new store to null because we cannot modify the CFG here.
9587 new StoreInst(ConstantInt::getTrue(),
9588 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
9589 return EraseInstFromFunction(FI);
9592 // If we have 'free null' delete the instruction. This can happen in stl code
9593 // when lots of inlining happens.
9594 if (isa<ConstantPointerNull>(Op))
9595 return EraseInstFromFunction(FI);
9597 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9598 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9599 FI.setOperand(0, CI->getOperand(0));
9603 // Change free (gep X, 0,0,0,0) into free(X)
9604 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9605 if (GEPI->hasAllZeroIndices()) {
9606 AddToWorkList(GEPI);
9607 FI.setOperand(0, GEPI->getOperand(0));
9612 // Change free(malloc) into nothing, if the malloc has a single use.
9613 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9614 if (MI->hasOneUse()) {
9615 EraseInstFromFunction(FI);
9616 return EraseInstFromFunction(*MI);
9623 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
9624 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
9625 const TargetData *TD) {
9626 User *CI = cast<User>(LI.getOperand(0));
9627 Value *CastOp = CI->getOperand(0);
9629 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9630 // Instead of loading constant c string, use corresponding integer value
9631 // directly if string length is small enough.
9632 const std::string &Str = CE->getOperand(0)->getStringValue();
9634 unsigned len = Str.length();
9635 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9636 unsigned numBits = Ty->getPrimitiveSizeInBits();
9637 // Replace LI with immediate integer store.
9638 if ((numBits >> 3) == len + 1) {
9639 APInt StrVal(numBits, 0);
9640 APInt SingleChar(numBits, 0);
9641 if (TD->isLittleEndian()) {
9642 for (signed i = len-1; i >= 0; i--) {
9643 SingleChar = (uint64_t) Str[i];
9644 StrVal = (StrVal << 8) | SingleChar;
9647 for (unsigned i = 0; i < len; i++) {
9648 SingleChar = (uint64_t) Str[i];
9649 StrVal = (StrVal << 8) | SingleChar;
9651 // Append NULL at the end.
9653 StrVal = (StrVal << 8) | SingleChar;
9655 Value *NL = ConstantInt::get(StrVal);
9656 return IC.ReplaceInstUsesWith(LI, NL);
9661 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9662 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9663 const Type *SrcPTy = SrcTy->getElementType();
9665 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
9666 isa<VectorType>(DestPTy)) {
9667 // If the source is an array, the code below will not succeed. Check to
9668 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9670 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9671 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9672 if (ASrcTy->getNumElements() != 0) {
9674 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9675 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9676 SrcTy = cast<PointerType>(CastOp->getType());
9677 SrcPTy = SrcTy->getElementType();
9680 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
9681 isa<VectorType>(SrcPTy)) &&
9682 // Do not allow turning this into a load of an integer, which is then
9683 // casted to a pointer, this pessimizes pointer analysis a lot.
9684 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
9685 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9686 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9688 // Okay, we are casting from one integer or pointer type to another of
9689 // the same size. Instead of casting the pointer before the load, cast
9690 // the result of the loaded value.
9691 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9693 LI.isVolatile()),LI);
9694 // Now cast the result of the load.
9695 return new BitCastInst(NewLoad, LI.getType());
9702 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
9703 /// from this value cannot trap. If it is not obviously safe to load from the
9704 /// specified pointer, we do a quick local scan of the basic block containing
9705 /// ScanFrom, to determine if the address is already accessed.
9706 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
9707 // If it is an alloca it is always safe to load from.
9708 if (isa<AllocaInst>(V)) return true;
9710 // If it is a global variable it is mostly safe to load from.
9711 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
9712 // Don't try to evaluate aliases. External weak GV can be null.
9713 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
9715 // Otherwise, be a little bit agressive by scanning the local block where we
9716 // want to check to see if the pointer is already being loaded or stored
9717 // from/to. If so, the previous load or store would have already trapped,
9718 // so there is no harm doing an extra load (also, CSE will later eliminate
9719 // the load entirely).
9720 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9725 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9726 if (LI->getOperand(0) == V) return true;
9727 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9728 if (SI->getOperand(1) == V) return true;
9734 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9735 /// until we find the underlying object a pointer is referring to or something
9736 /// we don't understand. Note that the returned pointer may be offset from the
9737 /// input, because we ignore GEP indices.
9738 static Value *GetUnderlyingObject(Value *Ptr) {
9740 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9741 if (CE->getOpcode() == Instruction::BitCast ||
9742 CE->getOpcode() == Instruction::GetElementPtr)
9743 Ptr = CE->getOperand(0);
9746 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9747 Ptr = BCI->getOperand(0);
9748 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9749 Ptr = GEP->getOperand(0);
9756 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9757 Value *Op = LI.getOperand(0);
9759 // Attempt to improve the alignment.
9760 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
9761 if (KnownAlign > LI.getAlignment())
9762 LI.setAlignment(KnownAlign);
9764 // load (cast X) --> cast (load X) iff safe
9765 if (isa<CastInst>(Op))
9766 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
9769 // None of the following transforms are legal for volatile loads.
9770 if (LI.isVolatile()) return 0;
9772 if (&LI.getParent()->front() != &LI) {
9773 BasicBlock::iterator BBI = &LI; --BBI;
9774 // If the instruction immediately before this is a store to the same
9775 // address, do a simple form of store->load forwarding.
9776 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9777 if (SI->getOperand(1) == LI.getOperand(0))
9778 return ReplaceInstUsesWith(LI, SI->getOperand(0));
9779 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9780 if (LIB->getOperand(0) == LI.getOperand(0))
9781 return ReplaceInstUsesWith(LI, LIB);
9784 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9785 const Value *GEPI0 = GEPI->getOperand(0);
9786 // TODO: Consider a target hook for valid address spaces for this xform.
9787 if (isa<ConstantPointerNull>(GEPI0) &&
9788 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
9789 // Insert a new store to null instruction before the load to indicate
9790 // that this code is not reachable. We do this instead of inserting
9791 // an unreachable instruction directly because we cannot modify the
9793 new StoreInst(UndefValue::get(LI.getType()),
9794 Constant::getNullValue(Op->getType()), &LI);
9795 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9799 if (Constant *C = dyn_cast<Constant>(Op)) {
9800 // load null/undef -> undef
9801 // TODO: Consider a target hook for valid address spaces for this xform.
9802 if (isa<UndefValue>(C) || (C->isNullValue() &&
9803 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
9804 // Insert a new store to null instruction before the load to indicate that
9805 // this code is not reachable. We do this instead of inserting an
9806 // unreachable instruction directly because we cannot modify the CFG.
9807 new StoreInst(UndefValue::get(LI.getType()),
9808 Constant::getNullValue(Op->getType()), &LI);
9809 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9812 // Instcombine load (constant global) into the value loaded.
9813 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
9814 if (GV->isConstant() && !GV->isDeclaration())
9815 return ReplaceInstUsesWith(LI, GV->getInitializer());
9817 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9818 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
9819 if (CE->getOpcode() == Instruction::GetElementPtr) {
9820 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
9821 if (GV->isConstant() && !GV->isDeclaration())
9823 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
9824 return ReplaceInstUsesWith(LI, V);
9825 if (CE->getOperand(0)->isNullValue()) {
9826 // Insert a new store to null instruction before the load to indicate
9827 // that this code is not reachable. We do this instead of inserting
9828 // an unreachable instruction directly because we cannot modify the
9830 new StoreInst(UndefValue::get(LI.getType()),
9831 Constant::getNullValue(Op->getType()), &LI);
9832 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9835 } else if (CE->isCast()) {
9836 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
9842 // If this load comes from anywhere in a constant global, and if the global
9843 // is all undef or zero, we know what it loads.
9844 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9845 if (GV->isConstant() && GV->hasInitializer()) {
9846 if (GV->getInitializer()->isNullValue())
9847 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9848 else if (isa<UndefValue>(GV->getInitializer()))
9849 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9853 if (Op->hasOneUse()) {
9854 // Change select and PHI nodes to select values instead of addresses: this
9855 // helps alias analysis out a lot, allows many others simplifications, and
9856 // exposes redundancy in the code.
9858 // Note that we cannot do the transformation unless we know that the
9859 // introduced loads cannot trap! Something like this is valid as long as
9860 // the condition is always false: load (select bool %C, int* null, int* %G),
9861 // but it would not be valid if we transformed it to load from null
9864 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9865 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
9866 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9867 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
9868 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
9869 SI->getOperand(1)->getName()+".val"), LI);
9870 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
9871 SI->getOperand(2)->getName()+".val"), LI);
9872 return new SelectInst(SI->getCondition(), V1, V2);
9875 // load (select (cond, null, P)) -> load P
9876 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9877 if (C->isNullValue()) {
9878 LI.setOperand(0, SI->getOperand(2));
9882 // load (select (cond, P, null)) -> load P
9883 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9884 if (C->isNullValue()) {
9885 LI.setOperand(0, SI->getOperand(1));
9893 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
9895 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9896 User *CI = cast<User>(SI.getOperand(1));
9897 Value *CastOp = CI->getOperand(0);
9899 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9900 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9901 const Type *SrcPTy = SrcTy->getElementType();
9903 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
9904 // If the source is an array, the code below will not succeed. Check to
9905 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9907 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9908 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9909 if (ASrcTy->getNumElements() != 0) {
9911 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9912 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9913 SrcTy = cast<PointerType>(CastOp->getType());
9914 SrcPTy = SrcTy->getElementType();
9917 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9918 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9919 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9921 // Okay, we are casting from one integer or pointer type to another of
9922 // the same size. Instead of casting the pointer before
9923 // the store, cast the value to be stored.
9925 Value *SIOp0 = SI.getOperand(0);
9926 Instruction::CastOps opcode = Instruction::BitCast;
9927 const Type* CastSrcTy = SIOp0->getType();
9928 const Type* CastDstTy = SrcPTy;
9929 if (isa<PointerType>(CastDstTy)) {
9930 if (CastSrcTy->isInteger())
9931 opcode = Instruction::IntToPtr;
9932 } else if (isa<IntegerType>(CastDstTy)) {
9933 if (isa<PointerType>(SIOp0->getType()))
9934 opcode = Instruction::PtrToInt;
9936 if (Constant *C = dyn_cast<Constant>(SIOp0))
9937 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
9939 NewCast = IC.InsertNewInstBefore(
9940 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
9942 return new StoreInst(NewCast, CastOp);
9949 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9950 Value *Val = SI.getOperand(0);
9951 Value *Ptr = SI.getOperand(1);
9953 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
9954 EraseInstFromFunction(SI);
9959 // If the RHS is an alloca with a single use, zapify the store, making the
9961 if (Ptr->hasOneUse()) {
9962 if (isa<AllocaInst>(Ptr)) {
9963 EraseInstFromFunction(SI);
9968 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9969 if (isa<AllocaInst>(GEP->getOperand(0)) &&
9970 GEP->getOperand(0)->hasOneUse()) {
9971 EraseInstFromFunction(SI);
9977 // Attempt to improve the alignment.
9978 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
9979 if (KnownAlign > SI.getAlignment())
9980 SI.setAlignment(KnownAlign);
9982 // Do really simple DSE, to catch cases where there are several consequtive
9983 // stores to the same location, separated by a few arithmetic operations. This
9984 // situation often occurs with bitfield accesses.
9985 BasicBlock::iterator BBI = &SI;
9986 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9990 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9991 // Prev store isn't volatile, and stores to the same location?
9992 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9995 EraseInstFromFunction(*PrevSI);
10001 // If this is a load, we have to stop. However, if the loaded value is from
10002 // the pointer we're loading and is producing the pointer we're storing,
10003 // then *this* store is dead (X = load P; store X -> P).
10004 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10005 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
10006 EraseInstFromFunction(SI);
10010 // Otherwise, this is a load from some other location. Stores before it
10011 // may not be dead.
10015 // Don't skip over loads or things that can modify memory.
10016 if (BBI->mayWriteToMemory())
10021 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
10023 // store X, null -> turns into 'unreachable' in SimplifyCFG
10024 if (isa<ConstantPointerNull>(Ptr)) {
10025 if (!isa<UndefValue>(Val)) {
10026 SI.setOperand(0, UndefValue::get(Val->getType()));
10027 if (Instruction *U = dyn_cast<Instruction>(Val))
10028 AddToWorkList(U); // Dropped a use.
10031 return 0; // Do not modify these!
10034 // store undef, Ptr -> noop
10035 if (isa<UndefValue>(Val)) {
10036 EraseInstFromFunction(SI);
10041 // If the pointer destination is a cast, see if we can fold the cast into the
10043 if (isa<CastInst>(Ptr))
10044 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10046 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10048 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10052 // If this store is the last instruction in the basic block, and if the block
10053 // ends with an unconditional branch, try to move it to the successor block.
10055 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10056 if (BI->isUnconditional())
10057 if (SimplifyStoreAtEndOfBlock(SI))
10058 return 0; // xform done!
10063 /// SimplifyStoreAtEndOfBlock - Turn things like:
10064 /// if () { *P = v1; } else { *P = v2 }
10065 /// into a phi node with a store in the successor.
10067 /// Simplify things like:
10068 /// *P = v1; if () { *P = v2; }
10069 /// into a phi node with a store in the successor.
10071 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10072 BasicBlock *StoreBB = SI.getParent();
10074 // Check to see if the successor block has exactly two incoming edges. If
10075 // so, see if the other predecessor contains a store to the same location.
10076 // if so, insert a PHI node (if needed) and move the stores down.
10077 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10079 // Determine whether Dest has exactly two predecessors and, if so, compute
10080 // the other predecessor.
10081 pred_iterator PI = pred_begin(DestBB);
10082 BasicBlock *OtherBB = 0;
10083 if (*PI != StoreBB)
10086 if (PI == pred_end(DestBB))
10089 if (*PI != StoreBB) {
10094 if (++PI != pred_end(DestBB))
10098 // Verify that the other block ends in a branch and is not otherwise empty.
10099 BasicBlock::iterator BBI = OtherBB->getTerminator();
10100 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10101 if (!OtherBr || BBI == OtherBB->begin())
10104 // If the other block ends in an unconditional branch, check for the 'if then
10105 // else' case. there is an instruction before the branch.
10106 StoreInst *OtherStore = 0;
10107 if (OtherBr->isUnconditional()) {
10108 // If this isn't a store, or isn't a store to the same location, bail out.
10110 OtherStore = dyn_cast<StoreInst>(BBI);
10111 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10114 // Otherwise, the other block ended with a conditional branch. If one of the
10115 // destinations is StoreBB, then we have the if/then case.
10116 if (OtherBr->getSuccessor(0) != StoreBB &&
10117 OtherBr->getSuccessor(1) != StoreBB)
10120 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10121 // if/then triangle. See if there is a store to the same ptr as SI that
10122 // lives in OtherBB.
10124 // Check to see if we find the matching store.
10125 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10126 if (OtherStore->getOperand(1) != SI.getOperand(1))
10130 // If we find something that may be using the stored value, or if we run
10131 // out of instructions, we can't do the xform.
10132 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10133 BBI == OtherBB->begin())
10137 // In order to eliminate the store in OtherBr, we have to
10138 // make sure nothing reads the stored value in StoreBB.
10139 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10140 // FIXME: This should really be AA driven.
10141 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10146 // Insert a PHI node now if we need it.
10147 Value *MergedVal = OtherStore->getOperand(0);
10148 if (MergedVal != SI.getOperand(0)) {
10149 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
10150 PN->reserveOperandSpace(2);
10151 PN->addIncoming(SI.getOperand(0), SI.getParent());
10152 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10153 MergedVal = InsertNewInstBefore(PN, DestBB->front());
10156 // Advance to a place where it is safe to insert the new store and
10158 BBI = DestBB->begin();
10159 while (isa<PHINode>(BBI)) ++BBI;
10160 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10161 OtherStore->isVolatile()), *BBI);
10163 // Nuke the old stores.
10164 EraseInstFromFunction(SI);
10165 EraseInstFromFunction(*OtherStore);
10171 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10172 // Change br (not X), label True, label False to: br X, label False, True
10174 BasicBlock *TrueDest;
10175 BasicBlock *FalseDest;
10176 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10177 !isa<Constant>(X)) {
10178 // Swap Destinations and condition...
10179 BI.setCondition(X);
10180 BI.setSuccessor(0, FalseDest);
10181 BI.setSuccessor(1, TrueDest);
10185 // Cannonicalize fcmp_one -> fcmp_oeq
10186 FCmpInst::Predicate FPred; Value *Y;
10187 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10188 TrueDest, FalseDest)))
10189 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10190 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10191 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10192 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10193 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10194 NewSCC->takeName(I);
10195 // Swap Destinations and condition...
10196 BI.setCondition(NewSCC);
10197 BI.setSuccessor(0, FalseDest);
10198 BI.setSuccessor(1, TrueDest);
10199 RemoveFromWorkList(I);
10200 I->eraseFromParent();
10201 AddToWorkList(NewSCC);
10205 // Cannonicalize icmp_ne -> icmp_eq
10206 ICmpInst::Predicate IPred;
10207 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10208 TrueDest, FalseDest)))
10209 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10210 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10211 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10212 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10213 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10214 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10215 NewSCC->takeName(I);
10216 // Swap Destinations and condition...
10217 BI.setCondition(NewSCC);
10218 BI.setSuccessor(0, FalseDest);
10219 BI.setSuccessor(1, TrueDest);
10220 RemoveFromWorkList(I);
10221 I->eraseFromParent();;
10222 AddToWorkList(NewSCC);
10229 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10230 Value *Cond = SI.getCondition();
10231 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10232 if (I->getOpcode() == Instruction::Add)
10233 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10234 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10235 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10236 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10238 SI.setOperand(0, I->getOperand(0));
10246 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10247 /// is to leave as a vector operation.
10248 static bool CheapToScalarize(Value *V, bool isConstant) {
10249 if (isa<ConstantAggregateZero>(V))
10251 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10252 if (isConstant) return true;
10253 // If all elts are the same, we can extract.
10254 Constant *Op0 = C->getOperand(0);
10255 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10256 if (C->getOperand(i) != Op0)
10260 Instruction *I = dyn_cast<Instruction>(V);
10261 if (!I) return false;
10263 // Insert element gets simplified to the inserted element or is deleted if
10264 // this is constant idx extract element and its a constant idx insertelt.
10265 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10266 isa<ConstantInt>(I->getOperand(2)))
10268 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10270 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10271 if (BO->hasOneUse() &&
10272 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10273 CheapToScalarize(BO->getOperand(1), isConstant)))
10275 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10276 if (CI->hasOneUse() &&
10277 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10278 CheapToScalarize(CI->getOperand(1), isConstant)))
10284 /// Read and decode a shufflevector mask.
10286 /// It turns undef elements into values that are larger than the number of
10287 /// elements in the input.
10288 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10289 unsigned NElts = SVI->getType()->getNumElements();
10290 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10291 return std::vector<unsigned>(NElts, 0);
10292 if (isa<UndefValue>(SVI->getOperand(2)))
10293 return std::vector<unsigned>(NElts, 2*NElts);
10295 std::vector<unsigned> Result;
10296 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10297 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10298 if (isa<UndefValue>(CP->getOperand(i)))
10299 Result.push_back(NElts*2); // undef -> 8
10301 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
10305 /// FindScalarElement - Given a vector and an element number, see if the scalar
10306 /// value is already around as a register, for example if it were inserted then
10307 /// extracted from the vector.
10308 static Value *FindScalarElement(Value *V, unsigned EltNo) {
10309 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10310 const VectorType *PTy = cast<VectorType>(V->getType());
10311 unsigned Width = PTy->getNumElements();
10312 if (EltNo >= Width) // Out of range access.
10313 return UndefValue::get(PTy->getElementType());
10315 if (isa<UndefValue>(V))
10316 return UndefValue::get(PTy->getElementType());
10317 else if (isa<ConstantAggregateZero>(V))
10318 return Constant::getNullValue(PTy->getElementType());
10319 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10320 return CP->getOperand(EltNo);
10321 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10322 // If this is an insert to a variable element, we don't know what it is.
10323 if (!isa<ConstantInt>(III->getOperand(2)))
10325 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10327 // If this is an insert to the element we are looking for, return the
10329 if (EltNo == IIElt)
10330 return III->getOperand(1);
10332 // Otherwise, the insertelement doesn't modify the value, recurse on its
10334 return FindScalarElement(III->getOperand(0), EltNo);
10335 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10336 unsigned InEl = getShuffleMask(SVI)[EltNo];
10338 return FindScalarElement(SVI->getOperand(0), InEl);
10339 else if (InEl < Width*2)
10340 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10342 return UndefValue::get(PTy->getElementType());
10345 // Otherwise, we don't know.
10349 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10351 // If vector val is undef, replace extract with scalar undef.
10352 if (isa<UndefValue>(EI.getOperand(0)))
10353 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10355 // If vector val is constant 0, replace extract with scalar 0.
10356 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10357 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10359 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10360 // If vector val is constant with uniform operands, replace EI
10361 // with that operand
10362 Constant *op0 = C->getOperand(0);
10363 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10364 if (C->getOperand(i) != op0) {
10369 return ReplaceInstUsesWith(EI, op0);
10372 // If extracting a specified index from the vector, see if we can recursively
10373 // find a previously computed scalar that was inserted into the vector.
10374 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10375 unsigned IndexVal = IdxC->getZExtValue();
10376 unsigned VectorWidth =
10377 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10379 // If this is extracting an invalid index, turn this into undef, to avoid
10380 // crashing the code below.
10381 if (IndexVal >= VectorWidth)
10382 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10384 // This instruction only demands the single element from the input vector.
10385 // If the input vector has a single use, simplify it based on this use
10387 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10388 uint64_t UndefElts;
10389 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10392 EI.setOperand(0, V);
10397 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10398 return ReplaceInstUsesWith(EI, Elt);
10400 // If the this extractelement is directly using a bitcast from a vector of
10401 // the same number of elements, see if we can find the source element from
10402 // it. In this case, we will end up needing to bitcast the scalars.
10403 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10404 if (const VectorType *VT =
10405 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10406 if (VT->getNumElements() == VectorWidth)
10407 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10408 return new BitCastInst(Elt, EI.getType());
10412 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10413 if (I->hasOneUse()) {
10414 // Push extractelement into predecessor operation if legal and
10415 // profitable to do so
10416 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10417 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10418 if (CheapToScalarize(BO, isConstantElt)) {
10419 ExtractElementInst *newEI0 =
10420 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10421 EI.getName()+".lhs");
10422 ExtractElementInst *newEI1 =
10423 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10424 EI.getName()+".rhs");
10425 InsertNewInstBefore(newEI0, EI);
10426 InsertNewInstBefore(newEI1, EI);
10427 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10429 } else if (isa<LoadInst>(I)) {
10431 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
10432 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10433 PointerType::get(EI.getType(), AS),EI);
10434 GetElementPtrInst *GEP =
10435 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
10436 InsertNewInstBefore(GEP, EI);
10437 return new LoadInst(GEP);
10440 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10441 // Extracting the inserted element?
10442 if (IE->getOperand(2) == EI.getOperand(1))
10443 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10444 // If the inserted and extracted elements are constants, they must not
10445 // be the same value, extract from the pre-inserted value instead.
10446 if (isa<Constant>(IE->getOperand(2)) &&
10447 isa<Constant>(EI.getOperand(1))) {
10448 AddUsesToWorkList(EI);
10449 EI.setOperand(0, IE->getOperand(0));
10452 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10453 // If this is extracting an element from a shufflevector, figure out where
10454 // it came from and extract from the appropriate input element instead.
10455 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10456 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10458 if (SrcIdx < SVI->getType()->getNumElements())
10459 Src = SVI->getOperand(0);
10460 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10461 SrcIdx -= SVI->getType()->getNumElements();
10462 Src = SVI->getOperand(1);
10464 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10466 return new ExtractElementInst(Src, SrcIdx);
10473 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10474 /// elements from either LHS or RHS, return the shuffle mask and true.
10475 /// Otherwise, return false.
10476 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10477 std::vector<Constant*> &Mask) {
10478 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10479 "Invalid CollectSingleShuffleElements");
10480 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10482 if (isa<UndefValue>(V)) {
10483 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10485 } else if (V == LHS) {
10486 for (unsigned i = 0; i != NumElts; ++i)
10487 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10489 } else if (V == RHS) {
10490 for (unsigned i = 0; i != NumElts; ++i)
10491 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10493 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10494 // If this is an insert of an extract from some other vector, include it.
10495 Value *VecOp = IEI->getOperand(0);
10496 Value *ScalarOp = IEI->getOperand(1);
10497 Value *IdxOp = IEI->getOperand(2);
10499 if (!isa<ConstantInt>(IdxOp))
10501 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10503 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10504 // Okay, we can handle this if the vector we are insertinting into is
10505 // transitively ok.
10506 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10507 // If so, update the mask to reflect the inserted undef.
10508 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10511 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10512 if (isa<ConstantInt>(EI->getOperand(1)) &&
10513 EI->getOperand(0)->getType() == V->getType()) {
10514 unsigned ExtractedIdx =
10515 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10517 // This must be extracting from either LHS or RHS.
10518 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10519 // Okay, we can handle this if the vector we are insertinting into is
10520 // transitively ok.
10521 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10522 // If so, update the mask to reflect the inserted value.
10523 if (EI->getOperand(0) == LHS) {
10524 Mask[InsertedIdx & (NumElts-1)] =
10525 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10527 assert(EI->getOperand(0) == RHS);
10528 Mask[InsertedIdx & (NumElts-1)] =
10529 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10538 // TODO: Handle shufflevector here!
10543 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10544 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10545 /// that computes V and the LHS value of the shuffle.
10546 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10548 assert(isa<VectorType>(V->getType()) &&
10549 (RHS == 0 || V->getType() == RHS->getType()) &&
10550 "Invalid shuffle!");
10551 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10553 if (isa<UndefValue>(V)) {
10554 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10556 } else if (isa<ConstantAggregateZero>(V)) {
10557 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10559 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10560 // If this is an insert of an extract from some other vector, include it.
10561 Value *VecOp = IEI->getOperand(0);
10562 Value *ScalarOp = IEI->getOperand(1);
10563 Value *IdxOp = IEI->getOperand(2);
10565 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10566 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10567 EI->getOperand(0)->getType() == V->getType()) {
10568 unsigned ExtractedIdx =
10569 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10570 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10572 // Either the extracted from or inserted into vector must be RHSVec,
10573 // otherwise we'd end up with a shuffle of three inputs.
10574 if (EI->getOperand(0) == RHS || RHS == 0) {
10575 RHS = EI->getOperand(0);
10576 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10577 Mask[InsertedIdx & (NumElts-1)] =
10578 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10582 if (VecOp == RHS) {
10583 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
10584 // Everything but the extracted element is replaced with the RHS.
10585 for (unsigned i = 0; i != NumElts; ++i) {
10586 if (i != InsertedIdx)
10587 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
10592 // If this insertelement is a chain that comes from exactly these two
10593 // vectors, return the vector and the effective shuffle.
10594 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10595 return EI->getOperand(0);
10600 // TODO: Handle shufflevector here!
10602 // Otherwise, can't do anything fancy. Return an identity vector.
10603 for (unsigned i = 0; i != NumElts; ++i)
10604 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10608 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10609 Value *VecOp = IE.getOperand(0);
10610 Value *ScalarOp = IE.getOperand(1);
10611 Value *IdxOp = IE.getOperand(2);
10613 // Inserting an undef or into an undefined place, remove this.
10614 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10615 ReplaceInstUsesWith(IE, VecOp);
10617 // If the inserted element was extracted from some other vector, and if the
10618 // indexes are constant, try to turn this into a shufflevector operation.
10619 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10620 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10621 EI->getOperand(0)->getType() == IE.getType()) {
10622 unsigned NumVectorElts = IE.getType()->getNumElements();
10623 unsigned ExtractedIdx =
10624 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10625 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10627 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10628 return ReplaceInstUsesWith(IE, VecOp);
10630 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10631 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10633 // If we are extracting a value from a vector, then inserting it right
10634 // back into the same place, just use the input vector.
10635 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10636 return ReplaceInstUsesWith(IE, VecOp);
10638 // We could theoretically do this for ANY input. However, doing so could
10639 // turn chains of insertelement instructions into a chain of shufflevector
10640 // instructions, and right now we do not merge shufflevectors. As such,
10641 // only do this in a situation where it is clear that there is benefit.
10642 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10643 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
10644 // the values of VecOp, except then one read from EIOp0.
10645 // Build a new shuffle mask.
10646 std::vector<Constant*> Mask;
10647 if (isa<UndefValue>(VecOp))
10648 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
10650 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
10651 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
10654 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10655 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
10656 ConstantVector::get(Mask));
10659 // If this insertelement isn't used by some other insertelement, turn it
10660 // (and any insertelements it points to), into one big shuffle.
10661 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10662 std::vector<Constant*> Mask;
10664 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10665 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10666 // We now have a shuffle of LHS, RHS, Mask.
10667 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
10676 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10677 Value *LHS = SVI.getOperand(0);
10678 Value *RHS = SVI.getOperand(1);
10679 std::vector<unsigned> Mask = getShuffleMask(&SVI);
10681 bool MadeChange = false;
10683 // Undefined shuffle mask -> undefined value.
10684 if (isa<UndefValue>(SVI.getOperand(2)))
10685 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10687 // If we have shuffle(x, undef, mask) and any elements of mask refer to
10688 // the undef, change them to undefs.
10689 if (isa<UndefValue>(SVI.getOperand(1))) {
10690 // Scan to see if there are any references to the RHS. If so, replace them
10691 // with undef element refs and set MadeChange to true.
10692 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10693 if (Mask[i] >= e && Mask[i] != 2*e) {
10700 // Remap any references to RHS to use LHS.
10701 std::vector<Constant*> Elts;
10702 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10703 if (Mask[i] == 2*e)
10704 Elts.push_back(UndefValue::get(Type::Int32Ty));
10706 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10708 SVI.setOperand(2, ConstantVector::get(Elts));
10712 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
10713 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10714 if (LHS == RHS || isa<UndefValue>(LHS)) {
10715 if (isa<UndefValue>(LHS) && LHS == RHS) {
10716 // shuffle(undef,undef,mask) -> undef.
10717 return ReplaceInstUsesWith(SVI, LHS);
10720 // Remap any references to RHS to use LHS.
10721 std::vector<Constant*> Elts;
10722 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10723 if (Mask[i] >= 2*e)
10724 Elts.push_back(UndefValue::get(Type::Int32Ty));
10726 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10727 (Mask[i] < e && isa<UndefValue>(LHS)))
10728 Mask[i] = 2*e; // Turn into undef.
10730 Mask[i] &= (e-1); // Force to LHS.
10731 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10734 SVI.setOperand(0, SVI.getOperand(1));
10735 SVI.setOperand(1, UndefValue::get(RHS->getType()));
10736 SVI.setOperand(2, ConstantVector::get(Elts));
10737 LHS = SVI.getOperand(0);
10738 RHS = SVI.getOperand(1);
10742 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
10743 bool isLHSID = true, isRHSID = true;
10745 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10746 if (Mask[i] >= e*2) continue; // Ignore undef values.
10747 // Is this an identity shuffle of the LHS value?
10748 isLHSID &= (Mask[i] == i);
10750 // Is this an identity shuffle of the RHS value?
10751 isRHSID &= (Mask[i]-e == i);
10754 // Eliminate identity shuffles.
10755 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10756 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
10758 // If the LHS is a shufflevector itself, see if we can combine it with this
10759 // one without producing an unusual shuffle. Here we are really conservative:
10760 // we are absolutely afraid of producing a shuffle mask not in the input
10761 // program, because the code gen may not be smart enough to turn a merged
10762 // shuffle into two specific shuffles: it may produce worse code. As such,
10763 // we only merge two shuffles if the result is one of the two input shuffle
10764 // masks. In this case, merging the shuffles just removes one instruction,
10765 // which we know is safe. This is good for things like turning:
10766 // (splat(splat)) -> splat.
10767 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10768 if (isa<UndefValue>(RHS)) {
10769 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10771 std::vector<unsigned> NewMask;
10772 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10773 if (Mask[i] >= 2*e)
10774 NewMask.push_back(2*e);
10776 NewMask.push_back(LHSMask[Mask[i]]);
10778 // If the result mask is equal to the src shuffle or this shuffle mask, do
10779 // the replacement.
10780 if (NewMask == LHSMask || NewMask == Mask) {
10781 std::vector<Constant*> Elts;
10782 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10783 if (NewMask[i] >= e*2) {
10784 Elts.push_back(UndefValue::get(Type::Int32Ty));
10786 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
10789 return new ShuffleVectorInst(LHSSVI->getOperand(0),
10790 LHSSVI->getOperand(1),
10791 ConstantVector::get(Elts));
10796 return MadeChange ? &SVI : 0;
10802 /// TryToSinkInstruction - Try to move the specified instruction from its
10803 /// current block into the beginning of DestBlock, which can only happen if it's
10804 /// safe to move the instruction past all of the instructions between it and the
10805 /// end of its block.
10806 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10807 assert(I->hasOneUse() && "Invariants didn't hold!");
10809 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10810 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
10812 // Do not sink alloca instructions out of the entry block.
10813 if (isa<AllocaInst>(I) && I->getParent() ==
10814 &DestBlock->getParent()->getEntryBlock())
10817 // We can only sink load instructions if there is nothing between the load and
10818 // the end of block that could change the value.
10819 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10820 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10822 if (Scan->mayWriteToMemory())
10826 BasicBlock::iterator InsertPos = DestBlock->begin();
10827 while (isa<PHINode>(InsertPos)) ++InsertPos;
10829 I->moveBefore(InsertPos);
10835 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10836 /// all reachable code to the worklist.
10838 /// This has a couple of tricks to make the code faster and more powerful. In
10839 /// particular, we constant fold and DCE instructions as we go, to avoid adding
10840 /// them to the worklist (this significantly speeds up instcombine on code where
10841 /// many instructions are dead or constant). Additionally, if we find a branch
10842 /// whose condition is a known constant, we only visit the reachable successors.
10844 static void AddReachableCodeToWorklist(BasicBlock *BB,
10845 SmallPtrSet<BasicBlock*, 64> &Visited,
10847 const TargetData *TD) {
10848 std::vector<BasicBlock*> Worklist;
10849 Worklist.push_back(BB);
10851 while (!Worklist.empty()) {
10852 BB = Worklist.back();
10853 Worklist.pop_back();
10855 // We have now visited this block! If we've already been here, ignore it.
10856 if (!Visited.insert(BB)) continue;
10858 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10859 Instruction *Inst = BBI++;
10861 // DCE instruction if trivially dead.
10862 if (isInstructionTriviallyDead(Inst)) {
10864 DOUT << "IC: DCE: " << *Inst;
10865 Inst->eraseFromParent();
10869 // ConstantProp instruction if trivially constant.
10870 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10871 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10872 Inst->replaceAllUsesWith(C);
10874 Inst->eraseFromParent();
10878 IC.AddToWorkList(Inst);
10881 // Recursively visit successors. If this is a branch or switch on a
10882 // constant, only visit the reachable successor.
10883 if (BB->getUnwindDest())
10884 Worklist.push_back(BB->getUnwindDest());
10885 TerminatorInst *TI = BB->getTerminator();
10886 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10887 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10888 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
10889 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
10890 if (ReachableBB != BB->getUnwindDest())
10891 Worklist.push_back(ReachableBB);
10894 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10895 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10896 // See if this is an explicit destination.
10897 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10898 if (SI->getCaseValue(i) == Cond) {
10899 BasicBlock *ReachableBB = SI->getSuccessor(i);
10900 if (ReachableBB != BB->getUnwindDest())
10901 Worklist.push_back(ReachableBB);
10905 // Otherwise it is the default destination.
10906 Worklist.push_back(SI->getSuccessor(0));
10911 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10912 Worklist.push_back(TI->getSuccessor(i));
10916 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
10917 bool Changed = false;
10918 TD = &getAnalysis<TargetData>();
10920 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10921 << F.getNameStr() << "\n");
10924 // Do a depth-first traversal of the function, populate the worklist with
10925 // the reachable instructions. Ignore blocks that are not reachable. Keep
10926 // track of which blocks we visit.
10927 SmallPtrSet<BasicBlock*, 64> Visited;
10928 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
10930 // Do a quick scan over the function. If we find any blocks that are
10931 // unreachable, remove any instructions inside of them. This prevents
10932 // the instcombine code from having to deal with some bad special cases.
10933 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10934 if (!Visited.count(BB)) {
10935 Instruction *Term = BB->getTerminator();
10936 while (Term != BB->begin()) { // Remove instrs bottom-up
10937 BasicBlock::iterator I = Term; --I;
10939 DOUT << "IC: DCE: " << *I;
10942 if (!I->use_empty())
10943 I->replaceAllUsesWith(UndefValue::get(I->getType()));
10944 I->eraseFromParent();
10949 while (!Worklist.empty()) {
10950 Instruction *I = RemoveOneFromWorkList();
10951 if (I == 0) continue; // skip null values.
10953 // Check to see if we can DCE the instruction.
10954 if (isInstructionTriviallyDead(I)) {
10955 // Add operands to the worklist.
10956 if (I->getNumOperands() < 4)
10957 AddUsesToWorkList(*I);
10960 DOUT << "IC: DCE: " << *I;
10962 I->eraseFromParent();
10963 RemoveFromWorkList(I);
10967 // Instruction isn't dead, see if we can constant propagate it.
10968 if (Constant *C = ConstantFoldInstruction(I, TD)) {
10969 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
10971 // Add operands to the worklist.
10972 AddUsesToWorkList(*I);
10973 ReplaceInstUsesWith(*I, C);
10976 I->eraseFromParent();
10977 RemoveFromWorkList(I);
10981 // See if we can trivially sink this instruction to a successor basic block.
10982 if (I->hasOneUse()) {
10983 BasicBlock *BB = I->getParent();
10984 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10985 if (UserParent != BB) {
10986 bool UserIsSuccessor = false;
10987 // See if the user is one of our successors.
10988 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10989 if (*SI == UserParent) {
10990 UserIsSuccessor = true;
10994 // If the user is one of our immediate successors, and if that successor
10995 // only has us as a predecessors (we'd have to split the critical edge
10996 // otherwise), we can keep going.
10997 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10998 next(pred_begin(UserParent)) == pred_end(UserParent))
10999 // Okay, the CFG is simple enough, try to sink this instruction.
11000 Changed |= TryToSinkInstruction(I, UserParent);
11004 // Now that we have an instruction, try combining it to simplify it...
11008 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11009 if (Instruction *Result = visit(*I)) {
11011 // Should we replace the old instruction with a new one?
11013 DOUT << "IC: Old = " << *I
11014 << " New = " << *Result;
11016 // Everything uses the new instruction now.
11017 I->replaceAllUsesWith(Result);
11019 // Push the new instruction and any users onto the worklist.
11020 AddToWorkList(Result);
11021 AddUsersToWorkList(*Result);
11023 // Move the name to the new instruction first.
11024 Result->takeName(I);
11026 // Insert the new instruction into the basic block...
11027 BasicBlock *InstParent = I->getParent();
11028 BasicBlock::iterator InsertPos = I;
11030 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11031 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11034 InstParent->getInstList().insert(InsertPos, Result);
11036 // Make sure that we reprocess all operands now that we reduced their
11038 AddUsesToWorkList(*I);
11040 // Instructions can end up on the worklist more than once. Make sure
11041 // we do not process an instruction that has been deleted.
11042 RemoveFromWorkList(I);
11044 // Erase the old instruction.
11045 InstParent->getInstList().erase(I);
11048 DOUT << "IC: Mod = " << OrigI
11049 << " New = " << *I;
11052 // If the instruction was modified, it's possible that it is now dead.
11053 // if so, remove it.
11054 if (isInstructionTriviallyDead(I)) {
11055 // Make sure we process all operands now that we are reducing their
11057 AddUsesToWorkList(*I);
11059 // Instructions may end up in the worklist more than once. Erase all
11060 // occurrences of this instruction.
11061 RemoveFromWorkList(I);
11062 I->eraseFromParent();
11065 AddUsersToWorkList(*I);
11072 assert(WorklistMap.empty() && "Worklist empty, but map not?");
11074 // Do an explicit clear, this shrinks the map if needed.
11075 WorklistMap.clear();
11080 bool InstCombiner::runOnFunction(Function &F) {
11081 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11083 bool EverMadeChange = false;
11085 // Iterate while there is work to do.
11086 unsigned Iteration = 0;
11087 while (DoOneIteration(F, Iteration++))
11088 EverMadeChange = true;
11089 return EverMadeChange;
11092 FunctionPass *llvm::createInstructionCombiningPass() {
11093 return new InstCombiner();