1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions. This pass does not modify the CFG. This pass is where
12 // algebraic simplification happens.
14 // This pass combines things like:
20 // This is a simple worklist driven algorithm.
22 // This pass guarantees that the following canonicalizations are performed on
24 // 1. If a binary operator has a constant operand, it is moved to the RHS
25 // 2. Bitwise operators with constant operands are always grouped so that
26 // shifts are performed first, then or's, then and's, then xor's.
27 // 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All cmp instructions on boolean values are replaced with logical ops
29 // 5. add X, X is represented as (X*2) => (X << 1)
30 // 6. Multiplies with a power-of-two constant argument are transformed into
34 //===----------------------------------------------------------------------===//
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Analysis/ConstantFolding.h"
43 #include "llvm/Analysis/ValueTracking.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/ConstantRange.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/GetElementPtrTypeIterator.h"
51 #include "llvm/Support/InstVisitor.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/PatternMatch.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/ADT/DenseMap.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/Statistic.h"
59 #include "llvm/ADT/STLExtras.h"
64 using namespace llvm::PatternMatch;
66 STATISTIC(NumCombined , "Number of insts combined");
67 STATISTIC(NumConstProp, "Number of constant folds");
68 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70 STATISTIC(NumSunkInst , "Number of instructions sunk");
73 class VISIBILITY_HIDDEN InstCombiner
74 : public FunctionPass,
75 public InstVisitor<InstCombiner, Instruction*> {
76 // Worklist of all of the instructions that need to be simplified.
77 std::vector<Instruction*> Worklist;
78 DenseMap<Instruction*, unsigned> WorklistMap;
80 bool MustPreserveLCSSA;
82 static char ID; // Pass identification, replacement for typeid
83 InstCombiner() : FunctionPass((intptr_t)&ID) {}
85 /// AddToWorkList - Add the specified instruction to the worklist if it
86 /// isn't already in it.
87 void AddToWorkList(Instruction *I) {
88 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
89 Worklist.push_back(I);
92 // RemoveFromWorkList - remove I from the worklist if it exists.
93 void RemoveFromWorkList(Instruction *I) {
94 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95 if (It == WorklistMap.end()) return; // Not in worklist.
97 // Don't bother moving everything down, just null out the slot.
98 Worklist[It->second] = 0;
100 WorklistMap.erase(It);
103 Instruction *RemoveOneFromWorkList() {
104 Instruction *I = Worklist.back();
106 WorklistMap.erase(I);
111 /// AddUsersToWorkList - When an instruction is simplified, add all users of
112 /// the instruction to the work lists because they might get more simplified
115 void AddUsersToWorkList(Value &I) {
116 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
118 AddToWorkList(cast<Instruction>(*UI));
121 /// AddUsesToWorkList - When an instruction is simplified, add operands to
122 /// the work lists because they might get more simplified now.
124 void AddUsesToWorkList(Instruction &I) {
125 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126 if (Instruction *Op = dyn_cast<Instruction>(*i))
130 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131 /// dead. Add all of its operands to the worklist, turning them into
132 /// undef's to reduce the number of uses of those instructions.
134 /// Return the specified operand before it is turned into an undef.
136 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137 Value *R = I.getOperand(op);
139 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
142 // Set the operand to undef to drop the use.
143 *i = UndefValue::get(Op->getType());
150 virtual bool runOnFunction(Function &F);
152 bool DoOneIteration(Function &F, unsigned ItNum);
154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
155 AU.addRequired<TargetData>();
156 AU.addPreservedID(LCSSAID);
157 AU.setPreservesCFG();
160 TargetData &getTargetData() const { return *TD; }
162 // Visitation implementation - Implement instruction combining for different
163 // instruction types. The semantics are as follows:
165 // null - No change was made
166 // I - Change was made, I is still valid, I may be dead though
167 // otherwise - Change was made, replace I with returned instruction
169 Instruction *visitAdd(BinaryOperator &I);
170 Instruction *visitSub(BinaryOperator &I);
171 Instruction *visitMul(BinaryOperator &I);
172 Instruction *visitURem(BinaryOperator &I);
173 Instruction *visitSRem(BinaryOperator &I);
174 Instruction *visitFRem(BinaryOperator &I);
175 Instruction *commonRemTransforms(BinaryOperator &I);
176 Instruction *commonIRemTransforms(BinaryOperator &I);
177 Instruction *commonDivTransforms(BinaryOperator &I);
178 Instruction *commonIDivTransforms(BinaryOperator &I);
179 Instruction *visitUDiv(BinaryOperator &I);
180 Instruction *visitSDiv(BinaryOperator &I);
181 Instruction *visitFDiv(BinaryOperator &I);
182 Instruction *visitAnd(BinaryOperator &I);
183 Instruction *visitOr (BinaryOperator &I);
184 Instruction *visitXor(BinaryOperator &I);
185 Instruction *visitShl(BinaryOperator &I);
186 Instruction *visitAShr(BinaryOperator &I);
187 Instruction *visitLShr(BinaryOperator &I);
188 Instruction *commonShiftTransforms(BinaryOperator &I);
189 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
191 Instruction *visitFCmpInst(FCmpInst &I);
192 Instruction *visitICmpInst(ICmpInst &I);
193 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
194 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
197 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
198 ConstantInt *DivRHS);
200 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
201 ICmpInst::Predicate Cond, Instruction &I);
202 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
204 Instruction *commonCastTransforms(CastInst &CI);
205 Instruction *commonIntCastTransforms(CastInst &CI);
206 Instruction *commonPointerCastTransforms(CastInst &CI);
207 Instruction *visitTrunc(TruncInst &CI);
208 Instruction *visitZExt(ZExtInst &CI);
209 Instruction *visitSExt(SExtInst &CI);
210 Instruction *visitFPTrunc(FPTruncInst &CI);
211 Instruction *visitFPExt(CastInst &CI);
212 Instruction *visitFPToUI(FPToUIInst &FI);
213 Instruction *visitFPToSI(FPToSIInst &FI);
214 Instruction *visitUIToFP(CastInst &CI);
215 Instruction *visitSIToFP(CastInst &CI);
216 Instruction *visitPtrToInt(CastInst &CI);
217 Instruction *visitIntToPtr(IntToPtrInst &CI);
218 Instruction *visitBitCast(BitCastInst &CI);
219 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
221 Instruction *visitSelectInst(SelectInst &CI);
222 Instruction *visitCallInst(CallInst &CI);
223 Instruction *visitInvokeInst(InvokeInst &II);
224 Instruction *visitPHINode(PHINode &PN);
225 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
226 Instruction *visitAllocationInst(AllocationInst &AI);
227 Instruction *visitFreeInst(FreeInst &FI);
228 Instruction *visitLoadInst(LoadInst &LI);
229 Instruction *visitStoreInst(StoreInst &SI);
230 Instruction *visitBranchInst(BranchInst &BI);
231 Instruction *visitSwitchInst(SwitchInst &SI);
232 Instruction *visitInsertElementInst(InsertElementInst &IE);
233 Instruction *visitExtractElementInst(ExtractElementInst &EI);
234 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
235 Instruction *visitExtractValueInst(ExtractValueInst &EV);
237 // visitInstruction - Specify what to return for unhandled instructions...
238 Instruction *visitInstruction(Instruction &I) { return 0; }
241 Instruction *visitCallSite(CallSite CS);
242 bool transformConstExprCastCall(CallSite CS);
243 Instruction *transformCallThroughTrampoline(CallSite CS);
244 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
245 bool DoXform = true);
246 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
249 // InsertNewInstBefore - insert an instruction New before instruction Old
250 // in the program. Add the new instruction to the worklist.
252 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
253 assert(New && New->getParent() == 0 &&
254 "New instruction already inserted into a basic block!");
255 BasicBlock *BB = Old.getParent();
256 BB->getInstList().insert(&Old, New); // Insert inst
261 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
262 /// This also adds the cast to the worklist. Finally, this returns the
264 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
266 if (V->getType() == Ty) return V;
268 if (Constant *CV = dyn_cast<Constant>(V))
269 return ConstantExpr::getCast(opc, CV, Ty);
271 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
276 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
277 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
281 // ReplaceInstUsesWith - This method is to be used when an instruction is
282 // found to be dead, replacable with another preexisting expression. Here
283 // we add all uses of I to the worklist, replace all uses of I with the new
284 // value, then return I, so that the inst combiner will know that I was
287 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
288 AddUsersToWorkList(I); // Add all modified instrs to worklist
290 I.replaceAllUsesWith(V);
293 // If we are replacing the instruction with itself, this must be in a
294 // segment of unreachable code, so just clobber the instruction.
295 I.replaceAllUsesWith(UndefValue::get(I.getType()));
300 // UpdateValueUsesWith - This method is to be used when an value is
301 // found to be replacable with another preexisting expression or was
302 // updated. Here we add all uses of I to the worklist, replace all uses of
303 // I with the new value (unless the instruction was just updated), then
304 // return true, so that the inst combiner will know that I was modified.
306 bool UpdateValueUsesWith(Value *Old, Value *New) {
307 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
309 Old->replaceAllUsesWith(New);
310 if (Instruction *I = dyn_cast<Instruction>(Old))
312 if (Instruction *I = dyn_cast<Instruction>(New))
317 // EraseInstFromFunction - When dealing with an instruction that has side
318 // effects or produces a void value, we can't rely on DCE to delete the
319 // instruction. Instead, visit methods should return the value returned by
321 Instruction *EraseInstFromFunction(Instruction &I) {
322 assert(I.use_empty() && "Cannot erase instruction that is used!");
323 AddUsesToWorkList(I);
324 RemoveFromWorkList(&I);
326 return 0; // Don't do anything with FI
329 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
330 APInt &KnownOne, unsigned Depth = 0) const {
331 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
334 bool MaskedValueIsZero(Value *V, const APInt &Mask,
335 unsigned Depth = 0) const {
336 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
338 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
339 return llvm::ComputeNumSignBits(Op, TD, Depth);
343 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
344 /// InsertBefore instruction. This is specialized a bit to avoid inserting
345 /// casts that are known to not do anything...
347 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
348 Value *V, const Type *DestTy,
349 Instruction *InsertBefore);
351 /// SimplifyCommutative - This performs a few simplifications for
352 /// commutative operators.
353 bool SimplifyCommutative(BinaryOperator &I);
355 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
356 /// most-complex to least-complex order.
357 bool SimplifyCompare(CmpInst &I);
359 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
360 /// on the demanded bits.
361 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
362 APInt& KnownZero, APInt& KnownOne,
365 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
366 uint64_t &UndefElts, unsigned Depth = 0);
368 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
369 // PHI node as operand #0, see if we can fold the instruction into the PHI
370 // (which is only possible if all operands to the PHI are constants).
371 Instruction *FoldOpIntoPhi(Instruction &I);
373 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
374 // operator and they all are only used by the PHI, PHI together their
375 // inputs, and do the operation once, to the result of the PHI.
376 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
377 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
380 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
381 ConstantInt *AndRHS, BinaryOperator &TheAnd);
383 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
384 bool isSub, Instruction &I);
385 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
386 bool isSigned, bool Inside, Instruction &IB);
387 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
388 Instruction *MatchBSwap(BinaryOperator &I);
389 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
390 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
391 Instruction *SimplifyMemSet(MemSetInst *MI);
394 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
396 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
398 int &NumCastsRemoved);
399 unsigned GetOrEnforceKnownAlignment(Value *V,
400 unsigned PrefAlign = 0);
405 char InstCombiner::ID = 0;
406 static RegisterPass<InstCombiner>
407 X("instcombine", "Combine redundant instructions");
409 // getComplexity: Assign a complexity or rank value to LLVM Values...
410 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
411 static unsigned getComplexity(Value *V) {
412 if (isa<Instruction>(V)) {
413 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
417 if (isa<Argument>(V)) return 3;
418 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
421 // isOnlyUse - Return true if this instruction will be deleted if we stop using
423 static bool isOnlyUse(Value *V) {
424 return V->hasOneUse() || isa<Constant>(V);
427 // getPromotedType - Return the specified type promoted as it would be to pass
428 // though a va_arg area...
429 static const Type *getPromotedType(const Type *Ty) {
430 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
431 if (ITy->getBitWidth() < 32)
432 return Type::Int32Ty;
437 /// getBitCastOperand - If the specified operand is a CastInst or a constant
438 /// expression bitcast, return the operand value, otherwise return null.
439 static Value *getBitCastOperand(Value *V) {
440 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
441 return I->getOperand(0);
442 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
443 if (CE->getOpcode() == Instruction::BitCast)
444 return CE->getOperand(0);
448 /// This function is a wrapper around CastInst::isEliminableCastPair. It
449 /// simply extracts arguments and returns what that function returns.
450 static Instruction::CastOps
451 isEliminableCastPair(
452 const CastInst *CI, ///< The first cast instruction
453 unsigned opcode, ///< The opcode of the second cast instruction
454 const Type *DstTy, ///< The target type for the second cast instruction
455 TargetData *TD ///< The target data for pointer size
458 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
459 const Type *MidTy = CI->getType(); // B from above
461 // Get the opcodes of the two Cast instructions
462 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
463 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
465 return Instruction::CastOps(
466 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
467 DstTy, TD->getIntPtrType()));
470 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
471 /// in any code being generated. It does not require codegen if V is simple
472 /// enough or if the cast can be folded into other casts.
473 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
474 const Type *Ty, TargetData *TD) {
475 if (V->getType() == Ty || isa<Constant>(V)) return false;
477 // If this is another cast that can be eliminated, it isn't codegen either.
478 if (const CastInst *CI = dyn_cast<CastInst>(V))
479 if (isEliminableCastPair(CI, opcode, Ty, TD))
484 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
485 /// InsertBefore instruction. This is specialized a bit to avoid inserting
486 /// casts that are known to not do anything...
488 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
489 Value *V, const Type *DestTy,
490 Instruction *InsertBefore) {
491 if (V->getType() == DestTy) return V;
492 if (Constant *C = dyn_cast<Constant>(V))
493 return ConstantExpr::getCast(opcode, C, DestTy);
495 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
498 // SimplifyCommutative - This performs a few simplifications for commutative
501 // 1. Order operands such that they are listed from right (least complex) to
502 // left (most complex). This puts constants before unary operators before
505 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
506 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
508 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
509 bool Changed = false;
510 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
511 Changed = !I.swapOperands();
513 if (!I.isAssociative()) return Changed;
514 Instruction::BinaryOps Opcode = I.getOpcode();
515 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
516 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
517 if (isa<Constant>(I.getOperand(1))) {
518 Constant *Folded = ConstantExpr::get(I.getOpcode(),
519 cast<Constant>(I.getOperand(1)),
520 cast<Constant>(Op->getOperand(1)));
521 I.setOperand(0, Op->getOperand(0));
522 I.setOperand(1, Folded);
524 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
525 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
526 isOnlyUse(Op) && isOnlyUse(Op1)) {
527 Constant *C1 = cast<Constant>(Op->getOperand(1));
528 Constant *C2 = cast<Constant>(Op1->getOperand(1));
530 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
531 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
532 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
536 I.setOperand(0, New);
537 I.setOperand(1, Folded);
544 /// SimplifyCompare - For a CmpInst this function just orders the operands
545 /// so that theyare listed from right (least complex) to left (most complex).
546 /// This puts constants before unary operators before binary operators.
547 bool InstCombiner::SimplifyCompare(CmpInst &I) {
548 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
551 // Compare instructions are not associative so there's nothing else we can do.
555 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
556 // if the LHS is a constant zero (which is the 'negate' form).
558 static inline Value *dyn_castNegVal(Value *V) {
559 if (BinaryOperator::isNeg(V))
560 return BinaryOperator::getNegArgument(V);
562 // Constants can be considered to be negated values if they can be folded.
563 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
564 return ConstantExpr::getNeg(C);
566 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
567 if (C->getType()->getElementType()->isInteger())
568 return ConstantExpr::getNeg(C);
573 static inline Value *dyn_castNotVal(Value *V) {
574 if (BinaryOperator::isNot(V))
575 return BinaryOperator::getNotArgument(V);
577 // Constants can be considered to be not'ed values...
578 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
579 return ConstantInt::get(~C->getValue());
583 // dyn_castFoldableMul - If this value is a multiply that can be folded into
584 // other computations (because it has a constant operand), return the
585 // non-constant operand of the multiply, and set CST to point to the multiplier.
586 // Otherwise, return null.
588 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
589 if (V->hasOneUse() && V->getType()->isInteger())
590 if (Instruction *I = dyn_cast<Instruction>(V)) {
591 if (I->getOpcode() == Instruction::Mul)
592 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
593 return I->getOperand(0);
594 if (I->getOpcode() == Instruction::Shl)
595 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
596 // The multiplier is really 1 << CST.
597 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
598 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
599 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
600 return I->getOperand(0);
606 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
607 /// expression, return it.
608 static User *dyn_castGetElementPtr(Value *V) {
609 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
610 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
611 if (CE->getOpcode() == Instruction::GetElementPtr)
612 return cast<User>(V);
616 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
617 /// opcode value. Otherwise return UserOp1.
618 static unsigned getOpcode(const Value *V) {
619 if (const Instruction *I = dyn_cast<Instruction>(V))
620 return I->getOpcode();
621 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
622 return CE->getOpcode();
623 // Use UserOp1 to mean there's no opcode.
624 return Instruction::UserOp1;
627 /// AddOne - Add one to a ConstantInt
628 static ConstantInt *AddOne(ConstantInt *C) {
629 APInt Val(C->getValue());
630 return ConstantInt::get(++Val);
632 /// SubOne - Subtract one from a ConstantInt
633 static ConstantInt *SubOne(ConstantInt *C) {
634 APInt Val(C->getValue());
635 return ConstantInt::get(--Val);
637 /// Add - Add two ConstantInts together
638 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
639 return ConstantInt::get(C1->getValue() + C2->getValue());
641 /// And - Bitwise AND two ConstantInts together
642 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
643 return ConstantInt::get(C1->getValue() & C2->getValue());
645 /// Subtract - Subtract one ConstantInt from another
646 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
647 return ConstantInt::get(C1->getValue() - C2->getValue());
649 /// Multiply - Multiply two ConstantInts together
650 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
651 return ConstantInt::get(C1->getValue() * C2->getValue());
653 /// MultiplyOverflows - True if the multiply can not be expressed in an int
655 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
656 uint32_t W = C1->getBitWidth();
657 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
666 APInt MulExt = LHSExt * RHSExt;
669 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
670 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
671 return MulExt.slt(Min) || MulExt.sgt(Max);
673 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
677 /// ShrinkDemandedConstant - Check to see if the specified operand of the
678 /// specified instruction is a constant integer. If so, check to see if there
679 /// are any bits set in the constant that are not demanded. If so, shrink the
680 /// constant and return true.
681 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
683 assert(I && "No instruction?");
684 assert(OpNo < I->getNumOperands() && "Operand index too large");
686 // If the operand is not a constant integer, nothing to do.
687 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
688 if (!OpC) return false;
690 // If there are no bits set that aren't demanded, nothing to do.
691 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
692 if ((~Demanded & OpC->getValue()) == 0)
695 // This instruction is producing bits that are not demanded. Shrink the RHS.
696 Demanded &= OpC->getValue();
697 I->setOperand(OpNo, ConstantInt::get(Demanded));
701 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
702 // set of known zero and one bits, compute the maximum and minimum values that
703 // could have the specified known zero and known one bits, returning them in
705 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
706 const APInt& KnownZero,
707 const APInt& KnownOne,
708 APInt& Min, APInt& Max) {
709 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
710 assert(KnownZero.getBitWidth() == BitWidth &&
711 KnownOne.getBitWidth() == BitWidth &&
712 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
713 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
714 APInt UnknownBits = ~(KnownZero|KnownOne);
716 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
717 // bit if it is unknown.
719 Max = KnownOne|UnknownBits;
721 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
723 Max.clear(BitWidth-1);
727 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
728 // a set of known zero and one bits, compute the maximum and minimum values that
729 // could have the specified known zero and known one bits, returning them in
731 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
732 const APInt &KnownZero,
733 const APInt &KnownOne,
734 APInt &Min, APInt &Max) {
735 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
736 assert(KnownZero.getBitWidth() == BitWidth &&
737 KnownOne.getBitWidth() == BitWidth &&
738 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
739 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
740 APInt UnknownBits = ~(KnownZero|KnownOne);
742 // The minimum value is when the unknown bits are all zeros.
744 // The maximum value is when the unknown bits are all ones.
745 Max = KnownOne|UnknownBits;
748 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
749 /// value based on the demanded bits. When this function is called, it is known
750 /// that only the bits set in DemandedMask of the result of V are ever used
751 /// downstream. Consequently, depending on the mask and V, it may be possible
752 /// to replace V with a constant or one of its operands. In such cases, this
753 /// function does the replacement and returns true. In all other cases, it
754 /// returns false after analyzing the expression and setting KnownOne and known
755 /// to be one in the expression. KnownZero contains all the bits that are known
756 /// to be zero in the expression. These are provided to potentially allow the
757 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
758 /// the expression. KnownOne and KnownZero always follow the invariant that
759 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
760 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
761 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
762 /// and KnownOne must all be the same.
763 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
764 APInt& KnownZero, APInt& KnownOne,
766 assert(V != 0 && "Null pointer of Value???");
767 assert(Depth <= 6 && "Limit Search Depth");
768 uint32_t BitWidth = DemandedMask.getBitWidth();
769 const IntegerType *VTy = cast<IntegerType>(V->getType());
770 assert(VTy->getBitWidth() == BitWidth &&
771 KnownZero.getBitWidth() == BitWidth &&
772 KnownOne.getBitWidth() == BitWidth &&
773 "Value *V, DemandedMask, KnownZero and KnownOne \
774 must have same BitWidth");
775 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
776 // We know all of the bits for a constant!
777 KnownOne = CI->getValue() & DemandedMask;
778 KnownZero = ~KnownOne & DemandedMask;
784 if (!V->hasOneUse()) { // Other users may use these bits.
785 if (Depth != 0) { // Not at the root.
786 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
787 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
790 // If this is the root being simplified, allow it to have multiple uses,
791 // just set the DemandedMask to all bits.
792 DemandedMask = APInt::getAllOnesValue(BitWidth);
793 } else if (DemandedMask == 0) { // Not demanding any bits from V.
794 if (V != UndefValue::get(VTy))
795 return UpdateValueUsesWith(V, UndefValue::get(VTy));
797 } else if (Depth == 6) { // Limit search depth.
801 Instruction *I = dyn_cast<Instruction>(V);
802 if (!I) return false; // Only analyze instructions.
804 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
805 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
806 switch (I->getOpcode()) {
808 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
810 case Instruction::And:
811 // If either the LHS or the RHS are Zero, the result is zero.
812 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
813 RHSKnownZero, RHSKnownOne, Depth+1))
815 assert((RHSKnownZero & RHSKnownOne) == 0 &&
816 "Bits known to be one AND zero?");
818 // If something is known zero on the RHS, the bits aren't demanded on the
820 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
821 LHSKnownZero, LHSKnownOne, Depth+1))
823 assert((LHSKnownZero & LHSKnownOne) == 0 &&
824 "Bits known to be one AND zero?");
826 // If all of the demanded bits are known 1 on one side, return the other.
827 // These bits cannot contribute to the result of the 'and'.
828 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
829 (DemandedMask & ~LHSKnownZero))
830 return UpdateValueUsesWith(I, I->getOperand(0));
831 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
832 (DemandedMask & ~RHSKnownZero))
833 return UpdateValueUsesWith(I, I->getOperand(1));
835 // If all of the demanded bits in the inputs are known zeros, return zero.
836 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
837 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
839 // If the RHS is a constant, see if we can simplify it.
840 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
841 return UpdateValueUsesWith(I, I);
843 // Output known-1 bits are only known if set in both the LHS & RHS.
844 RHSKnownOne &= LHSKnownOne;
845 // Output known-0 are known to be clear if zero in either the LHS | RHS.
846 RHSKnownZero |= LHSKnownZero;
848 case Instruction::Or:
849 // If either the LHS or the RHS are One, the result is One.
850 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
851 RHSKnownZero, RHSKnownOne, Depth+1))
853 assert((RHSKnownZero & RHSKnownOne) == 0 &&
854 "Bits known to be one AND zero?");
855 // If something is known one on the RHS, the bits aren't demanded on the
857 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
858 LHSKnownZero, LHSKnownOne, Depth+1))
860 assert((LHSKnownZero & LHSKnownOne) == 0 &&
861 "Bits known to be one AND zero?");
863 // If all of the demanded bits are known zero on one side, return the other.
864 // These bits cannot contribute to the result of the 'or'.
865 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
866 (DemandedMask & ~LHSKnownOne))
867 return UpdateValueUsesWith(I, I->getOperand(0));
868 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
869 (DemandedMask & ~RHSKnownOne))
870 return UpdateValueUsesWith(I, I->getOperand(1));
872 // If all of the potentially set bits on one side are known to be set on
873 // the other side, just use the 'other' side.
874 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
875 (DemandedMask & (~RHSKnownZero)))
876 return UpdateValueUsesWith(I, I->getOperand(0));
877 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
878 (DemandedMask & (~LHSKnownZero)))
879 return UpdateValueUsesWith(I, I->getOperand(1));
881 // If the RHS is a constant, see if we can simplify it.
882 if (ShrinkDemandedConstant(I, 1, DemandedMask))
883 return UpdateValueUsesWith(I, I);
885 // Output known-0 bits are only known if clear in both the LHS & RHS.
886 RHSKnownZero &= LHSKnownZero;
887 // Output known-1 are known to be set if set in either the LHS | RHS.
888 RHSKnownOne |= LHSKnownOne;
890 case Instruction::Xor: {
891 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
892 RHSKnownZero, RHSKnownOne, Depth+1))
894 assert((RHSKnownZero & RHSKnownOne) == 0 &&
895 "Bits known to be one AND zero?");
896 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
897 LHSKnownZero, LHSKnownOne, Depth+1))
899 assert((LHSKnownZero & LHSKnownOne) == 0 &&
900 "Bits known to be one AND zero?");
902 // If all of the demanded bits are known zero on one side, return the other.
903 // These bits cannot contribute to the result of the 'xor'.
904 if ((DemandedMask & RHSKnownZero) == DemandedMask)
905 return UpdateValueUsesWith(I, I->getOperand(0));
906 if ((DemandedMask & LHSKnownZero) == DemandedMask)
907 return UpdateValueUsesWith(I, I->getOperand(1));
909 // Output known-0 bits are known if clear or set in both the LHS & RHS.
910 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
911 (RHSKnownOne & LHSKnownOne);
912 // Output known-1 are known to be set if set in only one of the LHS, RHS.
913 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
914 (RHSKnownOne & LHSKnownZero);
916 // If all of the demanded bits are known to be zero on one side or the
917 // other, turn this into an *inclusive* or.
918 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
919 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
921 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
923 InsertNewInstBefore(Or, *I);
924 return UpdateValueUsesWith(I, Or);
927 // If all of the demanded bits on one side are known, and all of the set
928 // bits on that side are also known to be set on the other side, turn this
929 // into an AND, as we know the bits will be cleared.
930 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
931 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
933 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
934 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
936 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
937 InsertNewInstBefore(And, *I);
938 return UpdateValueUsesWith(I, And);
942 // If the RHS is a constant, see if we can simplify it.
943 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
944 if (ShrinkDemandedConstant(I, 1, DemandedMask))
945 return UpdateValueUsesWith(I, I);
947 RHSKnownZero = KnownZeroOut;
948 RHSKnownOne = KnownOneOut;
951 case Instruction::Select:
952 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
953 RHSKnownZero, RHSKnownOne, Depth+1))
955 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
956 LHSKnownZero, LHSKnownOne, Depth+1))
958 assert((RHSKnownZero & RHSKnownOne) == 0 &&
959 "Bits known to be one AND zero?");
960 assert((LHSKnownZero & LHSKnownOne) == 0 &&
961 "Bits known to be one AND zero?");
963 // If the operands are constants, see if we can simplify them.
964 if (ShrinkDemandedConstant(I, 1, DemandedMask))
965 return UpdateValueUsesWith(I, I);
966 if (ShrinkDemandedConstant(I, 2, DemandedMask))
967 return UpdateValueUsesWith(I, I);
969 // Only known if known in both the LHS and RHS.
970 RHSKnownOne &= LHSKnownOne;
971 RHSKnownZero &= LHSKnownZero;
973 case Instruction::Trunc: {
975 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
976 DemandedMask.zext(truncBf);
977 RHSKnownZero.zext(truncBf);
978 RHSKnownOne.zext(truncBf);
979 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
980 RHSKnownZero, RHSKnownOne, Depth+1))
982 DemandedMask.trunc(BitWidth);
983 RHSKnownZero.trunc(BitWidth);
984 RHSKnownOne.trunc(BitWidth);
985 assert((RHSKnownZero & RHSKnownOne) == 0 &&
986 "Bits known to be one AND zero?");
989 case Instruction::BitCast:
990 if (!I->getOperand(0)->getType()->isInteger())
993 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
994 RHSKnownZero, RHSKnownOne, Depth+1))
996 assert((RHSKnownZero & RHSKnownOne) == 0 &&
997 "Bits known to be one AND zero?");
999 case Instruction::ZExt: {
1000 // Compute the bits in the result that are not present in the input.
1001 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1002 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1004 DemandedMask.trunc(SrcBitWidth);
1005 RHSKnownZero.trunc(SrcBitWidth);
1006 RHSKnownOne.trunc(SrcBitWidth);
1007 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1008 RHSKnownZero, RHSKnownOne, Depth+1))
1010 DemandedMask.zext(BitWidth);
1011 RHSKnownZero.zext(BitWidth);
1012 RHSKnownOne.zext(BitWidth);
1013 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1014 "Bits known to be one AND zero?");
1015 // The top bits are known to be zero.
1016 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1019 case Instruction::SExt: {
1020 // Compute the bits in the result that are not present in the input.
1021 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1022 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1024 APInt InputDemandedBits = DemandedMask &
1025 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1027 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1028 // If any of the sign extended bits are demanded, we know that the sign
1030 if ((NewBits & DemandedMask) != 0)
1031 InputDemandedBits.set(SrcBitWidth-1);
1033 InputDemandedBits.trunc(SrcBitWidth);
1034 RHSKnownZero.trunc(SrcBitWidth);
1035 RHSKnownOne.trunc(SrcBitWidth);
1036 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1037 RHSKnownZero, RHSKnownOne, Depth+1))
1039 InputDemandedBits.zext(BitWidth);
1040 RHSKnownZero.zext(BitWidth);
1041 RHSKnownOne.zext(BitWidth);
1042 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1043 "Bits known to be one AND zero?");
1045 // If the sign bit of the input is known set or clear, then we know the
1046 // top bits of the result.
1048 // If the input sign bit is known zero, or if the NewBits are not demanded
1049 // convert this into a zero extension.
1050 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1052 // Convert to ZExt cast
1053 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1054 return UpdateValueUsesWith(I, NewCast);
1055 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1056 RHSKnownOne |= NewBits;
1060 case Instruction::Add: {
1061 // Figure out what the input bits are. If the top bits of the and result
1062 // are not demanded, then the add doesn't demand them from its input
1064 uint32_t NLZ = DemandedMask.countLeadingZeros();
1066 // If there is a constant on the RHS, there are a variety of xformations
1068 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1069 // If null, this should be simplified elsewhere. Some of the xforms here
1070 // won't work if the RHS is zero.
1074 // If the top bit of the output is demanded, demand everything from the
1075 // input. Otherwise, we demand all the input bits except NLZ top bits.
1076 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1078 // Find information about known zero/one bits in the input.
1079 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1080 LHSKnownZero, LHSKnownOne, Depth+1))
1083 // If the RHS of the add has bits set that can't affect the input, reduce
1085 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1086 return UpdateValueUsesWith(I, I);
1088 // Avoid excess work.
1089 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1092 // Turn it into OR if input bits are zero.
1093 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1095 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1097 InsertNewInstBefore(Or, *I);
1098 return UpdateValueUsesWith(I, Or);
1101 // We can say something about the output known-zero and known-one bits,
1102 // depending on potential carries from the input constant and the
1103 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1104 // bits set and the RHS constant is 0x01001, then we know we have a known
1105 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1107 // To compute this, we first compute the potential carry bits. These are
1108 // the bits which may be modified. I'm not aware of a better way to do
1110 const APInt& RHSVal = RHS->getValue();
1111 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1113 // Now that we know which bits have carries, compute the known-1/0 sets.
1115 // Bits are known one if they are known zero in one operand and one in the
1116 // other, and there is no input carry.
1117 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1118 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1120 // Bits are known zero if they are known zero in both operands and there
1121 // is no input carry.
1122 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1124 // If the high-bits of this ADD are not demanded, then it does not demand
1125 // the high bits of its LHS or RHS.
1126 if (DemandedMask[BitWidth-1] == 0) {
1127 // Right fill the mask of bits for this ADD to demand the most
1128 // significant bit and all those below it.
1129 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1130 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1131 LHSKnownZero, LHSKnownOne, Depth+1))
1133 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1134 LHSKnownZero, LHSKnownOne, Depth+1))
1140 case Instruction::Sub:
1141 // If the high-bits of this SUB are not demanded, then it does not demand
1142 // the high bits of its LHS or RHS.
1143 if (DemandedMask[BitWidth-1] == 0) {
1144 // Right fill the mask of bits for this SUB to demand the most
1145 // significant bit and all those below it.
1146 uint32_t NLZ = DemandedMask.countLeadingZeros();
1147 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1148 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1149 LHSKnownZero, LHSKnownOne, Depth+1))
1151 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1152 LHSKnownZero, LHSKnownOne, Depth+1))
1155 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1156 // the known zeros and ones.
1157 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1159 case Instruction::Shl:
1160 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1161 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1162 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1163 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1164 RHSKnownZero, RHSKnownOne, Depth+1))
1166 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1167 "Bits known to be one AND zero?");
1168 RHSKnownZero <<= ShiftAmt;
1169 RHSKnownOne <<= ShiftAmt;
1170 // low bits known zero.
1172 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1175 case Instruction::LShr:
1176 // For a logical shift right
1177 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1178 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1180 // Unsigned shift right.
1181 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1182 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1183 RHSKnownZero, RHSKnownOne, Depth+1))
1185 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1186 "Bits known to be one AND zero?");
1187 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1188 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1190 // Compute the new bits that are at the top now.
1191 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1192 RHSKnownZero |= HighBits; // high bits known zero.
1196 case Instruction::AShr:
1197 // If this is an arithmetic shift right and only the low-bit is set, we can
1198 // always convert this into a logical shr, even if the shift amount is
1199 // variable. The low bit of the shift cannot be an input sign bit unless
1200 // the shift amount is >= the size of the datatype, which is undefined.
1201 if (DemandedMask == 1) {
1202 // Perform the logical shift right.
1203 Value *NewVal = BinaryOperator::CreateLShr(
1204 I->getOperand(0), I->getOperand(1), I->getName());
1205 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1206 return UpdateValueUsesWith(I, NewVal);
1209 // If the sign bit is the only bit demanded by this ashr, then there is no
1210 // need to do it, the shift doesn't change the high bit.
1211 if (DemandedMask.isSignBit())
1212 return UpdateValueUsesWith(I, I->getOperand(0));
1214 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1215 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1217 // Signed shift right.
1218 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1219 // If any of the "high bits" are demanded, we should set the sign bit as
1221 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1222 DemandedMaskIn.set(BitWidth-1);
1223 if (SimplifyDemandedBits(I->getOperand(0),
1225 RHSKnownZero, RHSKnownOne, Depth+1))
1227 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1228 "Bits known to be one AND zero?");
1229 // Compute the new bits that are at the top now.
1230 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1231 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1232 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1234 // Handle the sign bits.
1235 APInt SignBit(APInt::getSignBit(BitWidth));
1236 // Adjust to where it is now in the mask.
1237 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1239 // If the input sign bit is known to be zero, or if none of the top bits
1240 // are demanded, turn this into an unsigned shift right.
1241 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
1242 (HighBits & ~DemandedMask) == HighBits) {
1243 // Perform the logical shift right.
1244 Value *NewVal = BinaryOperator::CreateLShr(
1245 I->getOperand(0), SA, I->getName());
1246 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1247 return UpdateValueUsesWith(I, NewVal);
1248 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1249 RHSKnownOne |= HighBits;
1253 case Instruction::SRem:
1254 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1255 APInt RA = Rem->getValue();
1256 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1257 if (DemandedMask.ule(RA)) // srem won't affect demanded bits
1258 return UpdateValueUsesWith(I, I->getOperand(0));
1260 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1261 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1262 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1263 LHSKnownZero, LHSKnownOne, Depth+1))
1266 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1267 LHSKnownZero |= ~LowBits;
1268 else if (LHSKnownOne[BitWidth-1])
1269 LHSKnownOne |= ~LowBits;
1271 KnownZero |= LHSKnownZero & DemandedMask;
1272 KnownOne |= LHSKnownOne & DemandedMask;
1274 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1278 case Instruction::URem: {
1279 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1280 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1281 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1282 KnownZero2, KnownOne2, Depth+1))
1285 uint32_t Leaders = KnownZero2.countLeadingOnes();
1286 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1287 KnownZero2, KnownOne2, Depth+1))
1290 Leaders = std::max(Leaders,
1291 KnownZero2.countLeadingOnes());
1292 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1295 case Instruction::Call:
1296 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1297 switch (II->getIntrinsicID()) {
1299 case Intrinsic::bswap: {
1300 // If the only bits demanded come from one byte of the bswap result,
1301 // just shift the input byte into position to eliminate the bswap.
1302 unsigned NLZ = DemandedMask.countLeadingZeros();
1303 unsigned NTZ = DemandedMask.countTrailingZeros();
1305 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1306 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1307 // have 14 leading zeros, round to 8.
1310 // If we need exactly one byte, we can do this transformation.
1311 if (BitWidth-NLZ-NTZ == 8) {
1312 unsigned ResultBit = NTZ;
1313 unsigned InputBit = BitWidth-NTZ-8;
1315 // Replace this with either a left or right shift to get the byte into
1317 Instruction *NewVal;
1318 if (InputBit > ResultBit)
1319 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1320 ConstantInt::get(I->getType(), InputBit-ResultBit));
1322 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1323 ConstantInt::get(I->getType(), ResultBit-InputBit));
1324 NewVal->takeName(I);
1325 InsertNewInstBefore(NewVal, *I);
1326 return UpdateValueUsesWith(I, NewVal);
1329 // TODO: Could compute known zero/one bits based on the input.
1334 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1338 // If the client is only demanding bits that we know, return the known
1340 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1341 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1346 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1347 /// 64 or fewer elements. DemandedElts contains the set of elements that are
1348 /// actually used by the caller. This method analyzes which elements of the
1349 /// operand are undef and returns that information in UndefElts.
1351 /// If the information about demanded elements can be used to simplify the
1352 /// operation, the operation is simplified, then the resultant value is
1353 /// returned. This returns null if no change was made.
1354 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1355 uint64_t &UndefElts,
1357 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1358 assert(VWidth <= 64 && "Vector too wide to analyze!");
1359 uint64_t EltMask = ~0ULL >> (64-VWidth);
1360 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1361 "Invalid DemandedElts!");
1363 if (isa<UndefValue>(V)) {
1364 // If the entire vector is undefined, just return this info.
1365 UndefElts = EltMask;
1367 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1368 UndefElts = EltMask;
1369 return UndefValue::get(V->getType());
1373 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1374 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1375 Constant *Undef = UndefValue::get(EltTy);
1377 std::vector<Constant*> Elts;
1378 for (unsigned i = 0; i != VWidth; ++i)
1379 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1380 Elts.push_back(Undef);
1381 UndefElts |= (1ULL << i);
1382 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1383 Elts.push_back(Undef);
1384 UndefElts |= (1ULL << i);
1385 } else { // Otherwise, defined.
1386 Elts.push_back(CP->getOperand(i));
1389 // If we changed the constant, return it.
1390 Constant *NewCP = ConstantVector::get(Elts);
1391 return NewCP != CP ? NewCP : 0;
1392 } else if (isa<ConstantAggregateZero>(V)) {
1393 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1395 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1396 Constant *Zero = Constant::getNullValue(EltTy);
1397 Constant *Undef = UndefValue::get(EltTy);
1398 std::vector<Constant*> Elts;
1399 for (unsigned i = 0; i != VWidth; ++i)
1400 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1401 UndefElts = DemandedElts ^ EltMask;
1402 return ConstantVector::get(Elts);
1405 if (!V->hasOneUse()) { // Other users may use these bits.
1406 if (Depth != 0) { // Not at the root.
1407 // TODO: Just compute the UndefElts information recursively.
1411 } else if (Depth == 10) { // Limit search depth.
1415 Instruction *I = dyn_cast<Instruction>(V);
1416 if (!I) return false; // Only analyze instructions.
1418 bool MadeChange = false;
1419 uint64_t UndefElts2;
1421 switch (I->getOpcode()) {
1424 case Instruction::InsertElement: {
1425 // If this is a variable index, we don't know which element it overwrites.
1426 // demand exactly the same input as we produce.
1427 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1429 // Note that we can't propagate undef elt info, because we don't know
1430 // which elt is getting updated.
1431 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1432 UndefElts2, Depth+1);
1433 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1437 // If this is inserting an element that isn't demanded, remove this
1439 unsigned IdxNo = Idx->getZExtValue();
1440 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1441 return AddSoonDeadInstToWorklist(*I, 0);
1443 // Otherwise, the element inserted overwrites whatever was there, so the
1444 // input demanded set is simpler than the output set.
1445 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1446 DemandedElts & ~(1ULL << IdxNo),
1447 UndefElts, Depth+1);
1448 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1450 // The inserted element is defined.
1451 UndefElts |= 1ULL << IdxNo;
1454 case Instruction::BitCast: {
1455 // Vector->vector casts only.
1456 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1458 unsigned InVWidth = VTy->getNumElements();
1459 uint64_t InputDemandedElts = 0;
1462 if (VWidth == InVWidth) {
1463 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1464 // elements as are demanded of us.
1466 InputDemandedElts = DemandedElts;
1467 } else if (VWidth > InVWidth) {
1471 // If there are more elements in the result than there are in the source,
1472 // then an input element is live if any of the corresponding output
1473 // elements are live.
1474 Ratio = VWidth/InVWidth;
1475 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1476 if (DemandedElts & (1ULL << OutIdx))
1477 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1483 // If there are more elements in the source than there are in the result,
1484 // then an input element is live if the corresponding output element is
1486 Ratio = InVWidth/VWidth;
1487 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1488 if (DemandedElts & (1ULL << InIdx/Ratio))
1489 InputDemandedElts |= 1ULL << InIdx;
1492 // div/rem demand all inputs, because they don't want divide by zero.
1493 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1494 UndefElts2, Depth+1);
1496 I->setOperand(0, TmpV);
1500 UndefElts = UndefElts2;
1501 if (VWidth > InVWidth) {
1502 assert(0 && "Unimp");
1503 // If there are more elements in the result than there are in the source,
1504 // then an output element is undef if the corresponding input element is
1506 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1507 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1508 UndefElts |= 1ULL << OutIdx;
1509 } else if (VWidth < InVWidth) {
1510 assert(0 && "Unimp");
1511 // If there are more elements in the source than there are in the result,
1512 // then a result element is undef if all of the corresponding input
1513 // elements are undef.
1514 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1515 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1516 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1517 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1521 case Instruction::And:
1522 case Instruction::Or:
1523 case Instruction::Xor:
1524 case Instruction::Add:
1525 case Instruction::Sub:
1526 case Instruction::Mul:
1527 // div/rem demand all inputs, because they don't want divide by zero.
1528 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1529 UndefElts, Depth+1);
1530 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1531 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1532 UndefElts2, Depth+1);
1533 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1535 // Output elements are undefined if both are undefined. Consider things
1536 // like undef&0. The result is known zero, not undef.
1537 UndefElts &= UndefElts2;
1540 case Instruction::Call: {
1541 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1543 switch (II->getIntrinsicID()) {
1546 // Binary vector operations that work column-wise. A dest element is a
1547 // function of the corresponding input elements from the two inputs.
1548 case Intrinsic::x86_sse_sub_ss:
1549 case Intrinsic::x86_sse_mul_ss:
1550 case Intrinsic::x86_sse_min_ss:
1551 case Intrinsic::x86_sse_max_ss:
1552 case Intrinsic::x86_sse2_sub_sd:
1553 case Intrinsic::x86_sse2_mul_sd:
1554 case Intrinsic::x86_sse2_min_sd:
1555 case Intrinsic::x86_sse2_max_sd:
1556 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1557 UndefElts, Depth+1);
1558 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1559 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1560 UndefElts2, Depth+1);
1561 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1563 // If only the low elt is demanded and this is a scalarizable intrinsic,
1564 // scalarize it now.
1565 if (DemandedElts == 1) {
1566 switch (II->getIntrinsicID()) {
1568 case Intrinsic::x86_sse_sub_ss:
1569 case Intrinsic::x86_sse_mul_ss:
1570 case Intrinsic::x86_sse2_sub_sd:
1571 case Intrinsic::x86_sse2_mul_sd:
1572 // TODO: Lower MIN/MAX/ABS/etc
1573 Value *LHS = II->getOperand(1);
1574 Value *RHS = II->getOperand(2);
1575 // Extract the element as scalars.
1576 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1577 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1579 switch (II->getIntrinsicID()) {
1580 default: assert(0 && "Case stmts out of sync!");
1581 case Intrinsic::x86_sse_sub_ss:
1582 case Intrinsic::x86_sse2_sub_sd:
1583 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1584 II->getName()), *II);
1586 case Intrinsic::x86_sse_mul_ss:
1587 case Intrinsic::x86_sse2_mul_sd:
1588 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1589 II->getName()), *II);
1594 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1596 InsertNewInstBefore(New, *II);
1597 AddSoonDeadInstToWorklist(*II, 0);
1602 // Output elements are undefined if both are undefined. Consider things
1603 // like undef&0. The result is known zero, not undef.
1604 UndefElts &= UndefElts2;
1610 return MadeChange ? I : 0;
1614 /// AssociativeOpt - Perform an optimization on an associative operator. This
1615 /// function is designed to check a chain of associative operators for a
1616 /// potential to apply a certain optimization. Since the optimization may be
1617 /// applicable if the expression was reassociated, this checks the chain, then
1618 /// reassociates the expression as necessary to expose the optimization
1619 /// opportunity. This makes use of a special Functor, which must define
1620 /// 'shouldApply' and 'apply' methods.
1622 template<typename Functor>
1623 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1624 unsigned Opcode = Root.getOpcode();
1625 Value *LHS = Root.getOperand(0);
1627 // Quick check, see if the immediate LHS matches...
1628 if (F.shouldApply(LHS))
1629 return F.apply(Root);
1631 // Otherwise, if the LHS is not of the same opcode as the root, return.
1632 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1633 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1634 // Should we apply this transform to the RHS?
1635 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1637 // If not to the RHS, check to see if we should apply to the LHS...
1638 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1639 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1643 // If the functor wants to apply the optimization to the RHS of LHSI,
1644 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1646 // Now all of the instructions are in the current basic block, go ahead
1647 // and perform the reassociation.
1648 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1650 // First move the selected RHS to the LHS of the root...
1651 Root.setOperand(0, LHSI->getOperand(1));
1653 // Make what used to be the LHS of the root be the user of the root...
1654 Value *ExtraOperand = TmpLHSI->getOperand(1);
1655 if (&Root == TmpLHSI) {
1656 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1659 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1660 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1661 BasicBlock::iterator ARI = &Root; ++ARI;
1662 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
1665 // Now propagate the ExtraOperand down the chain of instructions until we
1667 while (TmpLHSI != LHSI) {
1668 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1669 // Move the instruction to immediately before the chain we are
1670 // constructing to avoid breaking dominance properties.
1671 NextLHSI->moveBefore(ARI);
1674 Value *NextOp = NextLHSI->getOperand(1);
1675 NextLHSI->setOperand(1, ExtraOperand);
1677 ExtraOperand = NextOp;
1680 // Now that the instructions are reassociated, have the functor perform
1681 // the transformation...
1682 return F.apply(Root);
1685 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1692 // AddRHS - Implements: X + X --> X << 1
1695 AddRHS(Value *rhs) : RHS(rhs) {}
1696 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1697 Instruction *apply(BinaryOperator &Add) const {
1698 return BinaryOperator::CreateShl(Add.getOperand(0),
1699 ConstantInt::get(Add.getType(), 1));
1703 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1705 struct AddMaskingAnd {
1707 AddMaskingAnd(Constant *c) : C2(c) {}
1708 bool shouldApply(Value *LHS) const {
1710 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1711 ConstantExpr::getAnd(C1, C2)->isNullValue();
1713 Instruction *apply(BinaryOperator &Add) const {
1714 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1720 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1722 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1723 if (Constant *SOC = dyn_cast<Constant>(SO))
1724 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1726 return IC->InsertNewInstBefore(CastInst::Create(
1727 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1730 // Figure out if the constant is the left or the right argument.
1731 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1732 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1734 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1736 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1737 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1740 Value *Op0 = SO, *Op1 = ConstOperand;
1742 std::swap(Op0, Op1);
1744 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1745 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1746 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1747 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1748 SO->getName()+".cmp");
1750 assert(0 && "Unknown binary instruction type!");
1753 return IC->InsertNewInstBefore(New, I);
1756 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1757 // constant as the other operand, try to fold the binary operator into the
1758 // select arguments. This also works for Cast instructions, which obviously do
1759 // not have a second operand.
1760 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1762 // Don't modify shared select instructions
1763 if (!SI->hasOneUse()) return 0;
1764 Value *TV = SI->getOperand(1);
1765 Value *FV = SI->getOperand(2);
1767 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1768 // Bool selects with constant operands can be folded to logical ops.
1769 if (SI->getType() == Type::Int1Ty) return 0;
1771 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1772 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1774 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1781 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1782 /// node as operand #0, see if we can fold the instruction into the PHI (which
1783 /// is only possible if all operands to the PHI are constants).
1784 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1785 PHINode *PN = cast<PHINode>(I.getOperand(0));
1786 unsigned NumPHIValues = PN->getNumIncomingValues();
1787 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1789 // Check to see if all of the operands of the PHI are constants. If there is
1790 // one non-constant value, remember the BB it is. If there is more than one
1791 // or if *it* is a PHI, bail out.
1792 BasicBlock *NonConstBB = 0;
1793 for (unsigned i = 0; i != NumPHIValues; ++i)
1794 if (!isa<Constant>(PN->getIncomingValue(i))) {
1795 if (NonConstBB) return 0; // More than one non-const value.
1796 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1797 NonConstBB = PN->getIncomingBlock(i);
1799 // If the incoming non-constant value is in I's block, we have an infinite
1801 if (NonConstBB == I.getParent())
1805 // If there is exactly one non-constant value, we can insert a copy of the
1806 // operation in that block. However, if this is a critical edge, we would be
1807 // inserting the computation one some other paths (e.g. inside a loop). Only
1808 // do this if the pred block is unconditionally branching into the phi block.
1810 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1811 if (!BI || !BI->isUnconditional()) return 0;
1814 // Okay, we can do the transformation: create the new PHI node.
1815 PHINode *NewPN = PHINode::Create(I.getType(), "");
1816 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1817 InsertNewInstBefore(NewPN, *PN);
1818 NewPN->takeName(PN);
1820 // Next, add all of the operands to the PHI.
1821 if (I.getNumOperands() == 2) {
1822 Constant *C = cast<Constant>(I.getOperand(1));
1823 for (unsigned i = 0; i != NumPHIValues; ++i) {
1825 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1826 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1827 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1829 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1831 assert(PN->getIncomingBlock(i) == NonConstBB);
1832 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1833 InV = BinaryOperator::Create(BO->getOpcode(),
1834 PN->getIncomingValue(i), C, "phitmp",
1835 NonConstBB->getTerminator());
1836 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1837 InV = CmpInst::Create(CI->getOpcode(),
1839 PN->getIncomingValue(i), C, "phitmp",
1840 NonConstBB->getTerminator());
1842 assert(0 && "Unknown binop!");
1844 AddToWorkList(cast<Instruction>(InV));
1846 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1849 CastInst *CI = cast<CastInst>(&I);
1850 const Type *RetTy = CI->getType();
1851 for (unsigned i = 0; i != NumPHIValues; ++i) {
1853 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1854 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1856 assert(PN->getIncomingBlock(i) == NonConstBB);
1857 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
1858 I.getType(), "phitmp",
1859 NonConstBB->getTerminator());
1860 AddToWorkList(cast<Instruction>(InV));
1862 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1865 return ReplaceInstUsesWith(I, NewPN);
1869 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1870 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1871 /// This basically requires proving that the add in the original type would not
1872 /// overflow to change the sign bit or have a carry out.
1873 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1874 // There are different heuristics we can use for this. Here are some simple
1877 // Add has the property that adding any two 2's complement numbers can only
1878 // have one carry bit which can change a sign. As such, if LHS and RHS each
1879 // have at least two sign bits, we know that the addition of the two values will
1880 // sign extend fine.
1881 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1885 // If one of the operands only has one non-zero bit, and if the other operand
1886 // has a known-zero bit in a more significant place than it (not including the
1887 // sign bit) the ripple may go up to and fill the zero, but won't change the
1888 // sign. For example, (X & ~4) + 1.
1896 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1897 bool Changed = SimplifyCommutative(I);
1898 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1900 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1901 // X + undef -> undef
1902 if (isa<UndefValue>(RHS))
1903 return ReplaceInstUsesWith(I, RHS);
1906 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1907 if (RHSC->isNullValue())
1908 return ReplaceInstUsesWith(I, LHS);
1909 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1910 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1911 (I.getType())->getValueAPF()))
1912 return ReplaceInstUsesWith(I, LHS);
1915 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1916 // X + (signbit) --> X ^ signbit
1917 const APInt& Val = CI->getValue();
1918 uint32_t BitWidth = Val.getBitWidth();
1919 if (Val == APInt::getSignBit(BitWidth))
1920 return BinaryOperator::CreateXor(LHS, RHS);
1922 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1923 // (X & 254)+1 -> (X&254)|1
1924 if (!isa<VectorType>(I.getType())) {
1925 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1926 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1927 KnownZero, KnownOne))
1932 if (isa<PHINode>(LHS))
1933 if (Instruction *NV = FoldOpIntoPhi(I))
1936 ConstantInt *XorRHS = 0;
1938 if (isa<ConstantInt>(RHSC) &&
1939 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1940 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
1941 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
1943 uint32_t Size = TySizeBits / 2;
1944 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1945 APInt CFF80Val(-C0080Val);
1947 if (TySizeBits > Size) {
1948 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1949 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1950 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1951 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
1952 // This is a sign extend if the top bits are known zero.
1953 if (!MaskedValueIsZero(XorLHS,
1954 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
1955 Size = 0; // Not a sign ext, but can't be any others either.
1960 C0080Val = APIntOps::lshr(C0080Val, Size);
1961 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1962 } while (Size >= 1);
1964 // FIXME: This shouldn't be necessary. When the backends can handle types
1965 // with funny bit widths then this switch statement should be removed. It
1966 // is just here to get the size of the "middle" type back up to something
1967 // that the back ends can handle.
1968 const Type *MiddleType = 0;
1971 case 32: MiddleType = Type::Int32Ty; break;
1972 case 16: MiddleType = Type::Int16Ty; break;
1973 case 8: MiddleType = Type::Int8Ty; break;
1976 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1977 InsertNewInstBefore(NewTrunc, I);
1978 return new SExtInst(NewTrunc, I.getType(), I.getName());
1983 if (I.getType() == Type::Int1Ty)
1984 return BinaryOperator::CreateXor(LHS, RHS);
1987 if (I.getType()->isInteger()) {
1988 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1990 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1991 if (RHSI->getOpcode() == Instruction::Sub)
1992 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1993 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1995 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1996 if (LHSI->getOpcode() == Instruction::Sub)
1997 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1998 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2003 // -A + -B --> -(A + B)
2004 if (Value *LHSV = dyn_castNegVal(LHS)) {
2005 if (LHS->getType()->isIntOrIntVector()) {
2006 if (Value *RHSV = dyn_castNegVal(RHS)) {
2007 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2008 InsertNewInstBefore(NewAdd, I);
2009 return BinaryOperator::CreateNeg(NewAdd);
2013 return BinaryOperator::CreateSub(RHS, LHSV);
2017 if (!isa<Constant>(RHS))
2018 if (Value *V = dyn_castNegVal(RHS))
2019 return BinaryOperator::CreateSub(LHS, V);
2023 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2024 if (X == RHS) // X*C + X --> X * (C+1)
2025 return BinaryOperator::CreateMul(RHS, AddOne(C2));
2027 // X*C1 + X*C2 --> X * (C1+C2)
2029 if (X == dyn_castFoldableMul(RHS, C1))
2030 return BinaryOperator::CreateMul(X, Add(C1, C2));
2033 // X + X*C --> X * (C+1)
2034 if (dyn_castFoldableMul(RHS, C2) == LHS)
2035 return BinaryOperator::CreateMul(LHS, AddOne(C2));
2037 // X + ~X --> -1 since ~X = -X-1
2038 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2039 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2042 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2043 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2044 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2047 // A+B --> A|B iff A and B have no bits set in common.
2048 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2049 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2050 APInt LHSKnownOne(IT->getBitWidth(), 0);
2051 APInt LHSKnownZero(IT->getBitWidth(), 0);
2052 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2053 if (LHSKnownZero != 0) {
2054 APInt RHSKnownOne(IT->getBitWidth(), 0);
2055 APInt RHSKnownZero(IT->getBitWidth(), 0);
2056 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2058 // No bits in common -> bitwise or.
2059 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2060 return BinaryOperator::CreateOr(LHS, RHS);
2064 // W*X + Y*Z --> W * (X+Z) iff W == Y
2065 if (I.getType()->isIntOrIntVector()) {
2066 Value *W, *X, *Y, *Z;
2067 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2068 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2072 } else if (Y == X) {
2074 } else if (X == Z) {
2081 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2082 LHS->getName()), I);
2083 return BinaryOperator::CreateMul(W, NewAdd);
2088 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2090 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2091 return BinaryOperator::CreateSub(SubOne(CRHS), X);
2093 // (X & FF00) + xx00 -> (X+xx00) & FF00
2094 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2095 Constant *Anded = And(CRHS, C2);
2096 if (Anded == CRHS) {
2097 // See if all bits from the first bit set in the Add RHS up are included
2098 // in the mask. First, get the rightmost bit.
2099 const APInt& AddRHSV = CRHS->getValue();
2101 // Form a mask of all bits from the lowest bit added through the top.
2102 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2104 // See if the and mask includes all of these bits.
2105 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2107 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2108 // Okay, the xform is safe. Insert the new add pronto.
2109 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2110 LHS->getName()), I);
2111 return BinaryOperator::CreateAnd(NewAdd, C2);
2116 // Try to fold constant add into select arguments.
2117 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2118 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2122 // add (cast *A to intptrtype) B ->
2123 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
2125 CastInst *CI = dyn_cast<CastInst>(LHS);
2128 CI = dyn_cast<CastInst>(RHS);
2131 if (CI && CI->getType()->isSized() &&
2132 (CI->getType()->getPrimitiveSizeInBits() ==
2133 TD->getIntPtrType()->getPrimitiveSizeInBits())
2134 && isa<PointerType>(CI->getOperand(0)->getType())) {
2136 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2137 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2138 PointerType::get(Type::Int8Ty, AS), I);
2139 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2140 return new PtrToIntInst(I2, CI->getType());
2144 // add (select X 0 (sub n A)) A --> select X A n
2146 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2149 SI = dyn_cast<SelectInst>(RHS);
2152 if (SI && SI->hasOneUse()) {
2153 Value *TV = SI->getTrueValue();
2154 Value *FV = SI->getFalseValue();
2157 // Can we fold the add into the argument of the select?
2158 // We check both true and false select arguments for a matching subtract.
2159 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2160 A == Other) // Fold the add into the true select value.
2161 return SelectInst::Create(SI->getCondition(), N, A);
2162 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2163 A == Other) // Fold the add into the false select value.
2164 return SelectInst::Create(SI->getCondition(), A, N);
2168 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2169 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2170 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2171 return ReplaceInstUsesWith(I, LHS);
2173 // Check for (add (sext x), y), see if we can merge this into an
2174 // integer add followed by a sext.
2175 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2176 // (add (sext x), cst) --> (sext (add x, cst'))
2177 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2179 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2180 if (LHSConv->hasOneUse() &&
2181 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2182 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2183 // Insert the new, smaller add.
2184 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2186 InsertNewInstBefore(NewAdd, I);
2187 return new SExtInst(NewAdd, I.getType());
2191 // (add (sext x), (sext y)) --> (sext (add int x, y))
2192 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2193 // Only do this if x/y have the same type, if at last one of them has a
2194 // single use (so we don't increase the number of sexts), and if the
2195 // integer add will not overflow.
2196 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2197 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2198 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2199 RHSConv->getOperand(0))) {
2200 // Insert the new integer add.
2201 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2202 RHSConv->getOperand(0),
2204 InsertNewInstBefore(NewAdd, I);
2205 return new SExtInst(NewAdd, I.getType());
2210 // Check for (add double (sitofp x), y), see if we can merge this into an
2211 // integer add followed by a promotion.
2212 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2213 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2214 // ... if the constant fits in the integer value. This is useful for things
2215 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2216 // requires a constant pool load, and generally allows the add to be better
2218 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2220 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2221 if (LHSConv->hasOneUse() &&
2222 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2223 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2224 // Insert the new integer add.
2225 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2227 InsertNewInstBefore(NewAdd, I);
2228 return new SIToFPInst(NewAdd, I.getType());
2232 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2233 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2234 // Only do this if x/y have the same type, if at last one of them has a
2235 // single use (so we don't increase the number of int->fp conversions),
2236 // and if the integer add will not overflow.
2237 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2238 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2239 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2240 RHSConv->getOperand(0))) {
2241 // Insert the new integer add.
2242 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2243 RHSConv->getOperand(0),
2245 InsertNewInstBefore(NewAdd, I);
2246 return new SIToFPInst(NewAdd, I.getType());
2251 return Changed ? &I : 0;
2254 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2255 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2257 if (Op0 == Op1) // sub X, X -> 0
2258 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2260 // If this is a 'B = x-(-A)', change to B = x+A...
2261 if (Value *V = dyn_castNegVal(Op1))
2262 return BinaryOperator::CreateAdd(Op0, V);
2264 if (isa<UndefValue>(Op0))
2265 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2266 if (isa<UndefValue>(Op1))
2267 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2269 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2270 // Replace (-1 - A) with (~A)...
2271 if (C->isAllOnesValue())
2272 return BinaryOperator::CreateNot(Op1);
2274 // C - ~X == X + (1+C)
2276 if (match(Op1, m_Not(m_Value(X))))
2277 return BinaryOperator::CreateAdd(X, AddOne(C));
2279 // -(X >>u 31) -> (X >>s 31)
2280 // -(X >>s 31) -> (X >>u 31)
2282 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2283 if (SI->getOpcode() == Instruction::LShr) {
2284 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2285 // Check to see if we are shifting out everything but the sign bit.
2286 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2287 SI->getType()->getPrimitiveSizeInBits()-1) {
2288 // Ok, the transformation is safe. Insert AShr.
2289 return BinaryOperator::Create(Instruction::AShr,
2290 SI->getOperand(0), CU, SI->getName());
2294 else if (SI->getOpcode() == Instruction::AShr) {
2295 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2296 // Check to see if we are shifting out everything but the sign bit.
2297 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2298 SI->getType()->getPrimitiveSizeInBits()-1) {
2299 // Ok, the transformation is safe. Insert LShr.
2300 return BinaryOperator::CreateLShr(
2301 SI->getOperand(0), CU, SI->getName());
2308 // Try to fold constant sub into select arguments.
2309 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2310 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2313 if (isa<PHINode>(Op0))
2314 if (Instruction *NV = FoldOpIntoPhi(I))
2318 if (I.getType() == Type::Int1Ty)
2319 return BinaryOperator::CreateXor(Op0, Op1);
2321 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2322 if (Op1I->getOpcode() == Instruction::Add &&
2323 !Op0->getType()->isFPOrFPVector()) {
2324 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2325 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2326 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2327 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2328 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2329 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2330 // C1-(X+C2) --> (C1-C2)-X
2331 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
2332 Op1I->getOperand(0));
2336 if (Op1I->hasOneUse()) {
2337 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2338 // is not used by anyone else...
2340 if (Op1I->getOpcode() == Instruction::Sub &&
2341 !Op1I->getType()->isFPOrFPVector()) {
2342 // Swap the two operands of the subexpr...
2343 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2344 Op1I->setOperand(0, IIOp1);
2345 Op1I->setOperand(1, IIOp0);
2347 // Create the new top level add instruction...
2348 return BinaryOperator::CreateAdd(Op0, Op1);
2351 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2353 if (Op1I->getOpcode() == Instruction::And &&
2354 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2355 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2358 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2359 return BinaryOperator::CreateAnd(Op0, NewNot);
2362 // 0 - (X sdiv C) -> (X sdiv -C)
2363 if (Op1I->getOpcode() == Instruction::SDiv)
2364 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2366 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2367 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2368 ConstantExpr::getNeg(DivRHS));
2370 // X - X*C --> X * (1-C)
2371 ConstantInt *C2 = 0;
2372 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2373 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2374 return BinaryOperator::CreateMul(Op0, CP1);
2377 // X - ((X / Y) * Y) --> X % Y
2378 if (Op1I->getOpcode() == Instruction::Mul)
2379 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2380 if (Op0 == I->getOperand(0) &&
2381 Op1I->getOperand(1) == I->getOperand(1)) {
2382 if (I->getOpcode() == Instruction::SDiv)
2383 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
2384 if (I->getOpcode() == Instruction::UDiv)
2385 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
2390 if (!Op0->getType()->isFPOrFPVector())
2391 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2392 if (Op0I->getOpcode() == Instruction::Add) {
2393 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2394 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2395 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2396 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2397 } else if (Op0I->getOpcode() == Instruction::Sub) {
2398 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2399 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2404 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2405 if (X == Op1) // X*C - X --> X * (C-1)
2406 return BinaryOperator::CreateMul(Op1, SubOne(C1));
2408 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2409 if (X == dyn_castFoldableMul(Op1, C2))
2410 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2415 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2416 /// comparison only checks the sign bit. If it only checks the sign bit, set
2417 /// TrueIfSigned if the result of the comparison is true when the input value is
2419 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2420 bool &TrueIfSigned) {
2422 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2423 TrueIfSigned = true;
2424 return RHS->isZero();
2425 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2426 TrueIfSigned = true;
2427 return RHS->isAllOnesValue();
2428 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2429 TrueIfSigned = false;
2430 return RHS->isAllOnesValue();
2431 case ICmpInst::ICMP_UGT:
2432 // True if LHS u> RHS and RHS == high-bit-mask - 1
2433 TrueIfSigned = true;
2434 return RHS->getValue() ==
2435 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2436 case ICmpInst::ICMP_UGE:
2437 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2438 TrueIfSigned = true;
2439 return RHS->getValue().isSignBit();
2445 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2446 bool Changed = SimplifyCommutative(I);
2447 Value *Op0 = I.getOperand(0);
2449 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2450 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2452 // Simplify mul instructions with a constant RHS...
2453 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2454 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2456 // ((X << C1)*C2) == (X * (C2 << C1))
2457 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2458 if (SI->getOpcode() == Instruction::Shl)
2459 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2460 return BinaryOperator::CreateMul(SI->getOperand(0),
2461 ConstantExpr::getShl(CI, ShOp));
2464 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2465 if (CI->equalsInt(1)) // X * 1 == X
2466 return ReplaceInstUsesWith(I, Op0);
2467 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2468 return BinaryOperator::CreateNeg(Op0, I.getName());
2470 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2471 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2472 return BinaryOperator::CreateShl(Op0,
2473 ConstantInt::get(Op0->getType(), Val.logBase2()));
2475 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2476 if (Op1F->isNullValue())
2477 return ReplaceInstUsesWith(I, Op1);
2479 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2480 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2481 // We need a better interface for long double here.
2482 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2483 if (Op1F->isExactlyValue(1.0))
2484 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2487 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2488 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2489 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2490 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2491 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2493 InsertNewInstBefore(Add, I);
2494 Value *C1C2 = ConstantExpr::getMul(Op1,
2495 cast<Constant>(Op0I->getOperand(1)));
2496 return BinaryOperator::CreateAdd(Add, C1C2);
2500 // Try to fold constant mul into select arguments.
2501 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2502 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2505 if (isa<PHINode>(Op0))
2506 if (Instruction *NV = FoldOpIntoPhi(I))
2510 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2511 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2512 return BinaryOperator::CreateMul(Op0v, Op1v);
2514 if (I.getType() == Type::Int1Ty)
2515 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2517 // If one of the operands of the multiply is a cast from a boolean value, then
2518 // we know the bool is either zero or one, so this is a 'masking' multiply.
2519 // See if we can simplify things based on how the boolean was originally
2521 CastInst *BoolCast = 0;
2522 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2523 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2526 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2527 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2530 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2531 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2532 const Type *SCOpTy = SCIOp0->getType();
2535 // If the icmp is true iff the sign bit of X is set, then convert this
2536 // multiply into a shift/and combination.
2537 if (isa<ConstantInt>(SCIOp1) &&
2538 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2540 // Shift the X value right to turn it into "all signbits".
2541 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2542 SCOpTy->getPrimitiveSizeInBits()-1);
2544 InsertNewInstBefore(
2545 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2546 BoolCast->getOperand(0)->getName()+
2549 // If the multiply type is not the same as the source type, sign extend
2550 // or truncate to the multiply type.
2551 if (I.getType() != V->getType()) {
2552 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2553 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2554 Instruction::CastOps opcode =
2555 (SrcBits == DstBits ? Instruction::BitCast :
2556 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2557 V = InsertCastBefore(opcode, V, I.getType(), I);
2560 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2561 return BinaryOperator::CreateAnd(V, OtherOp);
2566 return Changed ? &I : 0;
2569 /// This function implements the transforms on div instructions that work
2570 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2571 /// used by the visitors to those instructions.
2572 /// @brief Transforms common to all three div instructions
2573 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2574 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2576 // undef / X -> 0 for integer.
2577 // undef / X -> undef for FP (the undef could be a snan).
2578 if (isa<UndefValue>(Op0)) {
2579 if (Op0->getType()->isFPOrFPVector())
2580 return ReplaceInstUsesWith(I, Op0);
2581 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2584 // X / undef -> undef
2585 if (isa<UndefValue>(Op1))
2586 return ReplaceInstUsesWith(I, Op1);
2588 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2589 // This does not apply for fdiv.
2590 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2591 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2592 // the same basic block, then we replace the select with Y, and the
2593 // condition of the select with false (if the cond value is in the same BB).
2594 // If the select has uses other than the div, this allows them to be
2595 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2596 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
2597 if (ST->isNullValue()) {
2598 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2599 if (CondI && CondI->getParent() == I.getParent())
2600 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2601 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2602 I.setOperand(1, SI->getOperand(2));
2604 UpdateValueUsesWith(SI, SI->getOperand(2));
2608 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2609 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
2610 if (ST->isNullValue()) {
2611 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2612 if (CondI && CondI->getParent() == I.getParent())
2613 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2614 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2615 I.setOperand(1, SI->getOperand(1));
2617 UpdateValueUsesWith(SI, SI->getOperand(1));
2625 /// This function implements the transforms common to both integer division
2626 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2627 /// division instructions.
2628 /// @brief Common integer divide transforms
2629 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2630 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2632 // (sdiv X, X) --> 1 (udiv X, X) --> 1
2634 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2635 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2636 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2637 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2640 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2641 return ReplaceInstUsesWith(I, CI);
2644 if (Instruction *Common = commonDivTransforms(I))
2647 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2649 if (RHS->equalsInt(1))
2650 return ReplaceInstUsesWith(I, Op0);
2652 // (X / C1) / C2 -> X / (C1*C2)
2653 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2654 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2655 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2656 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2657 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2659 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2660 Multiply(RHS, LHSRHS));
2663 if (!RHS->isZero()) { // avoid X udiv 0
2664 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2665 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2667 if (isa<PHINode>(Op0))
2668 if (Instruction *NV = FoldOpIntoPhi(I))
2673 // 0 / X == 0, we don't need to preserve faults!
2674 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2675 if (LHS->equalsInt(0))
2676 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2678 // It can't be division by zero, hence it must be division by one.
2679 if (I.getType() == Type::Int1Ty)
2680 return ReplaceInstUsesWith(I, Op0);
2685 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2686 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2688 // Handle the integer div common cases
2689 if (Instruction *Common = commonIDivTransforms(I))
2692 // X udiv C^2 -> X >> C
2693 // Check to see if this is an unsigned division with an exact power of 2,
2694 // if so, convert to a right shift.
2695 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2696 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
2697 return BinaryOperator::CreateLShr(Op0,
2698 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2701 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2702 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2703 if (RHSI->getOpcode() == Instruction::Shl &&
2704 isa<ConstantInt>(RHSI->getOperand(0))) {
2705 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2706 if (C1.isPowerOf2()) {
2707 Value *N = RHSI->getOperand(1);
2708 const Type *NTy = N->getType();
2709 if (uint32_t C2 = C1.logBase2()) {
2710 Constant *C2V = ConstantInt::get(NTy, C2);
2711 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2713 return BinaryOperator::CreateLShr(Op0, N);
2718 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2719 // where C1&C2 are powers of two.
2720 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2721 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2722 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2723 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2724 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2725 // Compute the shift amounts
2726 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2727 // Construct the "on true" case of the select
2728 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2729 Instruction *TSI = BinaryOperator::CreateLShr(
2730 Op0, TC, SI->getName()+".t");
2731 TSI = InsertNewInstBefore(TSI, I);
2733 // Construct the "on false" case of the select
2734 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2735 Instruction *FSI = BinaryOperator::CreateLShr(
2736 Op0, FC, SI->getName()+".f");
2737 FSI = InsertNewInstBefore(FSI, I);
2739 // construct the select instruction and return it.
2740 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2746 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2747 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2749 // Handle the integer div common cases
2750 if (Instruction *Common = commonIDivTransforms(I))
2753 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2755 if (RHS->isAllOnesValue())
2756 return BinaryOperator::CreateNeg(Op0);
2759 if (Value *LHSNeg = dyn_castNegVal(Op0))
2760 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2763 // If the sign bits of both operands are zero (i.e. we can prove they are
2764 // unsigned inputs), turn this into a udiv.
2765 if (I.getType()->isInteger()) {
2766 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2767 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2768 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2769 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2776 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2777 return commonDivTransforms(I);
2780 /// This function implements the transforms on rem instructions that work
2781 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2782 /// is used by the visitors to those instructions.
2783 /// @brief Transforms common to all three rem instructions
2784 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2785 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2787 // 0 % X == 0 for integer, we don't need to preserve faults!
2788 if (Constant *LHS = dyn_cast<Constant>(Op0))
2789 if (LHS->isNullValue())
2790 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2792 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2793 if (I.getType()->isFPOrFPVector())
2794 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
2795 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2797 if (isa<UndefValue>(Op1))
2798 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2800 // Handle cases involving: rem X, (select Cond, Y, Z)
2801 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2802 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2803 // the same basic block, then we replace the select with Y, and the
2804 // condition of the select with false (if the cond value is in the same
2805 // BB). If the select has uses other than the div, this allows them to be
2807 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2808 if (ST->isNullValue()) {
2809 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2810 if (CondI && CondI->getParent() == I.getParent())
2811 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2812 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2813 I.setOperand(1, SI->getOperand(2));
2815 UpdateValueUsesWith(SI, SI->getOperand(2));
2818 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2819 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2820 if (ST->isNullValue()) {
2821 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2822 if (CondI && CondI->getParent() == I.getParent())
2823 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2824 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2825 I.setOperand(1, SI->getOperand(1));
2827 UpdateValueUsesWith(SI, SI->getOperand(1));
2835 /// This function implements the transforms common to both integer remainder
2836 /// instructions (urem and srem). It is called by the visitors to those integer
2837 /// remainder instructions.
2838 /// @brief Common integer remainder transforms
2839 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2840 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2842 if (Instruction *common = commonRemTransforms(I))
2845 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2846 // X % 0 == undef, we don't need to preserve faults!
2847 if (RHS->equalsInt(0))
2848 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2850 if (RHS->equalsInt(1)) // X % 1 == 0
2851 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2853 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2854 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2855 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2857 } else if (isa<PHINode>(Op0I)) {
2858 if (Instruction *NV = FoldOpIntoPhi(I))
2862 // See if we can fold away this rem instruction.
2863 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2864 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2865 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2866 KnownZero, KnownOne))
2874 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2875 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2877 if (Instruction *common = commonIRemTransforms(I))
2880 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2881 // X urem C^2 -> X and C
2882 // Check to see if this is an unsigned remainder with an exact power of 2,
2883 // if so, convert to a bitwise and.
2884 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2885 if (C->getValue().isPowerOf2())
2886 return BinaryOperator::CreateAnd(Op0, SubOne(C));
2889 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2890 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2891 if (RHSI->getOpcode() == Instruction::Shl &&
2892 isa<ConstantInt>(RHSI->getOperand(0))) {
2893 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2894 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2895 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
2897 return BinaryOperator::CreateAnd(Op0, Add);
2902 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2903 // where C1&C2 are powers of two.
2904 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2905 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2906 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2907 // STO == 0 and SFO == 0 handled above.
2908 if ((STO->getValue().isPowerOf2()) &&
2909 (SFO->getValue().isPowerOf2())) {
2910 Value *TrueAnd = InsertNewInstBefore(
2911 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2912 Value *FalseAnd = InsertNewInstBefore(
2913 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2914 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
2922 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2923 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2925 // Handle the integer rem common cases
2926 if (Instruction *common = commonIRemTransforms(I))
2929 if (Value *RHSNeg = dyn_castNegVal(Op1))
2930 if (!isa<ConstantInt>(RHSNeg) ||
2931 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2933 AddUsesToWorkList(I);
2934 I.setOperand(1, RHSNeg);
2938 // If the sign bits of both operands are zero (i.e. we can prove they are
2939 // unsigned inputs), turn this into a urem.
2940 if (I.getType()->isInteger()) {
2941 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2942 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2943 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2944 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
2951 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2952 return commonRemTransforms(I);
2955 // isOneBitSet - Return true if there is exactly one bit set in the specified
2957 static bool isOneBitSet(const ConstantInt *CI) {
2958 return CI->getValue().isPowerOf2();
2961 // isHighOnes - Return true if the constant is of the form 1+0+.
2962 // This is the same as lowones(~X).
2963 static bool isHighOnes(const ConstantInt *CI) {
2964 return (~CI->getValue() + 1).isPowerOf2();
2967 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
2968 /// are carefully arranged to allow folding of expressions such as:
2970 /// (A < B) | (A > B) --> (A != B)
2972 /// Note that this is only valid if the first and second predicates have the
2973 /// same sign. Is illegal to do: (A u< B) | (A s> B)
2975 /// Three bits are used to represent the condition, as follows:
2980 /// <=> Value Definition
2981 /// 000 0 Always false
2988 /// 111 7 Always true
2990 static unsigned getICmpCode(const ICmpInst *ICI) {
2991 switch (ICI->getPredicate()) {
2993 case ICmpInst::ICMP_UGT: return 1; // 001
2994 case ICmpInst::ICMP_SGT: return 1; // 001
2995 case ICmpInst::ICMP_EQ: return 2; // 010
2996 case ICmpInst::ICMP_UGE: return 3; // 011
2997 case ICmpInst::ICMP_SGE: return 3; // 011
2998 case ICmpInst::ICMP_ULT: return 4; // 100
2999 case ICmpInst::ICMP_SLT: return 4; // 100
3000 case ICmpInst::ICMP_NE: return 5; // 101
3001 case ICmpInst::ICMP_ULE: return 6; // 110
3002 case ICmpInst::ICMP_SLE: return 6; // 110
3005 assert(0 && "Invalid ICmp predicate!");
3010 /// getICmpValue - This is the complement of getICmpCode, which turns an
3011 /// opcode and two operands into either a constant true or false, or a brand
3012 /// new ICmp instruction. The sign is passed in to determine which kind
3013 /// of predicate to use in new icmp instructions.
3014 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3016 default: assert(0 && "Illegal ICmp code!");
3017 case 0: return ConstantInt::getFalse();
3020 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3022 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3023 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3026 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3028 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3031 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3033 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3034 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3037 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3039 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3040 case 7: return ConstantInt::getTrue();
3044 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3045 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3046 (ICmpInst::isSignedPredicate(p1) &&
3047 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3048 (ICmpInst::isSignedPredicate(p2) &&
3049 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3053 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3054 struct FoldICmpLogical {
3057 ICmpInst::Predicate pred;
3058 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3059 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3060 pred(ICI->getPredicate()) {}
3061 bool shouldApply(Value *V) const {
3062 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3063 if (PredicatesFoldable(pred, ICI->getPredicate()))
3064 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3065 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3068 Instruction *apply(Instruction &Log) const {
3069 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3070 if (ICI->getOperand(0) != LHS) {
3071 assert(ICI->getOperand(1) == LHS);
3072 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3075 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3076 unsigned LHSCode = getICmpCode(ICI);
3077 unsigned RHSCode = getICmpCode(RHSICI);
3079 switch (Log.getOpcode()) {
3080 case Instruction::And: Code = LHSCode & RHSCode; break;
3081 case Instruction::Or: Code = LHSCode | RHSCode; break;
3082 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3083 default: assert(0 && "Illegal logical opcode!"); return 0;
3086 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3087 ICmpInst::isSignedPredicate(ICI->getPredicate());
3089 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3090 if (Instruction *I = dyn_cast<Instruction>(RV))
3092 // Otherwise, it's a constant boolean value...
3093 return IC.ReplaceInstUsesWith(Log, RV);
3096 } // end anonymous namespace
3098 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3099 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3100 // guaranteed to be a binary operator.
3101 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3103 ConstantInt *AndRHS,
3104 BinaryOperator &TheAnd) {
3105 Value *X = Op->getOperand(0);
3106 Constant *Together = 0;
3108 Together = And(AndRHS, OpRHS);
3110 switch (Op->getOpcode()) {
3111 case Instruction::Xor:
3112 if (Op->hasOneUse()) {
3113 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3114 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3115 InsertNewInstBefore(And, TheAnd);
3117 return BinaryOperator::CreateXor(And, Together);
3120 case Instruction::Or:
3121 if (Together == AndRHS) // (X | C) & C --> C
3122 return ReplaceInstUsesWith(TheAnd, AndRHS);
3124 if (Op->hasOneUse() && Together != OpRHS) {
3125 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3126 Instruction *Or = BinaryOperator::CreateOr(X, Together);
3127 InsertNewInstBefore(Or, TheAnd);
3129 return BinaryOperator::CreateAnd(Or, AndRHS);
3132 case Instruction::Add:
3133 if (Op->hasOneUse()) {
3134 // Adding a one to a single bit bit-field should be turned into an XOR
3135 // of the bit. First thing to check is to see if this AND is with a
3136 // single bit constant.
3137 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3139 // If there is only one bit set...
3140 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3141 // Ok, at this point, we know that we are masking the result of the
3142 // ADD down to exactly one bit. If the constant we are adding has
3143 // no bits set below this bit, then we can eliminate the ADD.
3144 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3146 // Check to see if any bits below the one bit set in AndRHSV are set.
3147 if ((AddRHS & (AndRHSV-1)) == 0) {
3148 // If not, the only thing that can effect the output of the AND is
3149 // the bit specified by AndRHSV. If that bit is set, the effect of
3150 // the XOR is to toggle the bit. If it is clear, then the ADD has
3152 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3153 TheAnd.setOperand(0, X);
3156 // Pull the XOR out of the AND.
3157 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3158 InsertNewInstBefore(NewAnd, TheAnd);
3159 NewAnd->takeName(Op);
3160 return BinaryOperator::CreateXor(NewAnd, AndRHS);
3167 case Instruction::Shl: {
3168 // We know that the AND will not produce any of the bits shifted in, so if
3169 // the anded constant includes them, clear them now!
3171 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3172 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3173 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3174 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3176 if (CI->getValue() == ShlMask) {
3177 // Masking out bits that the shift already masks
3178 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3179 } else if (CI != AndRHS) { // Reducing bits set in and.
3180 TheAnd.setOperand(1, CI);
3185 case Instruction::LShr:
3187 // We know that the AND will not produce any of the bits shifted in, so if
3188 // the anded constant includes them, clear them now! This only applies to
3189 // unsigned shifts, because a signed shr may bring in set bits!
3191 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3192 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3193 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3194 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3196 if (CI->getValue() == ShrMask) {
3197 // Masking out bits that the shift already masks.
3198 return ReplaceInstUsesWith(TheAnd, Op);
3199 } else if (CI != AndRHS) {
3200 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3205 case Instruction::AShr:
3207 // See if this is shifting in some sign extension, then masking it out
3209 if (Op->hasOneUse()) {
3210 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3211 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3212 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3213 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3214 if (C == AndRHS) { // Masking out bits shifted in.
3215 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3216 // Make the argument unsigned.
3217 Value *ShVal = Op->getOperand(0);
3218 ShVal = InsertNewInstBefore(
3219 BinaryOperator::CreateLShr(ShVal, OpRHS,
3220 Op->getName()), TheAnd);
3221 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3230 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3231 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3232 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3233 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3234 /// insert new instructions.
3235 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3236 bool isSigned, bool Inside,
3238 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3239 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3240 "Lo is not <= Hi in range emission code!");
3243 if (Lo == Hi) // Trivially false.
3244 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3246 // V >= Min && V < Hi --> V < Hi
3247 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3248 ICmpInst::Predicate pred = (isSigned ?
3249 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3250 return new ICmpInst(pred, V, Hi);
3253 // Emit V-Lo <u Hi-Lo
3254 Constant *NegLo = ConstantExpr::getNeg(Lo);
3255 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3256 InsertNewInstBefore(Add, IB);
3257 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3258 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3261 if (Lo == Hi) // Trivially true.
3262 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3264 // V < Min || V >= Hi -> V > Hi-1
3265 Hi = SubOne(cast<ConstantInt>(Hi));
3266 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3267 ICmpInst::Predicate pred = (isSigned ?
3268 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3269 return new ICmpInst(pred, V, Hi);
3272 // Emit V-Lo >u Hi-1-Lo
3273 // Note that Hi has already had one subtracted from it, above.
3274 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3275 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3276 InsertNewInstBefore(Add, IB);
3277 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3278 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3281 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3282 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3283 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3284 // not, since all 1s are not contiguous.
3285 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3286 const APInt& V = Val->getValue();
3287 uint32_t BitWidth = Val->getType()->getBitWidth();
3288 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3290 // look for the first zero bit after the run of ones
3291 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3292 // look for the first non-zero bit
3293 ME = V.getActiveBits();
3297 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3298 /// where isSub determines whether the operator is a sub. If we can fold one of
3299 /// the following xforms:
3301 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3302 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3303 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3305 /// return (A +/- B).
3307 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3308 ConstantInt *Mask, bool isSub,
3310 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3311 if (!LHSI || LHSI->getNumOperands() != 2 ||
3312 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3314 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3316 switch (LHSI->getOpcode()) {
3318 case Instruction::And:
3319 if (And(N, Mask) == Mask) {
3320 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3321 if ((Mask->getValue().countLeadingZeros() +
3322 Mask->getValue().countPopulation()) ==
3323 Mask->getValue().getBitWidth())
3326 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3327 // part, we don't need any explicit masks to take them out of A. If that
3328 // is all N is, ignore it.
3329 uint32_t MB = 0, ME = 0;
3330 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3331 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3332 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3333 if (MaskedValueIsZero(RHS, Mask))
3338 case Instruction::Or:
3339 case Instruction::Xor:
3340 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3341 if ((Mask->getValue().countLeadingZeros() +
3342 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3343 && And(N, Mask)->isZero())
3350 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3352 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3353 return InsertNewInstBefore(New, I);
3356 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3357 bool Changed = SimplifyCommutative(I);
3358 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3360 if (isa<UndefValue>(Op1)) // X & undef -> 0
3361 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3365 return ReplaceInstUsesWith(I, Op1);
3367 // See if we can simplify any instructions used by the instruction whose sole
3368 // purpose is to compute bits we don't care about.
3369 if (!isa<VectorType>(I.getType())) {
3370 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3371 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3372 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3373 KnownZero, KnownOne))
3376 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3377 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3378 return ReplaceInstUsesWith(I, I.getOperand(0));
3379 } else if (isa<ConstantAggregateZero>(Op1)) {
3380 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3384 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3385 const APInt& AndRHSMask = AndRHS->getValue();
3386 APInt NotAndRHS(~AndRHSMask);
3388 // Optimize a variety of ((val OP C1) & C2) combinations...
3389 if (isa<BinaryOperator>(Op0)) {
3390 Instruction *Op0I = cast<Instruction>(Op0);
3391 Value *Op0LHS = Op0I->getOperand(0);
3392 Value *Op0RHS = Op0I->getOperand(1);
3393 switch (Op0I->getOpcode()) {
3394 case Instruction::Xor:
3395 case Instruction::Or:
3396 // If the mask is only needed on one incoming arm, push it up.
3397 if (Op0I->hasOneUse()) {
3398 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3399 // Not masking anything out for the LHS, move to RHS.
3400 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3401 Op0RHS->getName()+".masked");
3402 InsertNewInstBefore(NewRHS, I);
3403 return BinaryOperator::Create(
3404 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3406 if (!isa<Constant>(Op0RHS) &&
3407 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3408 // Not masking anything out for the RHS, move to LHS.
3409 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3410 Op0LHS->getName()+".masked");
3411 InsertNewInstBefore(NewLHS, I);
3412 return BinaryOperator::Create(
3413 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3418 case Instruction::Add:
3419 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3420 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3421 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3422 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3423 return BinaryOperator::CreateAnd(V, AndRHS);
3424 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3425 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
3428 case Instruction::Sub:
3429 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3430 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3431 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3432 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3433 return BinaryOperator::CreateAnd(V, AndRHS);
3435 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3436 // has 1's for all bits that the subtraction with A might affect.
3437 if (Op0I->hasOneUse()) {
3438 uint32_t BitWidth = AndRHSMask.getBitWidth();
3439 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3440 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3442 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3443 if (!(A && A->isZero()) && // avoid infinite recursion.
3444 MaskedValueIsZero(Op0LHS, Mask)) {
3445 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3446 InsertNewInstBefore(NewNeg, I);
3447 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3452 case Instruction::Shl:
3453 case Instruction::LShr:
3454 // (1 << x) & 1 --> zext(x == 0)
3455 // (1 >> x) & 1 --> zext(x == 0)
3456 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3457 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3458 Constant::getNullValue(I.getType()));
3459 InsertNewInstBefore(NewICmp, I);
3460 return new ZExtInst(NewICmp, I.getType());
3465 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3466 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3468 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3469 // If this is an integer truncation or change from signed-to-unsigned, and
3470 // if the source is an and/or with immediate, transform it. This
3471 // frequently occurs for bitfield accesses.
3472 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3473 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3474 CastOp->getNumOperands() == 2)
3475 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3476 if (CastOp->getOpcode() == Instruction::And) {
3477 // Change: and (cast (and X, C1) to T), C2
3478 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3479 // This will fold the two constants together, which may allow
3480 // other simplifications.
3481 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3482 CastOp->getOperand(0), I.getType(),
3483 CastOp->getName()+".shrunk");
3484 NewCast = InsertNewInstBefore(NewCast, I);
3485 // trunc_or_bitcast(C1)&C2
3486 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3487 C3 = ConstantExpr::getAnd(C3, AndRHS);
3488 return BinaryOperator::CreateAnd(NewCast, C3);
3489 } else if (CastOp->getOpcode() == Instruction::Or) {
3490 // Change: and (cast (or X, C1) to T), C2
3491 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3492 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3493 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3494 return ReplaceInstUsesWith(I, AndRHS);
3500 // Try to fold constant and into select arguments.
3501 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3502 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3504 if (isa<PHINode>(Op0))
3505 if (Instruction *NV = FoldOpIntoPhi(I))
3509 Value *Op0NotVal = dyn_castNotVal(Op0);
3510 Value *Op1NotVal = dyn_castNotVal(Op1);
3512 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3513 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3515 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3516 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3517 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3518 I.getName()+".demorgan");
3519 InsertNewInstBefore(Or, I);
3520 return BinaryOperator::CreateNot(Or);
3524 Value *A = 0, *B = 0, *C = 0, *D = 0;
3525 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3526 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3527 return ReplaceInstUsesWith(I, Op1);
3529 // (A|B) & ~(A&B) -> A^B
3530 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3531 if ((A == C && B == D) || (A == D && B == C))
3532 return BinaryOperator::CreateXor(A, B);
3536 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3537 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3538 return ReplaceInstUsesWith(I, Op0);
3540 // ~(A&B) & (A|B) -> A^B
3541 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3542 if ((A == C && B == D) || (A == D && B == C))
3543 return BinaryOperator::CreateXor(A, B);
3547 if (Op0->hasOneUse() &&
3548 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3549 if (A == Op1) { // (A^B)&A -> A&(A^B)
3550 I.swapOperands(); // Simplify below
3551 std::swap(Op0, Op1);
3552 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3553 cast<BinaryOperator>(Op0)->swapOperands();
3554 I.swapOperands(); // Simplify below
3555 std::swap(Op0, Op1);
3558 if (Op1->hasOneUse() &&
3559 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3560 if (B == Op0) { // B&(A^B) -> B&(B^A)
3561 cast<BinaryOperator>(Op1)->swapOperands();
3564 if (A == Op0) { // A&(A^B) -> A & ~B
3565 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
3566 InsertNewInstBefore(NotB, I);
3567 return BinaryOperator::CreateAnd(A, NotB);
3573 { // (icmp ugt/ult A, C) & (icmp B, C) --> (icmp (A|B), C)
3574 // where C is a power of 2
3576 ConstantInt *C1, *C2;
3577 ICmpInst::Predicate LHSCC, RHSCC;
3578 if (match(&I, m_And(m_ICmp(LHSCC, m_Value(A), m_ConstantInt(C1)),
3579 m_ICmp(RHSCC, m_Value(B), m_ConstantInt(C2)))))
3580 if (C1 == C2 && LHSCC == RHSCC && C1->getValue().isPowerOf2() &&
3581 (LHSCC == ICmpInst::ICMP_ULT || LHSCC == ICmpInst::ICMP_UGT)) {
3582 Instruction *NewOr = BinaryOperator::CreateOr(A, B);
3583 InsertNewInstBefore(NewOr, I);
3584 return new ICmpInst(LHSCC, NewOr, C1);
3588 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3589 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3590 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3593 Value *LHSVal, *RHSVal;
3594 ConstantInt *LHSCst, *RHSCst;
3595 ICmpInst::Predicate LHSCC, RHSCC;
3596 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3597 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3598 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3599 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3600 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3601 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3602 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3603 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3605 // Don't try to fold ICMP_SLT + ICMP_ULT.
3606 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3607 ICmpInst::isSignedPredicate(LHSCC) ==
3608 ICmpInst::isSignedPredicate(RHSCC))) {
3609 // Ensure that the larger constant is on the RHS.
3610 ICmpInst::Predicate GT;
3611 if (ICmpInst::isSignedPredicate(LHSCC) ||
3612 (ICmpInst::isEquality(LHSCC) &&
3613 ICmpInst::isSignedPredicate(RHSCC)))
3614 GT = ICmpInst::ICMP_SGT;
3616 GT = ICmpInst::ICMP_UGT;
3618 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3619 ICmpInst *LHS = cast<ICmpInst>(Op0);
3620 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3621 std::swap(LHS, RHS);
3622 std::swap(LHSCst, RHSCst);
3623 std::swap(LHSCC, RHSCC);
3626 // At this point, we know we have have two icmp instructions
3627 // comparing a value against two constants and and'ing the result
3628 // together. Because of the above check, we know that we only have
3629 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3630 // (from the FoldICmpLogical check above), that the two constants
3631 // are not equal and that the larger constant is on the RHS
3632 assert(LHSCst != RHSCst && "Compares not folded above?");
3635 default: assert(0 && "Unknown integer condition code!");
3636 case ICmpInst::ICMP_EQ:
3638 default: assert(0 && "Unknown integer condition code!");
3639 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3640 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3641 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3642 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3643 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3644 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3645 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3646 return ReplaceInstUsesWith(I, LHS);
3648 case ICmpInst::ICMP_NE:
3650 default: assert(0 && "Unknown integer condition code!");
3651 case ICmpInst::ICMP_ULT:
3652 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3653 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3654 break; // (X != 13 & X u< 15) -> no change
3655 case ICmpInst::ICMP_SLT:
3656 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3657 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3658 break; // (X != 13 & X s< 15) -> no change
3659 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3660 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3661 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3662 return ReplaceInstUsesWith(I, RHS);
3663 case ICmpInst::ICMP_NE:
3664 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3665 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3666 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
3667 LHSVal->getName()+".off");
3668 InsertNewInstBefore(Add, I);
3669 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3670 ConstantInt::get(Add->getType(), 1));
3672 break; // (X != 13 & X != 15) -> no change
3675 case ICmpInst::ICMP_ULT:
3677 default: assert(0 && "Unknown integer condition code!");
3678 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3679 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3680 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3681 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3683 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3684 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3685 return ReplaceInstUsesWith(I, LHS);
3686 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3690 case ICmpInst::ICMP_SLT:
3692 default: assert(0 && "Unknown integer condition code!");
3693 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3694 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3695 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3696 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3698 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3699 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3700 return ReplaceInstUsesWith(I, LHS);
3701 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3705 case ICmpInst::ICMP_UGT:
3707 default: assert(0 && "Unknown integer condition code!");
3708 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3709 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3710 return ReplaceInstUsesWith(I, RHS);
3711 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3713 case ICmpInst::ICMP_NE:
3714 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3715 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3716 break; // (X u> 13 & X != 15) -> no change
3717 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3718 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3720 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3724 case ICmpInst::ICMP_SGT:
3726 default: assert(0 && "Unknown integer condition code!");
3727 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3728 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3729 return ReplaceInstUsesWith(I, RHS);
3730 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3732 case ICmpInst::ICMP_NE:
3733 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3734 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3735 break; // (X s> 13 & X != 15) -> no change
3736 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3737 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3739 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3747 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3748 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3749 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3750 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3751 const Type *SrcTy = Op0C->getOperand(0)->getType();
3752 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3753 // Only do this if the casts both really cause code to be generated.
3754 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3756 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3758 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
3759 Op1C->getOperand(0),
3761 InsertNewInstBefore(NewOp, I);
3762 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
3766 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3767 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3768 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3769 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
3770 SI0->getOperand(1) == SI1->getOperand(1) &&
3771 (SI0->hasOneUse() || SI1->hasOneUse())) {
3772 Instruction *NewOp =
3773 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
3775 SI0->getName()), I);
3776 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
3777 SI1->getOperand(1));
3781 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3782 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3783 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3784 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3785 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3786 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3787 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3788 // If either of the constants are nans, then the whole thing returns
3790 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3791 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3792 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3793 RHS->getOperand(0));
3798 return Changed ? &I : 0;
3801 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3802 /// in the result. If it does, and if the specified byte hasn't been filled in
3803 /// yet, fill it in and return false.
3804 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3805 Instruction *I = dyn_cast<Instruction>(V);
3806 if (I == 0) return true;
3808 // If this is an or instruction, it is an inner node of the bswap.
3809 if (I->getOpcode() == Instruction::Or)
3810 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3811 CollectBSwapParts(I->getOperand(1), ByteValues);
3813 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3814 // If this is a shift by a constant int, and it is "24", then its operand
3815 // defines a byte. We only handle unsigned types here.
3816 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3817 // Not shifting the entire input by N-1 bytes?
3818 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3819 8*(ByteValues.size()-1))
3823 if (I->getOpcode() == Instruction::Shl) {
3824 // X << 24 defines the top byte with the lowest of the input bytes.
3825 DestNo = ByteValues.size()-1;
3827 // X >>u 24 defines the low byte with the highest of the input bytes.
3831 // If the destination byte value is already defined, the values are or'd
3832 // together, which isn't a bswap (unless it's an or of the same bits).
3833 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3835 ByteValues[DestNo] = I->getOperand(0);
3839 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3841 Value *Shift = 0, *ShiftLHS = 0;
3842 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3843 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3844 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3846 Instruction *SI = cast<Instruction>(Shift);
3848 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3849 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3850 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3853 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3855 if (AndAmt->getValue().getActiveBits() > 64)
3857 uint64_t AndAmtVal = AndAmt->getZExtValue();
3858 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3859 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3861 // Unknown mask for bswap.
3862 if (DestByte == ByteValues.size()) return true;
3864 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3866 if (SI->getOpcode() == Instruction::Shl)
3867 SrcByte = DestByte - ShiftBytes;
3869 SrcByte = DestByte + ShiftBytes;
3871 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3872 if (SrcByte != ByteValues.size()-DestByte-1)
3875 // If the destination byte value is already defined, the values are or'd
3876 // together, which isn't a bswap (unless it's an or of the same bits).
3877 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3879 ByteValues[DestByte] = SI->getOperand(0);
3883 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3884 /// If so, insert the new bswap intrinsic and return it.
3885 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3886 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3887 if (!ITy || ITy->getBitWidth() % 16)
3888 return 0; // Can only bswap pairs of bytes. Can't do vectors.
3890 /// ByteValues - For each byte of the result, we keep track of which value
3891 /// defines each byte.
3892 SmallVector<Value*, 8> ByteValues;
3893 ByteValues.resize(ITy->getBitWidth()/8);
3895 // Try to find all the pieces corresponding to the bswap.
3896 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3897 CollectBSwapParts(I.getOperand(1), ByteValues))
3900 // Check to see if all of the bytes come from the same value.
3901 Value *V = ByteValues[0];
3902 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3904 // Check to make sure that all of the bytes come from the same value.
3905 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3906 if (ByteValues[i] != V)
3908 const Type *Tys[] = { ITy };
3909 Module *M = I.getParent()->getParent()->getParent();
3910 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
3911 return CallInst::Create(F, V);
3915 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3916 bool Changed = SimplifyCommutative(I);
3917 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3919 if (isa<UndefValue>(Op1)) // X | undef -> -1
3920 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3924 return ReplaceInstUsesWith(I, Op0);
3926 // See if we can simplify any instructions used by the instruction whose sole
3927 // purpose is to compute bits we don't care about.
3928 if (!isa<VectorType>(I.getType())) {
3929 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3930 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3931 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3932 KnownZero, KnownOne))
3934 } else if (isa<ConstantAggregateZero>(Op1)) {
3935 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3936 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3937 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3938 return ReplaceInstUsesWith(I, I.getOperand(1));
3944 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3945 ConstantInt *C1 = 0; Value *X = 0;
3946 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3947 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3948 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3949 InsertNewInstBefore(Or, I);
3951 return BinaryOperator::CreateAnd(Or,
3952 ConstantInt::get(RHS->getValue() | C1->getValue()));
3955 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3956 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3957 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3958 InsertNewInstBefore(Or, I);
3960 return BinaryOperator::CreateXor(Or,
3961 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3964 // Try to fold constant and into select arguments.
3965 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3966 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3968 if (isa<PHINode>(Op0))
3969 if (Instruction *NV = FoldOpIntoPhi(I))
3973 Value *A = 0, *B = 0;
3974 ConstantInt *C1 = 0, *C2 = 0;
3976 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3977 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3978 return ReplaceInstUsesWith(I, Op1);
3979 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3980 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3981 return ReplaceInstUsesWith(I, Op0);
3983 // (A | B) | C and A | (B | C) -> bswap if possible.
3984 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
3985 if (match(Op0, m_Or(m_Value(), m_Value())) ||
3986 match(Op1, m_Or(m_Value(), m_Value())) ||
3987 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3988 match(Op1, m_Shift(m_Value(), m_Value())))) {
3989 if (Instruction *BSwap = MatchBSwap(I))
3993 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3994 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3995 MaskedValueIsZero(Op1, C1->getValue())) {
3996 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
3997 InsertNewInstBefore(NOr, I);
3999 return BinaryOperator::CreateXor(NOr, C1);
4002 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4003 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4004 MaskedValueIsZero(Op0, C1->getValue())) {
4005 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4006 InsertNewInstBefore(NOr, I);
4008 return BinaryOperator::CreateXor(NOr, C1);
4012 Value *C = 0, *D = 0;
4013 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4014 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4015 Value *V1 = 0, *V2 = 0, *V3 = 0;
4016 C1 = dyn_cast<ConstantInt>(C);
4017 C2 = dyn_cast<ConstantInt>(D);
4018 if (C1 && C2) { // (A & C1)|(B & C2)
4019 // If we have: ((V + N) & C1) | (V & C2)
4020 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4021 // replace with V+N.
4022 if (C1->getValue() == ~C2->getValue()) {
4023 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4024 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4025 // Add commutes, try both ways.
4026 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4027 return ReplaceInstUsesWith(I, A);
4028 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4029 return ReplaceInstUsesWith(I, A);
4031 // Or commutes, try both ways.
4032 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4033 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4034 // Add commutes, try both ways.
4035 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4036 return ReplaceInstUsesWith(I, B);
4037 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4038 return ReplaceInstUsesWith(I, B);
4041 V1 = 0; V2 = 0; V3 = 0;
4044 // Check to see if we have any common things being and'ed. If so, find the
4045 // terms for V1 & (V2|V3).
4046 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4047 if (A == B) // (A & C)|(A & D) == A & (C|D)
4048 V1 = A, V2 = C, V3 = D;
4049 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4050 V1 = A, V2 = B, V3 = C;
4051 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4052 V1 = C, V2 = A, V3 = D;
4053 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4054 V1 = C, V2 = A, V3 = B;
4058 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4059 return BinaryOperator::CreateAnd(V1, Or);
4064 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4065 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4066 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4067 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4068 SI0->getOperand(1) == SI1->getOperand(1) &&
4069 (SI0->hasOneUse() || SI1->hasOneUse())) {
4070 Instruction *NewOp =
4071 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4073 SI0->getName()), I);
4074 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4075 SI1->getOperand(1));
4079 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4080 if (A == Op1) // ~A | A == -1
4081 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4085 // Note, A is still live here!
4086 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4088 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4090 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4091 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4092 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4093 I.getName()+".demorgan"), I);
4094 return BinaryOperator::CreateNot(And);
4098 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4099 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4100 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4103 Value *LHSVal, *RHSVal;
4104 ConstantInt *LHSCst, *RHSCst;
4105 ICmpInst::Predicate LHSCC, RHSCC;
4106 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4107 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4108 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4109 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4110 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4111 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4112 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4113 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4114 // We can't fold (ugt x, C) | (sgt x, C2).
4115 PredicatesFoldable(LHSCC, RHSCC)) {
4116 // Ensure that the larger constant is on the RHS.
4117 ICmpInst *LHS = cast<ICmpInst>(Op0);
4119 if (ICmpInst::isSignedPredicate(LHSCC))
4120 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4122 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4125 std::swap(LHS, RHS);
4126 std::swap(LHSCst, RHSCst);
4127 std::swap(LHSCC, RHSCC);
4130 // At this point, we know we have have two icmp instructions
4131 // comparing a value against two constants and or'ing the result
4132 // together. Because of the above check, we know that we only have
4133 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4134 // FoldICmpLogical check above), that the two constants are not
4136 assert(LHSCst != RHSCst && "Compares not folded above?");
4139 default: assert(0 && "Unknown integer condition code!");
4140 case ICmpInst::ICMP_EQ:
4142 default: assert(0 && "Unknown integer condition code!");
4143 case ICmpInst::ICMP_EQ:
4144 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4145 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4146 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4147 LHSVal->getName()+".off");
4148 InsertNewInstBefore(Add, I);
4149 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4150 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4152 break; // (X == 13 | X == 15) -> no change
4153 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4154 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4156 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4157 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4158 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4159 return ReplaceInstUsesWith(I, RHS);
4162 case ICmpInst::ICMP_NE:
4164 default: assert(0 && "Unknown integer condition code!");
4165 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4166 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4167 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4168 return ReplaceInstUsesWith(I, LHS);
4169 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4170 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4171 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4172 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4175 case ICmpInst::ICMP_ULT:
4177 default: assert(0 && "Unknown integer condition code!");
4178 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4180 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
4181 // If RHSCst is [us]MAXINT, it is always false. Not handling
4182 // this can cause overflow.
4183 if (RHSCst->isMaxValue(false))
4184 return ReplaceInstUsesWith(I, LHS);
4185 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4187 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4189 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4190 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4191 return ReplaceInstUsesWith(I, RHS);
4192 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4196 case ICmpInst::ICMP_SLT:
4198 default: assert(0 && "Unknown integer condition code!");
4199 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4201 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
4202 // If RHSCst is [us]MAXINT, it is always false. Not handling
4203 // this can cause overflow.
4204 if (RHSCst->isMaxValue(true))
4205 return ReplaceInstUsesWith(I, LHS);
4206 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4208 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4210 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4211 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4212 return ReplaceInstUsesWith(I, RHS);
4213 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4217 case ICmpInst::ICMP_UGT:
4219 default: assert(0 && "Unknown integer condition code!");
4220 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4221 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4222 return ReplaceInstUsesWith(I, LHS);
4223 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4225 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4226 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4227 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4228 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4232 case ICmpInst::ICMP_SGT:
4234 default: assert(0 && "Unknown integer condition code!");
4235 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4236 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4237 return ReplaceInstUsesWith(I, LHS);
4238 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4240 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4241 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4242 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4243 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4251 // fold (or (cast A), (cast B)) -> (cast (or A, B))
4252 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4253 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4254 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4255 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4256 !isa<ICmpInst>(Op1C->getOperand(0))) {
4257 const Type *SrcTy = Op0C->getOperand(0)->getType();
4258 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4259 // Only do this if the casts both really cause code to be
4261 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4263 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4265 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4266 Op1C->getOperand(0),
4268 InsertNewInstBefore(NewOp, I);
4269 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4276 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4277 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4278 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4279 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4280 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4281 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
4282 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4283 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4284 // If either of the constants are nans, then the whole thing returns
4286 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4287 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4289 // Otherwise, no need to compare the two constants, compare the
4291 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4292 RHS->getOperand(0));
4297 return Changed ? &I : 0;
4302 // XorSelf - Implements: X ^ X --> 0
4305 XorSelf(Value *rhs) : RHS(rhs) {}
4306 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4307 Instruction *apply(BinaryOperator &Xor) const {
4314 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4315 bool Changed = SimplifyCommutative(I);
4316 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4318 if (isa<UndefValue>(Op1)) {
4319 if (isa<UndefValue>(Op0))
4320 // Handle undef ^ undef -> 0 special case. This is a common
4322 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4323 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4326 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4327 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4328 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4329 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4332 // See if we can simplify any instructions used by the instruction whose sole
4333 // purpose is to compute bits we don't care about.
4334 if (!isa<VectorType>(I.getType())) {
4335 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4336 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4337 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4338 KnownZero, KnownOne))
4340 } else if (isa<ConstantAggregateZero>(Op1)) {
4341 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4344 // Is this a ~ operation?
4345 if (Value *NotOp = dyn_castNotVal(&I)) {
4346 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4347 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4348 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4349 if (Op0I->getOpcode() == Instruction::And ||
4350 Op0I->getOpcode() == Instruction::Or) {
4351 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4352 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4354 BinaryOperator::CreateNot(Op0I->getOperand(1),
4355 Op0I->getOperand(1)->getName()+".not");
4356 InsertNewInstBefore(NotY, I);
4357 if (Op0I->getOpcode() == Instruction::And)
4358 return BinaryOperator::CreateOr(Op0NotVal, NotY);
4360 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4367 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4368 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4369 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4370 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4371 return new ICmpInst(ICI->getInversePredicate(),
4372 ICI->getOperand(0), ICI->getOperand(1));
4374 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4375 return new FCmpInst(FCI->getInversePredicate(),
4376 FCI->getOperand(0), FCI->getOperand(1));
4379 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4380 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4381 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4382 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4383 Instruction::CastOps Opcode = Op0C->getOpcode();
4384 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4385 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4386 Op0C->getDestTy())) {
4387 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4388 CI->getOpcode(), CI->getInversePredicate(),
4389 CI->getOperand(0), CI->getOperand(1)), I);
4390 NewCI->takeName(CI);
4391 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4398 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4399 // ~(c-X) == X-c-1 == X+(-c-1)
4400 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4401 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4402 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4403 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4404 ConstantInt::get(I.getType(), 1));
4405 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4408 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4409 if (Op0I->getOpcode() == Instruction::Add) {
4410 // ~(X-c) --> (-c-1)-X
4411 if (RHS->isAllOnesValue()) {
4412 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4413 return BinaryOperator::CreateSub(
4414 ConstantExpr::getSub(NegOp0CI,
4415 ConstantInt::get(I.getType(), 1)),
4416 Op0I->getOperand(0));
4417 } else if (RHS->getValue().isSignBit()) {
4418 // (X + C) ^ signbit -> (X + C + signbit)
4419 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4420 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4423 } else if (Op0I->getOpcode() == Instruction::Or) {
4424 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4425 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4426 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4427 // Anything in both C1 and C2 is known to be zero, remove it from
4429 Constant *CommonBits = And(Op0CI, RHS);
4430 NewRHS = ConstantExpr::getAnd(NewRHS,
4431 ConstantExpr::getNot(CommonBits));
4432 AddToWorkList(Op0I);
4433 I.setOperand(0, Op0I->getOperand(0));
4434 I.setOperand(1, NewRHS);
4441 // Try to fold constant and into select arguments.
4442 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4443 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4445 if (isa<PHINode>(Op0))
4446 if (Instruction *NV = FoldOpIntoPhi(I))
4450 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4452 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4454 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4456 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4459 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4462 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4463 if (A == Op0) { // B^(B|A) == (A|B)^B
4464 Op1I->swapOperands();
4466 std::swap(Op0, Op1);
4467 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4468 I.swapOperands(); // Simplified below.
4469 std::swap(Op0, Op1);
4471 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4472 if (Op0 == A) // A^(A^B) == B
4473 return ReplaceInstUsesWith(I, B);
4474 else if (Op0 == B) // A^(B^A) == B
4475 return ReplaceInstUsesWith(I, A);
4476 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4477 if (A == Op0) { // A^(A&B) -> A^(B&A)
4478 Op1I->swapOperands();
4481 if (B == Op0) { // A^(B&A) -> (B&A)^A
4482 I.swapOperands(); // Simplified below.
4483 std::swap(Op0, Op1);
4488 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4491 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4492 if (A == Op1) // (B|A)^B == (A|B)^B
4494 if (B == Op1) { // (A|B)^B == A & ~B
4496 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4497 return BinaryOperator::CreateAnd(A, NotB);
4499 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4500 if (Op1 == A) // (A^B)^A == B
4501 return ReplaceInstUsesWith(I, B);
4502 else if (Op1 == B) // (B^A)^A == B
4503 return ReplaceInstUsesWith(I, A);
4504 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4505 if (A == Op1) // (A&B)^A -> (B&A)^A
4507 if (B == Op1 && // (B&A)^A == ~B & A
4508 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
4510 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4511 return BinaryOperator::CreateAnd(N, Op1);
4516 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4517 if (Op0I && Op1I && Op0I->isShift() &&
4518 Op0I->getOpcode() == Op1I->getOpcode() &&
4519 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4520 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4521 Instruction *NewOp =
4522 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
4523 Op1I->getOperand(0),
4524 Op0I->getName()), I);
4525 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
4526 Op1I->getOperand(1));
4530 Value *A, *B, *C, *D;
4531 // (A & B)^(A | B) -> A ^ B
4532 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4533 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4534 if ((A == C && B == D) || (A == D && B == C))
4535 return BinaryOperator::CreateXor(A, B);
4537 // (A | B)^(A & B) -> A ^ B
4538 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4539 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4540 if ((A == C && B == D) || (A == D && B == C))
4541 return BinaryOperator::CreateXor(A, B);
4545 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4546 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4547 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4548 // (X & Y)^(X & Y) -> (Y^Z) & X
4549 Value *X = 0, *Y = 0, *Z = 0;
4551 X = A, Y = B, Z = D;
4553 X = A, Y = B, Z = C;
4555 X = B, Y = A, Z = D;
4557 X = B, Y = A, Z = C;
4560 Instruction *NewOp =
4561 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4562 return BinaryOperator::CreateAnd(NewOp, X);
4567 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4568 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4569 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4572 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4573 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4574 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4575 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4576 const Type *SrcTy = Op0C->getOperand(0)->getType();
4577 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4578 // Only do this if the casts both really cause code to be generated.
4579 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4581 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4583 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
4584 Op1C->getOperand(0),
4586 InsertNewInstBefore(NewOp, I);
4587 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4592 return Changed ? &I : 0;
4595 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4596 /// overflowed for this type.
4597 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4598 ConstantInt *In2, bool IsSigned = false) {
4599 Result = cast<ConstantInt>(Add(In1, In2));
4602 if (In2->getValue().isNegative())
4603 return Result->getValue().sgt(In1->getValue());
4605 return Result->getValue().slt(In1->getValue());
4607 return Result->getValue().ult(In1->getValue());
4610 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4611 /// code necessary to compute the offset from the base pointer (without adding
4612 /// in the base pointer). Return the result as a signed integer of intptr size.
4613 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4614 TargetData &TD = IC.getTargetData();
4615 gep_type_iterator GTI = gep_type_begin(GEP);
4616 const Type *IntPtrTy = TD.getIntPtrType();
4617 Value *Result = Constant::getNullValue(IntPtrTy);
4619 // Build a mask for high order bits.
4620 unsigned IntPtrWidth = TD.getPointerSizeInBits();
4621 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4623 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4626 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
4627 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4628 if (OpC->isZero()) continue;
4630 // Handle a struct index, which adds its field offset to the pointer.
4631 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4632 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4634 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4635 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4637 Result = IC.InsertNewInstBefore(
4638 BinaryOperator::CreateAdd(Result,
4639 ConstantInt::get(IntPtrTy, Size),
4640 GEP->getName()+".offs"), I);
4644 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4645 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4646 Scale = ConstantExpr::getMul(OC, Scale);
4647 if (Constant *RC = dyn_cast<Constant>(Result))
4648 Result = ConstantExpr::getAdd(RC, Scale);
4650 // Emit an add instruction.
4651 Result = IC.InsertNewInstBefore(
4652 BinaryOperator::CreateAdd(Result, Scale,
4653 GEP->getName()+".offs"), I);
4657 // Convert to correct type.
4658 if (Op->getType() != IntPtrTy) {
4659 if (Constant *OpC = dyn_cast<Constant>(Op))
4660 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4662 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4663 Op->getName()+".c"), I);
4666 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4667 if (Constant *OpC = dyn_cast<Constant>(Op))
4668 Op = ConstantExpr::getMul(OpC, Scale);
4669 else // We'll let instcombine(mul) convert this to a shl if possible.
4670 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
4671 GEP->getName()+".idx"), I);
4674 // Emit an add instruction.
4675 if (isa<Constant>(Op) && isa<Constant>(Result))
4676 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4677 cast<Constant>(Result));
4679 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
4680 GEP->getName()+".offs"), I);
4686 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4687 /// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
4688 /// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
4689 /// complex, and scales are involved. The above expression would also be legal
4690 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
4691 /// later form is less amenable to optimization though, and we are allowed to
4692 /// generate the first by knowing that pointer arithmetic doesn't overflow.
4694 /// If we can't emit an optimized form for this expression, this returns null.
4696 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4698 TargetData &TD = IC.getTargetData();
4699 gep_type_iterator GTI = gep_type_begin(GEP);
4701 // Check to see if this gep only has a single variable index. If so, and if
4702 // any constant indices are a multiple of its scale, then we can compute this
4703 // in terms of the scale of the variable index. For example, if the GEP
4704 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4705 // because the expression will cross zero at the same point.
4706 unsigned i, e = GEP->getNumOperands();
4708 for (i = 1; i != e; ++i, ++GTI) {
4709 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4710 // Compute the aggregate offset of constant indices.
4711 if (CI->isZero()) continue;
4713 // Handle a struct index, which adds its field offset to the pointer.
4714 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4715 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4717 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4718 Offset += Size*CI->getSExtValue();
4721 // Found our variable index.
4726 // If there are no variable indices, we must have a constant offset, just
4727 // evaluate it the general way.
4728 if (i == e) return 0;
4730 Value *VariableIdx = GEP->getOperand(i);
4731 // Determine the scale factor of the variable element. For example, this is
4732 // 4 if the variable index is into an array of i32.
4733 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4735 // Verify that there are no other variable indices. If so, emit the hard way.
4736 for (++i, ++GTI; i != e; ++i, ++GTI) {
4737 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4740 // Compute the aggregate offset of constant indices.
4741 if (CI->isZero()) continue;
4743 // Handle a struct index, which adds its field offset to the pointer.
4744 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4745 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4747 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4748 Offset += Size*CI->getSExtValue();
4752 // Okay, we know we have a single variable index, which must be a
4753 // pointer/array/vector index. If there is no offset, life is simple, return
4755 unsigned IntPtrWidth = TD.getPointerSizeInBits();
4757 // Cast to intptrty in case a truncation occurs. If an extension is needed,
4758 // we don't need to bother extending: the extension won't affect where the
4759 // computation crosses zero.
4760 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4761 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4762 VariableIdx->getNameStart(), &I);
4766 // Otherwise, there is an index. The computation we will do will be modulo
4767 // the pointer size, so get it.
4768 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4770 Offset &= PtrSizeMask;
4771 VariableScale &= PtrSizeMask;
4773 // To do this transformation, any constant index must be a multiple of the
4774 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
4775 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
4776 // multiple of the variable scale.
4777 int64_t NewOffs = Offset / (int64_t)VariableScale;
4778 if (Offset != NewOffs*(int64_t)VariableScale)
4781 // Okay, we can do this evaluation. Start by converting the index to intptr.
4782 const Type *IntPtrTy = TD.getIntPtrType();
4783 if (VariableIdx->getType() != IntPtrTy)
4784 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
4786 VariableIdx->getNameStart(), &I);
4787 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
4788 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
4792 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4793 /// else. At this point we know that the GEP is on the LHS of the comparison.
4794 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4795 ICmpInst::Predicate Cond,
4797 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4799 // Look through bitcasts.
4800 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4801 RHS = BCI->getOperand(0);
4803 Value *PtrBase = GEPLHS->getOperand(0);
4804 if (PtrBase == RHS) {
4805 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4806 // This transformation (ignoring the base and scales) is valid because we
4807 // know pointers can't overflow. See if we can output an optimized form.
4808 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4810 // If not, synthesize the offset the hard way.
4812 Offset = EmitGEPOffset(GEPLHS, I, *this);
4813 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4814 Constant::getNullValue(Offset->getType()));
4815 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4816 // If the base pointers are different, but the indices are the same, just
4817 // compare the base pointer.
4818 if (PtrBase != GEPRHS->getOperand(0)) {
4819 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4820 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4821 GEPRHS->getOperand(0)->getType();
4823 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4824 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4825 IndicesTheSame = false;
4829 // If all indices are the same, just compare the base pointers.
4831 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4832 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4834 // Otherwise, the base pointers are different and the indices are
4835 // different, bail out.
4839 // If one of the GEPs has all zero indices, recurse.
4840 bool AllZeros = true;
4841 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4842 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4843 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4848 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4849 ICmpInst::getSwappedPredicate(Cond), I);
4851 // If the other GEP has all zero indices, recurse.
4853 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4854 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4855 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4860 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4862 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4863 // If the GEPs only differ by one index, compare it.
4864 unsigned NumDifferences = 0; // Keep track of # differences.
4865 unsigned DiffOperand = 0; // The operand that differs.
4866 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4867 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4868 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4869 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4870 // Irreconcilable differences.
4874 if (NumDifferences++) break;
4879 if (NumDifferences == 0) // SAME GEP?
4880 return ReplaceInstUsesWith(I, // No comparison is needed here.
4881 ConstantInt::get(Type::Int1Ty,
4882 ICmpInst::isTrueWhenEqual(Cond)));
4884 else if (NumDifferences == 1) {
4885 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4886 Value *RHSV = GEPRHS->getOperand(DiffOperand);
4887 // Make sure we do a signed comparison here.
4888 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4892 // Only lower this if the icmp is the only user of the GEP or if we expect
4893 // the result to fold to a constant!
4894 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4895 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4896 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4897 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4898 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4899 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4905 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4907 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4910 if (!isa<ConstantFP>(RHSC)) return 0;
4911 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4913 // Get the width of the mantissa. We don't want to hack on conversions that
4914 // might lose information from the integer, e.g. "i64 -> float"
4915 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
4916 if (MantissaWidth == -1) return 0; // Unknown.
4918 // Check to see that the input is converted from an integer type that is small
4919 // enough that preserves all bits. TODO: check here for "known" sign bits.
4920 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4921 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4923 // If this is a uitofp instruction, we need an extra bit to hold the sign.
4924 if (isa<UIToFPInst>(LHSI))
4927 // If the conversion would lose info, don't hack on this.
4928 if ((int)InputSize > MantissaWidth)
4931 // Otherwise, we can potentially simplify the comparison. We know that it
4932 // will always come through as an integer value and we know the constant is
4933 // not a NAN (it would have been previously simplified).
4934 assert(!RHS.isNaN() && "NaN comparison not already folded!");
4936 ICmpInst::Predicate Pred;
4937 switch (I.getPredicate()) {
4938 default: assert(0 && "Unexpected predicate!");
4939 case FCmpInst::FCMP_UEQ:
4940 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4941 case FCmpInst::FCMP_UGT:
4942 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4943 case FCmpInst::FCMP_UGE:
4944 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4945 case FCmpInst::FCMP_ULT:
4946 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4947 case FCmpInst::FCMP_ULE:
4948 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4949 case FCmpInst::FCMP_UNE:
4950 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4951 case FCmpInst::FCMP_ORD:
4952 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4953 case FCmpInst::FCMP_UNO:
4954 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4957 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4959 // Now we know that the APFloat is a normal number, zero or inf.
4961 // See if the FP constant is too large for the integer. For example,
4962 // comparing an i8 to 300.0.
4963 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4965 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4966 // and large values.
4967 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4968 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4969 APFloat::rmNearestTiesToEven);
4970 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
4971 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4972 Pred == ICmpInst::ICMP_SLE)
4973 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4974 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4977 // See if the RHS value is < SignedMin.
4978 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
4979 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4980 APFloat::rmNearestTiesToEven);
4981 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4982 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4983 Pred == ICmpInst::ICMP_SGE)
4984 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4985 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4988 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
4989 // it may still be fractional. See if it is fractional by casting the FP
4990 // value to the integer value and back, checking for equality. Don't do this
4991 // for zero, because -0.0 is not fractional.
4992 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
4993 if (!RHS.isZero() &&
4994 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
4995 // If we had a comparison against a fractional value, we have to adjust
4996 // the compare predicate and sometimes the value. RHSC is rounded towards
4997 // zero at this point.
4999 default: assert(0 && "Unexpected integer comparison!");
5000 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5001 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5002 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5003 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5004 case ICmpInst::ICMP_SLE:
5005 // (float)int <= 4.4 --> int <= 4
5006 // (float)int <= -4.4 --> int < -4
5007 if (RHS.isNegative())
5008 Pred = ICmpInst::ICMP_SLT;
5010 case ICmpInst::ICMP_SLT:
5011 // (float)int < -4.4 --> int < -4
5012 // (float)int < 4.4 --> int <= 4
5013 if (!RHS.isNegative())
5014 Pred = ICmpInst::ICMP_SLE;
5016 case ICmpInst::ICMP_SGT:
5017 // (float)int > 4.4 --> int > 4
5018 // (float)int > -4.4 --> int >= -4
5019 if (RHS.isNegative())
5020 Pred = ICmpInst::ICMP_SGE;
5022 case ICmpInst::ICMP_SGE:
5023 // (float)int >= -4.4 --> int >= -4
5024 // (float)int >= 4.4 --> int > 4
5025 if (!RHS.isNegative())
5026 Pred = ICmpInst::ICMP_SGT;
5031 // Lower this FP comparison into an appropriate integer version of the
5033 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5036 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5037 bool Changed = SimplifyCompare(I);
5038 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5040 // Fold trivial predicates.
5041 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5042 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5043 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5044 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5046 // Simplify 'fcmp pred X, X'
5048 switch (I.getPredicate()) {
5049 default: assert(0 && "Unknown predicate!");
5050 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5051 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5052 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5053 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5054 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5055 case FCmpInst::FCMP_OLT: // True if ordered and less than
5056 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5057 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5059 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5060 case FCmpInst::FCMP_ULT: // True if unordered or less than
5061 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5062 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5063 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5064 I.setPredicate(FCmpInst::FCMP_UNO);
5065 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5068 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5069 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5070 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5071 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5072 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5073 I.setPredicate(FCmpInst::FCMP_ORD);
5074 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5079 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5080 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5082 // Handle fcmp with constant RHS
5083 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5084 // If the constant is a nan, see if we can fold the comparison based on it.
5085 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5086 if (CFP->getValueAPF().isNaN()) {
5087 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5088 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5089 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5090 "Comparison must be either ordered or unordered!");
5091 // True if unordered.
5092 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5096 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5097 switch (LHSI->getOpcode()) {
5098 case Instruction::PHI:
5099 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5100 // block. If in the same block, we're encouraging jump threading. If
5101 // not, we are just pessimizing the code by making an i1 phi.
5102 if (LHSI->getParent() == I.getParent())
5103 if (Instruction *NV = FoldOpIntoPhi(I))
5106 case Instruction::SIToFP:
5107 case Instruction::UIToFP:
5108 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5111 case Instruction::Select:
5112 // If either operand of the select is a constant, we can fold the
5113 // comparison into the select arms, which will cause one to be
5114 // constant folded and the select turned into a bitwise or.
5115 Value *Op1 = 0, *Op2 = 0;
5116 if (LHSI->hasOneUse()) {
5117 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5118 // Fold the known value into the constant operand.
5119 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5120 // Insert a new FCmp of the other select operand.
5121 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5122 LHSI->getOperand(2), RHSC,
5124 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5125 // Fold the known value into the constant operand.
5126 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5127 // Insert a new FCmp of the other select operand.
5128 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5129 LHSI->getOperand(1), RHSC,
5135 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5140 return Changed ? &I : 0;
5143 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5144 bool Changed = SimplifyCompare(I);
5145 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5146 const Type *Ty = Op0->getType();
5150 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5151 I.isTrueWhenEqual()));
5153 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5154 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5156 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5157 // addresses never equal each other! We already know that Op0 != Op1.
5158 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5159 isa<ConstantPointerNull>(Op0)) &&
5160 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5161 isa<ConstantPointerNull>(Op1)))
5162 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5163 !I.isTrueWhenEqual()));
5165 // icmp's with boolean values can always be turned into bitwise operations
5166 if (Ty == Type::Int1Ty) {
5167 switch (I.getPredicate()) {
5168 default: assert(0 && "Invalid icmp instruction!");
5169 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
5170 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5171 InsertNewInstBefore(Xor, I);
5172 return BinaryOperator::CreateNot(Xor);
5174 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
5175 return BinaryOperator::CreateXor(Op0, Op1);
5177 case ICmpInst::ICMP_UGT:
5178 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
5180 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
5181 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5182 InsertNewInstBefore(Not, I);
5183 return BinaryOperator::CreateAnd(Not, Op1);
5185 case ICmpInst::ICMP_SGT:
5186 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
5188 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5189 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5190 InsertNewInstBefore(Not, I);
5191 return BinaryOperator::CreateAnd(Not, Op0);
5193 case ICmpInst::ICMP_UGE:
5194 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5196 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
5197 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5198 InsertNewInstBefore(Not, I);
5199 return BinaryOperator::CreateOr(Not, Op1);
5201 case ICmpInst::ICMP_SGE:
5202 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5204 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5205 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5206 InsertNewInstBefore(Not, I);
5207 return BinaryOperator::CreateOr(Not, Op0);
5212 // See if we are doing a comparison between a constant and an instruction that
5213 // can be folded into the comparison.
5214 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5217 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5218 if (I.isEquality() && CI->isNullValue() &&
5219 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5220 // (icmp cond A B) if cond is equality
5221 return new ICmpInst(I.getPredicate(), A, B);
5224 // If we have a icmp le or icmp ge instruction, turn it into the appropriate
5225 // icmp lt or icmp gt instruction. This allows us to rely on them being
5226 // folded in the code below.
5227 switch (I.getPredicate()) {
5229 case ICmpInst::ICMP_ULE:
5230 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5231 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5232 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5233 case ICmpInst::ICMP_SLE:
5234 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5235 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5236 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5237 case ICmpInst::ICMP_UGE:
5238 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5239 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5240 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5241 case ICmpInst::ICMP_SGE:
5242 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5243 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5244 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5247 // See if we can fold the comparison based on range information we can get
5248 // by checking whether bits are known to be zero or one in the input.
5249 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5250 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5252 // If this comparison is a normal comparison, it demands all
5253 // bits, if it is a sign bit comparison, it only demands the sign bit.
5255 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5257 if (SimplifyDemandedBits(Op0,
5258 isSignBit ? APInt::getSignBit(BitWidth)
5259 : APInt::getAllOnesValue(BitWidth),
5260 KnownZero, KnownOne, 0))
5263 // Given the known and unknown bits, compute a range that the LHS could be
5264 // in. Compute the Min, Max and RHS values based on the known bits. For the
5265 // EQ and NE we use unsigned values.
5266 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5267 if (ICmpInst::isSignedPredicate(I.getPredicate()))
5268 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5270 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5272 // If Min and Max are known to be the same, then SimplifyDemandedBits
5273 // figured out that the LHS is a constant. Just constant fold this now so
5274 // that code below can assume that Min != Max.
5276 return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5277 ConstantInt::get(Min),
5280 // Based on the range information we know about the LHS, see if we can
5281 // simplify this comparison. For example, (x&4) < 8 is always true.
5282 const APInt &RHSVal = CI->getValue();
5283 switch (I.getPredicate()) { // LE/GE have been folded already.
5284 default: assert(0 && "Unknown icmp opcode!");
5285 case ICmpInst::ICMP_EQ:
5286 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5287 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5289 case ICmpInst::ICMP_NE:
5290 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5291 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5293 case ICmpInst::ICMP_ULT:
5294 if (Max.ult(RHSVal)) // A <u C -> true iff max(A) < C
5295 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5296 if (Min.uge(RHSVal)) // A <u C -> false iff min(A) >= C
5297 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5298 if (RHSVal == Max) // A <u MAX -> A != MAX
5299 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5300 if (RHSVal == Min+1) // A <u MIN+1 -> A == MIN
5301 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5303 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5304 if (CI->isMinValue(true))
5305 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5306 ConstantInt::getAllOnesValue(Op0->getType()));
5308 case ICmpInst::ICMP_UGT:
5309 if (Min.ugt(RHSVal)) // A >u C -> true iff min(A) > C
5310 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5311 if (Max.ule(RHSVal)) // A >u C -> false iff max(A) <= C
5312 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5314 if (RHSVal == Min) // A >u MIN -> A != MIN
5315 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5316 if (RHSVal == Max-1) // A >u MAX-1 -> A == MAX
5317 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5319 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5320 if (CI->isMaxValue(true))
5321 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5322 ConstantInt::getNullValue(Op0->getType()));
5324 case ICmpInst::ICMP_SLT:
5325 if (Max.slt(RHSVal)) // A <s C -> true iff max(A) < C
5326 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5327 if (Min.sge(RHSVal)) // A <s C -> false iff min(A) >= C
5328 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5329 if (RHSVal == Max) // A <s MAX -> A != MAX
5330 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5331 if (RHSVal == Min+1) // A <s MIN+1 -> A == MIN
5332 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5334 case ICmpInst::ICMP_SGT:
5335 if (Min.sgt(RHSVal)) // A >s C -> true iff min(A) > C
5336 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5337 if (Max.sle(RHSVal)) // A >s C -> false iff max(A) <= C
5338 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5340 if (RHSVal == Min) // A >s MIN -> A != MIN
5341 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5342 if (RHSVal == Max-1) // A >s MAX-1 -> A == MAX
5343 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5347 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5348 // instruction, see if that instruction also has constants so that the
5349 // instruction can be folded into the icmp
5350 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5351 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5355 // Handle icmp with constant (but not simple integer constant) RHS
5356 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5357 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5358 switch (LHSI->getOpcode()) {
5359 case Instruction::GetElementPtr:
5360 if (RHSC->isNullValue()) {
5361 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5362 bool isAllZeros = true;
5363 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5364 if (!isa<Constant>(LHSI->getOperand(i)) ||
5365 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5370 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5371 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5375 case Instruction::PHI:
5376 // Only fold icmp into the PHI if the phi and fcmp are in the same
5377 // block. If in the same block, we're encouraging jump threading. If
5378 // not, we are just pessimizing the code by making an i1 phi.
5379 if (LHSI->getParent() == I.getParent())
5380 if (Instruction *NV = FoldOpIntoPhi(I))
5383 case Instruction::Select: {
5384 // If either operand of the select is a constant, we can fold the
5385 // comparison into the select arms, which will cause one to be
5386 // constant folded and the select turned into a bitwise or.
5387 Value *Op1 = 0, *Op2 = 0;
5388 if (LHSI->hasOneUse()) {
5389 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5390 // Fold the known value into the constant operand.
5391 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5392 // Insert a new ICmp of the other select operand.
5393 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5394 LHSI->getOperand(2), RHSC,
5396 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5397 // Fold the known value into the constant operand.
5398 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5399 // Insert a new ICmp of the other select operand.
5400 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5401 LHSI->getOperand(1), RHSC,
5407 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5410 case Instruction::Malloc:
5411 // If we have (malloc != null), and if the malloc has a single use, we
5412 // can assume it is successful and remove the malloc.
5413 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5414 AddToWorkList(LHSI);
5415 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5416 !I.isTrueWhenEqual()));
5422 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5423 if (User *GEP = dyn_castGetElementPtr(Op0))
5424 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5426 if (User *GEP = dyn_castGetElementPtr(Op1))
5427 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5428 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5431 // Test to see if the operands of the icmp are casted versions of other
5432 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5434 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5435 if (isa<PointerType>(Op0->getType()) &&
5436 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
5437 // We keep moving the cast from the left operand over to the right
5438 // operand, where it can often be eliminated completely.
5439 Op0 = CI->getOperand(0);
5441 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5442 // so eliminate it as well.
5443 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5444 Op1 = CI2->getOperand(0);
5446 // If Op1 is a constant, we can fold the cast into the constant.
5447 if (Op0->getType() != Op1->getType()) {
5448 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5449 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5451 // Otherwise, cast the RHS right before the icmp
5452 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5455 return new ICmpInst(I.getPredicate(), Op0, Op1);
5459 if (isa<CastInst>(Op0)) {
5460 // Handle the special case of: icmp (cast bool to X), <cst>
5461 // This comes up when you have code like
5464 // For generality, we handle any zero-extension of any operand comparison
5465 // with a constant or another cast from the same type.
5466 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5467 if (Instruction *R = visitICmpInstWithCastAndCast(I))
5471 // See if it's the same type of instruction on the left and right.
5472 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5473 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
5474 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
5475 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
5477 switch (Op0I->getOpcode()) {
5479 case Instruction::Add:
5480 case Instruction::Sub:
5481 case Instruction::Xor:
5482 // a+x icmp eq/ne b+x --> a icmp b
5483 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
5484 Op1I->getOperand(0));
5486 case Instruction::Mul:
5487 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5488 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
5489 // Mask = -1 >> count-trailing-zeros(Cst).
5490 if (!CI->isZero() && !CI->isOne()) {
5491 const APInt &AP = CI->getValue();
5492 ConstantInt *Mask = ConstantInt::get(
5493 APInt::getLowBitsSet(AP.getBitWidth(),
5495 AP.countTrailingZeros()));
5496 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
5498 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
5500 InsertNewInstBefore(And1, I);
5501 InsertNewInstBefore(And2, I);
5502 return new ICmpInst(I.getPredicate(), And1, And2);
5511 // ~x < ~y --> y < x
5513 if (match(Op0, m_Not(m_Value(A))) &&
5514 match(Op1, m_Not(m_Value(B))))
5515 return new ICmpInst(I.getPredicate(), B, A);
5518 if (I.isEquality()) {
5519 Value *A, *B, *C, *D;
5521 // -x == -y --> x == y
5522 if (match(Op0, m_Neg(m_Value(A))) &&
5523 match(Op1, m_Neg(m_Value(B))))
5524 return new ICmpInst(I.getPredicate(), A, B);
5526 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5527 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5528 Value *OtherVal = A == Op1 ? B : A;
5529 return new ICmpInst(I.getPredicate(), OtherVal,
5530 Constant::getNullValue(A->getType()));
5533 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5534 // A^c1 == C^c2 --> A == C^(c1^c2)
5535 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5536 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5537 if (Op1->hasOneUse()) {
5538 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5539 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
5540 return new ICmpInst(I.getPredicate(), A,
5541 InsertNewInstBefore(Xor, I));
5544 // A^B == A^D -> B == D
5545 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5546 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5547 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5548 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5552 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5553 (A == Op0 || B == Op0)) {
5554 // A == (A^B) -> B == 0
5555 Value *OtherVal = A == Op0 ? B : A;
5556 return new ICmpInst(I.getPredicate(), OtherVal,
5557 Constant::getNullValue(A->getType()));
5559 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5560 // (A-B) == A -> B == 0
5561 return new ICmpInst(I.getPredicate(), B,
5562 Constant::getNullValue(B->getType()));
5564 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5565 // A == (A-B) -> B == 0
5566 return new ICmpInst(I.getPredicate(), B,
5567 Constant::getNullValue(B->getType()));
5570 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5571 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5572 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5573 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5574 Value *X = 0, *Y = 0, *Z = 0;
5577 X = B; Y = D; Z = A;
5578 } else if (A == D) {
5579 X = B; Y = C; Z = A;
5580 } else if (B == C) {
5581 X = A; Y = D; Z = B;
5582 } else if (B == D) {
5583 X = A; Y = C; Z = B;
5586 if (X) { // Build (X^Y) & Z
5587 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5588 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
5589 I.setOperand(0, Op1);
5590 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5595 return Changed ? &I : 0;
5599 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5600 /// and CmpRHS are both known to be integer constants.
5601 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5602 ConstantInt *DivRHS) {
5603 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5604 const APInt &CmpRHSV = CmpRHS->getValue();
5606 // FIXME: If the operand types don't match the type of the divide
5607 // then don't attempt this transform. The code below doesn't have the
5608 // logic to deal with a signed divide and an unsigned compare (and
5609 // vice versa). This is because (x /s C1) <s C2 produces different
5610 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5611 // (x /u C1) <u C2. Simply casting the operands and result won't
5612 // work. :( The if statement below tests that condition and bails
5614 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5615 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5617 if (DivRHS->isZero())
5618 return 0; // The ProdOV computation fails on divide by zero.
5620 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5621 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5622 // C2 (CI). By solving for X we can turn this into a range check
5623 // instead of computing a divide.
5624 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5626 // Determine if the product overflows by seeing if the product is
5627 // not equal to the divide. Make sure we do the same kind of divide
5628 // as in the LHS instruction that we're folding.
5629 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5630 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5632 // Get the ICmp opcode
5633 ICmpInst::Predicate Pred = ICI.getPredicate();
5635 // Figure out the interval that is being checked. For example, a comparison
5636 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5637 // Compute this interval based on the constants involved and the signedness of
5638 // the compare/divide. This computes a half-open interval, keeping track of
5639 // whether either value in the interval overflows. After analysis each
5640 // overflow variable is set to 0 if it's corresponding bound variable is valid
5641 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5642 int LoOverflow = 0, HiOverflow = 0;
5643 ConstantInt *LoBound = 0, *HiBound = 0;
5646 if (!DivIsSigned) { // udiv
5647 // e.g. X/5 op 3 --> [15, 20)
5649 HiOverflow = LoOverflow = ProdOV;
5651 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5652 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
5653 if (CmpRHSV == 0) { // (X / pos) op 0
5654 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
5655 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5657 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
5658 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5659 HiOverflow = LoOverflow = ProdOV;
5661 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5662 } else { // (X / pos) op neg
5663 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
5664 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5665 LoOverflow = AddWithOverflow(LoBound, Prod,
5666 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5667 HiBound = AddOne(Prod);
5668 HiOverflow = ProdOV ? -1 : 0;
5670 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
5671 if (CmpRHSV == 0) { // (X / neg) op 0
5672 // e.g. X/-5 op 0 --> [-4, 5)
5673 LoBound = AddOne(DivRHS);
5674 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5675 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5676 HiOverflow = 1; // [INTMIN+1, overflow)
5677 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5679 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
5680 // e.g. X/-5 op 3 --> [-19, -14)
5681 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5683 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5684 HiBound = AddOne(Prod);
5685 } else { // (X / neg) op neg
5686 // e.g. X/-5 op -3 --> [15, 20)
5688 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5689 HiBound = Subtract(Prod, DivRHS);
5692 // Dividing by a negative swaps the condition. LT <-> GT
5693 Pred = ICmpInst::getSwappedPredicate(Pred);
5696 Value *X = DivI->getOperand(0);
5698 default: assert(0 && "Unhandled icmp opcode!");
5699 case ICmpInst::ICMP_EQ:
5700 if (LoOverflow && HiOverflow)
5701 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5702 else if (HiOverflow)
5703 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5704 ICmpInst::ICMP_UGE, X, LoBound);
5705 else if (LoOverflow)
5706 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5707 ICmpInst::ICMP_ULT, X, HiBound);
5709 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5710 case ICmpInst::ICMP_NE:
5711 if (LoOverflow && HiOverflow)
5712 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5713 else if (HiOverflow)
5714 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5715 ICmpInst::ICMP_ULT, X, LoBound);
5716 else if (LoOverflow)
5717 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5718 ICmpInst::ICMP_UGE, X, HiBound);
5720 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5721 case ICmpInst::ICMP_ULT:
5722 case ICmpInst::ICMP_SLT:
5723 if (LoOverflow == +1) // Low bound is greater than input range.
5724 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5725 if (LoOverflow == -1) // Low bound is less than input range.
5726 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5727 return new ICmpInst(Pred, X, LoBound);
5728 case ICmpInst::ICMP_UGT:
5729 case ICmpInst::ICMP_SGT:
5730 if (HiOverflow == +1) // High bound greater than input range.
5731 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5732 else if (HiOverflow == -1) // High bound less than input range.
5733 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5734 if (Pred == ICmpInst::ICMP_UGT)
5735 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5737 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5742 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5744 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5747 const APInt &RHSV = RHS->getValue();
5749 switch (LHSI->getOpcode()) {
5750 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
5751 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5752 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5754 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5755 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
5756 Value *CompareVal = LHSI->getOperand(0);
5758 // If the sign bit of the XorCST is not set, there is no change to
5759 // the operation, just stop using the Xor.
5760 if (!XorCST->getValue().isNegative()) {
5761 ICI.setOperand(0, CompareVal);
5762 AddToWorkList(LHSI);
5766 // Was the old condition true if the operand is positive?
5767 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5769 // If so, the new one isn't.
5770 isTrueIfPositive ^= true;
5772 if (isTrueIfPositive)
5773 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5775 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5779 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5780 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5781 LHSI->getOperand(0)->hasOneUse()) {
5782 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5784 // If the LHS is an AND of a truncating cast, we can widen the
5785 // and/compare to be the input width without changing the value
5786 // produced, eliminating a cast.
5787 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5788 // We can do this transformation if either the AND constant does not
5789 // have its sign bit set or if it is an equality comparison.
5790 // Extending a relational comparison when we're checking the sign
5791 // bit would not work.
5792 if (Cast->hasOneUse() &&
5793 (ICI.isEquality() ||
5794 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
5796 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5797 APInt NewCST = AndCST->getValue();
5798 NewCST.zext(BitWidth);
5800 NewCI.zext(BitWidth);
5801 Instruction *NewAnd =
5802 BinaryOperator::CreateAnd(Cast->getOperand(0),
5803 ConstantInt::get(NewCST),LHSI->getName());
5804 InsertNewInstBefore(NewAnd, ICI);
5805 return new ICmpInst(ICI.getPredicate(), NewAnd,
5806 ConstantInt::get(NewCI));
5810 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5811 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5812 // happens a LOT in code produced by the C front-end, for bitfield
5814 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5815 if (Shift && !Shift->isShift())
5819 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5820 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5821 const Type *AndTy = AndCST->getType(); // Type of the and.
5823 // We can fold this as long as we can't shift unknown bits
5824 // into the mask. This can only happen with signed shift
5825 // rights, as they sign-extend.
5827 bool CanFold = Shift->isLogicalShift();
5829 // To test for the bad case of the signed shr, see if any
5830 // of the bits shifted in could be tested after the mask.
5831 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5832 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5834 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5835 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5836 AndCST->getValue()) == 0)
5842 if (Shift->getOpcode() == Instruction::Shl)
5843 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5845 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5847 // Check to see if we are shifting out any of the bits being
5849 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5850 // If we shifted bits out, the fold is not going to work out.
5851 // As a special case, check to see if this means that the
5852 // result is always true or false now.
5853 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5854 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5855 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5856 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5858 ICI.setOperand(1, NewCst);
5859 Constant *NewAndCST;
5860 if (Shift->getOpcode() == Instruction::Shl)
5861 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5863 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5864 LHSI->setOperand(1, NewAndCST);
5865 LHSI->setOperand(0, Shift->getOperand(0));
5866 AddToWorkList(Shift); // Shift is dead.
5867 AddUsesToWorkList(ICI);
5873 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5874 // preferable because it allows the C<<Y expression to be hoisted out
5875 // of a loop if Y is invariant and X is not.
5876 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5877 ICI.isEquality() && !Shift->isArithmeticShift() &&
5878 isa<Instruction>(Shift->getOperand(0))) {
5881 if (Shift->getOpcode() == Instruction::LShr) {
5882 NS = BinaryOperator::CreateShl(AndCST,
5883 Shift->getOperand(1), "tmp");
5885 // Insert a logical shift.
5886 NS = BinaryOperator::CreateLShr(AndCST,
5887 Shift->getOperand(1), "tmp");
5889 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5891 // Compute X & (C << Y).
5892 Instruction *NewAnd =
5893 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
5894 InsertNewInstBefore(NewAnd, ICI);
5896 ICI.setOperand(0, NewAnd);
5902 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5903 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5906 uint32_t TypeBits = RHSV.getBitWidth();
5908 // Check that the shift amount is in range. If not, don't perform
5909 // undefined shifts. When the shift is visited it will be
5911 if (ShAmt->uge(TypeBits))
5914 if (ICI.isEquality()) {
5915 // If we are comparing against bits always shifted out, the
5916 // comparison cannot succeed.
5918 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5919 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5920 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5921 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5922 return ReplaceInstUsesWith(ICI, Cst);
5925 if (LHSI->hasOneUse()) {
5926 // Otherwise strength reduce the shift into an and.
5927 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5929 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5932 BinaryOperator::CreateAnd(LHSI->getOperand(0),
5933 Mask, LHSI->getName()+".mask");
5934 Value *And = InsertNewInstBefore(AndI, ICI);
5935 return new ICmpInst(ICI.getPredicate(), And,
5936 ConstantInt::get(RHSV.lshr(ShAmtVal)));
5940 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5941 bool TrueIfSigned = false;
5942 if (LHSI->hasOneUse() &&
5943 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5944 // (X << 31) <s 0 --> (X&1) != 0
5945 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5946 (TypeBits-ShAmt->getZExtValue()-1));
5948 BinaryOperator::CreateAnd(LHSI->getOperand(0),
5949 Mask, LHSI->getName()+".mask");
5950 Value *And = InsertNewInstBefore(AndI, ICI);
5952 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5953 And, Constant::getNullValue(And->getType()));
5958 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
5959 case Instruction::AShr: {
5960 // Only handle equality comparisons of shift-by-constant.
5961 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5962 if (!ShAmt || !ICI.isEquality()) break;
5964 // Check that the shift amount is in range. If not, don't perform
5965 // undefined shifts. When the shift is visited it will be
5967 uint32_t TypeBits = RHSV.getBitWidth();
5968 if (ShAmt->uge(TypeBits))
5971 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5973 // If we are comparing against bits always shifted out, the
5974 // comparison cannot succeed.
5975 APInt Comp = RHSV << ShAmtVal;
5976 if (LHSI->getOpcode() == Instruction::LShr)
5977 Comp = Comp.lshr(ShAmtVal);
5979 Comp = Comp.ashr(ShAmtVal);
5981 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5982 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5983 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5984 return ReplaceInstUsesWith(ICI, Cst);
5987 // Otherwise, check to see if the bits shifted out are known to be zero.
5988 // If so, we can compare against the unshifted value:
5989 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
5990 if (LHSI->hasOneUse() &&
5991 MaskedValueIsZero(LHSI->getOperand(0),
5992 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
5993 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
5994 ConstantExpr::getShl(RHS, ShAmt));
5997 if (LHSI->hasOneUse()) {
5998 // Otherwise strength reduce the shift into an and.
5999 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6000 Constant *Mask = ConstantInt::get(Val);
6003 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6004 Mask, LHSI->getName()+".mask");
6005 Value *And = InsertNewInstBefore(AndI, ICI);
6006 return new ICmpInst(ICI.getPredicate(), And,
6007 ConstantExpr::getShl(RHS, ShAmt));
6012 case Instruction::SDiv:
6013 case Instruction::UDiv:
6014 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6015 // Fold this div into the comparison, producing a range check.
6016 // Determine, based on the divide type, what the range is being
6017 // checked. If there is an overflow on the low or high side, remember
6018 // it, otherwise compute the range [low, hi) bounding the new value.
6019 // See: InsertRangeTest above for the kinds of replacements possible.
6020 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6021 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6026 case Instruction::Add:
6027 // Fold: icmp pred (add, X, C1), C2
6029 if (!ICI.isEquality()) {
6030 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6032 const APInt &LHSV = LHSC->getValue();
6034 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6037 if (ICI.isSignedPredicate()) {
6038 if (CR.getLower().isSignBit()) {
6039 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6040 ConstantInt::get(CR.getUpper()));
6041 } else if (CR.getUpper().isSignBit()) {
6042 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6043 ConstantInt::get(CR.getLower()));
6046 if (CR.getLower().isMinValue()) {
6047 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6048 ConstantInt::get(CR.getUpper()));
6049 } else if (CR.getUpper().isMinValue()) {
6050 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6051 ConstantInt::get(CR.getLower()));
6058 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6059 if (ICI.isEquality()) {
6060 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6062 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6063 // the second operand is a constant, simplify a bit.
6064 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6065 switch (BO->getOpcode()) {
6066 case Instruction::SRem:
6067 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6068 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6069 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6070 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6071 Instruction *NewRem =
6072 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6074 InsertNewInstBefore(NewRem, ICI);
6075 return new ICmpInst(ICI.getPredicate(), NewRem,
6076 Constant::getNullValue(BO->getType()));
6080 case Instruction::Add:
6081 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6082 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6083 if (BO->hasOneUse())
6084 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6085 Subtract(RHS, BOp1C));
6086 } else if (RHSV == 0) {
6087 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6088 // efficiently invertible, or if the add has just this one use.
6089 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6091 if (Value *NegVal = dyn_castNegVal(BOp1))
6092 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6093 else if (Value *NegVal = dyn_castNegVal(BOp0))
6094 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6095 else if (BO->hasOneUse()) {
6096 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6097 InsertNewInstBefore(Neg, ICI);
6099 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6103 case Instruction::Xor:
6104 // For the xor case, we can xor two constants together, eliminating
6105 // the explicit xor.
6106 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6107 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6108 ConstantExpr::getXor(RHS, BOC));
6111 case Instruction::Sub:
6112 // Replace (([sub|xor] A, B) != 0) with (A != B)
6114 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6118 case Instruction::Or:
6119 // If bits are being or'd in that are not present in the constant we
6120 // are comparing against, then the comparison could never succeed!
6121 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6122 Constant *NotCI = ConstantExpr::getNot(RHS);
6123 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6124 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6129 case Instruction::And:
6130 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6131 // If bits are being compared against that are and'd out, then the
6132 // comparison can never succeed!
6133 if ((RHSV & ~BOC->getValue()) != 0)
6134 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6137 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6138 if (RHS == BOC && RHSV.isPowerOf2())
6139 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6140 ICmpInst::ICMP_NE, LHSI,
6141 Constant::getNullValue(RHS->getType()));
6143 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6144 if (BOC->getValue().isSignBit()) {
6145 Value *X = BO->getOperand(0);
6146 Constant *Zero = Constant::getNullValue(X->getType());
6147 ICmpInst::Predicate pred = isICMP_NE ?
6148 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6149 return new ICmpInst(pred, X, Zero);
6152 // ((X & ~7) == 0) --> X < 8
6153 if (RHSV == 0 && isHighOnes(BOC)) {
6154 Value *X = BO->getOperand(0);
6155 Constant *NegX = ConstantExpr::getNeg(BOC);
6156 ICmpInst::Predicate pred = isICMP_NE ?
6157 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6158 return new ICmpInst(pred, X, NegX);
6163 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6164 // Handle icmp {eq|ne} <intrinsic>, intcst.
6165 if (II->getIntrinsicID() == Intrinsic::bswap) {
6167 ICI.setOperand(0, II->getOperand(1));
6168 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6172 } else { // Not a ICMP_EQ/ICMP_NE
6173 // If the LHS is a cast from an integral value of the same size,
6174 // then since we know the RHS is a constant, try to simlify.
6175 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6176 Value *CastOp = Cast->getOperand(0);
6177 const Type *SrcTy = CastOp->getType();
6178 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6179 if (SrcTy->isInteger() &&
6180 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6181 // If this is an unsigned comparison, try to make the comparison use
6182 // smaller constant values.
6183 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6184 // X u< 128 => X s> -1
6185 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6186 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6187 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6188 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6189 // X u> 127 => X s< 0
6190 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6191 Constant::getNullValue(SrcTy));
6199 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6200 /// We only handle extending casts so far.
6202 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6203 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6204 Value *LHSCIOp = LHSCI->getOperand(0);
6205 const Type *SrcTy = LHSCIOp->getType();
6206 const Type *DestTy = LHSCI->getType();
6209 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6210 // integer type is the same size as the pointer type.
6211 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6212 getTargetData().getPointerSizeInBits() ==
6213 cast<IntegerType>(DestTy)->getBitWidth()) {
6215 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6216 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6217 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6218 RHSOp = RHSC->getOperand(0);
6219 // If the pointer types don't match, insert a bitcast.
6220 if (LHSCIOp->getType() != RHSOp->getType())
6221 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6225 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6228 // The code below only handles extension cast instructions, so far.
6230 if (LHSCI->getOpcode() != Instruction::ZExt &&
6231 LHSCI->getOpcode() != Instruction::SExt)
6234 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6235 bool isSignedCmp = ICI.isSignedPredicate();
6237 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6238 // Not an extension from the same type?
6239 RHSCIOp = CI->getOperand(0);
6240 if (RHSCIOp->getType() != LHSCIOp->getType())
6243 // If the signedness of the two casts doesn't agree (i.e. one is a sext
6244 // and the other is a zext), then we can't handle this.
6245 if (CI->getOpcode() != LHSCI->getOpcode())
6248 // Deal with equality cases early.
6249 if (ICI.isEquality())
6250 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6252 // A signed comparison of sign extended values simplifies into a
6253 // signed comparison.
6254 if (isSignedCmp && isSignedExt)
6255 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6257 // The other three cases all fold into an unsigned comparison.
6258 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6261 // If we aren't dealing with a constant on the RHS, exit early
6262 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6266 // Compute the constant that would happen if we truncated to SrcTy then
6267 // reextended to DestTy.
6268 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6269 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6271 // If the re-extended constant didn't change...
6273 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6274 // For example, we might have:
6275 // %A = sext short %X to uint
6276 // %B = icmp ugt uint %A, 1330
6277 // It is incorrect to transform this into
6278 // %B = icmp ugt short %X, 1330
6279 // because %A may have negative value.
6281 // However, we allow this when the compare is EQ/NE, because they are
6283 if (isSignedExt == isSignedCmp || ICI.isEquality())
6284 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6288 // The re-extended constant changed so the constant cannot be represented
6289 // in the shorter type. Consequently, we cannot emit a simple comparison.
6291 // First, handle some easy cases. We know the result cannot be equal at this
6292 // point so handle the ICI.isEquality() cases
6293 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6294 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6295 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6296 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6298 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6299 // should have been folded away previously and not enter in here.
6302 // We're performing a signed comparison.
6303 if (cast<ConstantInt>(CI)->getValue().isNegative())
6304 Result = ConstantInt::getFalse(); // X < (small) --> false
6306 Result = ConstantInt::getTrue(); // X < (large) --> true
6308 // We're performing an unsigned comparison.
6310 // We're performing an unsigned comp with a sign extended value.
6311 // This is true if the input is >= 0. [aka >s -1]
6312 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6313 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6314 NegOne, ICI.getName()), ICI);
6316 // Unsigned extend & unsigned compare -> always true.
6317 Result = ConstantInt::getTrue();
6321 // Finally, return the value computed.
6322 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6323 ICI.getPredicate() == ICmpInst::ICMP_SLT)
6324 return ReplaceInstUsesWith(ICI, Result);
6326 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6327 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6328 "ICmp should be folded!");
6329 if (Constant *CI = dyn_cast<Constant>(Result))
6330 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6331 return BinaryOperator::CreateNot(Result);
6334 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6335 return commonShiftTransforms(I);
6338 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6339 return commonShiftTransforms(I);
6342 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6343 if (Instruction *R = commonShiftTransforms(I))
6346 Value *Op0 = I.getOperand(0);
6348 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6349 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6350 if (CSI->isAllOnesValue())
6351 return ReplaceInstUsesWith(I, CSI);
6353 // See if we can turn a signed shr into an unsigned shr.
6354 if (MaskedValueIsZero(Op0,
6355 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6356 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6361 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6362 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6363 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6365 // shl X, 0 == X and shr X, 0 == X
6366 // shl 0, X == 0 and shr 0, X == 0
6367 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6368 Op0 == Constant::getNullValue(Op0->getType()))
6369 return ReplaceInstUsesWith(I, Op0);
6371 if (isa<UndefValue>(Op0)) {
6372 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6373 return ReplaceInstUsesWith(I, Op0);
6374 else // undef << X -> 0, undef >>u X -> 0
6375 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6377 if (isa<UndefValue>(Op1)) {
6378 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6379 return ReplaceInstUsesWith(I, Op0);
6380 else // X << undef, X >>u undef -> 0
6381 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6384 // Try to fold constant and into select arguments.
6385 if (isa<Constant>(Op0))
6386 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6387 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6390 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6391 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6396 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6397 BinaryOperator &I) {
6398 bool isLeftShift = I.getOpcode() == Instruction::Shl;
6400 // See if we can simplify any instructions used by the instruction whose sole
6401 // purpose is to compute bits we don't care about.
6402 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6403 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6404 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6405 KnownZero, KnownOne))
6408 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6409 // of a signed value.
6411 if (Op1->uge(TypeBits)) {
6412 if (I.getOpcode() != Instruction::AShr)
6413 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6415 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6420 // ((X*C1) << C2) == (X * (C1 << C2))
6421 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6422 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6423 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6424 return BinaryOperator::CreateMul(BO->getOperand(0),
6425 ConstantExpr::getShl(BOOp, Op1));
6427 // Try to fold constant and into select arguments.
6428 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6429 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6431 if (isa<PHINode>(Op0))
6432 if (Instruction *NV = FoldOpIntoPhi(I))
6435 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6436 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6437 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6438 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6439 // place. Don't try to do this transformation in this case. Also, we
6440 // require that the input operand is a shift-by-constant so that we have
6441 // confidence that the shifts will get folded together. We could do this
6442 // xform in more cases, but it is unlikely to be profitable.
6443 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6444 isa<ConstantInt>(TrOp->getOperand(1))) {
6445 // Okay, we'll do this xform. Make the shift of shift.
6446 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6447 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
6449 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6451 // For logical shifts, the truncation has the effect of making the high
6452 // part of the register be zeros. Emulate this by inserting an AND to
6453 // clear the top bits as needed. This 'and' will usually be zapped by
6454 // other xforms later if dead.
6455 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6456 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6457 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6459 // The mask we constructed says what the trunc would do if occurring
6460 // between the shifts. We want to know the effect *after* the second
6461 // shift. We know that it is a logical shift by a constant, so adjust the
6462 // mask as appropriate.
6463 if (I.getOpcode() == Instruction::Shl)
6464 MaskV <<= Op1->getZExtValue();
6466 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6467 MaskV = MaskV.lshr(Op1->getZExtValue());
6470 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
6472 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6474 // Return the value truncated to the interesting size.
6475 return new TruncInst(And, I.getType());
6479 if (Op0->hasOneUse()) {
6480 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6481 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6484 switch (Op0BO->getOpcode()) {
6486 case Instruction::Add:
6487 case Instruction::And:
6488 case Instruction::Or:
6489 case Instruction::Xor: {
6490 // These operators commute.
6491 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
6492 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6493 match(Op0BO->getOperand(1),
6494 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6495 Instruction *YS = BinaryOperator::CreateShl(
6496 Op0BO->getOperand(0), Op1,
6498 InsertNewInstBefore(YS, I); // (Y << C)
6500 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
6501 Op0BO->getOperand(1)->getName());
6502 InsertNewInstBefore(X, I); // (X + (Y << C))
6503 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6504 return BinaryOperator::CreateAnd(X, ConstantInt::get(
6505 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6508 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
6509 Value *Op0BOOp1 = Op0BO->getOperand(1);
6510 if (isLeftShift && Op0BOOp1->hasOneUse() &&
6512 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6513 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6515 Instruction *YS = BinaryOperator::CreateShl(
6516 Op0BO->getOperand(0), Op1,
6518 InsertNewInstBefore(YS, I); // (Y << C)
6520 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6521 V1->getName()+".mask");
6522 InsertNewInstBefore(XM, I); // X & (CC << C)
6524 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
6529 case Instruction::Sub: {
6530 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6531 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6532 match(Op0BO->getOperand(0),
6533 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6534 Instruction *YS = BinaryOperator::CreateShl(
6535 Op0BO->getOperand(1), Op1,
6537 InsertNewInstBefore(YS, I); // (Y << C)
6539 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
6540 Op0BO->getOperand(0)->getName());
6541 InsertNewInstBefore(X, I); // (X + (Y << C))
6542 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6543 return BinaryOperator::CreateAnd(X, ConstantInt::get(
6544 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6547 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
6548 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6549 match(Op0BO->getOperand(0),
6550 m_And(m_Shr(m_Value(V1), m_Value(V2)),
6551 m_ConstantInt(CC))) && V2 == Op1 &&
6552 cast<BinaryOperator>(Op0BO->getOperand(0))
6553 ->getOperand(0)->hasOneUse()) {
6554 Instruction *YS = BinaryOperator::CreateShl(
6555 Op0BO->getOperand(1), Op1,
6557 InsertNewInstBefore(YS, I); // (Y << C)
6559 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6560 V1->getName()+".mask");
6561 InsertNewInstBefore(XM, I); // X & (CC << C)
6563 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
6571 // If the operand is an bitwise operator with a constant RHS, and the
6572 // shift is the only use, we can pull it out of the shift.
6573 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6574 bool isValid = true; // Valid only for And, Or, Xor
6575 bool highBitSet = false; // Transform if high bit of constant set?
6577 switch (Op0BO->getOpcode()) {
6578 default: isValid = false; break; // Do not perform transform!
6579 case Instruction::Add:
6580 isValid = isLeftShift;
6582 case Instruction::Or:
6583 case Instruction::Xor:
6586 case Instruction::And:
6591 // If this is a signed shift right, and the high bit is modified
6592 // by the logical operation, do not perform the transformation.
6593 // The highBitSet boolean indicates the value of the high bit of
6594 // the constant which would cause it to be modified for this
6597 if (isValid && I.getOpcode() == Instruction::AShr)
6598 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6601 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6603 Instruction *NewShift =
6604 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6605 InsertNewInstBefore(NewShift, I);
6606 NewShift->takeName(Op0BO);
6608 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
6615 // Find out if this is a shift of a shift by a constant.
6616 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6617 if (ShiftOp && !ShiftOp->isShift())
6620 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6621 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6622 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6623 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6624 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6625 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6626 Value *X = ShiftOp->getOperand(0);
6628 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
6629 if (AmtSum > TypeBits)
6632 const IntegerType *Ty = cast<IntegerType>(I.getType());
6634 // Check for (X << c1) << c2 and (X >> c1) >> c2
6635 if (I.getOpcode() == ShiftOp->getOpcode()) {
6636 return BinaryOperator::Create(I.getOpcode(), X,
6637 ConstantInt::get(Ty, AmtSum));
6638 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6639 I.getOpcode() == Instruction::AShr) {
6640 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6641 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
6642 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6643 I.getOpcode() == Instruction::LShr) {
6644 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6645 Instruction *Shift =
6646 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
6647 InsertNewInstBefore(Shift, I);
6649 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6650 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6653 // Okay, if we get here, one shift must be left, and the other shift must be
6654 // right. See if the amounts are equal.
6655 if (ShiftAmt1 == ShiftAmt2) {
6656 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6657 if (I.getOpcode() == Instruction::Shl) {
6658 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6659 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6661 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6662 if (I.getOpcode() == Instruction::LShr) {
6663 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6664 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6666 // We can simplify ((X << C) >>s C) into a trunc + sext.
6667 // NOTE: we could do this for any C, but that would make 'unusual' integer
6668 // types. For now, just stick to ones well-supported by the code
6670 const Type *SExtType = 0;
6671 switch (Ty->getBitWidth() - ShiftAmt1) {
6678 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6683 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6684 InsertNewInstBefore(NewTrunc, I);
6685 return new SExtInst(NewTrunc, Ty);
6687 // Otherwise, we can't handle it yet.
6688 } else if (ShiftAmt1 < ShiftAmt2) {
6689 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6691 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6692 if (I.getOpcode() == Instruction::Shl) {
6693 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6694 ShiftOp->getOpcode() == Instruction::AShr);
6695 Instruction *Shift =
6696 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6697 InsertNewInstBefore(Shift, I);
6699 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6700 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6703 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
6704 if (I.getOpcode() == Instruction::LShr) {
6705 assert(ShiftOp->getOpcode() == Instruction::Shl);
6706 Instruction *Shift =
6707 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
6708 InsertNewInstBefore(Shift, I);
6710 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6711 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6714 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6716 assert(ShiftAmt2 < ShiftAmt1);
6717 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6719 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6720 if (I.getOpcode() == Instruction::Shl) {
6721 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6722 ShiftOp->getOpcode() == Instruction::AShr);
6723 Instruction *Shift =
6724 BinaryOperator::Create(ShiftOp->getOpcode(), X,
6725 ConstantInt::get(Ty, ShiftDiff));
6726 InsertNewInstBefore(Shift, I);
6728 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6729 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6732 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
6733 if (I.getOpcode() == Instruction::LShr) {
6734 assert(ShiftOp->getOpcode() == Instruction::Shl);
6735 Instruction *Shift =
6736 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6737 InsertNewInstBefore(Shift, I);
6739 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6740 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6743 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6750 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6751 /// expression. If so, decompose it, returning some value X, such that Val is
6754 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6756 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6757 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6758 Offset = CI->getZExtValue();
6760 return ConstantInt::get(Type::Int32Ty, 0);
6761 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6762 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6763 if (I->getOpcode() == Instruction::Shl) {
6764 // This is a value scaled by '1 << the shift amt'.
6765 Scale = 1U << RHS->getZExtValue();
6767 return I->getOperand(0);
6768 } else if (I->getOpcode() == Instruction::Mul) {
6769 // This value is scaled by 'RHS'.
6770 Scale = RHS->getZExtValue();
6772 return I->getOperand(0);
6773 } else if (I->getOpcode() == Instruction::Add) {
6774 // We have X+C. Check to see if we really have (X*C2)+C1,
6775 // where C1 is divisible by C2.
6778 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6779 Offset += RHS->getZExtValue();
6786 // Otherwise, we can't look past this.
6793 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6794 /// try to eliminate the cast by moving the type information into the alloc.
6795 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6796 AllocationInst &AI) {
6797 const PointerType *PTy = cast<PointerType>(CI.getType());
6799 // Remove any uses of AI that are dead.
6800 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6802 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6803 Instruction *User = cast<Instruction>(*UI++);
6804 if (isInstructionTriviallyDead(User)) {
6805 while (UI != E && *UI == User)
6806 ++UI; // If this instruction uses AI more than once, don't break UI.
6809 DOUT << "IC: DCE: " << *User;
6810 EraseInstFromFunction(*User);
6814 // Get the type really allocated and the type casted to.
6815 const Type *AllocElTy = AI.getAllocatedType();
6816 const Type *CastElTy = PTy->getElementType();
6817 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6819 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6820 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6821 if (CastElTyAlign < AllocElTyAlign) return 0;
6823 // If the allocation has multiple uses, only promote it if we are strictly
6824 // increasing the alignment of the resultant allocation. If we keep it the
6825 // same, we open the door to infinite loops of various kinds.
6826 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6828 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6829 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
6830 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6832 // See if we can satisfy the modulus by pulling a scale out of the array
6834 unsigned ArraySizeScale;
6836 Value *NumElements = // See if the array size is a decomposable linear expr.
6837 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6839 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6841 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6842 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
6844 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6849 // If the allocation size is constant, form a constant mul expression
6850 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6851 if (isa<ConstantInt>(NumElements))
6852 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6853 // otherwise multiply the amount and the number of elements
6854 else if (Scale != 1) {
6855 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
6856 Amt = InsertNewInstBefore(Tmp, AI);
6860 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6861 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6862 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
6863 Amt = InsertNewInstBefore(Tmp, AI);
6866 AllocationInst *New;
6867 if (isa<MallocInst>(AI))
6868 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6870 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6871 InsertNewInstBefore(New, AI);
6874 // If the allocation has multiple uses, insert a cast and change all things
6875 // that used it to use the new cast. This will also hack on CI, but it will
6877 if (!AI.hasOneUse()) {
6878 AddUsesToWorkList(AI);
6879 // New is the allocation instruction, pointer typed. AI is the original
6880 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6881 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6882 InsertNewInstBefore(NewCast, AI);
6883 AI.replaceAllUsesWith(NewCast);
6885 return ReplaceInstUsesWith(CI, New);
6888 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6889 /// and return it as type Ty without inserting any new casts and without
6890 /// changing the computed value. This is used by code that tries to decide
6891 /// whether promoting or shrinking integer operations to wider or smaller types
6892 /// will allow us to eliminate a truncate or extend.
6894 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6895 /// extension operation if Ty is larger.
6897 /// If CastOpc is a truncation, then Ty will be a type smaller than V. We
6898 /// should return true if trunc(V) can be computed by computing V in the smaller
6899 /// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
6900 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
6901 /// efficiently truncated.
6903 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
6904 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
6905 /// the final result.
6906 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6908 int &NumCastsRemoved) {
6909 // We can always evaluate constants in another type.
6910 if (isa<ConstantInt>(V))
6913 Instruction *I = dyn_cast<Instruction>(V);
6914 if (!I) return false;
6916 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6918 // If this is an extension or truncate, we can often eliminate it.
6919 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6920 // If this is a cast from the destination type, we can trivially eliminate
6921 // it, and this will remove a cast overall.
6922 if (I->getOperand(0)->getType() == Ty) {
6923 // If the first operand is itself a cast, and is eliminable, do not count
6924 // this as an eliminable cast. We would prefer to eliminate those two
6926 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
6932 // We can't extend or shrink something that has multiple uses: doing so would
6933 // require duplicating the instruction in general, which isn't profitable.
6934 if (!I->hasOneUse()) return false;
6936 switch (I->getOpcode()) {
6937 case Instruction::Add:
6938 case Instruction::Sub:
6939 case Instruction::Mul:
6940 case Instruction::And:
6941 case Instruction::Or:
6942 case Instruction::Xor:
6943 // These operators can all arbitrarily be extended or truncated.
6944 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6946 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6949 case Instruction::Shl:
6950 // If we are truncating the result of this SHL, and if it's a shift of a
6951 // constant amount, we can always perform a SHL in a smaller type.
6952 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6953 uint32_t BitWidth = Ty->getBitWidth();
6954 if (BitWidth < OrigTy->getBitWidth() &&
6955 CI->getLimitedValue(BitWidth) < BitWidth)
6956 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6960 case Instruction::LShr:
6961 // If this is a truncate of a logical shr, we can truncate it to a smaller
6962 // lshr iff we know that the bits we would otherwise be shifting in are
6964 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6965 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6966 uint32_t BitWidth = Ty->getBitWidth();
6967 if (BitWidth < OrigBitWidth &&
6968 MaskedValueIsZero(I->getOperand(0),
6969 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6970 CI->getLimitedValue(BitWidth) < BitWidth) {
6971 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6976 case Instruction::ZExt:
6977 case Instruction::SExt:
6978 case Instruction::Trunc:
6979 // If this is the same kind of case as our original (e.g. zext+zext), we
6980 // can safely replace it. Note that replacing it does not reduce the number
6981 // of casts in the input.
6982 if (I->getOpcode() == CastOpc)
6985 case Instruction::Select: {
6986 SelectInst *SI = cast<SelectInst>(I);
6987 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
6989 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
6992 case Instruction::PHI: {
6993 // We can change a phi if we can change all operands.
6994 PHINode *PN = cast<PHINode>(I);
6995 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
6996 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7002 // TODO: Can handle more cases here.
7009 /// EvaluateInDifferentType - Given an expression that
7010 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7011 /// evaluate the expression.
7012 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7014 if (Constant *C = dyn_cast<Constant>(V))
7015 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7017 // Otherwise, it must be an instruction.
7018 Instruction *I = cast<Instruction>(V);
7019 Instruction *Res = 0;
7020 switch (I->getOpcode()) {
7021 case Instruction::Add:
7022 case Instruction::Sub:
7023 case Instruction::Mul:
7024 case Instruction::And:
7025 case Instruction::Or:
7026 case Instruction::Xor:
7027 case Instruction::AShr:
7028 case Instruction::LShr:
7029 case Instruction::Shl: {
7030 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7031 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7032 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
7036 case Instruction::Trunc:
7037 case Instruction::ZExt:
7038 case Instruction::SExt:
7039 // If the source type of the cast is the type we're trying for then we can
7040 // just return the source. There's no need to insert it because it is not
7042 if (I->getOperand(0)->getType() == Ty)
7043 return I->getOperand(0);
7045 // Otherwise, must be the same type of cast, so just reinsert a new one.
7046 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7049 case Instruction::Select: {
7050 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7051 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7052 Res = SelectInst::Create(I->getOperand(0), True, False);
7055 case Instruction::PHI: {
7056 PHINode *OPN = cast<PHINode>(I);
7057 PHINode *NPN = PHINode::Create(Ty);
7058 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7059 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7060 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7066 // TODO: Can handle more cases here.
7067 assert(0 && "Unreachable!");
7072 return InsertNewInstBefore(Res, *I);
7075 /// @brief Implement the transforms common to all CastInst visitors.
7076 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7077 Value *Src = CI.getOperand(0);
7079 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7080 // eliminate it now.
7081 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7082 if (Instruction::CastOps opc =
7083 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7084 // The first cast (CSrc) is eliminable so we need to fix up or replace
7085 // the second cast (CI). CSrc will then have a good chance of being dead.
7086 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7090 // If we are casting a select then fold the cast into the select
7091 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7092 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7095 // If we are casting a PHI then fold the cast into the PHI
7096 if (isa<PHINode>(Src))
7097 if (Instruction *NV = FoldOpIntoPhi(CI))
7103 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7104 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7105 Value *Src = CI.getOperand(0);
7107 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7108 // If casting the result of a getelementptr instruction with no offset, turn
7109 // this into a cast of the original pointer!
7110 if (GEP->hasAllZeroIndices()) {
7111 // Changing the cast operand is usually not a good idea but it is safe
7112 // here because the pointer operand is being replaced with another
7113 // pointer operand so the opcode doesn't need to change.
7115 CI.setOperand(0, GEP->getOperand(0));
7119 // If the GEP has a single use, and the base pointer is a bitcast, and the
7120 // GEP computes a constant offset, see if we can convert these three
7121 // instructions into fewer. This typically happens with unions and other
7122 // non-type-safe code.
7123 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7124 if (GEP->hasAllConstantIndices()) {
7125 // We are guaranteed to get a constant from EmitGEPOffset.
7126 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7127 int64_t Offset = OffsetV->getSExtValue();
7129 // Get the base pointer input of the bitcast, and the type it points to.
7130 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7131 const Type *GEPIdxTy =
7132 cast<PointerType>(OrigBase->getType())->getElementType();
7133 if (GEPIdxTy->isSized()) {
7134 SmallVector<Value*, 8> NewIndices;
7136 // Start with the index over the outer type. Note that the type size
7137 // might be zero (even if the offset isn't zero) if the indexed type
7138 // is something like [0 x {int, int}]
7139 const Type *IntPtrTy = TD->getIntPtrType();
7140 int64_t FirstIdx = 0;
7141 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7142 FirstIdx = Offset/TySize;
7145 // Handle silly modulus not returning values values [0..TySize).
7149 assert(Offset >= 0);
7151 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7154 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7156 // Index into the types. If we fail, set OrigBase to null.
7158 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7159 const StructLayout *SL = TD->getStructLayout(STy);
7160 if (Offset < (int64_t)SL->getSizeInBytes()) {
7161 unsigned Elt = SL->getElementContainingOffset(Offset);
7162 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7164 Offset -= SL->getElementOffset(Elt);
7165 GEPIdxTy = STy->getElementType(Elt);
7167 // Otherwise, we can't index into this, bail out.
7171 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7172 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7173 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7174 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7177 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7179 GEPIdxTy = STy->getElementType();
7181 // Otherwise, we can't index into this, bail out.
7187 // If we were able to index down into an element, create the GEP
7188 // and bitcast the result. This eliminates one bitcast, potentially
7190 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7192 NewIndices.end(), "");
7193 InsertNewInstBefore(NGEP, CI);
7194 NGEP->takeName(GEP);
7196 if (isa<BitCastInst>(CI))
7197 return new BitCastInst(NGEP, CI.getType());
7198 assert(isa<PtrToIntInst>(CI));
7199 return new PtrToIntInst(NGEP, CI.getType());
7206 return commonCastTransforms(CI);
7211 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7212 /// integer types. This function implements the common transforms for all those
7214 /// @brief Implement the transforms common to CastInst with integer operands
7215 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7216 if (Instruction *Result = commonCastTransforms(CI))
7219 Value *Src = CI.getOperand(0);
7220 const Type *SrcTy = Src->getType();
7221 const Type *DestTy = CI.getType();
7222 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7223 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7225 // See if we can simplify any instructions used by the LHS whose sole
7226 // purpose is to compute bits we don't care about.
7227 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7228 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7229 KnownZero, KnownOne))
7232 // If the source isn't an instruction or has more than one use then we
7233 // can't do anything more.
7234 Instruction *SrcI = dyn_cast<Instruction>(Src);
7235 if (!SrcI || !Src->hasOneUse())
7238 // Attempt to propagate the cast into the instruction for int->int casts.
7239 int NumCastsRemoved = 0;
7240 if (!isa<BitCastInst>(CI) &&
7241 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7242 CI.getOpcode(), NumCastsRemoved)) {
7243 // If this cast is a truncate, evaluting in a different type always
7244 // eliminates the cast, so it is always a win. If this is a zero-extension,
7245 // we need to do an AND to maintain the clear top-part of the computation,
7246 // so we require that the input have eliminated at least one cast. If this
7247 // is a sign extension, we insert two new casts (to do the extension) so we
7248 // require that two casts have been eliminated.
7250 switch (CI.getOpcode()) {
7252 // All the others use floating point so we shouldn't actually
7253 // get here because of the check above.
7254 assert(0 && "Unknown cast type");
7255 case Instruction::Trunc:
7258 case Instruction::ZExt:
7259 DoXForm = NumCastsRemoved >= 1;
7261 case Instruction::SExt:
7262 DoXForm = NumCastsRemoved >= 2;
7267 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7268 CI.getOpcode() == Instruction::SExt);
7269 assert(Res->getType() == DestTy);
7270 switch (CI.getOpcode()) {
7271 default: assert(0 && "Unknown cast type!");
7272 case Instruction::Trunc:
7273 case Instruction::BitCast:
7274 // Just replace this cast with the result.
7275 return ReplaceInstUsesWith(CI, Res);
7276 case Instruction::ZExt: {
7277 // We need to emit an AND to clear the high bits.
7278 assert(SrcBitSize < DestBitSize && "Not a zext?");
7279 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7281 return BinaryOperator::CreateAnd(Res, C);
7283 case Instruction::SExt:
7284 // We need to emit a cast to truncate, then a cast to sext.
7285 return CastInst::Create(Instruction::SExt,
7286 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7292 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7293 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7295 switch (SrcI->getOpcode()) {
7296 case Instruction::Add:
7297 case Instruction::Mul:
7298 case Instruction::And:
7299 case Instruction::Or:
7300 case Instruction::Xor:
7301 // If we are discarding information, rewrite.
7302 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7303 // Don't insert two casts if they cannot be eliminated. We allow
7304 // two casts to be inserted if the sizes are the same. This could
7305 // only be converting signedness, which is a noop.
7306 if (DestBitSize == SrcBitSize ||
7307 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7308 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7309 Instruction::CastOps opcode = CI.getOpcode();
7310 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7311 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7312 return BinaryOperator::Create(
7313 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7317 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7318 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7319 SrcI->getOpcode() == Instruction::Xor &&
7320 Op1 == ConstantInt::getTrue() &&
7321 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7322 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7323 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7326 case Instruction::SDiv:
7327 case Instruction::UDiv:
7328 case Instruction::SRem:
7329 case Instruction::URem:
7330 // If we are just changing the sign, rewrite.
7331 if (DestBitSize == SrcBitSize) {
7332 // Don't insert two casts if they cannot be eliminated. We allow
7333 // two casts to be inserted if the sizes are the same. This could
7334 // only be converting signedness, which is a noop.
7335 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7336 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7337 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7339 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7341 return BinaryOperator::Create(
7342 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7347 case Instruction::Shl:
7348 // Allow changing the sign of the source operand. Do not allow
7349 // changing the size of the shift, UNLESS the shift amount is a
7350 // constant. We must not change variable sized shifts to a smaller
7351 // size, because it is undefined to shift more bits out than exist
7353 if (DestBitSize == SrcBitSize ||
7354 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7355 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7356 Instruction::BitCast : Instruction::Trunc);
7357 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7358 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7359 return BinaryOperator::CreateShl(Op0c, Op1c);
7362 case Instruction::AShr:
7363 // If this is a signed shr, and if all bits shifted in are about to be
7364 // truncated off, turn it into an unsigned shr to allow greater
7366 if (DestBitSize < SrcBitSize &&
7367 isa<ConstantInt>(Op1)) {
7368 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7369 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7370 // Insert the new logical shift right.
7371 return BinaryOperator::CreateLShr(Op0, Op1);
7379 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7380 if (Instruction *Result = commonIntCastTransforms(CI))
7383 Value *Src = CI.getOperand(0);
7384 const Type *Ty = CI.getType();
7385 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7386 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7388 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7389 switch (SrcI->getOpcode()) {
7391 case Instruction::LShr:
7392 // We can shrink lshr to something smaller if we know the bits shifted in
7393 // are already zeros.
7394 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7395 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7397 // Get a mask for the bits shifting in.
7398 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7399 Value* SrcIOp0 = SrcI->getOperand(0);
7400 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7401 if (ShAmt >= DestBitWidth) // All zeros.
7402 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7404 // Okay, we can shrink this. Truncate the input, then return a new
7406 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7407 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7409 return BinaryOperator::CreateLShr(V1, V2);
7411 } else { // This is a variable shr.
7413 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7414 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7415 // loop-invariant and CSE'd.
7416 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7417 Value *One = ConstantInt::get(SrcI->getType(), 1);
7419 Value *V = InsertNewInstBefore(
7420 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
7422 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
7423 SrcI->getOperand(0),
7425 Value *Zero = Constant::getNullValue(V->getType());
7426 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7436 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7437 /// in order to eliminate the icmp.
7438 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7440 // If we are just checking for a icmp eq of a single bit and zext'ing it
7441 // to an integer, then shift the bit to the appropriate place and then
7442 // cast to integer to avoid the comparison.
7443 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7444 const APInt &Op1CV = Op1C->getValue();
7446 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7447 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7448 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7449 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7450 if (!DoXform) return ICI;
7452 Value *In = ICI->getOperand(0);
7453 Value *Sh = ConstantInt::get(In->getType(),
7454 In->getType()->getPrimitiveSizeInBits()-1);
7455 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
7456 In->getName()+".lobit"),
7458 if (In->getType() != CI.getType())
7459 In = CastInst::CreateIntegerCast(In, CI.getType(),
7460 false/*ZExt*/, "tmp", &CI);
7462 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7463 Constant *One = ConstantInt::get(In->getType(), 1);
7464 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
7465 In->getName()+".not"),
7469 return ReplaceInstUsesWith(CI, In);
7474 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7475 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7476 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7477 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7478 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7479 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7480 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7481 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7482 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7483 // This only works for EQ and NE
7484 ICI->isEquality()) {
7485 // If Op1C some other power of two, convert:
7486 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7487 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7488 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7489 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7491 APInt KnownZeroMask(~KnownZero);
7492 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7493 if (!DoXform) return ICI;
7495 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7496 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7497 // (X&4) == 2 --> false
7498 // (X&4) != 2 --> true
7499 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7500 Res = ConstantExpr::getZExt(Res, CI.getType());
7501 return ReplaceInstUsesWith(CI, Res);
7504 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7505 Value *In = ICI->getOperand(0);
7507 // Perform a logical shr by shiftamt.
7508 // Insert the shift to put the result in the low bit.
7509 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
7510 ConstantInt::get(In->getType(), ShiftAmt),
7511 In->getName()+".lobit"), CI);
7514 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7515 Constant *One = ConstantInt::get(In->getType(), 1);
7516 In = BinaryOperator::CreateXor(In, One, "tmp");
7517 InsertNewInstBefore(cast<Instruction>(In), CI);
7520 if (CI.getType() == In->getType())
7521 return ReplaceInstUsesWith(CI, In);
7523 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
7531 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7532 // If one of the common conversion will work ..
7533 if (Instruction *Result = commonIntCastTransforms(CI))
7536 Value *Src = CI.getOperand(0);
7538 // If this is a cast of a cast
7539 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7540 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7541 // types and if the sizes are just right we can convert this into a logical
7542 // 'and' which will be much cheaper than the pair of casts.
7543 if (isa<TruncInst>(CSrc)) {
7544 // Get the sizes of the types involved
7545 Value *A = CSrc->getOperand(0);
7546 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7547 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7548 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7549 // If we're actually extending zero bits and the trunc is a no-op
7550 if (MidSize < DstSize && SrcSize == DstSize) {
7551 // Replace both of the casts with an And of the type mask.
7552 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7553 Constant *AndConst = ConstantInt::get(AndValue);
7555 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
7556 // Unfortunately, if the type changed, we need to cast it back.
7557 if (And->getType() != CI.getType()) {
7558 And->setName(CSrc->getName()+".mask");
7559 InsertNewInstBefore(And, CI);
7560 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
7567 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7568 return transformZExtICmp(ICI, CI);
7570 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7571 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7572 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7573 // of the (zext icmp) will be transformed.
7574 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7575 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7576 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7577 (transformZExtICmp(LHS, CI, false) ||
7578 transformZExtICmp(RHS, CI, false))) {
7579 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7580 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7581 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
7588 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7589 if (Instruction *I = commonIntCastTransforms(CI))
7592 Value *Src = CI.getOperand(0);
7594 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7595 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7596 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7597 // If we are just checking for a icmp eq of a single bit and zext'ing it
7598 // to an integer, then shift the bit to the appropriate place and then
7599 // cast to integer to avoid the comparison.
7600 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7601 const APInt &Op1CV = Op1C->getValue();
7603 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7604 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7605 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7606 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7607 Value *In = ICI->getOperand(0);
7608 Value *Sh = ConstantInt::get(In->getType(),
7609 In->getType()->getPrimitiveSizeInBits()-1);
7610 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
7611 In->getName()+".lobit"),
7613 if (In->getType() != CI.getType())
7614 In = CastInst::CreateIntegerCast(In, CI.getType(),
7615 true/*SExt*/, "tmp", &CI);
7617 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7618 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
7619 In->getName()+".not"), CI);
7621 return ReplaceInstUsesWith(CI, In);
7626 // See if the value being truncated is already sign extended. If so, just
7627 // eliminate the trunc/sext pair.
7628 if (getOpcode(Src) == Instruction::Trunc) {
7629 Value *Op = cast<User>(Src)->getOperand(0);
7630 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
7631 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
7632 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7633 unsigned NumSignBits = ComputeNumSignBits(Op);
7635 if (OpBits == DestBits) {
7636 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
7637 // bits, it is already ready.
7638 if (NumSignBits > DestBits-MidBits)
7639 return ReplaceInstUsesWith(CI, Op);
7640 } else if (OpBits < DestBits) {
7641 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
7642 // bits, just sext from i32.
7643 if (NumSignBits > OpBits-MidBits)
7644 return new SExtInst(Op, CI.getType(), "tmp");
7646 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
7647 // bits, just truncate to i32.
7648 if (NumSignBits > OpBits-MidBits)
7649 return new TruncInst(Op, CI.getType(), "tmp");
7656 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7657 /// in the specified FP type without changing its value.
7658 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
7659 APFloat F = CFP->getValueAPF();
7660 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7661 return ConstantFP::get(F);
7665 /// LookThroughFPExtensions - If this is an fp extension instruction, look
7666 /// through it until we get the source value.
7667 static Value *LookThroughFPExtensions(Value *V) {
7668 if (Instruction *I = dyn_cast<Instruction>(V))
7669 if (I->getOpcode() == Instruction::FPExt)
7670 return LookThroughFPExtensions(I->getOperand(0));
7672 // If this value is a constant, return the constant in the smallest FP type
7673 // that can accurately represent it. This allows us to turn
7674 // (float)((double)X+2.0) into x+2.0f.
7675 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7676 if (CFP->getType() == Type::PPC_FP128Ty)
7677 return V; // No constant folding of this.
7678 // See if the value can be truncated to float and then reextended.
7679 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
7681 if (CFP->getType() == Type::DoubleTy)
7682 return V; // Won't shrink.
7683 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
7685 // Don't try to shrink to various long double types.
7691 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7692 if (Instruction *I = commonCastTransforms(CI))
7695 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7696 // smaller than the destination type, we can eliminate the truncate by doing
7697 // the add as the smaller type. This applies to add/sub/mul/div as well as
7698 // many builtins (sqrt, etc).
7699 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7700 if (OpI && OpI->hasOneUse()) {
7701 switch (OpI->getOpcode()) {
7703 case Instruction::Add:
7704 case Instruction::Sub:
7705 case Instruction::Mul:
7706 case Instruction::FDiv:
7707 case Instruction::FRem:
7708 const Type *SrcTy = OpI->getType();
7709 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7710 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7711 if (LHSTrunc->getType() != SrcTy &&
7712 RHSTrunc->getType() != SrcTy) {
7713 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7714 // If the source types were both smaller than the destination type of
7715 // the cast, do this xform.
7716 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7717 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7718 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7720 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7722 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7731 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7732 return commonCastTransforms(CI);
7735 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7736 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
7737 // mantissa to accurately represent all values of X. For example, do not
7738 // do this with i64->float->i64.
7739 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
7740 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7741 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
7742 SrcI->getType()->getFPMantissaWidth())
7743 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7745 return commonCastTransforms(FI);
7748 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7749 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
7750 // mantissa to accurately represent all values of X. For example, do not
7751 // do this with i64->float->i64.
7752 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
7753 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7754 (int)FI.getType()->getPrimitiveSizeInBits() <=
7755 SrcI->getType()->getFPMantissaWidth())
7756 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7758 return commonCastTransforms(FI);
7761 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7762 return commonCastTransforms(CI);
7765 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7766 return commonCastTransforms(CI);
7769 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7770 return commonPointerCastTransforms(CI);
7773 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7774 if (Instruction *I = commonCastTransforms(CI))
7777 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7778 if (!DestPointee->isSized()) return 0;
7780 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7783 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7784 m_ConstantInt(Cst)))) {
7785 // If the source and destination operands have the same type, see if this
7786 // is a single-index GEP.
7787 if (X->getType() == CI.getType()) {
7788 // Get the size of the pointee type.
7789 uint64_t Size = TD->getABITypeSize(DestPointee);
7791 // Convert the constant to intptr type.
7792 APInt Offset = Cst->getValue();
7793 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7795 // If Offset is evenly divisible by Size, we can do this xform.
7796 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7797 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7798 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
7801 // TODO: Could handle other cases, e.g. where add is indexing into field of
7803 } else if (CI.getOperand(0)->hasOneUse() &&
7804 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7805 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7806 // "inttoptr+GEP" instead of "add+intptr".
7808 // Get the size of the pointee type.
7809 uint64_t Size = TD->getABITypeSize(DestPointee);
7811 // Convert the constant to intptr type.
7812 APInt Offset = Cst->getValue();
7813 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7815 // If Offset is evenly divisible by Size, we can do this xform.
7816 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7817 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7819 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7821 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
7827 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7828 // If the operands are integer typed then apply the integer transforms,
7829 // otherwise just apply the common ones.
7830 Value *Src = CI.getOperand(0);
7831 const Type *SrcTy = Src->getType();
7832 const Type *DestTy = CI.getType();
7834 if (SrcTy->isInteger() && DestTy->isInteger()) {
7835 if (Instruction *Result = commonIntCastTransforms(CI))
7837 } else if (isa<PointerType>(SrcTy)) {
7838 if (Instruction *I = commonPointerCastTransforms(CI))
7841 if (Instruction *Result = commonCastTransforms(CI))
7846 // Get rid of casts from one type to the same type. These are useless and can
7847 // be replaced by the operand.
7848 if (DestTy == Src->getType())
7849 return ReplaceInstUsesWith(CI, Src);
7851 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7852 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7853 const Type *DstElTy = DstPTy->getElementType();
7854 const Type *SrcElTy = SrcPTy->getElementType();
7856 // If the address spaces don't match, don't eliminate the bitcast, which is
7857 // required for changing types.
7858 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7861 // If we are casting a malloc or alloca to a pointer to a type of the same
7862 // size, rewrite the allocation instruction to allocate the "right" type.
7863 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7864 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7867 // If the source and destination are pointers, and this cast is equivalent
7868 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
7869 // This can enhance SROA and other transforms that want type-safe pointers.
7870 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7871 unsigned NumZeros = 0;
7872 while (SrcElTy != DstElTy &&
7873 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7874 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7875 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7879 // If we found a path from the src to dest, create the getelementptr now.
7880 if (SrcElTy == DstElTy) {
7881 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7882 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
7883 ((Instruction*) NULL));
7887 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7888 if (SVI->hasOneUse()) {
7889 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7890 // a bitconvert to a vector with the same # elts.
7891 if (isa<VectorType>(DestTy) &&
7892 cast<VectorType>(DestTy)->getNumElements() ==
7893 SVI->getType()->getNumElements()) {
7895 // If either of the operands is a cast from CI.getType(), then
7896 // evaluating the shuffle in the casted destination's type will allow
7897 // us to eliminate at least one cast.
7898 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7899 Tmp->getOperand(0)->getType() == DestTy) ||
7900 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7901 Tmp->getOperand(0)->getType() == DestTy)) {
7902 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7903 SVI->getOperand(0), DestTy, &CI);
7904 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7905 SVI->getOperand(1), DestTy, &CI);
7906 // Return a new shuffle vector. Use the same element ID's, as we
7907 // know the vector types match #elts.
7908 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7916 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7918 /// %D = select %cond, %C, %A
7920 /// %C = select %cond, %B, 0
7923 /// Assuming that the specified instruction is an operand to the select, return
7924 /// a bitmask indicating which operands of this instruction are foldable if they
7925 /// equal the other incoming value of the select.
7927 static unsigned GetSelectFoldableOperands(Instruction *I) {
7928 switch (I->getOpcode()) {
7929 case Instruction::Add:
7930 case Instruction::Mul:
7931 case Instruction::And:
7932 case Instruction::Or:
7933 case Instruction::Xor:
7934 return 3; // Can fold through either operand.
7935 case Instruction::Sub: // Can only fold on the amount subtracted.
7936 case Instruction::Shl: // Can only fold on the shift amount.
7937 case Instruction::LShr:
7938 case Instruction::AShr:
7941 return 0; // Cannot fold
7945 /// GetSelectFoldableConstant - For the same transformation as the previous
7946 /// function, return the identity constant that goes into the select.
7947 static Constant *GetSelectFoldableConstant(Instruction *I) {
7948 switch (I->getOpcode()) {
7949 default: assert(0 && "This cannot happen!"); abort();
7950 case Instruction::Add:
7951 case Instruction::Sub:
7952 case Instruction::Or:
7953 case Instruction::Xor:
7954 case Instruction::Shl:
7955 case Instruction::LShr:
7956 case Instruction::AShr:
7957 return Constant::getNullValue(I->getType());
7958 case Instruction::And:
7959 return Constant::getAllOnesValue(I->getType());
7960 case Instruction::Mul:
7961 return ConstantInt::get(I->getType(), 1);
7965 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7966 /// have the same opcode and only one use each. Try to simplify this.
7967 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7969 if (TI->getNumOperands() == 1) {
7970 // If this is a non-volatile load or a cast from the same type,
7973 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7976 return 0; // unknown unary op.
7979 // Fold this by inserting a select from the input values.
7980 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
7981 FI->getOperand(0), SI.getName()+".v");
7982 InsertNewInstBefore(NewSI, SI);
7983 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
7987 // Only handle binary operators here.
7988 if (!isa<BinaryOperator>(TI))
7991 // Figure out if the operations have any operands in common.
7992 Value *MatchOp, *OtherOpT, *OtherOpF;
7994 if (TI->getOperand(0) == FI->getOperand(0)) {
7995 MatchOp = TI->getOperand(0);
7996 OtherOpT = TI->getOperand(1);
7997 OtherOpF = FI->getOperand(1);
7998 MatchIsOpZero = true;
7999 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8000 MatchOp = TI->getOperand(1);
8001 OtherOpT = TI->getOperand(0);
8002 OtherOpF = FI->getOperand(0);
8003 MatchIsOpZero = false;
8004 } else if (!TI->isCommutative()) {
8006 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8007 MatchOp = TI->getOperand(0);
8008 OtherOpT = TI->getOperand(1);
8009 OtherOpF = FI->getOperand(0);
8010 MatchIsOpZero = true;
8011 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8012 MatchOp = TI->getOperand(1);
8013 OtherOpT = TI->getOperand(0);
8014 OtherOpF = FI->getOperand(1);
8015 MatchIsOpZero = true;
8020 // If we reach here, they do have operations in common.
8021 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8022 OtherOpF, SI.getName()+".v");
8023 InsertNewInstBefore(NewSI, SI);
8025 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8027 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8029 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8031 assert(0 && "Shouldn't get here");
8035 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8036 Value *CondVal = SI.getCondition();
8037 Value *TrueVal = SI.getTrueValue();
8038 Value *FalseVal = SI.getFalseValue();
8040 // select true, X, Y -> X
8041 // select false, X, Y -> Y
8042 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8043 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8045 // select C, X, X -> X
8046 if (TrueVal == FalseVal)
8047 return ReplaceInstUsesWith(SI, TrueVal);
8049 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8050 return ReplaceInstUsesWith(SI, FalseVal);
8051 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8052 return ReplaceInstUsesWith(SI, TrueVal);
8053 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8054 if (isa<Constant>(TrueVal))
8055 return ReplaceInstUsesWith(SI, TrueVal);
8057 return ReplaceInstUsesWith(SI, FalseVal);
8060 if (SI.getType() == Type::Int1Ty) {
8061 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8062 if (C->getZExtValue()) {
8063 // Change: A = select B, true, C --> A = or B, C
8064 return BinaryOperator::CreateOr(CondVal, FalseVal);
8066 // Change: A = select B, false, C --> A = and !B, C
8068 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8069 "not."+CondVal->getName()), SI);
8070 return BinaryOperator::CreateAnd(NotCond, FalseVal);
8072 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8073 if (C->getZExtValue() == false) {
8074 // Change: A = select B, C, false --> A = and B, C
8075 return BinaryOperator::CreateAnd(CondVal, TrueVal);
8077 // Change: A = select B, C, true --> A = or !B, C
8079 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8080 "not."+CondVal->getName()), SI);
8081 return BinaryOperator::CreateOr(NotCond, TrueVal);
8085 // select a, b, a -> a&b
8086 // select a, a, b -> a|b
8087 if (CondVal == TrueVal)
8088 return BinaryOperator::CreateOr(CondVal, FalseVal);
8089 else if (CondVal == FalseVal)
8090 return BinaryOperator::CreateAnd(CondVal, TrueVal);
8093 // Selecting between two integer constants?
8094 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8095 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8096 // select C, 1, 0 -> zext C to int
8097 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8098 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8099 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8100 // select C, 0, 1 -> zext !C to int
8102 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8103 "not."+CondVal->getName()), SI);
8104 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8107 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8109 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8111 // (x <s 0) ? -1 : 0 -> ashr x, 31
8112 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8113 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8114 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8115 // The comparison constant and the result are not neccessarily the
8116 // same width. Make an all-ones value by inserting a AShr.
8117 Value *X = IC->getOperand(0);
8118 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8119 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8120 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8122 InsertNewInstBefore(SRA, SI);
8124 // Finally, convert to the type of the select RHS. We figure out
8125 // if this requires a SExt, Trunc or BitCast based on the sizes.
8126 Instruction::CastOps opc = Instruction::BitCast;
8127 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8128 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
8129 if (SRASize < SISize)
8130 opc = Instruction::SExt;
8131 else if (SRASize > SISize)
8132 opc = Instruction::Trunc;
8133 return CastInst::Create(opc, SRA, SI.getType());
8138 // If one of the constants is zero (we know they can't both be) and we
8139 // have an icmp instruction with zero, and we have an 'and' with the
8140 // non-constant value, eliminate this whole mess. This corresponds to
8141 // cases like this: ((X & 27) ? 27 : 0)
8142 if (TrueValC->isZero() || FalseValC->isZero())
8143 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8144 cast<Constant>(IC->getOperand(1))->isNullValue())
8145 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8146 if (ICA->getOpcode() == Instruction::And &&
8147 isa<ConstantInt>(ICA->getOperand(1)) &&
8148 (ICA->getOperand(1) == TrueValC ||
8149 ICA->getOperand(1) == FalseValC) &&
8150 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8151 // Okay, now we know that everything is set up, we just don't
8152 // know whether we have a icmp_ne or icmp_eq and whether the
8153 // true or false val is the zero.
8154 bool ShouldNotVal = !TrueValC->isZero();
8155 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8158 V = InsertNewInstBefore(BinaryOperator::Create(
8159 Instruction::Xor, V, ICA->getOperand(1)), SI);
8160 return ReplaceInstUsesWith(SI, V);
8165 // See if we are selecting two values based on a comparison of the two values.
8166 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8167 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8168 // Transform (X == Y) ? X : Y -> Y
8169 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8170 // This is not safe in general for floating point:
8171 // consider X== -0, Y== +0.
8172 // It becomes safe if either operand is a nonzero constant.
8173 ConstantFP *CFPt, *CFPf;
8174 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8175 !CFPt->getValueAPF().isZero()) ||
8176 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8177 !CFPf->getValueAPF().isZero()))
8178 return ReplaceInstUsesWith(SI, FalseVal);
8180 // Transform (X != Y) ? X : Y -> X
8181 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8182 return ReplaceInstUsesWith(SI, TrueVal);
8183 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8185 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8186 // Transform (X == Y) ? Y : X -> X
8187 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8188 // This is not safe in general for floating point:
8189 // consider X== -0, Y== +0.
8190 // It becomes safe if either operand is a nonzero constant.
8191 ConstantFP *CFPt, *CFPf;
8192 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8193 !CFPt->getValueAPF().isZero()) ||
8194 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8195 !CFPf->getValueAPF().isZero()))
8196 return ReplaceInstUsesWith(SI, FalseVal);
8198 // Transform (X != Y) ? Y : X -> Y
8199 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8200 return ReplaceInstUsesWith(SI, TrueVal);
8201 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8205 // See if we are selecting two values based on a comparison of the two values.
8206 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8207 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8208 // Transform (X == Y) ? X : Y -> Y
8209 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8210 return ReplaceInstUsesWith(SI, FalseVal);
8211 // Transform (X != Y) ? X : Y -> X
8212 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8213 return ReplaceInstUsesWith(SI, TrueVal);
8214 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8216 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8217 // Transform (X == Y) ? Y : X -> X
8218 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8219 return ReplaceInstUsesWith(SI, FalseVal);
8220 // Transform (X != Y) ? Y : X -> Y
8221 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8222 return ReplaceInstUsesWith(SI, TrueVal);
8223 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8227 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8228 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8229 if (TI->hasOneUse() && FI->hasOneUse()) {
8230 Instruction *AddOp = 0, *SubOp = 0;
8232 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8233 if (TI->getOpcode() == FI->getOpcode())
8234 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8237 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8238 // even legal for FP.
8239 if (TI->getOpcode() == Instruction::Sub &&
8240 FI->getOpcode() == Instruction::Add) {
8241 AddOp = FI; SubOp = TI;
8242 } else if (FI->getOpcode() == Instruction::Sub &&
8243 TI->getOpcode() == Instruction::Add) {
8244 AddOp = TI; SubOp = FI;
8248 Value *OtherAddOp = 0;
8249 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8250 OtherAddOp = AddOp->getOperand(1);
8251 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8252 OtherAddOp = AddOp->getOperand(0);
8256 // So at this point we know we have (Y -> OtherAddOp):
8257 // select C, (add X, Y), (sub X, Z)
8258 Value *NegVal; // Compute -Z
8259 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8260 NegVal = ConstantExpr::getNeg(C);
8262 NegVal = InsertNewInstBefore(
8263 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8266 Value *NewTrueOp = OtherAddOp;
8267 Value *NewFalseOp = NegVal;
8269 std::swap(NewTrueOp, NewFalseOp);
8270 Instruction *NewSel =
8271 SelectInst::Create(CondVal, NewTrueOp,
8272 NewFalseOp, SI.getName() + ".p");
8274 NewSel = InsertNewInstBefore(NewSel, SI);
8275 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8280 // See if we can fold the select into one of our operands.
8281 if (SI.getType()->isInteger()) {
8282 // See the comment above GetSelectFoldableOperands for a description of the
8283 // transformation we are doing here.
8284 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8285 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8286 !isa<Constant>(FalseVal))
8287 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8288 unsigned OpToFold = 0;
8289 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8291 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8296 Constant *C = GetSelectFoldableConstant(TVI);
8297 Instruction *NewSel =
8298 SelectInst::Create(SI.getCondition(),
8299 TVI->getOperand(2-OpToFold), C);
8300 InsertNewInstBefore(NewSel, SI);
8301 NewSel->takeName(TVI);
8302 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8303 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8305 assert(0 && "Unknown instruction!!");
8310 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8311 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8312 !isa<Constant>(TrueVal))
8313 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8314 unsigned OpToFold = 0;
8315 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8317 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8322 Constant *C = GetSelectFoldableConstant(FVI);
8323 Instruction *NewSel =
8324 SelectInst::Create(SI.getCondition(), C,
8325 FVI->getOperand(2-OpToFold));
8326 InsertNewInstBefore(NewSel, SI);
8327 NewSel->takeName(FVI);
8328 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8329 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
8331 assert(0 && "Unknown instruction!!");
8336 if (BinaryOperator::isNot(CondVal)) {
8337 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8338 SI.setOperand(1, FalseVal);
8339 SI.setOperand(2, TrueVal);
8346 /// EnforceKnownAlignment - If the specified pointer points to an object that
8347 /// we control, modify the object's alignment to PrefAlign. This isn't
8348 /// often possible though. If alignment is important, a more reliable approach
8349 /// is to simply align all global variables and allocation instructions to
8350 /// their preferred alignment from the beginning.
8352 static unsigned EnforceKnownAlignment(Value *V,
8353 unsigned Align, unsigned PrefAlign) {
8355 User *U = dyn_cast<User>(V);
8356 if (!U) return Align;
8358 switch (getOpcode(U)) {
8360 case Instruction::BitCast:
8361 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8362 case Instruction::GetElementPtr: {
8363 // If all indexes are zero, it is just the alignment of the base pointer.
8364 bool AllZeroOperands = true;
8365 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
8366 if (!isa<Constant>(*i) ||
8367 !cast<Constant>(*i)->isNullValue()) {
8368 AllZeroOperands = false;
8372 if (AllZeroOperands) {
8373 // Treat this like a bitcast.
8374 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8380 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8381 // If there is a large requested alignment and we can, bump up the alignment
8383 if (!GV->isDeclaration()) {
8384 GV->setAlignment(PrefAlign);
8387 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8388 // If there is a requested alignment and if this is an alloca, round up. We
8389 // don't do this for malloc, because some systems can't respect the request.
8390 if (isa<AllocaInst>(AI)) {
8391 AI->setAlignment(PrefAlign);
8399 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8400 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8401 /// and it is more than the alignment of the ultimate object, see if we can
8402 /// increase the alignment of the ultimate object, making this check succeed.
8403 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8404 unsigned PrefAlign) {
8405 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8406 sizeof(PrefAlign) * CHAR_BIT;
8407 APInt Mask = APInt::getAllOnesValue(BitWidth);
8408 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8409 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8410 unsigned TrailZ = KnownZero.countTrailingOnes();
8411 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8413 if (PrefAlign > Align)
8414 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8416 // We don't need to make any adjustment.
8420 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8421 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8422 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
8423 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8424 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8426 if (CopyAlign < MinAlign) {
8427 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8431 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8433 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8434 if (MemOpLength == 0) return 0;
8436 // Source and destination pointer types are always "i8*" for intrinsic. See
8437 // if the size is something we can handle with a single primitive load/store.
8438 // A single load+store correctly handles overlapping memory in the memmove
8440 unsigned Size = MemOpLength->getZExtValue();
8441 if (Size == 0) return MI; // Delete this mem transfer.
8443 if (Size > 8 || (Size&(Size-1)))
8444 return 0; // If not 1/2/4/8 bytes, exit.
8446 // Use an integer load+store unless we can find something better.
8447 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
8449 // Memcpy forces the use of i8* for the source and destination. That means
8450 // that if you're using memcpy to move one double around, you'll get a cast
8451 // from double* to i8*. We'd much rather use a double load+store rather than
8452 // an i64 load+store, here because this improves the odds that the source or
8453 // dest address will be promotable. See if we can find a better type than the
8454 // integer datatype.
8455 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8456 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8457 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8458 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8459 // down through these levels if so.
8460 while (!SrcETy->isSingleValueType()) {
8461 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8462 if (STy->getNumElements() == 1)
8463 SrcETy = STy->getElementType(0);
8466 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8467 if (ATy->getNumElements() == 1)
8468 SrcETy = ATy->getElementType();
8475 if (SrcETy->isSingleValueType())
8476 NewPtrTy = PointerType::getUnqual(SrcETy);
8481 // If the memcpy/memmove provides better alignment info than we can
8483 SrcAlign = std::max(SrcAlign, CopyAlign);
8484 DstAlign = std::max(DstAlign, CopyAlign);
8486 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8487 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
8488 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8489 InsertNewInstBefore(L, *MI);
8490 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8492 // Set the size of the copy to 0, it will be deleted on the next iteration.
8493 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8497 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8498 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8499 if (MI->getAlignment()->getZExtValue() < Alignment) {
8500 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8504 // Extract the length and alignment and fill if they are constant.
8505 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8506 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8507 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8509 uint64_t Len = LenC->getZExtValue();
8510 Alignment = MI->getAlignment()->getZExtValue();
8512 // If the length is zero, this is a no-op
8513 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8515 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8516 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8517 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8519 Value *Dest = MI->getDest();
8520 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8522 // Alignment 0 is identity for alignment 1 for memset, but not store.
8523 if (Alignment == 0) Alignment = 1;
8525 // Extract the fill value and store.
8526 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8527 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8530 // Set the size of the copy to 0, it will be deleted on the next iteration.
8531 MI->setLength(Constant::getNullValue(LenC->getType()));
8539 /// visitCallInst - CallInst simplification. This mostly only handles folding
8540 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8541 /// the heavy lifting.
8543 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8544 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8545 if (!II) return visitCallSite(&CI);
8547 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8549 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8550 bool Changed = false;
8552 // memmove/cpy/set of zero bytes is a noop.
8553 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8554 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8556 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8557 if (CI->getZExtValue() == 1) {
8558 // Replace the instruction with just byte operations. We would
8559 // transform other cases to loads/stores, but we don't know if
8560 // alignment is sufficient.
8564 // If we have a memmove and the source operation is a constant global,
8565 // then the source and dest pointers can't alias, so we can change this
8566 // into a call to memcpy.
8567 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
8568 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8569 if (GVSrc->isConstant()) {
8570 Module *M = CI.getParent()->getParent()->getParent();
8571 Intrinsic::ID MemCpyID;
8572 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8573 MemCpyID = Intrinsic::memcpy_i32;
8575 MemCpyID = Intrinsic::memcpy_i64;
8576 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
8580 // memmove(x,x,size) -> noop.
8581 if (MMI->getSource() == MMI->getDest())
8582 return EraseInstFromFunction(CI);
8585 // If we can determine a pointer alignment that is bigger than currently
8586 // set, update the alignment.
8587 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
8588 if (Instruction *I = SimplifyMemTransfer(MI))
8590 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8591 if (Instruction *I = SimplifyMemSet(MSI))
8595 if (Changed) return II;
8598 switch (II->getIntrinsicID()) {
8600 case Intrinsic::bswap:
8601 // bswap(bswap(x)) -> x
8602 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
8603 if (Operand->getIntrinsicID() == Intrinsic::bswap)
8604 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
8606 case Intrinsic::ppc_altivec_lvx:
8607 case Intrinsic::ppc_altivec_lvxl:
8608 case Intrinsic::x86_sse_loadu_ps:
8609 case Intrinsic::x86_sse2_loadu_pd:
8610 case Intrinsic::x86_sse2_loadu_dq:
8611 // Turn PPC lvx -> load if the pointer is known aligned.
8612 // Turn X86 loadups -> load if the pointer is known aligned.
8613 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8614 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8615 PointerType::getUnqual(II->getType()),
8617 return new LoadInst(Ptr);
8620 case Intrinsic::ppc_altivec_stvx:
8621 case Intrinsic::ppc_altivec_stvxl:
8622 // Turn stvx -> store if the pointer is known aligned.
8623 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
8624 const Type *OpPtrTy =
8625 PointerType::getUnqual(II->getOperand(1)->getType());
8626 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8627 return new StoreInst(II->getOperand(1), Ptr);
8630 case Intrinsic::x86_sse_storeu_ps:
8631 case Intrinsic::x86_sse2_storeu_pd:
8632 case Intrinsic::x86_sse2_storeu_dq:
8633 case Intrinsic::x86_sse2_storel_dq:
8634 // Turn X86 storeu -> store if the pointer is known aligned.
8635 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8636 const Type *OpPtrTy =
8637 PointerType::getUnqual(II->getOperand(2)->getType());
8638 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8639 return new StoreInst(II->getOperand(2), Ptr);
8643 case Intrinsic::x86_sse_cvttss2si: {
8644 // These intrinsics only demands the 0th element of its input vector. If
8645 // we can simplify the input based on that, do so now.
8647 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8649 II->setOperand(1, V);
8655 case Intrinsic::ppc_altivec_vperm:
8656 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8657 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8658 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8660 // Check that all of the elements are integer constants or undefs.
8661 bool AllEltsOk = true;
8662 for (unsigned i = 0; i != 16; ++i) {
8663 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8664 !isa<UndefValue>(Mask->getOperand(i))) {
8671 // Cast the input vectors to byte vectors.
8672 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8673 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8674 Value *Result = UndefValue::get(Op0->getType());
8676 // Only extract each element once.
8677 Value *ExtractedElts[32];
8678 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8680 for (unsigned i = 0; i != 16; ++i) {
8681 if (isa<UndefValue>(Mask->getOperand(i)))
8683 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8684 Idx &= 31; // Match the hardware behavior.
8686 if (ExtractedElts[Idx] == 0) {
8688 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8689 InsertNewInstBefore(Elt, CI);
8690 ExtractedElts[Idx] = Elt;
8693 // Insert this value into the result vector.
8694 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8696 InsertNewInstBefore(cast<Instruction>(Result), CI);
8698 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
8703 case Intrinsic::stackrestore: {
8704 // If the save is right next to the restore, remove the restore. This can
8705 // happen when variable allocas are DCE'd.
8706 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8707 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8708 BasicBlock::iterator BI = SS;
8710 return EraseInstFromFunction(CI);
8714 // Scan down this block to see if there is another stack restore in the
8715 // same block without an intervening call/alloca.
8716 BasicBlock::iterator BI = II;
8717 TerminatorInst *TI = II->getParent()->getTerminator();
8718 bool CannotRemove = false;
8719 for (++BI; &*BI != TI; ++BI) {
8720 if (isa<AllocaInst>(BI)) {
8721 CannotRemove = true;
8724 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
8725 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
8726 // If there is a stackrestore below this one, remove this one.
8727 if (II->getIntrinsicID() == Intrinsic::stackrestore)
8728 return EraseInstFromFunction(CI);
8729 // Otherwise, ignore the intrinsic.
8731 // If we found a non-intrinsic call, we can't remove the stack
8733 CannotRemove = true;
8739 // If the stack restore is in a return/unwind block and if there are no
8740 // allocas or calls between the restore and the return, nuke the restore.
8741 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8742 return EraseInstFromFunction(CI);
8747 return visitCallSite(II);
8750 // InvokeInst simplification
8752 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8753 return visitCallSite(&II);
8756 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
8757 /// passed through the varargs area, we can eliminate the use of the cast.
8758 static bool isSafeToEliminateVarargsCast(const CallSite CS,
8759 const CastInst * const CI,
8760 const TargetData * const TD,
8762 if (!CI->isLosslessCast())
8765 // The size of ByVal arguments is derived from the type, so we
8766 // can't change to a type with a different size. If the size were
8767 // passed explicitly we could avoid this check.
8768 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8772 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8773 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8774 if (!SrcTy->isSized() || !DstTy->isSized())
8776 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8781 // visitCallSite - Improvements for call and invoke instructions.
8783 Instruction *InstCombiner::visitCallSite(CallSite CS) {
8784 bool Changed = false;
8786 // If the callee is a constexpr cast of a function, attempt to move the cast
8787 // to the arguments of the call/invoke.
8788 if (transformConstExprCastCall(CS)) return 0;
8790 Value *Callee = CS.getCalledValue();
8792 if (Function *CalleeF = dyn_cast<Function>(Callee))
8793 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8794 Instruction *OldCall = CS.getInstruction();
8795 // If the call and callee calling conventions don't match, this call must
8796 // be unreachable, as the call is undefined.
8797 new StoreInst(ConstantInt::getTrue(),
8798 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8800 if (!OldCall->use_empty())
8801 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8802 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8803 return EraseInstFromFunction(*OldCall);
8807 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8808 // This instruction is not reachable, just remove it. We insert a store to
8809 // undef so that we know that this code is not reachable, despite the fact
8810 // that we can't modify the CFG here.
8811 new StoreInst(ConstantInt::getTrue(),
8812 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8813 CS.getInstruction());
8815 if (!CS.getInstruction()->use_empty())
8816 CS.getInstruction()->
8817 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8819 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8820 // Don't break the CFG, insert a dummy cond branch.
8821 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8822 ConstantInt::getTrue(), II);
8824 return EraseInstFromFunction(*CS.getInstruction());
8827 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8828 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8829 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8830 return transformCallThroughTrampoline(CS);
8832 const PointerType *PTy = cast<PointerType>(Callee->getType());
8833 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8834 if (FTy->isVarArg()) {
8835 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
8836 // See if we can optimize any arguments passed through the varargs area of
8838 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8839 E = CS.arg_end(); I != E; ++I, ++ix) {
8840 CastInst *CI = dyn_cast<CastInst>(*I);
8841 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8842 *I = CI->getOperand(0);
8848 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
8849 // Inline asm calls cannot throw - mark them 'nounwind'.
8850 CS.setDoesNotThrow();
8854 return Changed ? CS.getInstruction() : 0;
8857 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8858 // attempt to move the cast to the arguments of the call/invoke.
8860 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8861 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8862 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8863 if (CE->getOpcode() != Instruction::BitCast ||
8864 !isa<Function>(CE->getOperand(0)))
8866 Function *Callee = cast<Function>(CE->getOperand(0));
8867 Instruction *Caller = CS.getInstruction();
8868 const PAListPtr &CallerPAL = CS.getParamAttrs();
8870 // Okay, this is a cast from a function to a different type. Unless doing so
8871 // would cause a type conversion of one of our arguments, change this call to
8872 // be a direct call with arguments casted to the appropriate types.
8874 const FunctionType *FT = Callee->getFunctionType();
8875 const Type *OldRetTy = Caller->getType();
8876 const Type *NewRetTy = FT->getReturnType();
8878 if (isa<StructType>(NewRetTy))
8879 return false; // TODO: Handle multiple return values.
8881 // Check to see if we are changing the return type...
8882 if (OldRetTy != NewRetTy) {
8883 if (Callee->isDeclaration() &&
8884 // Conversion is ok if changing from one pointer type to another or from
8885 // a pointer to an integer of the same size.
8886 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
8887 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
8888 return false; // Cannot transform this return value.
8890 if (!Caller->use_empty() &&
8891 // void -> non-void is handled specially
8892 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
8893 return false; // Cannot transform this return value.
8895 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8896 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8897 if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
8898 return false; // Attribute not compatible with transformed value.
8901 // If the callsite is an invoke instruction, and the return value is used by
8902 // a PHI node in a successor, we cannot change the return type of the call
8903 // because there is no place to put the cast instruction (without breaking
8904 // the critical edge). Bail out in this case.
8905 if (!Caller->use_empty())
8906 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8907 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8909 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8910 if (PN->getParent() == II->getNormalDest() ||
8911 PN->getParent() == II->getUnwindDest())
8915 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8916 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8918 CallSite::arg_iterator AI = CS.arg_begin();
8919 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8920 const Type *ParamTy = FT->getParamType(i);
8921 const Type *ActTy = (*AI)->getType();
8923 if (!CastInst::isCastable(ActTy, ParamTy))
8924 return false; // Cannot transform this parameter value.
8926 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8927 return false; // Attribute not compatible with transformed value.
8929 // Converting from one pointer type to another or between a pointer and an
8930 // integer of the same size is safe even if we do not have a body.
8931 bool isConvertible = ActTy == ParamTy ||
8932 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
8933 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
8934 if (Callee->isDeclaration() && !isConvertible) return false;
8937 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8938 Callee->isDeclaration())
8939 return false; // Do not delete arguments unless we have a function body.
8941 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8942 !CallerPAL.isEmpty())
8943 // In this case we have more arguments than the new function type, but we
8944 // won't be dropping them. Check that these extra arguments have attributes
8945 // that are compatible with being a vararg call argument.
8946 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8947 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
8949 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
8950 if (PAttrs & ParamAttr::VarArgsIncompatible)
8954 // Okay, we decided that this is a safe thing to do: go ahead and start
8955 // inserting cast instructions as necessary...
8956 std::vector<Value*> Args;
8957 Args.reserve(NumActualArgs);
8958 SmallVector<ParamAttrsWithIndex, 8> attrVec;
8959 attrVec.reserve(NumCommonArgs);
8961 // Get any return attributes.
8962 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8964 // If the return value is not being used, the type may not be compatible
8965 // with the existing attributes. Wipe out any problematic attributes.
8966 RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
8968 // Add the new return attributes.
8970 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
8972 AI = CS.arg_begin();
8973 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8974 const Type *ParamTy = FT->getParamType(i);
8975 if ((*AI)->getType() == ParamTy) {
8976 Args.push_back(*AI);
8978 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8979 false, ParamTy, false);
8980 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
8981 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8984 // Add any parameter attributes.
8985 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
8986 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8989 // If the function takes more arguments than the call was taking, add them
8991 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8992 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8994 // If we are removing arguments to the function, emit an obnoxious warning...
8995 if (FT->getNumParams() < NumActualArgs) {
8996 if (!FT->isVarArg()) {
8997 cerr << "WARNING: While resolving call to function '"
8998 << Callee->getName() << "' arguments were dropped!\n";
9000 // Add all of the arguments in their promoted form to the arg list...
9001 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9002 const Type *PTy = getPromotedType((*AI)->getType());
9003 if (PTy != (*AI)->getType()) {
9004 // Must promote to pass through va_arg area!
9005 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9007 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9008 InsertNewInstBefore(Cast, *Caller);
9009 Args.push_back(Cast);
9011 Args.push_back(*AI);
9014 // Add any parameter attributes.
9015 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9016 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9021 if (NewRetTy == Type::VoidTy)
9022 Caller->setName(""); // Void type should not have a name.
9024 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
9027 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9028 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9029 Args.begin(), Args.end(),
9030 Caller->getName(), Caller);
9031 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9032 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
9034 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9035 Caller->getName(), Caller);
9036 CallInst *CI = cast<CallInst>(Caller);
9037 if (CI->isTailCall())
9038 cast<CallInst>(NC)->setTailCall();
9039 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9040 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
9043 // Insert a cast of the return type as necessary.
9045 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9046 if (NV->getType() != Type::VoidTy) {
9047 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
9049 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9051 // If this is an invoke instruction, we should insert it after the first
9052 // non-phi, instruction in the normal successor block.
9053 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9054 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9055 InsertNewInstBefore(NC, *I);
9057 // Otherwise, it's a call, just insert cast right after the call instr
9058 InsertNewInstBefore(NC, *Caller);
9060 AddUsersToWorkList(*Caller);
9062 NV = UndefValue::get(Caller->getType());
9066 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9067 Caller->replaceAllUsesWith(NV);
9068 Caller->eraseFromParent();
9069 RemoveFromWorkList(Caller);
9073 // transformCallThroughTrampoline - Turn a call to a function created by the
9074 // init_trampoline intrinsic into a direct call to the underlying function.
9076 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9077 Value *Callee = CS.getCalledValue();
9078 const PointerType *PTy = cast<PointerType>(Callee->getType());
9079 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9080 const PAListPtr &Attrs = CS.getParamAttrs();
9082 // If the call already has the 'nest' attribute somewhere then give up -
9083 // otherwise 'nest' would occur twice after splicing in the chain.
9084 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
9087 IntrinsicInst *Tramp =
9088 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9090 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9091 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9092 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9094 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9095 if (!NestAttrs.isEmpty()) {
9096 unsigned NestIdx = 1;
9097 const Type *NestTy = 0;
9098 ParameterAttributes NestAttr = ParamAttr::None;
9100 // Look for a parameter marked with the 'nest' attribute.
9101 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9102 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9103 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
9104 // Record the parameter type and any other attributes.
9106 NestAttr = NestAttrs.getParamAttrs(NestIdx);
9111 Instruction *Caller = CS.getInstruction();
9112 std::vector<Value*> NewArgs;
9113 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9115 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9116 NewAttrs.reserve(Attrs.getNumSlots() + 1);
9118 // Insert the nest argument into the call argument list, which may
9119 // mean appending it. Likewise for attributes.
9121 // Add any function result attributes.
9122 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9123 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
9127 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9129 if (Idx == NestIdx) {
9130 // Add the chain argument and attributes.
9131 Value *NestVal = Tramp->getOperand(3);
9132 if (NestVal->getType() != NestTy)
9133 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9134 NewArgs.push_back(NestVal);
9135 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
9141 // Add the original argument and attributes.
9142 NewArgs.push_back(*I);
9143 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
9145 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9151 // The trampoline may have been bitcast to a bogus type (FTy).
9152 // Handle this by synthesizing a new function type, equal to FTy
9153 // with the chain parameter inserted.
9155 std::vector<const Type*> NewTypes;
9156 NewTypes.reserve(FTy->getNumParams()+1);
9158 // Insert the chain's type into the list of parameter types, which may
9159 // mean appending it.
9162 FunctionType::param_iterator I = FTy->param_begin(),
9163 E = FTy->param_end();
9167 // Add the chain's type.
9168 NewTypes.push_back(NestTy);
9173 // Add the original type.
9174 NewTypes.push_back(*I);
9180 // Replace the trampoline call with a direct call. Let the generic
9181 // code sort out any function type mismatches.
9182 FunctionType *NewFTy =
9183 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9184 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9185 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9186 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
9188 Instruction *NewCaller;
9189 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9190 NewCaller = InvokeInst::Create(NewCallee,
9191 II->getNormalDest(), II->getUnwindDest(),
9192 NewArgs.begin(), NewArgs.end(),
9193 Caller->getName(), Caller);
9194 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9195 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
9197 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9198 Caller->getName(), Caller);
9199 if (cast<CallInst>(Caller)->isTailCall())
9200 cast<CallInst>(NewCaller)->setTailCall();
9201 cast<CallInst>(NewCaller)->
9202 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9203 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
9205 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9206 Caller->replaceAllUsesWith(NewCaller);
9207 Caller->eraseFromParent();
9208 RemoveFromWorkList(Caller);
9213 // Replace the trampoline call with a direct call. Since there is no 'nest'
9214 // parameter, there is no need to adjust the argument list. Let the generic
9215 // code sort out any function type mismatches.
9216 Constant *NewCallee =
9217 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9218 CS.setCalledFunction(NewCallee);
9219 return CS.getInstruction();
9222 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9223 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9224 /// and a single binop.
9225 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9226 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9227 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9228 isa<CmpInst>(FirstInst));
9229 unsigned Opc = FirstInst->getOpcode();
9230 Value *LHSVal = FirstInst->getOperand(0);
9231 Value *RHSVal = FirstInst->getOperand(1);
9233 const Type *LHSType = LHSVal->getType();
9234 const Type *RHSType = RHSVal->getType();
9236 // Scan to see if all operands are the same opcode, all have one use, and all
9237 // kill their operands (i.e. the operands have one use).
9238 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9239 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9240 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9241 // Verify type of the LHS matches so we don't fold cmp's of different
9242 // types or GEP's with different index types.
9243 I->getOperand(0)->getType() != LHSType ||
9244 I->getOperand(1)->getType() != RHSType)
9247 // If they are CmpInst instructions, check their predicates
9248 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9249 if (cast<CmpInst>(I)->getPredicate() !=
9250 cast<CmpInst>(FirstInst)->getPredicate())
9253 // Keep track of which operand needs a phi node.
9254 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9255 if (I->getOperand(1) != RHSVal) RHSVal = 0;
9258 // Otherwise, this is safe to transform, determine if it is profitable.
9260 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9261 // Indexes are often folded into load/store instructions, so we don't want to
9262 // hide them behind a phi.
9263 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9266 Value *InLHS = FirstInst->getOperand(0);
9267 Value *InRHS = FirstInst->getOperand(1);
9268 PHINode *NewLHS = 0, *NewRHS = 0;
9270 NewLHS = PHINode::Create(LHSType,
9271 FirstInst->getOperand(0)->getName() + ".pn");
9272 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9273 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9274 InsertNewInstBefore(NewLHS, PN);
9279 NewRHS = PHINode::Create(RHSType,
9280 FirstInst->getOperand(1)->getName() + ".pn");
9281 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9282 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9283 InsertNewInstBefore(NewRHS, PN);
9287 // Add all operands to the new PHIs.
9288 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9290 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9291 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9294 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9295 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9299 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9300 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
9301 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9302 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
9305 assert(isa<GetElementPtrInst>(FirstInst));
9306 return GetElementPtrInst::Create(LHSVal, RHSVal);
9310 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9311 /// of the block that defines it. This means that it must be obvious the value
9312 /// of the load is not changed from the point of the load to the end of the
9315 /// Finally, it is safe, but not profitable, to sink a load targetting a
9316 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
9318 static bool isSafeToSinkLoad(LoadInst *L) {
9319 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9321 for (++BBI; BBI != E; ++BBI)
9322 if (BBI->mayWriteToMemory())
9325 // Check for non-address taken alloca. If not address-taken already, it isn't
9326 // profitable to do this xform.
9327 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9328 bool isAddressTaken = false;
9329 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9331 if (isa<LoadInst>(UI)) continue;
9332 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9333 // If storing TO the alloca, then the address isn't taken.
9334 if (SI->getOperand(1) == AI) continue;
9336 isAddressTaken = true;
9340 if (!isAddressTaken)
9348 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9349 // operator and they all are only used by the PHI, PHI together their
9350 // inputs, and do the operation once, to the result of the PHI.
9351 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9352 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9354 // Scan the instruction, looking for input operations that can be folded away.
9355 // If all input operands to the phi are the same instruction (e.g. a cast from
9356 // the same type or "+42") we can pull the operation through the PHI, reducing
9357 // code size and simplifying code.
9358 Constant *ConstantOp = 0;
9359 const Type *CastSrcTy = 0;
9360 bool isVolatile = false;
9361 if (isa<CastInst>(FirstInst)) {
9362 CastSrcTy = FirstInst->getOperand(0)->getType();
9363 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9364 // Can fold binop, compare or shift here if the RHS is a constant,
9365 // otherwise call FoldPHIArgBinOpIntoPHI.
9366 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9367 if (ConstantOp == 0)
9368 return FoldPHIArgBinOpIntoPHI(PN);
9369 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9370 isVolatile = LI->isVolatile();
9371 // We can't sink the load if the loaded value could be modified between the
9372 // load and the PHI.
9373 if (LI->getParent() != PN.getIncomingBlock(0) ||
9374 !isSafeToSinkLoad(LI))
9377 // If the PHI is of volatile loads and the load block has multiple
9378 // successors, sinking it would remove a load of the volatile value from
9379 // the path through the other successor.
9381 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9384 } else if (isa<GetElementPtrInst>(FirstInst)) {
9385 if (FirstInst->getNumOperands() == 2)
9386 return FoldPHIArgBinOpIntoPHI(PN);
9387 // Can't handle general GEPs yet.
9390 return 0; // Cannot fold this operation.
9393 // Check to see if all arguments are the same operation.
9394 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9395 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9396 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9397 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9400 if (I->getOperand(0)->getType() != CastSrcTy)
9401 return 0; // Cast operation must match.
9402 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9403 // We can't sink the load if the loaded value could be modified between
9404 // the load and the PHI.
9405 if (LI->isVolatile() != isVolatile ||
9406 LI->getParent() != PN.getIncomingBlock(i) ||
9407 !isSafeToSinkLoad(LI))
9410 // If the PHI is of volatile loads and the load block has multiple
9411 // successors, sinking it would remove a load of the volatile value from
9412 // the path through the other successor.
9414 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9418 } else if (I->getOperand(1) != ConstantOp) {
9423 // Okay, they are all the same operation. Create a new PHI node of the
9424 // correct type, and PHI together all of the LHS's of the instructions.
9425 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9426 PN.getName()+".in");
9427 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9429 Value *InVal = FirstInst->getOperand(0);
9430 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9432 // Add all operands to the new PHI.
9433 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9434 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9435 if (NewInVal != InVal)
9437 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9442 // The new PHI unions all of the same values together. This is really
9443 // common, so we handle it intelligently here for compile-time speed.
9447 InsertNewInstBefore(NewPN, PN);
9451 // Insert and return the new operation.
9452 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9453 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
9454 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9455 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
9456 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9457 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
9458 PhiVal, ConstantOp);
9459 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9461 // If this was a volatile load that we are merging, make sure to loop through
9462 // and mark all the input loads as non-volatile. If we don't do this, we will
9463 // insert a new volatile load and the old ones will not be deletable.
9465 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9466 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9468 return new LoadInst(PhiVal, "", isVolatile);
9471 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9473 static bool DeadPHICycle(PHINode *PN,
9474 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9475 if (PN->use_empty()) return true;
9476 if (!PN->hasOneUse()) return false;
9478 // Remember this node, and if we find the cycle, return.
9479 if (!PotentiallyDeadPHIs.insert(PN))
9482 // Don't scan crazily complex things.
9483 if (PotentiallyDeadPHIs.size() == 16)
9486 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9487 return DeadPHICycle(PU, PotentiallyDeadPHIs);
9492 /// PHIsEqualValue - Return true if this phi node is always equal to
9493 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9494 /// z = some value; x = phi (y, z); y = phi (x, z)
9495 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9496 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9497 // See if we already saw this PHI node.
9498 if (!ValueEqualPHIs.insert(PN))
9501 // Don't scan crazily complex things.
9502 if (ValueEqualPHIs.size() == 16)
9505 // Scan the operands to see if they are either phi nodes or are equal to
9507 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9508 Value *Op = PN->getIncomingValue(i);
9509 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9510 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9512 } else if (Op != NonPhiInVal)
9520 // PHINode simplification
9522 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9523 // If LCSSA is around, don't mess with Phi nodes
9524 if (MustPreserveLCSSA) return 0;
9526 if (Value *V = PN.hasConstantValue())
9527 return ReplaceInstUsesWith(PN, V);
9529 // If all PHI operands are the same operation, pull them through the PHI,
9530 // reducing code size.
9531 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9532 PN.getIncomingValue(0)->hasOneUse())
9533 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9536 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9537 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9538 // PHI)... break the cycle.
9539 if (PN.hasOneUse()) {
9540 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9541 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9542 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9543 PotentiallyDeadPHIs.insert(&PN);
9544 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9545 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9548 // If this phi has a single use, and if that use just computes a value for
9549 // the next iteration of a loop, delete the phi. This occurs with unused
9550 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9551 // common case here is good because the only other things that catch this
9552 // are induction variable analysis (sometimes) and ADCE, which is only run
9554 if (PHIUser->hasOneUse() &&
9555 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9556 PHIUser->use_back() == &PN) {
9557 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9561 // We sometimes end up with phi cycles that non-obviously end up being the
9562 // same value, for example:
9563 // z = some value; x = phi (y, z); y = phi (x, z)
9564 // where the phi nodes don't necessarily need to be in the same block. Do a
9565 // quick check to see if the PHI node only contains a single non-phi value, if
9566 // so, scan to see if the phi cycle is actually equal to that value.
9568 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9569 // Scan for the first non-phi operand.
9570 while (InValNo != NumOperandVals &&
9571 isa<PHINode>(PN.getIncomingValue(InValNo)))
9574 if (InValNo != NumOperandVals) {
9575 Value *NonPhiInVal = PN.getOperand(InValNo);
9577 // Scan the rest of the operands to see if there are any conflicts, if so
9578 // there is no need to recursively scan other phis.
9579 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9580 Value *OpVal = PN.getIncomingValue(InValNo);
9581 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9585 // If we scanned over all operands, then we have one unique value plus
9586 // phi values. Scan PHI nodes to see if they all merge in each other or
9588 if (InValNo == NumOperandVals) {
9589 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9590 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9591 return ReplaceInstUsesWith(PN, NonPhiInVal);
9598 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9599 Instruction *InsertPoint,
9601 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9602 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9603 // We must cast correctly to the pointer type. Ensure that we
9604 // sign extend the integer value if it is smaller as this is
9605 // used for address computation.
9606 Instruction::CastOps opcode =
9607 (VTySize < PtrSize ? Instruction::SExt :
9608 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9609 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9613 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9614 Value *PtrOp = GEP.getOperand(0);
9615 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
9616 // If so, eliminate the noop.
9617 if (GEP.getNumOperands() == 1)
9618 return ReplaceInstUsesWith(GEP, PtrOp);
9620 if (isa<UndefValue>(GEP.getOperand(0)))
9621 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9623 bool HasZeroPointerIndex = false;
9624 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9625 HasZeroPointerIndex = C->isNullValue();
9627 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9628 return ReplaceInstUsesWith(GEP, PtrOp);
9630 // Eliminate unneeded casts for indices.
9631 bool MadeChange = false;
9633 gep_type_iterator GTI = gep_type_begin(GEP);
9634 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9635 i != e; ++i, ++GTI) {
9636 if (isa<SequentialType>(*GTI)) {
9637 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
9638 if (CI->getOpcode() == Instruction::ZExt ||
9639 CI->getOpcode() == Instruction::SExt) {
9640 const Type *SrcTy = CI->getOperand(0)->getType();
9641 // We can eliminate a cast from i32 to i64 iff the target
9642 // is a 32-bit pointer target.
9643 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9645 *i = CI->getOperand(0);
9649 // If we are using a wider index than needed for this platform, shrink it
9650 // to what we need. If the incoming value needs a cast instruction,
9651 // insert it. This explicit cast can make subsequent optimizations more
9654 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
9655 if (Constant *C = dyn_cast<Constant>(Op)) {
9656 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
9659 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9667 if (MadeChange) return &GEP;
9669 // If this GEP instruction doesn't move the pointer, and if the input operand
9670 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9671 // real input to the dest type.
9672 if (GEP.hasAllZeroIndices()) {
9673 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9674 // If the bitcast is of an allocation, and the allocation will be
9675 // converted to match the type of the cast, don't touch this.
9676 if (isa<AllocationInst>(BCI->getOperand(0))) {
9677 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
9678 if (Instruction *I = visitBitCast(*BCI)) {
9681 BCI->getParent()->getInstList().insert(BCI, I);
9682 ReplaceInstUsesWith(*BCI, I);
9687 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9691 // Combine Indices - If the source pointer to this getelementptr instruction
9692 // is a getelementptr instruction, combine the indices of the two
9693 // getelementptr instructions into a single instruction.
9695 SmallVector<Value*, 8> SrcGEPOperands;
9696 if (User *Src = dyn_castGetElementPtr(PtrOp))
9697 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9699 if (!SrcGEPOperands.empty()) {
9700 // Note that if our source is a gep chain itself that we wait for that
9701 // chain to be resolved before we perform this transformation. This
9702 // avoids us creating a TON of code in some cases.
9704 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9705 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9706 return 0; // Wait until our source is folded to completion.
9708 SmallVector<Value*, 8> Indices;
9710 // Find out whether the last index in the source GEP is a sequential idx.
9711 bool EndsWithSequential = false;
9712 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9713 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9714 EndsWithSequential = !isa<StructType>(*I);
9716 // Can we combine the two pointer arithmetics offsets?
9717 if (EndsWithSequential) {
9718 // Replace: gep (gep %P, long B), long A, ...
9719 // With: T = long A+B; gep %P, T, ...
9721 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9722 if (SO1 == Constant::getNullValue(SO1->getType())) {
9724 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9727 // If they aren't the same type, convert both to an integer of the
9728 // target's pointer size.
9729 if (SO1->getType() != GO1->getType()) {
9730 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9731 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9732 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9733 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9735 unsigned PS = TD->getPointerSizeInBits();
9736 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
9737 // Convert GO1 to SO1's type.
9738 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9740 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
9741 // Convert SO1 to GO1's type.
9742 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9744 const Type *PT = TD->getIntPtrType();
9745 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9746 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9750 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9751 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9753 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
9754 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9758 // Recycle the GEP we already have if possible.
9759 if (SrcGEPOperands.size() == 2) {
9760 GEP.setOperand(0, SrcGEPOperands[0]);
9761 GEP.setOperand(1, Sum);
9764 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9765 SrcGEPOperands.end()-1);
9766 Indices.push_back(Sum);
9767 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9769 } else if (isa<Constant>(*GEP.idx_begin()) &&
9770 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9771 SrcGEPOperands.size() != 1) {
9772 // Otherwise we can do the fold if the first index of the GEP is a zero
9773 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9774 SrcGEPOperands.end());
9775 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9778 if (!Indices.empty())
9779 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9780 Indices.end(), GEP.getName());
9782 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9783 // GEP of global variable. If all of the indices for this GEP are
9784 // constants, we can promote this to a constexpr instead of an instruction.
9786 // Scan for nonconstants...
9787 SmallVector<Constant*, 8> Indices;
9788 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9789 for (; I != E && isa<Constant>(*I); ++I)
9790 Indices.push_back(cast<Constant>(*I));
9792 if (I == E) { // If they are all constants...
9793 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9794 &Indices[0],Indices.size());
9796 // Replace all uses of the GEP with the new constexpr...
9797 return ReplaceInstUsesWith(GEP, CE);
9799 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
9800 if (!isa<PointerType>(X->getType())) {
9801 // Not interesting. Source pointer must be a cast from pointer.
9802 } else if (HasZeroPointerIndex) {
9803 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9804 // into : GEP [10 x i8]* X, i32 0, ...
9806 // This occurs when the program declares an array extern like "int X[];"
9808 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9809 const PointerType *XTy = cast<PointerType>(X->getType());
9810 if (const ArrayType *XATy =
9811 dyn_cast<ArrayType>(XTy->getElementType()))
9812 if (const ArrayType *CATy =
9813 dyn_cast<ArrayType>(CPTy->getElementType()))
9814 if (CATy->getElementType() == XATy->getElementType()) {
9815 // At this point, we know that the cast source type is a pointer
9816 // to an array of the same type as the destination pointer
9817 // array. Because the array type is never stepped over (there
9818 // is a leading zero) we can fold the cast into this GEP.
9819 GEP.setOperand(0, X);
9822 } else if (GEP.getNumOperands() == 2) {
9823 // Transform things like:
9824 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9825 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
9826 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9827 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9828 if (isa<ArrayType>(SrcElTy) &&
9829 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9830 TD->getABITypeSize(ResElTy)) {
9832 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9833 Idx[1] = GEP.getOperand(1);
9834 Value *V = InsertNewInstBefore(
9835 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
9836 // V and GEP are both pointer types --> BitCast
9837 return new BitCastInst(V, GEP.getType());
9840 // Transform things like:
9841 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
9842 // (where tmp = 8*tmp2) into:
9843 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
9845 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
9846 uint64_t ArrayEltSize =
9847 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
9849 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9850 // allow either a mul, shift, or constant here.
9852 ConstantInt *Scale = 0;
9853 if (ArrayEltSize == 1) {
9854 NewIdx = GEP.getOperand(1);
9855 Scale = ConstantInt::get(NewIdx->getType(), 1);
9856 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9857 NewIdx = ConstantInt::get(CI->getType(), 1);
9859 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9860 if (Inst->getOpcode() == Instruction::Shl &&
9861 isa<ConstantInt>(Inst->getOperand(1))) {
9862 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9863 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9864 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9865 NewIdx = Inst->getOperand(0);
9866 } else if (Inst->getOpcode() == Instruction::Mul &&
9867 isa<ConstantInt>(Inst->getOperand(1))) {
9868 Scale = cast<ConstantInt>(Inst->getOperand(1));
9869 NewIdx = Inst->getOperand(0);
9873 // If the index will be to exactly the right offset with the scale taken
9874 // out, perform the transformation. Note, we don't know whether Scale is
9875 // signed or not. We'll use unsigned version of division/modulo
9876 // operation after making sure Scale doesn't have the sign bit set.
9877 if (Scale && Scale->getSExtValue() >= 0LL &&
9878 Scale->getZExtValue() % ArrayEltSize == 0) {
9879 Scale = ConstantInt::get(Scale->getType(),
9880 Scale->getZExtValue() / ArrayEltSize);
9881 if (Scale->getZExtValue() != 1) {
9882 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
9884 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
9885 NewIdx = InsertNewInstBefore(Sc, GEP);
9888 // Insert the new GEP instruction.
9890 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9892 Instruction *NewGEP =
9893 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
9894 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9895 // The NewGEP must be pointer typed, so must the old one -> BitCast
9896 return new BitCastInst(NewGEP, GEP.getType());
9905 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9906 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9907 if (AI.isArrayAllocation()) { // Check C != 1
9908 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9910 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9911 AllocationInst *New = 0;
9913 // Create and insert the replacement instruction...
9914 if (isa<MallocInst>(AI))
9915 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9917 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9918 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9921 InsertNewInstBefore(New, AI);
9923 // Scan to the end of the allocation instructions, to skip over a block of
9924 // allocas if possible...
9926 BasicBlock::iterator It = New;
9927 while (isa<AllocationInst>(*It)) ++It;
9929 // Now that I is pointing to the first non-allocation-inst in the block,
9930 // insert our getelementptr instruction...
9932 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
9936 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9937 New->getName()+".sub", It);
9939 // Now make everything use the getelementptr instead of the original
9941 return ReplaceInstUsesWith(AI, V);
9942 } else if (isa<UndefValue>(AI.getArraySize())) {
9943 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9947 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9948 // Note that we only do this for alloca's, because malloc should allocate and
9949 // return a unique pointer, even for a zero byte allocation.
9950 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
9951 TD->getABITypeSize(AI.getAllocatedType()) == 0)
9952 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9957 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9958 Value *Op = FI.getOperand(0);
9960 // free undef -> unreachable.
9961 if (isa<UndefValue>(Op)) {
9962 // Insert a new store to null because we cannot modify the CFG here.
9963 new StoreInst(ConstantInt::getTrue(),
9964 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
9965 return EraseInstFromFunction(FI);
9968 // If we have 'free null' delete the instruction. This can happen in stl code
9969 // when lots of inlining happens.
9970 if (isa<ConstantPointerNull>(Op))
9971 return EraseInstFromFunction(FI);
9973 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9974 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9975 FI.setOperand(0, CI->getOperand(0));
9979 // Change free (gep X, 0,0,0,0) into free(X)
9980 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9981 if (GEPI->hasAllZeroIndices()) {
9982 AddToWorkList(GEPI);
9983 FI.setOperand(0, GEPI->getOperand(0));
9988 // Change free(malloc) into nothing, if the malloc has a single use.
9989 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9990 if (MI->hasOneUse()) {
9991 EraseInstFromFunction(FI);
9992 return EraseInstFromFunction(*MI);
9999 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10000 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10001 const TargetData *TD) {
10002 User *CI = cast<User>(LI.getOperand(0));
10003 Value *CastOp = CI->getOperand(0);
10005 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10006 // Instead of loading constant c string, use corresponding integer value
10007 // directly if string length is small enough.
10009 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
10010 unsigned len = Str.length();
10011 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10012 unsigned numBits = Ty->getPrimitiveSizeInBits();
10013 // Replace LI with immediate integer store.
10014 if ((numBits >> 3) == len + 1) {
10015 APInt StrVal(numBits, 0);
10016 APInt SingleChar(numBits, 0);
10017 if (TD->isLittleEndian()) {
10018 for (signed i = len-1; i >= 0; i--) {
10019 SingleChar = (uint64_t) Str[i];
10020 StrVal = (StrVal << 8) | SingleChar;
10023 for (unsigned i = 0; i < len; i++) {
10024 SingleChar = (uint64_t) Str[i];
10025 StrVal = (StrVal << 8) | SingleChar;
10027 // Append NULL at the end.
10029 StrVal = (StrVal << 8) | SingleChar;
10031 Value *NL = ConstantInt::get(StrVal);
10032 return IC.ReplaceInstUsesWith(LI, NL);
10037 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10038 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10039 const Type *SrcPTy = SrcTy->getElementType();
10041 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
10042 isa<VectorType>(DestPTy)) {
10043 // If the source is an array, the code below will not succeed. Check to
10044 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10046 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10047 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10048 if (ASrcTy->getNumElements() != 0) {
10050 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10051 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10052 SrcTy = cast<PointerType>(CastOp->getType());
10053 SrcPTy = SrcTy->getElementType();
10056 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
10057 isa<VectorType>(SrcPTy)) &&
10058 // Do not allow turning this into a load of an integer, which is then
10059 // casted to a pointer, this pessimizes pointer analysis a lot.
10060 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10061 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10062 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10064 // Okay, we are casting from one integer or pointer type to another of
10065 // the same size. Instead of casting the pointer before the load, cast
10066 // the result of the loaded value.
10067 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10069 LI.isVolatile()),LI);
10070 // Now cast the result of the load.
10071 return new BitCastInst(NewLoad, LI.getType());
10078 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10079 /// from this value cannot trap. If it is not obviously safe to load from the
10080 /// specified pointer, we do a quick local scan of the basic block containing
10081 /// ScanFrom, to determine if the address is already accessed.
10082 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10083 // If it is an alloca it is always safe to load from.
10084 if (isa<AllocaInst>(V)) return true;
10086 // If it is a global variable it is mostly safe to load from.
10087 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10088 // Don't try to evaluate aliases. External weak GV can be null.
10089 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10091 // Otherwise, be a little bit agressive by scanning the local block where we
10092 // want to check to see if the pointer is already being loaded or stored
10093 // from/to. If so, the previous load or store would have already trapped,
10094 // so there is no harm doing an extra load (also, CSE will later eliminate
10095 // the load entirely).
10096 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10101 // If we see a free or a call (which might do a free) the pointer could be
10103 if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10106 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10107 if (LI->getOperand(0) == V) return true;
10108 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
10109 if (SI->getOperand(1) == V) return true;
10116 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10117 /// until we find the underlying object a pointer is referring to or something
10118 /// we don't understand. Note that the returned pointer may be offset from the
10119 /// input, because we ignore GEP indices.
10120 static Value *GetUnderlyingObject(Value *Ptr) {
10122 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10123 if (CE->getOpcode() == Instruction::BitCast ||
10124 CE->getOpcode() == Instruction::GetElementPtr)
10125 Ptr = CE->getOperand(0);
10128 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10129 Ptr = BCI->getOperand(0);
10130 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10131 Ptr = GEP->getOperand(0);
10138 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10139 Value *Op = LI.getOperand(0);
10141 // Attempt to improve the alignment.
10142 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10144 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10145 LI.getAlignment()))
10146 LI.setAlignment(KnownAlign);
10148 // load (cast X) --> cast (load X) iff safe
10149 if (isa<CastInst>(Op))
10150 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10153 // None of the following transforms are legal for volatile loads.
10154 if (LI.isVolatile()) return 0;
10156 if (&LI.getParent()->front() != &LI) {
10157 BasicBlock::iterator BBI = &LI; --BBI;
10158 // If the instruction immediately before this is a store to the same
10159 // address, do a simple form of store->load forwarding.
10160 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10161 if (SI->getOperand(1) == LI.getOperand(0))
10162 return ReplaceInstUsesWith(LI, SI->getOperand(0));
10163 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10164 if (LIB->getOperand(0) == LI.getOperand(0))
10165 return ReplaceInstUsesWith(LI, LIB);
10168 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10169 const Value *GEPI0 = GEPI->getOperand(0);
10170 // TODO: Consider a target hook for valid address spaces for this xform.
10171 if (isa<ConstantPointerNull>(GEPI0) &&
10172 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10173 // Insert a new store to null instruction before the load to indicate
10174 // that this code is not reachable. We do this instead of inserting
10175 // an unreachable instruction directly because we cannot modify the
10177 new StoreInst(UndefValue::get(LI.getType()),
10178 Constant::getNullValue(Op->getType()), &LI);
10179 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10183 if (Constant *C = dyn_cast<Constant>(Op)) {
10184 // load null/undef -> undef
10185 // TODO: Consider a target hook for valid address spaces for this xform.
10186 if (isa<UndefValue>(C) || (C->isNullValue() &&
10187 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10188 // Insert a new store to null instruction before the load to indicate that
10189 // this code is not reachable. We do this instead of inserting an
10190 // unreachable instruction directly because we cannot modify the CFG.
10191 new StoreInst(UndefValue::get(LI.getType()),
10192 Constant::getNullValue(Op->getType()), &LI);
10193 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10196 // Instcombine load (constant global) into the value loaded.
10197 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10198 if (GV->isConstant() && !GV->isDeclaration())
10199 return ReplaceInstUsesWith(LI, GV->getInitializer());
10201 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10202 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10203 if (CE->getOpcode() == Instruction::GetElementPtr) {
10204 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10205 if (GV->isConstant() && !GV->isDeclaration())
10207 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10208 return ReplaceInstUsesWith(LI, V);
10209 if (CE->getOperand(0)->isNullValue()) {
10210 // Insert a new store to null instruction before the load to indicate
10211 // that this code is not reachable. We do this instead of inserting
10212 // an unreachable instruction directly because we cannot modify the
10214 new StoreInst(UndefValue::get(LI.getType()),
10215 Constant::getNullValue(Op->getType()), &LI);
10216 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10219 } else if (CE->isCast()) {
10220 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10226 // If this load comes from anywhere in a constant global, and if the global
10227 // is all undef or zero, we know what it loads.
10228 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10229 if (GV->isConstant() && GV->hasInitializer()) {
10230 if (GV->getInitializer()->isNullValue())
10231 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10232 else if (isa<UndefValue>(GV->getInitializer()))
10233 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10237 if (Op->hasOneUse()) {
10238 // Change select and PHI nodes to select values instead of addresses: this
10239 // helps alias analysis out a lot, allows many others simplifications, and
10240 // exposes redundancy in the code.
10242 // Note that we cannot do the transformation unless we know that the
10243 // introduced loads cannot trap! Something like this is valid as long as
10244 // the condition is always false: load (select bool %C, int* null, int* %G),
10245 // but it would not be valid if we transformed it to load from null
10246 // unconditionally.
10248 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10249 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
10250 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10251 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10252 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10253 SI->getOperand(1)->getName()+".val"), LI);
10254 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10255 SI->getOperand(2)->getName()+".val"), LI);
10256 return SelectInst::Create(SI->getCondition(), V1, V2);
10259 // load (select (cond, null, P)) -> load P
10260 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10261 if (C->isNullValue()) {
10262 LI.setOperand(0, SI->getOperand(2));
10266 // load (select (cond, P, null)) -> load P
10267 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10268 if (C->isNullValue()) {
10269 LI.setOperand(0, SI->getOperand(1));
10277 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10279 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10280 User *CI = cast<User>(SI.getOperand(1));
10281 Value *CastOp = CI->getOperand(0);
10283 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10284 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10285 const Type *SrcPTy = SrcTy->getElementType();
10287 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10288 // If the source is an array, the code below will not succeed. Check to
10289 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10291 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10292 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10293 if (ASrcTy->getNumElements() != 0) {
10295 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10296 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10297 SrcTy = cast<PointerType>(CastOp->getType());
10298 SrcPTy = SrcTy->getElementType();
10301 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10302 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10303 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10305 // Okay, we are casting from one integer or pointer type to another of
10306 // the same size. Instead of casting the pointer before
10307 // the store, cast the value to be stored.
10309 Value *SIOp0 = SI.getOperand(0);
10310 Instruction::CastOps opcode = Instruction::BitCast;
10311 const Type* CastSrcTy = SIOp0->getType();
10312 const Type* CastDstTy = SrcPTy;
10313 if (isa<PointerType>(CastDstTy)) {
10314 if (CastSrcTy->isInteger())
10315 opcode = Instruction::IntToPtr;
10316 } else if (isa<IntegerType>(CastDstTy)) {
10317 if (isa<PointerType>(SIOp0->getType()))
10318 opcode = Instruction::PtrToInt;
10320 if (Constant *C = dyn_cast<Constant>(SIOp0))
10321 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10323 NewCast = IC.InsertNewInstBefore(
10324 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
10326 return new StoreInst(NewCast, CastOp);
10333 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10334 Value *Val = SI.getOperand(0);
10335 Value *Ptr = SI.getOperand(1);
10337 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
10338 EraseInstFromFunction(SI);
10343 // If the RHS is an alloca with a single use, zapify the store, making the
10345 if (Ptr->hasOneUse() && !SI.isVolatile()) {
10346 if (isa<AllocaInst>(Ptr)) {
10347 EraseInstFromFunction(SI);
10352 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10353 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10354 GEP->getOperand(0)->hasOneUse()) {
10355 EraseInstFromFunction(SI);
10361 // Attempt to improve the alignment.
10362 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10364 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10365 SI.getAlignment()))
10366 SI.setAlignment(KnownAlign);
10368 // Do really simple DSE, to catch cases where there are several consequtive
10369 // stores to the same location, separated by a few arithmetic operations. This
10370 // situation often occurs with bitfield accesses.
10371 BasicBlock::iterator BBI = &SI;
10372 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10376 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10377 // Prev store isn't volatile, and stores to the same location?
10378 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10381 EraseInstFromFunction(*PrevSI);
10387 // If this is a load, we have to stop. However, if the loaded value is from
10388 // the pointer we're loading and is producing the pointer we're storing,
10389 // then *this* store is dead (X = load P; store X -> P).
10390 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10391 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
10392 EraseInstFromFunction(SI);
10396 // Otherwise, this is a load from some other location. Stores before it
10397 // may not be dead.
10401 // Don't skip over loads or things that can modify memory.
10402 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
10407 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
10409 // store X, null -> turns into 'unreachable' in SimplifyCFG
10410 if (isa<ConstantPointerNull>(Ptr)) {
10411 if (!isa<UndefValue>(Val)) {
10412 SI.setOperand(0, UndefValue::get(Val->getType()));
10413 if (Instruction *U = dyn_cast<Instruction>(Val))
10414 AddToWorkList(U); // Dropped a use.
10417 return 0; // Do not modify these!
10420 // store undef, Ptr -> noop
10421 if (isa<UndefValue>(Val)) {
10422 EraseInstFromFunction(SI);
10427 // If the pointer destination is a cast, see if we can fold the cast into the
10429 if (isa<CastInst>(Ptr))
10430 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10432 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10434 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10438 // If this store is the last instruction in the basic block, and if the block
10439 // ends with an unconditional branch, try to move it to the successor block.
10441 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10442 if (BI->isUnconditional())
10443 if (SimplifyStoreAtEndOfBlock(SI))
10444 return 0; // xform done!
10449 /// SimplifyStoreAtEndOfBlock - Turn things like:
10450 /// if () { *P = v1; } else { *P = v2 }
10451 /// into a phi node with a store in the successor.
10453 /// Simplify things like:
10454 /// *P = v1; if () { *P = v2; }
10455 /// into a phi node with a store in the successor.
10457 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10458 BasicBlock *StoreBB = SI.getParent();
10460 // Check to see if the successor block has exactly two incoming edges. If
10461 // so, see if the other predecessor contains a store to the same location.
10462 // if so, insert a PHI node (if needed) and move the stores down.
10463 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10465 // Determine whether Dest has exactly two predecessors and, if so, compute
10466 // the other predecessor.
10467 pred_iterator PI = pred_begin(DestBB);
10468 BasicBlock *OtherBB = 0;
10469 if (*PI != StoreBB)
10472 if (PI == pred_end(DestBB))
10475 if (*PI != StoreBB) {
10480 if (++PI != pred_end(DestBB))
10483 // Bail out if all the relevant blocks aren't distinct (this can happen,
10484 // for example, if SI is in an infinite loop)
10485 if (StoreBB == DestBB || OtherBB == DestBB)
10488 // Verify that the other block ends in a branch and is not otherwise empty.
10489 BasicBlock::iterator BBI = OtherBB->getTerminator();
10490 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10491 if (!OtherBr || BBI == OtherBB->begin())
10494 // If the other block ends in an unconditional branch, check for the 'if then
10495 // else' case. there is an instruction before the branch.
10496 StoreInst *OtherStore = 0;
10497 if (OtherBr->isUnconditional()) {
10498 // If this isn't a store, or isn't a store to the same location, bail out.
10500 OtherStore = dyn_cast<StoreInst>(BBI);
10501 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10504 // Otherwise, the other block ended with a conditional branch. If one of the
10505 // destinations is StoreBB, then we have the if/then case.
10506 if (OtherBr->getSuccessor(0) != StoreBB &&
10507 OtherBr->getSuccessor(1) != StoreBB)
10510 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10511 // if/then triangle. See if there is a store to the same ptr as SI that
10512 // lives in OtherBB.
10514 // Check to see if we find the matching store.
10515 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10516 if (OtherStore->getOperand(1) != SI.getOperand(1))
10520 // If we find something that may be using or overwriting the stored
10521 // value, or if we run out of instructions, we can't do the xform.
10522 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
10523 BBI == OtherBB->begin())
10527 // In order to eliminate the store in OtherBr, we have to
10528 // make sure nothing reads or overwrites the stored value in
10530 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10531 // FIXME: This should really be AA driven.
10532 if (I->mayReadFromMemory() || I->mayWriteToMemory())
10537 // Insert a PHI node now if we need it.
10538 Value *MergedVal = OtherStore->getOperand(0);
10539 if (MergedVal != SI.getOperand(0)) {
10540 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
10541 PN->reserveOperandSpace(2);
10542 PN->addIncoming(SI.getOperand(0), SI.getParent());
10543 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10544 MergedVal = InsertNewInstBefore(PN, DestBB->front());
10547 // Advance to a place where it is safe to insert the new store and
10549 BBI = DestBB->getFirstNonPHI();
10550 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10551 OtherStore->isVolatile()), *BBI);
10553 // Nuke the old stores.
10554 EraseInstFromFunction(SI);
10555 EraseInstFromFunction(*OtherStore);
10561 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10562 // Change br (not X), label True, label False to: br X, label False, True
10564 BasicBlock *TrueDest;
10565 BasicBlock *FalseDest;
10566 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10567 !isa<Constant>(X)) {
10568 // Swap Destinations and condition...
10569 BI.setCondition(X);
10570 BI.setSuccessor(0, FalseDest);
10571 BI.setSuccessor(1, TrueDest);
10575 // Cannonicalize fcmp_one -> fcmp_oeq
10576 FCmpInst::Predicate FPred; Value *Y;
10577 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10578 TrueDest, FalseDest)))
10579 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10580 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10581 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10582 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10583 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10584 NewSCC->takeName(I);
10585 // Swap Destinations and condition...
10586 BI.setCondition(NewSCC);
10587 BI.setSuccessor(0, FalseDest);
10588 BI.setSuccessor(1, TrueDest);
10589 RemoveFromWorkList(I);
10590 I->eraseFromParent();
10591 AddToWorkList(NewSCC);
10595 // Cannonicalize icmp_ne -> icmp_eq
10596 ICmpInst::Predicate IPred;
10597 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10598 TrueDest, FalseDest)))
10599 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10600 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10601 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10602 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10603 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10604 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10605 NewSCC->takeName(I);
10606 // Swap Destinations and condition...
10607 BI.setCondition(NewSCC);
10608 BI.setSuccessor(0, FalseDest);
10609 BI.setSuccessor(1, TrueDest);
10610 RemoveFromWorkList(I);
10611 I->eraseFromParent();;
10612 AddToWorkList(NewSCC);
10619 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10620 Value *Cond = SI.getCondition();
10621 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10622 if (I->getOpcode() == Instruction::Add)
10623 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10624 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10625 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10626 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10628 SI.setOperand(0, I->getOperand(0));
10636 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
10637 // See if we are trying to extract a known value. If so, use that instead.
10638 if (Value *Elt = FindInsertedValue(EV.getOperand(0), EV.idx_begin(),
10639 EV.idx_end(), &EV))
10640 return ReplaceInstUsesWith(EV, Elt);
10646 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10647 /// is to leave as a vector operation.
10648 static bool CheapToScalarize(Value *V, bool isConstant) {
10649 if (isa<ConstantAggregateZero>(V))
10651 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10652 if (isConstant) return true;
10653 // If all elts are the same, we can extract.
10654 Constant *Op0 = C->getOperand(0);
10655 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10656 if (C->getOperand(i) != Op0)
10660 Instruction *I = dyn_cast<Instruction>(V);
10661 if (!I) return false;
10663 // Insert element gets simplified to the inserted element or is deleted if
10664 // this is constant idx extract element and its a constant idx insertelt.
10665 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10666 isa<ConstantInt>(I->getOperand(2)))
10668 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10670 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10671 if (BO->hasOneUse() &&
10672 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10673 CheapToScalarize(BO->getOperand(1), isConstant)))
10675 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10676 if (CI->hasOneUse() &&
10677 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10678 CheapToScalarize(CI->getOperand(1), isConstant)))
10684 /// Read and decode a shufflevector mask.
10686 /// It turns undef elements into values that are larger than the number of
10687 /// elements in the input.
10688 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10689 unsigned NElts = SVI->getType()->getNumElements();
10690 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10691 return std::vector<unsigned>(NElts, 0);
10692 if (isa<UndefValue>(SVI->getOperand(2)))
10693 return std::vector<unsigned>(NElts, 2*NElts);
10695 std::vector<unsigned> Result;
10696 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10697 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
10698 if (isa<UndefValue>(*i))
10699 Result.push_back(NElts*2); // undef -> 8
10701 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
10705 /// FindScalarElement - Given a vector and an element number, see if the scalar
10706 /// value is already around as a register, for example if it were inserted then
10707 /// extracted from the vector.
10708 static Value *FindScalarElement(Value *V, unsigned EltNo) {
10709 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10710 const VectorType *PTy = cast<VectorType>(V->getType());
10711 unsigned Width = PTy->getNumElements();
10712 if (EltNo >= Width) // Out of range access.
10713 return UndefValue::get(PTy->getElementType());
10715 if (isa<UndefValue>(V))
10716 return UndefValue::get(PTy->getElementType());
10717 else if (isa<ConstantAggregateZero>(V))
10718 return Constant::getNullValue(PTy->getElementType());
10719 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10720 return CP->getOperand(EltNo);
10721 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10722 // If this is an insert to a variable element, we don't know what it is.
10723 if (!isa<ConstantInt>(III->getOperand(2)))
10725 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10727 // If this is an insert to the element we are looking for, return the
10729 if (EltNo == IIElt)
10730 return III->getOperand(1);
10732 // Otherwise, the insertelement doesn't modify the value, recurse on its
10734 return FindScalarElement(III->getOperand(0), EltNo);
10735 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10736 unsigned InEl = getShuffleMask(SVI)[EltNo];
10738 return FindScalarElement(SVI->getOperand(0), InEl);
10739 else if (InEl < Width*2)
10740 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10742 return UndefValue::get(PTy->getElementType());
10745 // Otherwise, we don't know.
10749 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10750 // If vector val is undef, replace extract with scalar undef.
10751 if (isa<UndefValue>(EI.getOperand(0)))
10752 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10754 // If vector val is constant 0, replace extract with scalar 0.
10755 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10756 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10758 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10759 // If vector val is constant with all elements the same, replace EI with
10760 // that element. When the elements are not identical, we cannot replace yet
10761 // (we do that below, but only when the index is constant).
10762 Constant *op0 = C->getOperand(0);
10763 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10764 if (C->getOperand(i) != op0) {
10769 return ReplaceInstUsesWith(EI, op0);
10772 // If extracting a specified index from the vector, see if we can recursively
10773 // find a previously computed scalar that was inserted into the vector.
10774 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10775 unsigned IndexVal = IdxC->getZExtValue();
10776 unsigned VectorWidth =
10777 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10779 // If this is extracting an invalid index, turn this into undef, to avoid
10780 // crashing the code below.
10781 if (IndexVal >= VectorWidth)
10782 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10784 // This instruction only demands the single element from the input vector.
10785 // If the input vector has a single use, simplify it based on this use
10787 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10788 uint64_t UndefElts;
10789 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10792 EI.setOperand(0, V);
10797 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10798 return ReplaceInstUsesWith(EI, Elt);
10800 // If the this extractelement is directly using a bitcast from a vector of
10801 // the same number of elements, see if we can find the source element from
10802 // it. In this case, we will end up needing to bitcast the scalars.
10803 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10804 if (const VectorType *VT =
10805 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10806 if (VT->getNumElements() == VectorWidth)
10807 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10808 return new BitCastInst(Elt, EI.getType());
10812 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10813 if (I->hasOneUse()) {
10814 // Push extractelement into predecessor operation if legal and
10815 // profitable to do so
10816 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10817 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10818 if (CheapToScalarize(BO, isConstantElt)) {
10819 ExtractElementInst *newEI0 =
10820 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10821 EI.getName()+".lhs");
10822 ExtractElementInst *newEI1 =
10823 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10824 EI.getName()+".rhs");
10825 InsertNewInstBefore(newEI0, EI);
10826 InsertNewInstBefore(newEI1, EI);
10827 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
10829 } else if (isa<LoadInst>(I)) {
10831 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
10832 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10833 PointerType::get(EI.getType(), AS),EI);
10834 GetElementPtrInst *GEP =
10835 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
10836 InsertNewInstBefore(GEP, EI);
10837 return new LoadInst(GEP);
10840 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10841 // Extracting the inserted element?
10842 if (IE->getOperand(2) == EI.getOperand(1))
10843 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10844 // If the inserted and extracted elements are constants, they must not
10845 // be the same value, extract from the pre-inserted value instead.
10846 if (isa<Constant>(IE->getOperand(2)) &&
10847 isa<Constant>(EI.getOperand(1))) {
10848 AddUsesToWorkList(EI);
10849 EI.setOperand(0, IE->getOperand(0));
10852 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10853 // If this is extracting an element from a shufflevector, figure out where
10854 // it came from and extract from the appropriate input element instead.
10855 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10856 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10858 if (SrcIdx < SVI->getType()->getNumElements())
10859 Src = SVI->getOperand(0);
10860 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10861 SrcIdx -= SVI->getType()->getNumElements();
10862 Src = SVI->getOperand(1);
10864 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10866 return new ExtractElementInst(Src, SrcIdx);
10873 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10874 /// elements from either LHS or RHS, return the shuffle mask and true.
10875 /// Otherwise, return false.
10876 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10877 std::vector<Constant*> &Mask) {
10878 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10879 "Invalid CollectSingleShuffleElements");
10880 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10882 if (isa<UndefValue>(V)) {
10883 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10885 } else if (V == LHS) {
10886 for (unsigned i = 0; i != NumElts; ++i)
10887 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10889 } else if (V == RHS) {
10890 for (unsigned i = 0; i != NumElts; ++i)
10891 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10893 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10894 // If this is an insert of an extract from some other vector, include it.
10895 Value *VecOp = IEI->getOperand(0);
10896 Value *ScalarOp = IEI->getOperand(1);
10897 Value *IdxOp = IEI->getOperand(2);
10899 if (!isa<ConstantInt>(IdxOp))
10901 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10903 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10904 // Okay, we can handle this if the vector we are insertinting into is
10905 // transitively ok.
10906 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10907 // If so, update the mask to reflect the inserted undef.
10908 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10911 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10912 if (isa<ConstantInt>(EI->getOperand(1)) &&
10913 EI->getOperand(0)->getType() == V->getType()) {
10914 unsigned ExtractedIdx =
10915 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10917 // This must be extracting from either LHS or RHS.
10918 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10919 // Okay, we can handle this if the vector we are insertinting into is
10920 // transitively ok.
10921 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10922 // If so, update the mask to reflect the inserted value.
10923 if (EI->getOperand(0) == LHS) {
10924 Mask[InsertedIdx & (NumElts-1)] =
10925 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10927 assert(EI->getOperand(0) == RHS);
10928 Mask[InsertedIdx & (NumElts-1)] =
10929 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10938 // TODO: Handle shufflevector here!
10943 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10944 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10945 /// that computes V and the LHS value of the shuffle.
10946 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10948 assert(isa<VectorType>(V->getType()) &&
10949 (RHS == 0 || V->getType() == RHS->getType()) &&
10950 "Invalid shuffle!");
10951 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10953 if (isa<UndefValue>(V)) {
10954 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10956 } else if (isa<ConstantAggregateZero>(V)) {
10957 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10959 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10960 // If this is an insert of an extract from some other vector, include it.
10961 Value *VecOp = IEI->getOperand(0);
10962 Value *ScalarOp = IEI->getOperand(1);
10963 Value *IdxOp = IEI->getOperand(2);
10965 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10966 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10967 EI->getOperand(0)->getType() == V->getType()) {
10968 unsigned ExtractedIdx =
10969 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10970 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10972 // Either the extracted from or inserted into vector must be RHSVec,
10973 // otherwise we'd end up with a shuffle of three inputs.
10974 if (EI->getOperand(0) == RHS || RHS == 0) {
10975 RHS = EI->getOperand(0);
10976 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10977 Mask[InsertedIdx & (NumElts-1)] =
10978 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10982 if (VecOp == RHS) {
10983 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
10984 // Everything but the extracted element is replaced with the RHS.
10985 for (unsigned i = 0; i != NumElts; ++i) {
10986 if (i != InsertedIdx)
10987 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
10992 // If this insertelement is a chain that comes from exactly these two
10993 // vectors, return the vector and the effective shuffle.
10994 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10995 return EI->getOperand(0);
11000 // TODO: Handle shufflevector here!
11002 // Otherwise, can't do anything fancy. Return an identity vector.
11003 for (unsigned i = 0; i != NumElts; ++i)
11004 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11008 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11009 Value *VecOp = IE.getOperand(0);
11010 Value *ScalarOp = IE.getOperand(1);
11011 Value *IdxOp = IE.getOperand(2);
11013 // Inserting an undef or into an undefined place, remove this.
11014 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11015 ReplaceInstUsesWith(IE, VecOp);
11017 // If the inserted element was extracted from some other vector, and if the
11018 // indexes are constant, try to turn this into a shufflevector operation.
11019 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11020 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11021 EI->getOperand(0)->getType() == IE.getType()) {
11022 unsigned NumVectorElts = IE.getType()->getNumElements();
11023 unsigned ExtractedIdx =
11024 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11025 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11027 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11028 return ReplaceInstUsesWith(IE, VecOp);
11030 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11031 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11033 // If we are extracting a value from a vector, then inserting it right
11034 // back into the same place, just use the input vector.
11035 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11036 return ReplaceInstUsesWith(IE, VecOp);
11038 // We could theoretically do this for ANY input. However, doing so could
11039 // turn chains of insertelement instructions into a chain of shufflevector
11040 // instructions, and right now we do not merge shufflevectors. As such,
11041 // only do this in a situation where it is clear that there is benefit.
11042 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11043 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11044 // the values of VecOp, except then one read from EIOp0.
11045 // Build a new shuffle mask.
11046 std::vector<Constant*> Mask;
11047 if (isa<UndefValue>(VecOp))
11048 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11050 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11051 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11054 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11055 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11056 ConstantVector::get(Mask));
11059 // If this insertelement isn't used by some other insertelement, turn it
11060 // (and any insertelements it points to), into one big shuffle.
11061 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11062 std::vector<Constant*> Mask;
11064 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11065 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11066 // We now have a shuffle of LHS, RHS, Mask.
11067 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11076 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11077 Value *LHS = SVI.getOperand(0);
11078 Value *RHS = SVI.getOperand(1);
11079 std::vector<unsigned> Mask = getShuffleMask(&SVI);
11081 bool MadeChange = false;
11083 // Undefined shuffle mask -> undefined value.
11084 if (isa<UndefValue>(SVI.getOperand(2)))
11085 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11087 // If we have shuffle(x, undef, mask) and any elements of mask refer to
11088 // the undef, change them to undefs.
11089 if (isa<UndefValue>(SVI.getOperand(1))) {
11090 // Scan to see if there are any references to the RHS. If so, replace them
11091 // with undef element refs and set MadeChange to true.
11092 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11093 if (Mask[i] >= e && Mask[i] != 2*e) {
11100 // Remap any references to RHS to use LHS.
11101 std::vector<Constant*> Elts;
11102 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11103 if (Mask[i] == 2*e)
11104 Elts.push_back(UndefValue::get(Type::Int32Ty));
11106 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11108 SVI.setOperand(2, ConstantVector::get(Elts));
11112 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11113 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11114 if (LHS == RHS || isa<UndefValue>(LHS)) {
11115 if (isa<UndefValue>(LHS) && LHS == RHS) {
11116 // shuffle(undef,undef,mask) -> undef.
11117 return ReplaceInstUsesWith(SVI, LHS);
11120 // Remap any references to RHS to use LHS.
11121 std::vector<Constant*> Elts;
11122 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11123 if (Mask[i] >= 2*e)
11124 Elts.push_back(UndefValue::get(Type::Int32Ty));
11126 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11127 (Mask[i] < e && isa<UndefValue>(LHS)))
11128 Mask[i] = 2*e; // Turn into undef.
11130 Mask[i] &= (e-1); // Force to LHS.
11131 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11134 SVI.setOperand(0, SVI.getOperand(1));
11135 SVI.setOperand(1, UndefValue::get(RHS->getType()));
11136 SVI.setOperand(2, ConstantVector::get(Elts));
11137 LHS = SVI.getOperand(0);
11138 RHS = SVI.getOperand(1);
11142 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11143 bool isLHSID = true, isRHSID = true;
11145 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11146 if (Mask[i] >= e*2) continue; // Ignore undef values.
11147 // Is this an identity shuffle of the LHS value?
11148 isLHSID &= (Mask[i] == i);
11150 // Is this an identity shuffle of the RHS value?
11151 isRHSID &= (Mask[i]-e == i);
11154 // Eliminate identity shuffles.
11155 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11156 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11158 // If the LHS is a shufflevector itself, see if we can combine it with this
11159 // one without producing an unusual shuffle. Here we are really conservative:
11160 // we are absolutely afraid of producing a shuffle mask not in the input
11161 // program, because the code gen may not be smart enough to turn a merged
11162 // shuffle into two specific shuffles: it may produce worse code. As such,
11163 // we only merge two shuffles if the result is one of the two input shuffle
11164 // masks. In this case, merging the shuffles just removes one instruction,
11165 // which we know is safe. This is good for things like turning:
11166 // (splat(splat)) -> splat.
11167 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11168 if (isa<UndefValue>(RHS)) {
11169 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11171 std::vector<unsigned> NewMask;
11172 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11173 if (Mask[i] >= 2*e)
11174 NewMask.push_back(2*e);
11176 NewMask.push_back(LHSMask[Mask[i]]);
11178 // If the result mask is equal to the src shuffle or this shuffle mask, do
11179 // the replacement.
11180 if (NewMask == LHSMask || NewMask == Mask) {
11181 std::vector<Constant*> Elts;
11182 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11183 if (NewMask[i] >= e*2) {
11184 Elts.push_back(UndefValue::get(Type::Int32Ty));
11186 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11189 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11190 LHSSVI->getOperand(1),
11191 ConstantVector::get(Elts));
11196 return MadeChange ? &SVI : 0;
11202 /// TryToSinkInstruction - Try to move the specified instruction from its
11203 /// current block into the beginning of DestBlock, which can only happen if it's
11204 /// safe to move the instruction past all of the instructions between it and the
11205 /// end of its block.
11206 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11207 assert(I->hasOneUse() && "Invariants didn't hold!");
11209 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11210 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11213 // Do not sink alloca instructions out of the entry block.
11214 if (isa<AllocaInst>(I) && I->getParent() ==
11215 &DestBlock->getParent()->getEntryBlock())
11218 // We can only sink load instructions if there is nothing between the load and
11219 // the end of block that could change the value.
11220 if (I->mayReadFromMemory()) {
11221 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
11223 if (Scan->mayWriteToMemory())
11227 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
11229 I->moveBefore(InsertPos);
11235 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11236 /// all reachable code to the worklist.
11238 /// This has a couple of tricks to make the code faster and more powerful. In
11239 /// particular, we constant fold and DCE instructions as we go, to avoid adding
11240 /// them to the worklist (this significantly speeds up instcombine on code where
11241 /// many instructions are dead or constant). Additionally, if we find a branch
11242 /// whose condition is a known constant, we only visit the reachable successors.
11244 static void AddReachableCodeToWorklist(BasicBlock *BB,
11245 SmallPtrSet<BasicBlock*, 64> &Visited,
11247 const TargetData *TD) {
11248 std::vector<BasicBlock*> Worklist;
11249 Worklist.push_back(BB);
11251 while (!Worklist.empty()) {
11252 BB = Worklist.back();
11253 Worklist.pop_back();
11255 // We have now visited this block! If we've already been here, ignore it.
11256 if (!Visited.insert(BB)) continue;
11258 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11259 Instruction *Inst = BBI++;
11261 // DCE instruction if trivially dead.
11262 if (isInstructionTriviallyDead(Inst)) {
11264 DOUT << "IC: DCE: " << *Inst;
11265 Inst->eraseFromParent();
11269 // ConstantProp instruction if trivially constant.
11270 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11271 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11272 Inst->replaceAllUsesWith(C);
11274 Inst->eraseFromParent();
11278 IC.AddToWorkList(Inst);
11281 // Recursively visit successors. If this is a branch or switch on a
11282 // constant, only visit the reachable successor.
11283 TerminatorInst *TI = BB->getTerminator();
11284 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11285 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11286 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
11287 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11288 Worklist.push_back(ReachableBB);
11291 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11292 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11293 // See if this is an explicit destination.
11294 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11295 if (SI->getCaseValue(i) == Cond) {
11296 BasicBlock *ReachableBB = SI->getSuccessor(i);
11297 Worklist.push_back(ReachableBB);
11301 // Otherwise it is the default destination.
11302 Worklist.push_back(SI->getSuccessor(0));
11307 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11308 Worklist.push_back(TI->getSuccessor(i));
11312 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11313 bool Changed = false;
11314 TD = &getAnalysis<TargetData>();
11316 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11317 << F.getNameStr() << "\n");
11320 // Do a depth-first traversal of the function, populate the worklist with
11321 // the reachable instructions. Ignore blocks that are not reachable. Keep
11322 // track of which blocks we visit.
11323 SmallPtrSet<BasicBlock*, 64> Visited;
11324 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11326 // Do a quick scan over the function. If we find any blocks that are
11327 // unreachable, remove any instructions inside of them. This prevents
11328 // the instcombine code from having to deal with some bad special cases.
11329 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11330 if (!Visited.count(BB)) {
11331 Instruction *Term = BB->getTerminator();
11332 while (Term != BB->begin()) { // Remove instrs bottom-up
11333 BasicBlock::iterator I = Term; --I;
11335 DOUT << "IC: DCE: " << *I;
11338 if (!I->use_empty())
11339 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11340 I->eraseFromParent();
11345 while (!Worklist.empty()) {
11346 Instruction *I = RemoveOneFromWorkList();
11347 if (I == 0) continue; // skip null values.
11349 // Check to see if we can DCE the instruction.
11350 if (isInstructionTriviallyDead(I)) {
11351 // Add operands to the worklist.
11352 if (I->getNumOperands() < 4)
11353 AddUsesToWorkList(*I);
11356 DOUT << "IC: DCE: " << *I;
11358 I->eraseFromParent();
11359 RemoveFromWorkList(I);
11363 // Instruction isn't dead, see if we can constant propagate it.
11364 if (Constant *C = ConstantFoldInstruction(I, TD)) {
11365 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11367 // Add operands to the worklist.
11368 AddUsesToWorkList(*I);
11369 ReplaceInstUsesWith(*I, C);
11372 I->eraseFromParent();
11373 RemoveFromWorkList(I);
11377 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11378 // See if we can constant fold its operands.
11379 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11380 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11381 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11387 // See if we can trivially sink this instruction to a successor basic block.
11388 // FIXME: Remove GetResultInst test when first class support for aggregates
11390 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
11391 BasicBlock *BB = I->getParent();
11392 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11393 if (UserParent != BB) {
11394 bool UserIsSuccessor = false;
11395 // See if the user is one of our successors.
11396 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11397 if (*SI == UserParent) {
11398 UserIsSuccessor = true;
11402 // If the user is one of our immediate successors, and if that successor
11403 // only has us as a predecessors (we'd have to split the critical edge
11404 // otherwise), we can keep going.
11405 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11406 next(pred_begin(UserParent)) == pred_end(UserParent))
11407 // Okay, the CFG is simple enough, try to sink this instruction.
11408 Changed |= TryToSinkInstruction(I, UserParent);
11412 // Now that we have an instruction, try combining it to simplify it...
11416 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11417 if (Instruction *Result = visit(*I)) {
11419 // Should we replace the old instruction with a new one?
11421 DOUT << "IC: Old = " << *I
11422 << " New = " << *Result;
11424 // Everything uses the new instruction now.
11425 I->replaceAllUsesWith(Result);
11427 // Push the new instruction and any users onto the worklist.
11428 AddToWorkList(Result);
11429 AddUsersToWorkList(*Result);
11431 // Move the name to the new instruction first.
11432 Result->takeName(I);
11434 // Insert the new instruction into the basic block...
11435 BasicBlock *InstParent = I->getParent();
11436 BasicBlock::iterator InsertPos = I;
11438 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11439 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11442 InstParent->getInstList().insert(InsertPos, Result);
11444 // Make sure that we reprocess all operands now that we reduced their
11446 AddUsesToWorkList(*I);
11448 // Instructions can end up on the worklist more than once. Make sure
11449 // we do not process an instruction that has been deleted.
11450 RemoveFromWorkList(I);
11452 // Erase the old instruction.
11453 InstParent->getInstList().erase(I);
11456 DOUT << "IC: Mod = " << OrigI
11457 << " New = " << *I;
11460 // If the instruction was modified, it's possible that it is now dead.
11461 // if so, remove it.
11462 if (isInstructionTriviallyDead(I)) {
11463 // Make sure we process all operands now that we are reducing their
11465 AddUsesToWorkList(*I);
11467 // Instructions may end up in the worklist more than once. Erase all
11468 // occurrences of this instruction.
11469 RemoveFromWorkList(I);
11470 I->eraseFromParent();
11473 AddUsersToWorkList(*I);
11480 assert(WorklistMap.empty() && "Worklist empty, but map not?");
11482 // Do an explicit clear, this shrinks the map if needed.
11483 WorklistMap.clear();
11488 bool InstCombiner::runOnFunction(Function &F) {
11489 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11491 bool EverMadeChange = false;
11493 // Iterate while there is work to do.
11494 unsigned Iteration = 0;
11495 while (DoOneIteration(F, Iteration++))
11496 EverMadeChange = true;
11497 return EverMadeChange;
11500 FunctionPass *llvm::createInstructionCombiningPass() {
11501 return new InstCombiner();