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 SmallVector<Instruction*, 256> Worklist;
78 DenseMap<Instruction*, unsigned> WorklistMap;
80 bool MustPreserveLCSSA;
82 static char ID; // Pass identification, replacement for typeid
83 InstCombiner() : FunctionPass(&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 bool SimplifyDivRemOfSelect(BinaryOperator &I);
176 Instruction *commonRemTransforms(BinaryOperator &I);
177 Instruction *commonIRemTransforms(BinaryOperator &I);
178 Instruction *commonDivTransforms(BinaryOperator &I);
179 Instruction *commonIDivTransforms(BinaryOperator &I);
180 Instruction *visitUDiv(BinaryOperator &I);
181 Instruction *visitSDiv(BinaryOperator &I);
182 Instruction *visitFDiv(BinaryOperator &I);
183 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
184 Instruction *visitAnd(BinaryOperator &I);
185 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
186 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
187 Value *A, Value *B, Value *C);
188 Instruction *visitOr (BinaryOperator &I);
189 Instruction *visitXor(BinaryOperator &I);
190 Instruction *visitShl(BinaryOperator &I);
191 Instruction *visitAShr(BinaryOperator &I);
192 Instruction *visitLShr(BinaryOperator &I);
193 Instruction *commonShiftTransforms(BinaryOperator &I);
194 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
196 Instruction *visitFCmpInst(FCmpInst &I);
197 Instruction *visitICmpInst(ICmpInst &I);
198 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
199 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
202 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
203 ConstantInt *DivRHS);
205 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
206 ICmpInst::Predicate Cond, Instruction &I);
207 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
209 Instruction *commonCastTransforms(CastInst &CI);
210 Instruction *commonIntCastTransforms(CastInst &CI);
211 Instruction *commonPointerCastTransforms(CastInst &CI);
212 Instruction *visitTrunc(TruncInst &CI);
213 Instruction *visitZExt(ZExtInst &CI);
214 Instruction *visitSExt(SExtInst &CI);
215 Instruction *visitFPTrunc(FPTruncInst &CI);
216 Instruction *visitFPExt(CastInst &CI);
217 Instruction *visitFPToUI(FPToUIInst &FI);
218 Instruction *visitFPToSI(FPToSIInst &FI);
219 Instruction *visitUIToFP(CastInst &CI);
220 Instruction *visitSIToFP(CastInst &CI);
221 Instruction *visitPtrToInt(CastInst &CI);
222 Instruction *visitIntToPtr(IntToPtrInst &CI);
223 Instruction *visitBitCast(BitCastInst &CI);
224 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
226 Instruction *visitSelectInst(SelectInst &SI);
227 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
228 Instruction *visitCallInst(CallInst &CI);
229 Instruction *visitInvokeInst(InvokeInst &II);
230 Instruction *visitPHINode(PHINode &PN);
231 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
232 Instruction *visitAllocationInst(AllocationInst &AI);
233 Instruction *visitFreeInst(FreeInst &FI);
234 Instruction *visitLoadInst(LoadInst &LI);
235 Instruction *visitStoreInst(StoreInst &SI);
236 Instruction *visitBranchInst(BranchInst &BI);
237 Instruction *visitSwitchInst(SwitchInst &SI);
238 Instruction *visitInsertElementInst(InsertElementInst &IE);
239 Instruction *visitExtractElementInst(ExtractElementInst &EI);
240 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
241 Instruction *visitExtractValueInst(ExtractValueInst &EV);
243 // visitInstruction - Specify what to return for unhandled instructions...
244 Instruction *visitInstruction(Instruction &I) { return 0; }
247 Instruction *visitCallSite(CallSite CS);
248 bool transformConstExprCastCall(CallSite CS);
249 Instruction *transformCallThroughTrampoline(CallSite CS);
250 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
251 bool DoXform = true);
252 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
255 // InsertNewInstBefore - insert an instruction New before instruction Old
256 // in the program. Add the new instruction to the worklist.
258 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
259 assert(New && New->getParent() == 0 &&
260 "New instruction already inserted into a basic block!");
261 BasicBlock *BB = Old.getParent();
262 BB->getInstList().insert(&Old, New); // Insert inst
267 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
268 /// This also adds the cast to the worklist. Finally, this returns the
270 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
272 if (V->getType() == Ty) return V;
274 if (Constant *CV = dyn_cast<Constant>(V))
275 return ConstantExpr::getCast(opc, CV, Ty);
277 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
282 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
283 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
287 // ReplaceInstUsesWith - This method is to be used when an instruction is
288 // found to be dead, replacable with another preexisting expression. Here
289 // we add all uses of I to the worklist, replace all uses of I with the new
290 // value, then return I, so that the inst combiner will know that I was
293 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
294 AddUsersToWorkList(I); // Add all modified instrs to worklist
296 I.replaceAllUsesWith(V);
299 // If we are replacing the instruction with itself, this must be in a
300 // segment of unreachable code, so just clobber the instruction.
301 I.replaceAllUsesWith(UndefValue::get(I.getType()));
306 // UpdateValueUsesWith - This method is to be used when an value is
307 // found to be replacable with another preexisting expression or was
308 // updated. Here we add all uses of I to the worklist, replace all uses of
309 // I with the new value (unless the instruction was just updated), then
310 // return true, so that the inst combiner will know that I was modified.
312 bool UpdateValueUsesWith(Value *Old, Value *New) {
313 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
315 Old->replaceAllUsesWith(New);
316 if (Instruction *I = dyn_cast<Instruction>(Old))
318 if (Instruction *I = dyn_cast<Instruction>(New))
323 // EraseInstFromFunction - When dealing with an instruction that has side
324 // effects or produces a void value, we can't rely on DCE to delete the
325 // instruction. Instead, visit methods should return the value returned by
327 Instruction *EraseInstFromFunction(Instruction &I) {
328 assert(I.use_empty() && "Cannot erase instruction that is used!");
329 AddUsesToWorkList(I);
330 RemoveFromWorkList(&I);
332 return 0; // Don't do anything with FI
335 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
336 APInt &KnownOne, unsigned Depth = 0) const {
337 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
340 bool MaskedValueIsZero(Value *V, const APInt &Mask,
341 unsigned Depth = 0) const {
342 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
344 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
345 return llvm::ComputeNumSignBits(Op, TD, Depth);
350 /// SimplifyCommutative - This performs a few simplifications for
351 /// commutative operators.
352 bool SimplifyCommutative(BinaryOperator &I);
354 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
355 /// most-complex to least-complex order.
356 bool SimplifyCompare(CmpInst &I);
358 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
359 /// on the demanded bits.
360 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
361 APInt& KnownZero, APInt& KnownOne,
364 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
365 uint64_t &UndefElts, unsigned Depth = 0);
367 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
368 // PHI node as operand #0, see if we can fold the instruction into the PHI
369 // (which is only possible if all operands to the PHI are constants).
370 Instruction *FoldOpIntoPhi(Instruction &I);
372 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
373 // operator and they all are only used by the PHI, PHI together their
374 // inputs, and do the operation once, to the result of the PHI.
375 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
376 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
377 Instruction *FoldPHIArgGEPIntoPHI(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, a constant
438 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
439 /// operand value, otherwise return null.
440 static Value *getBitCastOperand(Value *V) {
441 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
443 return I->getOperand(0);
444 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
445 // GetElementPtrInst?
446 if (GEP->hasAllZeroIndices())
447 return GEP->getOperand(0);
448 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
449 if (CE->getOpcode() == Instruction::BitCast)
450 // BitCast ConstantExp?
451 return CE->getOperand(0);
452 else if (CE->getOpcode() == Instruction::GetElementPtr) {
453 // GetElementPtr ConstantExp?
454 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
456 ConstantInt *CI = dyn_cast<ConstantInt>(I);
457 if (!CI || !CI->isZero())
458 // Any non-zero indices? Not cast-like.
461 // All-zero indices? This is just like casting.
462 return CE->getOperand(0);
468 /// This function is a wrapper around CastInst::isEliminableCastPair. It
469 /// simply extracts arguments and returns what that function returns.
470 static Instruction::CastOps
471 isEliminableCastPair(
472 const CastInst *CI, ///< The first cast instruction
473 unsigned opcode, ///< The opcode of the second cast instruction
474 const Type *DstTy, ///< The target type for the second cast instruction
475 TargetData *TD ///< The target data for pointer size
478 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
479 const Type *MidTy = CI->getType(); // B from above
481 // Get the opcodes of the two Cast instructions
482 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
483 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
485 return Instruction::CastOps(
486 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
487 DstTy, TD->getIntPtrType()));
490 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
491 /// in any code being generated. It does not require codegen if V is simple
492 /// enough or if the cast can be folded into other casts.
493 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
494 const Type *Ty, TargetData *TD) {
495 if (V->getType() == Ty || isa<Constant>(V)) return false;
497 // If this is another cast that can be eliminated, it isn't codegen either.
498 if (const CastInst *CI = dyn_cast<CastInst>(V))
499 if (isEliminableCastPair(CI, opcode, Ty, TD))
504 // SimplifyCommutative - This performs a few simplifications for commutative
507 // 1. Order operands such that they are listed from right (least complex) to
508 // left (most complex). This puts constants before unary operators before
511 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
512 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
514 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
515 bool Changed = false;
516 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
517 Changed = !I.swapOperands();
519 if (!I.isAssociative()) return Changed;
520 Instruction::BinaryOps Opcode = I.getOpcode();
521 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
522 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
523 if (isa<Constant>(I.getOperand(1))) {
524 Constant *Folded = ConstantExpr::get(I.getOpcode(),
525 cast<Constant>(I.getOperand(1)),
526 cast<Constant>(Op->getOperand(1)));
527 I.setOperand(0, Op->getOperand(0));
528 I.setOperand(1, Folded);
530 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
531 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
532 isOnlyUse(Op) && isOnlyUse(Op1)) {
533 Constant *C1 = cast<Constant>(Op->getOperand(1));
534 Constant *C2 = cast<Constant>(Op1->getOperand(1));
536 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
537 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
538 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
542 I.setOperand(0, New);
543 I.setOperand(1, Folded);
550 /// SimplifyCompare - For a CmpInst this function just orders the operands
551 /// so that theyare listed from right (least complex) to left (most complex).
552 /// This puts constants before unary operators before binary operators.
553 bool InstCombiner::SimplifyCompare(CmpInst &I) {
554 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
557 // Compare instructions are not associative so there's nothing else we can do.
561 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
562 // if the LHS is a constant zero (which is the 'negate' form).
564 static inline Value *dyn_castNegVal(Value *V) {
565 if (BinaryOperator::isNeg(V))
566 return BinaryOperator::getNegArgument(V);
568 // Constants can be considered to be negated values if they can be folded.
569 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
570 return ConstantExpr::getNeg(C);
572 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
573 if (C->getType()->getElementType()->isInteger())
574 return ConstantExpr::getNeg(C);
579 static inline Value *dyn_castNotVal(Value *V) {
580 if (BinaryOperator::isNot(V))
581 return BinaryOperator::getNotArgument(V);
583 // Constants can be considered to be not'ed values...
584 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
585 return ConstantInt::get(~C->getValue());
589 // dyn_castFoldableMul - If this value is a multiply that can be folded into
590 // other computations (because it has a constant operand), return the
591 // non-constant operand of the multiply, and set CST to point to the multiplier.
592 // Otherwise, return null.
594 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
595 if (V->hasOneUse() && V->getType()->isInteger())
596 if (Instruction *I = dyn_cast<Instruction>(V)) {
597 if (I->getOpcode() == Instruction::Mul)
598 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
599 return I->getOperand(0);
600 if (I->getOpcode() == Instruction::Shl)
601 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
602 // The multiplier is really 1 << CST.
603 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
604 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
605 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
606 return I->getOperand(0);
612 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
613 /// expression, return it.
614 static User *dyn_castGetElementPtr(Value *V) {
615 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
616 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
617 if (CE->getOpcode() == Instruction::GetElementPtr)
618 return cast<User>(V);
622 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
623 /// opcode value. Otherwise return UserOp1.
624 static unsigned getOpcode(const Value *V) {
625 if (const Instruction *I = dyn_cast<Instruction>(V))
626 return I->getOpcode();
627 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
628 return CE->getOpcode();
629 // Use UserOp1 to mean there's no opcode.
630 return Instruction::UserOp1;
633 /// AddOne - Add one to a ConstantInt
634 static ConstantInt *AddOne(ConstantInt *C) {
635 APInt Val(C->getValue());
636 return ConstantInt::get(++Val);
638 /// SubOne - Subtract one from a ConstantInt
639 static ConstantInt *SubOne(ConstantInt *C) {
640 APInt Val(C->getValue());
641 return ConstantInt::get(--Val);
643 /// Add - Add two ConstantInts together
644 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
645 return ConstantInt::get(C1->getValue() + C2->getValue());
647 /// And - Bitwise AND two ConstantInts together
648 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
649 return ConstantInt::get(C1->getValue() & C2->getValue());
651 /// Subtract - Subtract one ConstantInt from another
652 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
653 return ConstantInt::get(C1->getValue() - C2->getValue());
655 /// Multiply - Multiply two ConstantInts together
656 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
657 return ConstantInt::get(C1->getValue() * C2->getValue());
659 /// MultiplyOverflows - True if the multiply can not be expressed in an int
661 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
662 uint32_t W = C1->getBitWidth();
663 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
672 APInt MulExt = LHSExt * RHSExt;
675 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
676 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
677 return MulExt.slt(Min) || MulExt.sgt(Max);
679 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
683 /// ShrinkDemandedConstant - Check to see if the specified operand of the
684 /// specified instruction is a constant integer. If so, check to see if there
685 /// are any bits set in the constant that are not demanded. If so, shrink the
686 /// constant and return true.
687 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
689 assert(I && "No instruction?");
690 assert(OpNo < I->getNumOperands() && "Operand index too large");
692 // If the operand is not a constant integer, nothing to do.
693 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
694 if (!OpC) return false;
696 // If there are no bits set that aren't demanded, nothing to do.
697 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
698 if ((~Demanded & OpC->getValue()) == 0)
701 // This instruction is producing bits that are not demanded. Shrink the RHS.
702 Demanded &= OpC->getValue();
703 I->setOperand(OpNo, ConstantInt::get(Demanded));
707 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
708 // set of known zero and one bits, compute the maximum and minimum values that
709 // could have the specified known zero and known one bits, returning them in
711 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
712 const APInt& KnownZero,
713 const APInt& KnownOne,
714 APInt& Min, APInt& Max) {
715 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
716 assert(KnownZero.getBitWidth() == BitWidth &&
717 KnownOne.getBitWidth() == BitWidth &&
718 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
719 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
720 APInt UnknownBits = ~(KnownZero|KnownOne);
722 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
723 // bit if it is unknown.
725 Max = KnownOne|UnknownBits;
727 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
729 Max.clear(BitWidth-1);
733 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
734 // a set of known zero and one bits, compute the maximum and minimum values that
735 // could have the specified known zero and known one bits, returning them in
737 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
738 const APInt &KnownZero,
739 const APInt &KnownOne,
740 APInt &Min, APInt &Max) {
741 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
742 assert(KnownZero.getBitWidth() == BitWidth &&
743 KnownOne.getBitWidth() == BitWidth &&
744 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
745 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
746 APInt UnknownBits = ~(KnownZero|KnownOne);
748 // The minimum value is when the unknown bits are all zeros.
750 // The maximum value is when the unknown bits are all ones.
751 Max = KnownOne|UnknownBits;
754 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
755 /// value based on the demanded bits. When this function is called, it is known
756 /// that only the bits set in DemandedMask of the result of V are ever used
757 /// downstream. Consequently, depending on the mask and V, it may be possible
758 /// to replace V with a constant or one of its operands. In such cases, this
759 /// function does the replacement and returns true. In all other cases, it
760 /// returns false after analyzing the expression and setting KnownOne and known
761 /// to be one in the expression. KnownZero contains all the bits that are known
762 /// to be zero in the expression. These are provided to potentially allow the
763 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
764 /// the expression. KnownOne and KnownZero always follow the invariant that
765 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
766 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
767 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
768 /// and KnownOne must all be the same.
769 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
770 APInt& KnownZero, APInt& KnownOne,
772 assert(V != 0 && "Null pointer of Value???");
773 assert(Depth <= 6 && "Limit Search Depth");
774 uint32_t BitWidth = DemandedMask.getBitWidth();
775 const IntegerType *VTy = cast<IntegerType>(V->getType());
776 assert(VTy->getBitWidth() == BitWidth &&
777 KnownZero.getBitWidth() == BitWidth &&
778 KnownOne.getBitWidth() == BitWidth &&
779 "Value *V, DemandedMask, KnownZero and KnownOne \
780 must have same BitWidth");
781 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
782 // We know all of the bits for a constant!
783 KnownOne = CI->getValue() & DemandedMask;
784 KnownZero = ~KnownOne & DemandedMask;
790 if (!V->hasOneUse()) { // Other users may use these bits.
791 if (Depth != 0) { // Not at the root.
792 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
793 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
796 // If this is the root being simplified, allow it to have multiple uses,
797 // just set the DemandedMask to all bits.
798 DemandedMask = APInt::getAllOnesValue(BitWidth);
799 } else if (DemandedMask == 0) { // Not demanding any bits from V.
800 if (V != UndefValue::get(VTy))
801 return UpdateValueUsesWith(V, UndefValue::get(VTy));
803 } else if (Depth == 6) { // Limit search depth.
807 Instruction *I = dyn_cast<Instruction>(V);
808 if (!I) return false; // Only analyze instructions.
810 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
811 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
812 switch (I->getOpcode()) {
814 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
816 case Instruction::And:
817 // If either the LHS or the RHS are Zero, the result is zero.
818 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
819 RHSKnownZero, RHSKnownOne, Depth+1))
821 assert((RHSKnownZero & RHSKnownOne) == 0 &&
822 "Bits known to be one AND zero?");
824 // If something is known zero on the RHS, the bits aren't demanded on the
826 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
827 LHSKnownZero, LHSKnownOne, Depth+1))
829 assert((LHSKnownZero & LHSKnownOne) == 0 &&
830 "Bits known to be one AND zero?");
832 // If all of the demanded bits are known 1 on one side, return the other.
833 // These bits cannot contribute to the result of the 'and'.
834 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
835 (DemandedMask & ~LHSKnownZero))
836 return UpdateValueUsesWith(I, I->getOperand(0));
837 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
838 (DemandedMask & ~RHSKnownZero))
839 return UpdateValueUsesWith(I, I->getOperand(1));
841 // If all of the demanded bits in the inputs are known zeros, return zero.
842 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
843 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
845 // If the RHS is a constant, see if we can simplify it.
846 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
847 return UpdateValueUsesWith(I, I);
849 // Output known-1 bits are only known if set in both the LHS & RHS.
850 RHSKnownOne &= LHSKnownOne;
851 // Output known-0 are known to be clear if zero in either the LHS | RHS.
852 RHSKnownZero |= LHSKnownZero;
854 case Instruction::Or:
855 // If either the LHS or the RHS are One, the result is One.
856 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
857 RHSKnownZero, RHSKnownOne, Depth+1))
859 assert((RHSKnownZero & RHSKnownOne) == 0 &&
860 "Bits known to be one AND zero?");
861 // If something is known one on the RHS, the bits aren't demanded on the
863 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
864 LHSKnownZero, LHSKnownOne, Depth+1))
866 assert((LHSKnownZero & LHSKnownOne) == 0 &&
867 "Bits known to be one AND zero?");
869 // If all of the demanded bits are known zero on one side, return the other.
870 // These bits cannot contribute to the result of the 'or'.
871 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
872 (DemandedMask & ~LHSKnownOne))
873 return UpdateValueUsesWith(I, I->getOperand(0));
874 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
875 (DemandedMask & ~RHSKnownOne))
876 return UpdateValueUsesWith(I, I->getOperand(1));
878 // If all of the potentially set bits on one side are known to be set on
879 // the other side, just use the 'other' side.
880 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
881 (DemandedMask & (~RHSKnownZero)))
882 return UpdateValueUsesWith(I, I->getOperand(0));
883 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
884 (DemandedMask & (~LHSKnownZero)))
885 return UpdateValueUsesWith(I, I->getOperand(1));
887 // If the RHS is a constant, see if we can simplify it.
888 if (ShrinkDemandedConstant(I, 1, DemandedMask))
889 return UpdateValueUsesWith(I, I);
891 // Output known-0 bits are only known if clear in both the LHS & RHS.
892 RHSKnownZero &= LHSKnownZero;
893 // Output known-1 are known to be set if set in either the LHS | RHS.
894 RHSKnownOne |= LHSKnownOne;
896 case Instruction::Xor: {
897 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
898 RHSKnownZero, RHSKnownOne, Depth+1))
900 assert((RHSKnownZero & RHSKnownOne) == 0 &&
901 "Bits known to be one AND zero?");
902 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
903 LHSKnownZero, LHSKnownOne, Depth+1))
905 assert((LHSKnownZero & LHSKnownOne) == 0 &&
906 "Bits known to be one AND zero?");
908 // If all of the demanded bits are known zero on one side, return the other.
909 // These bits cannot contribute to the result of the 'xor'.
910 if ((DemandedMask & RHSKnownZero) == DemandedMask)
911 return UpdateValueUsesWith(I, I->getOperand(0));
912 if ((DemandedMask & LHSKnownZero) == DemandedMask)
913 return UpdateValueUsesWith(I, I->getOperand(1));
915 // Output known-0 bits are known if clear or set in both the LHS & RHS.
916 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
917 (RHSKnownOne & LHSKnownOne);
918 // Output known-1 are known to be set if set in only one of the LHS, RHS.
919 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
920 (RHSKnownOne & LHSKnownZero);
922 // If all of the demanded bits are known to be zero on one side or the
923 // other, turn this into an *inclusive* or.
924 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
925 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
927 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
929 InsertNewInstBefore(Or, *I);
930 return UpdateValueUsesWith(I, Or);
933 // If all of the demanded bits on one side are known, and all of the set
934 // bits on that side are also known to be set on the other side, turn this
935 // into an AND, as we know the bits will be cleared.
936 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
937 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
939 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
940 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
942 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
943 InsertNewInstBefore(And, *I);
944 return UpdateValueUsesWith(I, And);
948 // If the RHS is a constant, see if we can simplify it.
949 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
950 if (ShrinkDemandedConstant(I, 1, DemandedMask))
951 return UpdateValueUsesWith(I, I);
953 RHSKnownZero = KnownZeroOut;
954 RHSKnownOne = KnownOneOut;
957 case Instruction::Select:
958 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
959 RHSKnownZero, RHSKnownOne, Depth+1))
961 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
962 LHSKnownZero, LHSKnownOne, Depth+1))
964 assert((RHSKnownZero & RHSKnownOne) == 0 &&
965 "Bits known to be one AND zero?");
966 assert((LHSKnownZero & LHSKnownOne) == 0 &&
967 "Bits known to be one AND zero?");
969 // If the operands are constants, see if we can simplify them.
970 if (ShrinkDemandedConstant(I, 1, DemandedMask))
971 return UpdateValueUsesWith(I, I);
972 if (ShrinkDemandedConstant(I, 2, DemandedMask))
973 return UpdateValueUsesWith(I, I);
975 // Only known if known in both the LHS and RHS.
976 RHSKnownOne &= LHSKnownOne;
977 RHSKnownZero &= LHSKnownZero;
979 case Instruction::Trunc: {
981 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
982 DemandedMask.zext(truncBf);
983 RHSKnownZero.zext(truncBf);
984 RHSKnownOne.zext(truncBf);
985 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
986 RHSKnownZero, RHSKnownOne, Depth+1))
988 DemandedMask.trunc(BitWidth);
989 RHSKnownZero.trunc(BitWidth);
990 RHSKnownOne.trunc(BitWidth);
991 assert((RHSKnownZero & RHSKnownOne) == 0 &&
992 "Bits known to be one AND zero?");
995 case Instruction::BitCast:
996 if (!I->getOperand(0)->getType()->isInteger())
999 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1000 RHSKnownZero, RHSKnownOne, Depth+1))
1002 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1003 "Bits known to be one AND zero?");
1005 case Instruction::ZExt: {
1006 // Compute the bits in the result that are not present in the input.
1007 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1008 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1010 DemandedMask.trunc(SrcBitWidth);
1011 RHSKnownZero.trunc(SrcBitWidth);
1012 RHSKnownOne.trunc(SrcBitWidth);
1013 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1014 RHSKnownZero, RHSKnownOne, Depth+1))
1016 DemandedMask.zext(BitWidth);
1017 RHSKnownZero.zext(BitWidth);
1018 RHSKnownOne.zext(BitWidth);
1019 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1020 "Bits known to be one AND zero?");
1021 // The top bits are known to be zero.
1022 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1025 case Instruction::SExt: {
1026 // Compute the bits in the result that are not present in the input.
1027 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1028 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1030 APInt InputDemandedBits = DemandedMask &
1031 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1033 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1034 // If any of the sign extended bits are demanded, we know that the sign
1036 if ((NewBits & DemandedMask) != 0)
1037 InputDemandedBits.set(SrcBitWidth-1);
1039 InputDemandedBits.trunc(SrcBitWidth);
1040 RHSKnownZero.trunc(SrcBitWidth);
1041 RHSKnownOne.trunc(SrcBitWidth);
1042 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1043 RHSKnownZero, RHSKnownOne, Depth+1))
1045 InputDemandedBits.zext(BitWidth);
1046 RHSKnownZero.zext(BitWidth);
1047 RHSKnownOne.zext(BitWidth);
1048 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1049 "Bits known to be one AND zero?");
1051 // If the sign bit of the input is known set or clear, then we know the
1052 // top bits of the result.
1054 // If the input sign bit is known zero, or if the NewBits are not demanded
1055 // convert this into a zero extension.
1056 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1058 // Convert to ZExt cast
1059 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1060 return UpdateValueUsesWith(I, NewCast);
1061 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1062 RHSKnownOne |= NewBits;
1066 case Instruction::Add: {
1067 // Figure out what the input bits are. If the top bits of the and result
1068 // are not demanded, then the add doesn't demand them from its input
1070 uint32_t NLZ = DemandedMask.countLeadingZeros();
1072 // If there is a constant on the RHS, there are a variety of xformations
1074 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1075 // If null, this should be simplified elsewhere. Some of the xforms here
1076 // won't work if the RHS is zero.
1080 // If the top bit of the output is demanded, demand everything from the
1081 // input. Otherwise, we demand all the input bits except NLZ top bits.
1082 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1084 // Find information about known zero/one bits in the input.
1085 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1086 LHSKnownZero, LHSKnownOne, Depth+1))
1089 // If the RHS of the add has bits set that can't affect the input, reduce
1091 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1092 return UpdateValueUsesWith(I, I);
1094 // Avoid excess work.
1095 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1098 // Turn it into OR if input bits are zero.
1099 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1101 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1103 InsertNewInstBefore(Or, *I);
1104 return UpdateValueUsesWith(I, Or);
1107 // We can say something about the output known-zero and known-one bits,
1108 // depending on potential carries from the input constant and the
1109 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1110 // bits set and the RHS constant is 0x01001, then we know we have a known
1111 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1113 // To compute this, we first compute the potential carry bits. These are
1114 // the bits which may be modified. I'm not aware of a better way to do
1116 const APInt& RHSVal = RHS->getValue();
1117 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1119 // Now that we know which bits have carries, compute the known-1/0 sets.
1121 // Bits are known one if they are known zero in one operand and one in the
1122 // other, and there is no input carry.
1123 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1124 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1126 // Bits are known zero if they are known zero in both operands and there
1127 // is no input carry.
1128 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1130 // If the high-bits of this ADD are not demanded, then it does not demand
1131 // the high bits of its LHS or RHS.
1132 if (DemandedMask[BitWidth-1] == 0) {
1133 // Right fill the mask of bits for this ADD to demand the most
1134 // significant bit and all those below it.
1135 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1136 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1137 LHSKnownZero, LHSKnownOne, Depth+1))
1139 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1140 LHSKnownZero, LHSKnownOne, Depth+1))
1146 case Instruction::Sub:
1147 // If the high-bits of this SUB are not demanded, then it does not demand
1148 // the high bits of its LHS or RHS.
1149 if (DemandedMask[BitWidth-1] == 0) {
1150 // Right fill the mask of bits for this SUB to demand the most
1151 // significant bit and all those below it.
1152 uint32_t NLZ = DemandedMask.countLeadingZeros();
1153 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1154 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1155 LHSKnownZero, LHSKnownOne, Depth+1))
1157 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1158 LHSKnownZero, LHSKnownOne, Depth+1))
1161 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1162 // the known zeros and ones.
1163 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1165 case Instruction::Shl:
1166 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1167 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1168 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1169 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1170 RHSKnownZero, RHSKnownOne, Depth+1))
1172 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1173 "Bits known to be one AND zero?");
1174 RHSKnownZero <<= ShiftAmt;
1175 RHSKnownOne <<= ShiftAmt;
1176 // low bits known zero.
1178 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1181 case Instruction::LShr:
1182 // For a logical shift right
1183 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1184 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1186 // Unsigned shift right.
1187 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1188 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1189 RHSKnownZero, RHSKnownOne, Depth+1))
1191 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1192 "Bits known to be one AND zero?");
1193 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1194 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1196 // Compute the new bits that are at the top now.
1197 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1198 RHSKnownZero |= HighBits; // high bits known zero.
1202 case Instruction::AShr:
1203 // If this is an arithmetic shift right and only the low-bit is set, we can
1204 // always convert this into a logical shr, even if the shift amount is
1205 // variable. The low bit of the shift cannot be an input sign bit unless
1206 // the shift amount is >= the size of the datatype, which is undefined.
1207 if (DemandedMask == 1) {
1208 // Perform the logical shift right.
1209 Value *NewVal = BinaryOperator::CreateLShr(
1210 I->getOperand(0), I->getOperand(1), I->getName());
1211 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1212 return UpdateValueUsesWith(I, NewVal);
1215 // If the sign bit is the only bit demanded by this ashr, then there is no
1216 // need to do it, the shift doesn't change the high bit.
1217 if (DemandedMask.isSignBit())
1218 return UpdateValueUsesWith(I, I->getOperand(0));
1220 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1221 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1223 // Signed shift right.
1224 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1225 // If any of the "high bits" are demanded, we should set the sign bit as
1227 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1228 DemandedMaskIn.set(BitWidth-1);
1229 if (SimplifyDemandedBits(I->getOperand(0),
1231 RHSKnownZero, RHSKnownOne, Depth+1))
1233 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1234 "Bits known to be one AND zero?");
1235 // Compute the new bits that are at the top now.
1236 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1237 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1238 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1240 // Handle the sign bits.
1241 APInt SignBit(APInt::getSignBit(BitWidth));
1242 // Adjust to where it is now in the mask.
1243 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1245 // If the input sign bit is known to be zero, or if none of the top bits
1246 // are demanded, turn this into an unsigned shift right.
1247 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
1248 (HighBits & ~DemandedMask) == HighBits) {
1249 // Perform the logical shift right.
1250 Value *NewVal = BinaryOperator::CreateLShr(
1251 I->getOperand(0), SA, I->getName());
1252 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1253 return UpdateValueUsesWith(I, NewVal);
1254 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1255 RHSKnownOne |= HighBits;
1259 case Instruction::SRem:
1260 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1261 APInt RA = Rem->getValue().abs();
1262 if (RA.isPowerOf2()) {
1263 if (DemandedMask.ule(RA)) // srem won't affect demanded bits
1264 return UpdateValueUsesWith(I, I->getOperand(0));
1266 APInt LowBits = RA - 1;
1267 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1268 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1269 LHSKnownZero, LHSKnownOne, Depth+1))
1272 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1273 LHSKnownZero |= ~LowBits;
1275 KnownZero |= LHSKnownZero & DemandedMask;
1277 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1281 case Instruction::URem: {
1282 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1283 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1284 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1285 KnownZero2, KnownOne2, Depth+1))
1288 uint32_t Leaders = KnownZero2.countLeadingOnes();
1289 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1290 KnownZero2, KnownOne2, Depth+1))
1293 Leaders = std::max(Leaders,
1294 KnownZero2.countLeadingOnes());
1295 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1298 case Instruction::Call:
1299 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1300 switch (II->getIntrinsicID()) {
1302 case Intrinsic::bswap: {
1303 // If the only bits demanded come from one byte of the bswap result,
1304 // just shift the input byte into position to eliminate the bswap.
1305 unsigned NLZ = DemandedMask.countLeadingZeros();
1306 unsigned NTZ = DemandedMask.countTrailingZeros();
1308 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1309 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1310 // have 14 leading zeros, round to 8.
1313 // If we need exactly one byte, we can do this transformation.
1314 if (BitWidth-NLZ-NTZ == 8) {
1315 unsigned ResultBit = NTZ;
1316 unsigned InputBit = BitWidth-NTZ-8;
1318 // Replace this with either a left or right shift to get the byte into
1320 Instruction *NewVal;
1321 if (InputBit > ResultBit)
1322 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1323 ConstantInt::get(I->getType(), InputBit-ResultBit));
1325 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1326 ConstantInt::get(I->getType(), ResultBit-InputBit));
1327 NewVal->takeName(I);
1328 InsertNewInstBefore(NewVal, *I);
1329 return UpdateValueUsesWith(I, NewVal);
1332 // TODO: Could compute known zero/one bits based on the input.
1337 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1341 // If the client is only demanding bits that we know, return the known
1343 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1344 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1349 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1350 /// 64 or fewer elements. DemandedElts contains the set of elements that are
1351 /// actually used by the caller. This method analyzes which elements of the
1352 /// operand are undef and returns that information in UndefElts.
1354 /// If the information about demanded elements can be used to simplify the
1355 /// operation, the operation is simplified, then the resultant value is
1356 /// returned. This returns null if no change was made.
1357 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1358 uint64_t &UndefElts,
1360 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1361 assert(VWidth <= 64 && "Vector too wide to analyze!");
1362 uint64_t EltMask = ~0ULL >> (64-VWidth);
1363 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1365 if (isa<UndefValue>(V)) {
1366 // If the entire vector is undefined, just return this info.
1367 UndefElts = EltMask;
1369 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1370 UndefElts = EltMask;
1371 return UndefValue::get(V->getType());
1375 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1376 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1377 Constant *Undef = UndefValue::get(EltTy);
1379 std::vector<Constant*> Elts;
1380 for (unsigned i = 0; i != VWidth; ++i)
1381 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1382 Elts.push_back(Undef);
1383 UndefElts |= (1ULL << i);
1384 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1385 Elts.push_back(Undef);
1386 UndefElts |= (1ULL << i);
1387 } else { // Otherwise, defined.
1388 Elts.push_back(CP->getOperand(i));
1391 // If we changed the constant, return it.
1392 Constant *NewCP = ConstantVector::get(Elts);
1393 return NewCP != CP ? NewCP : 0;
1394 } else if (isa<ConstantAggregateZero>(V)) {
1395 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1398 // Check if this is identity. If so, return 0 since we are not simplifying
1400 if (DemandedElts == ((1ULL << VWidth) -1))
1403 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1404 Constant *Zero = Constant::getNullValue(EltTy);
1405 Constant *Undef = UndefValue::get(EltTy);
1406 std::vector<Constant*> Elts;
1407 for (unsigned i = 0; i != VWidth; ++i)
1408 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1409 UndefElts = DemandedElts ^ EltMask;
1410 return ConstantVector::get(Elts);
1413 // Limit search depth.
1417 // If multiple users are using the root value, procede with
1418 // simplification conservatively assuming that all elements
1420 if (!V->hasOneUse()) {
1421 // Quit if we find multiple users of a non-root value though.
1422 // They'll be handled when it's their turn to be visited by
1423 // the main instcombine process.
1425 // TODO: Just compute the UndefElts information recursively.
1428 // Conservatively assume that all elements are needed.
1429 DemandedElts = EltMask;
1432 Instruction *I = dyn_cast<Instruction>(V);
1433 if (!I) return false; // Only analyze instructions.
1435 bool MadeChange = false;
1436 uint64_t UndefElts2;
1438 switch (I->getOpcode()) {
1441 case Instruction::InsertElement: {
1442 // If this is a variable index, we don't know which element it overwrites.
1443 // demand exactly the same input as we produce.
1444 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1446 // Note that we can't propagate undef elt info, because we don't know
1447 // which elt is getting updated.
1448 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1449 UndefElts2, Depth+1);
1450 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1454 // If this is inserting an element that isn't demanded, remove this
1456 unsigned IdxNo = Idx->getZExtValue();
1457 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1458 return AddSoonDeadInstToWorklist(*I, 0);
1460 // Otherwise, the element inserted overwrites whatever was there, so the
1461 // input demanded set is simpler than the output set.
1462 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1463 DemandedElts & ~(1ULL << IdxNo),
1464 UndefElts, Depth+1);
1465 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1467 // The inserted element is defined.
1468 UndefElts &= ~(1ULL << IdxNo);
1471 case Instruction::ShuffleVector: {
1472 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1473 uint64_t LHSVWidth =
1474 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1475 uint64_t LeftDemanded = 0, RightDemanded = 0;
1476 for (unsigned i = 0; i < VWidth; i++) {
1477 if (DemandedElts & (1ULL << i)) {
1478 unsigned MaskVal = Shuffle->getMaskValue(i);
1479 if (MaskVal != -1u) {
1480 assert(MaskVal < LHSVWidth * 2 &&
1481 "shufflevector mask index out of range!");
1482 if (MaskVal < LHSVWidth)
1483 LeftDemanded |= 1ULL << MaskVal;
1485 RightDemanded |= 1ULL << (MaskVal - LHSVWidth);
1490 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1491 UndefElts2, Depth+1);
1492 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1494 uint64_t UndefElts3;
1495 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1496 UndefElts3, Depth+1);
1497 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1499 bool NewUndefElts = false;
1500 for (unsigned i = 0; i < VWidth; i++) {
1501 unsigned MaskVal = Shuffle->getMaskValue(i);
1502 if (MaskVal == -1u) {
1503 uint64_t NewBit = 1ULL << i;
1504 UndefElts |= NewBit;
1505 } else if (MaskVal < LHSVWidth) {
1506 uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i;
1507 NewUndefElts |= NewBit;
1508 UndefElts |= NewBit;
1510 uint64_t NewBit = ((UndefElts3 >> (MaskVal - LHSVWidth)) & 1) << i;
1511 NewUndefElts |= NewBit;
1512 UndefElts |= NewBit;
1517 // Add additional discovered undefs.
1518 std::vector<Constant*> Elts;
1519 for (unsigned i = 0; i < VWidth; ++i) {
1520 if (UndefElts & (1ULL << i))
1521 Elts.push_back(UndefValue::get(Type::Int32Ty));
1523 Elts.push_back(ConstantInt::get(Type::Int32Ty,
1524 Shuffle->getMaskValue(i)));
1526 I->setOperand(2, ConstantVector::get(Elts));
1531 case Instruction::BitCast: {
1532 // Vector->vector casts only.
1533 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1535 unsigned InVWidth = VTy->getNumElements();
1536 uint64_t InputDemandedElts = 0;
1539 if (VWidth == InVWidth) {
1540 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1541 // elements as are demanded of us.
1543 InputDemandedElts = DemandedElts;
1544 } else if (VWidth > InVWidth) {
1548 // If there are more elements in the result than there are in the source,
1549 // then an input element is live if any of the corresponding output
1550 // elements are live.
1551 Ratio = VWidth/InVWidth;
1552 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1553 if (DemandedElts & (1ULL << OutIdx))
1554 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1560 // If there are more elements in the source than there are in the result,
1561 // then an input element is live if the corresponding output element is
1563 Ratio = InVWidth/VWidth;
1564 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1565 if (DemandedElts & (1ULL << InIdx/Ratio))
1566 InputDemandedElts |= 1ULL << InIdx;
1569 // div/rem demand all inputs, because they don't want divide by zero.
1570 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1571 UndefElts2, Depth+1);
1573 I->setOperand(0, TmpV);
1577 UndefElts = UndefElts2;
1578 if (VWidth > InVWidth) {
1579 assert(0 && "Unimp");
1580 // If there are more elements in the result than there are in the source,
1581 // then an output element is undef if the corresponding input element is
1583 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1584 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1585 UndefElts |= 1ULL << OutIdx;
1586 } else if (VWidth < InVWidth) {
1587 assert(0 && "Unimp");
1588 // If there are more elements in the source than there are in the result,
1589 // then a result element is undef if all of the corresponding input
1590 // elements are undef.
1591 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1592 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1593 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1594 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1598 case Instruction::And:
1599 case Instruction::Or:
1600 case Instruction::Xor:
1601 case Instruction::Add:
1602 case Instruction::Sub:
1603 case Instruction::Mul:
1604 // div/rem demand all inputs, because they don't want divide by zero.
1605 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1606 UndefElts, Depth+1);
1607 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1608 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1609 UndefElts2, Depth+1);
1610 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1612 // Output elements are undefined if both are undefined. Consider things
1613 // like undef&0. The result is known zero, not undef.
1614 UndefElts &= UndefElts2;
1617 case Instruction::Call: {
1618 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1620 switch (II->getIntrinsicID()) {
1623 // Binary vector operations that work column-wise. A dest element is a
1624 // function of the corresponding input elements from the two inputs.
1625 case Intrinsic::x86_sse_sub_ss:
1626 case Intrinsic::x86_sse_mul_ss:
1627 case Intrinsic::x86_sse_min_ss:
1628 case Intrinsic::x86_sse_max_ss:
1629 case Intrinsic::x86_sse2_sub_sd:
1630 case Intrinsic::x86_sse2_mul_sd:
1631 case Intrinsic::x86_sse2_min_sd:
1632 case Intrinsic::x86_sse2_max_sd:
1633 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1634 UndefElts, Depth+1);
1635 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1636 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1637 UndefElts2, Depth+1);
1638 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1640 // If only the low elt is demanded and this is a scalarizable intrinsic,
1641 // scalarize it now.
1642 if (DemandedElts == 1) {
1643 switch (II->getIntrinsicID()) {
1645 case Intrinsic::x86_sse_sub_ss:
1646 case Intrinsic::x86_sse_mul_ss:
1647 case Intrinsic::x86_sse2_sub_sd:
1648 case Intrinsic::x86_sse2_mul_sd:
1649 // TODO: Lower MIN/MAX/ABS/etc
1650 Value *LHS = II->getOperand(1);
1651 Value *RHS = II->getOperand(2);
1652 // Extract the element as scalars.
1653 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1654 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1656 switch (II->getIntrinsicID()) {
1657 default: assert(0 && "Case stmts out of sync!");
1658 case Intrinsic::x86_sse_sub_ss:
1659 case Intrinsic::x86_sse2_sub_sd:
1660 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1661 II->getName()), *II);
1663 case Intrinsic::x86_sse_mul_ss:
1664 case Intrinsic::x86_sse2_mul_sd:
1665 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1666 II->getName()), *II);
1671 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1673 InsertNewInstBefore(New, *II);
1674 AddSoonDeadInstToWorklist(*II, 0);
1679 // Output elements are undefined if both are undefined. Consider things
1680 // like undef&0. The result is known zero, not undef.
1681 UndefElts &= UndefElts2;
1687 return MadeChange ? I : 0;
1691 /// AssociativeOpt - Perform an optimization on an associative operator. This
1692 /// function is designed to check a chain of associative operators for a
1693 /// potential to apply a certain optimization. Since the optimization may be
1694 /// applicable if the expression was reassociated, this checks the chain, then
1695 /// reassociates the expression as necessary to expose the optimization
1696 /// opportunity. This makes use of a special Functor, which must define
1697 /// 'shouldApply' and 'apply' methods.
1699 template<typename Functor>
1700 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1701 unsigned Opcode = Root.getOpcode();
1702 Value *LHS = Root.getOperand(0);
1704 // Quick check, see if the immediate LHS matches...
1705 if (F.shouldApply(LHS))
1706 return F.apply(Root);
1708 // Otherwise, if the LHS is not of the same opcode as the root, return.
1709 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1710 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1711 // Should we apply this transform to the RHS?
1712 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1714 // If not to the RHS, check to see if we should apply to the LHS...
1715 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1716 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1720 // If the functor wants to apply the optimization to the RHS of LHSI,
1721 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1723 // Now all of the instructions are in the current basic block, go ahead
1724 // and perform the reassociation.
1725 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1727 // First move the selected RHS to the LHS of the root...
1728 Root.setOperand(0, LHSI->getOperand(1));
1730 // Make what used to be the LHS of the root be the user of the root...
1731 Value *ExtraOperand = TmpLHSI->getOperand(1);
1732 if (&Root == TmpLHSI) {
1733 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1736 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1737 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1738 BasicBlock::iterator ARI = &Root; ++ARI;
1739 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
1742 // Now propagate the ExtraOperand down the chain of instructions until we
1744 while (TmpLHSI != LHSI) {
1745 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1746 // Move the instruction to immediately before the chain we are
1747 // constructing to avoid breaking dominance properties.
1748 NextLHSI->moveBefore(ARI);
1751 Value *NextOp = NextLHSI->getOperand(1);
1752 NextLHSI->setOperand(1, ExtraOperand);
1754 ExtraOperand = NextOp;
1757 // Now that the instructions are reassociated, have the functor perform
1758 // the transformation...
1759 return F.apply(Root);
1762 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1769 // AddRHS - Implements: X + X --> X << 1
1772 AddRHS(Value *rhs) : RHS(rhs) {}
1773 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1774 Instruction *apply(BinaryOperator &Add) const {
1775 return BinaryOperator::CreateShl(Add.getOperand(0),
1776 ConstantInt::get(Add.getType(), 1));
1780 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1782 struct AddMaskingAnd {
1784 AddMaskingAnd(Constant *c) : C2(c) {}
1785 bool shouldApply(Value *LHS) const {
1787 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1788 ConstantExpr::getAnd(C1, C2)->isNullValue();
1790 Instruction *apply(BinaryOperator &Add) const {
1791 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1797 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1799 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1800 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1803 // Figure out if the constant is the left or the right argument.
1804 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1805 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1807 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1809 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1810 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1813 Value *Op0 = SO, *Op1 = ConstOperand;
1815 std::swap(Op0, Op1);
1817 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1818 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1819 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1820 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1821 SO->getName()+".cmp");
1823 assert(0 && "Unknown binary instruction type!");
1826 return IC->InsertNewInstBefore(New, I);
1829 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1830 // constant as the other operand, try to fold the binary operator into the
1831 // select arguments. This also works for Cast instructions, which obviously do
1832 // not have a second operand.
1833 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1835 // Don't modify shared select instructions
1836 if (!SI->hasOneUse()) return 0;
1837 Value *TV = SI->getOperand(1);
1838 Value *FV = SI->getOperand(2);
1840 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1841 // Bool selects with constant operands can be folded to logical ops.
1842 if (SI->getType() == Type::Int1Ty) return 0;
1844 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1845 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1847 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1854 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1855 /// node as operand #0, see if we can fold the instruction into the PHI (which
1856 /// is only possible if all operands to the PHI are constants).
1857 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1858 PHINode *PN = cast<PHINode>(I.getOperand(0));
1859 unsigned NumPHIValues = PN->getNumIncomingValues();
1860 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1862 // Check to see if all of the operands of the PHI are constants. If there is
1863 // one non-constant value, remember the BB it is. If there is more than one
1864 // or if *it* is a PHI, bail out.
1865 BasicBlock *NonConstBB = 0;
1866 for (unsigned i = 0; i != NumPHIValues; ++i)
1867 if (!isa<Constant>(PN->getIncomingValue(i))) {
1868 if (NonConstBB) return 0; // More than one non-const value.
1869 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1870 NonConstBB = PN->getIncomingBlock(i);
1872 // If the incoming non-constant value is in I's block, we have an infinite
1874 if (NonConstBB == I.getParent())
1878 // If there is exactly one non-constant value, we can insert a copy of the
1879 // operation in that block. However, if this is a critical edge, we would be
1880 // inserting the computation one some other paths (e.g. inside a loop). Only
1881 // do this if the pred block is unconditionally branching into the phi block.
1883 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1884 if (!BI || !BI->isUnconditional()) return 0;
1887 // Okay, we can do the transformation: create the new PHI node.
1888 PHINode *NewPN = PHINode::Create(I.getType(), "");
1889 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1890 InsertNewInstBefore(NewPN, *PN);
1891 NewPN->takeName(PN);
1893 // Next, add all of the operands to the PHI.
1894 if (I.getNumOperands() == 2) {
1895 Constant *C = cast<Constant>(I.getOperand(1));
1896 for (unsigned i = 0; i != NumPHIValues; ++i) {
1898 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1899 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1900 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1902 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1904 assert(PN->getIncomingBlock(i) == NonConstBB);
1905 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1906 InV = BinaryOperator::Create(BO->getOpcode(),
1907 PN->getIncomingValue(i), C, "phitmp",
1908 NonConstBB->getTerminator());
1909 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1910 InV = CmpInst::Create(CI->getOpcode(),
1912 PN->getIncomingValue(i), C, "phitmp",
1913 NonConstBB->getTerminator());
1915 assert(0 && "Unknown binop!");
1917 AddToWorkList(cast<Instruction>(InV));
1919 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1922 CastInst *CI = cast<CastInst>(&I);
1923 const Type *RetTy = CI->getType();
1924 for (unsigned i = 0; i != NumPHIValues; ++i) {
1926 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1927 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1929 assert(PN->getIncomingBlock(i) == NonConstBB);
1930 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
1931 I.getType(), "phitmp",
1932 NonConstBB->getTerminator());
1933 AddToWorkList(cast<Instruction>(InV));
1935 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1938 return ReplaceInstUsesWith(I, NewPN);
1942 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1943 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1944 /// This basically requires proving that the add in the original type would not
1945 /// overflow to change the sign bit or have a carry out.
1946 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1947 // There are different heuristics we can use for this. Here are some simple
1950 // Add has the property that adding any two 2's complement numbers can only
1951 // have one carry bit which can change a sign. As such, if LHS and RHS each
1952 // have at least two sign bits, we know that the addition of the two values will
1953 // sign extend fine.
1954 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1958 // If one of the operands only has one non-zero bit, and if the other operand
1959 // has a known-zero bit in a more significant place than it (not including the
1960 // sign bit) the ripple may go up to and fill the zero, but won't change the
1961 // sign. For example, (X & ~4) + 1.
1969 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1970 bool Changed = SimplifyCommutative(I);
1971 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1973 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1974 // X + undef -> undef
1975 if (isa<UndefValue>(RHS))
1976 return ReplaceInstUsesWith(I, RHS);
1979 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1980 if (RHSC->isNullValue())
1981 return ReplaceInstUsesWith(I, LHS);
1982 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1983 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1984 (I.getType())->getValueAPF()))
1985 return ReplaceInstUsesWith(I, LHS);
1988 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1989 // X + (signbit) --> X ^ signbit
1990 const APInt& Val = CI->getValue();
1991 uint32_t BitWidth = Val.getBitWidth();
1992 if (Val == APInt::getSignBit(BitWidth))
1993 return BinaryOperator::CreateXor(LHS, RHS);
1995 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1996 // (X & 254)+1 -> (X&254)|1
1997 if (!isa<VectorType>(I.getType())) {
1998 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1999 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2000 KnownZero, KnownOne))
2004 // zext(i1) - 1 -> select i1, 0, -1
2005 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2006 if (CI->isAllOnesValue() &&
2007 ZI->getOperand(0)->getType() == Type::Int1Ty)
2008 return SelectInst::Create(ZI->getOperand(0),
2009 Constant::getNullValue(I.getType()),
2010 ConstantInt::getAllOnesValue(I.getType()));
2013 if (isa<PHINode>(LHS))
2014 if (Instruction *NV = FoldOpIntoPhi(I))
2017 ConstantInt *XorRHS = 0;
2019 if (isa<ConstantInt>(RHSC) &&
2020 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2021 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2022 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2024 uint32_t Size = TySizeBits / 2;
2025 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2026 APInt CFF80Val(-C0080Val);
2028 if (TySizeBits > Size) {
2029 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2030 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2031 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2032 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2033 // This is a sign extend if the top bits are known zero.
2034 if (!MaskedValueIsZero(XorLHS,
2035 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2036 Size = 0; // Not a sign ext, but can't be any others either.
2041 C0080Val = APIntOps::lshr(C0080Val, Size);
2042 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2043 } while (Size >= 1);
2045 // FIXME: This shouldn't be necessary. When the backends can handle types
2046 // with funny bit widths then this switch statement should be removed. It
2047 // is just here to get the size of the "middle" type back up to something
2048 // that the back ends can handle.
2049 const Type *MiddleType = 0;
2052 case 32: MiddleType = Type::Int32Ty; break;
2053 case 16: MiddleType = Type::Int16Ty; break;
2054 case 8: MiddleType = Type::Int8Ty; break;
2057 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2058 InsertNewInstBefore(NewTrunc, I);
2059 return new SExtInst(NewTrunc, I.getType(), I.getName());
2064 if (I.getType() == Type::Int1Ty)
2065 return BinaryOperator::CreateXor(LHS, RHS);
2068 if (I.getType()->isInteger()) {
2069 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2071 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2072 if (RHSI->getOpcode() == Instruction::Sub)
2073 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2074 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2076 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2077 if (LHSI->getOpcode() == Instruction::Sub)
2078 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2079 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2084 // -A + -B --> -(A + B)
2085 if (Value *LHSV = dyn_castNegVal(LHS)) {
2086 if (LHS->getType()->isIntOrIntVector()) {
2087 if (Value *RHSV = dyn_castNegVal(RHS)) {
2088 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2089 InsertNewInstBefore(NewAdd, I);
2090 return BinaryOperator::CreateNeg(NewAdd);
2094 return BinaryOperator::CreateSub(RHS, LHSV);
2098 if (!isa<Constant>(RHS))
2099 if (Value *V = dyn_castNegVal(RHS))
2100 return BinaryOperator::CreateSub(LHS, V);
2104 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2105 if (X == RHS) // X*C + X --> X * (C+1)
2106 return BinaryOperator::CreateMul(RHS, AddOne(C2));
2108 // X*C1 + X*C2 --> X * (C1+C2)
2110 if (X == dyn_castFoldableMul(RHS, C1))
2111 return BinaryOperator::CreateMul(X, Add(C1, C2));
2114 // X + X*C --> X * (C+1)
2115 if (dyn_castFoldableMul(RHS, C2) == LHS)
2116 return BinaryOperator::CreateMul(LHS, AddOne(C2));
2118 // X + ~X --> -1 since ~X = -X-1
2119 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2120 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2123 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2124 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2125 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2128 // A+B --> A|B iff A and B have no bits set in common.
2129 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2130 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2131 APInt LHSKnownOne(IT->getBitWidth(), 0);
2132 APInt LHSKnownZero(IT->getBitWidth(), 0);
2133 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2134 if (LHSKnownZero != 0) {
2135 APInt RHSKnownOne(IT->getBitWidth(), 0);
2136 APInt RHSKnownZero(IT->getBitWidth(), 0);
2137 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2139 // No bits in common -> bitwise or.
2140 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2141 return BinaryOperator::CreateOr(LHS, RHS);
2145 // W*X + Y*Z --> W * (X+Z) iff W == Y
2146 if (I.getType()->isIntOrIntVector()) {
2147 Value *W, *X, *Y, *Z;
2148 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2149 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2153 } else if (Y == X) {
2155 } else if (X == Z) {
2162 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2163 LHS->getName()), I);
2164 return BinaryOperator::CreateMul(W, NewAdd);
2169 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2171 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2172 return BinaryOperator::CreateSub(SubOne(CRHS), X);
2174 // (X & FF00) + xx00 -> (X+xx00) & FF00
2175 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2176 Constant *Anded = And(CRHS, C2);
2177 if (Anded == CRHS) {
2178 // See if all bits from the first bit set in the Add RHS up are included
2179 // in the mask. First, get the rightmost bit.
2180 const APInt& AddRHSV = CRHS->getValue();
2182 // Form a mask of all bits from the lowest bit added through the top.
2183 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2185 // See if the and mask includes all of these bits.
2186 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2188 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2189 // Okay, the xform is safe. Insert the new add pronto.
2190 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2191 LHS->getName()), I);
2192 return BinaryOperator::CreateAnd(NewAdd, C2);
2197 // Try to fold constant add into select arguments.
2198 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2199 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2203 // add (cast *A to intptrtype) B ->
2204 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
2206 CastInst *CI = dyn_cast<CastInst>(LHS);
2209 CI = dyn_cast<CastInst>(RHS);
2212 if (CI && CI->getType()->isSized() &&
2213 (CI->getType()->getPrimitiveSizeInBits() ==
2214 TD->getIntPtrType()->getPrimitiveSizeInBits())
2215 && isa<PointerType>(CI->getOperand(0)->getType())) {
2217 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2218 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2219 PointerType::get(Type::Int8Ty, AS), I);
2220 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2221 return new PtrToIntInst(I2, CI->getType());
2225 // add (select X 0 (sub n A)) A --> select X A n
2227 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2230 SI = dyn_cast<SelectInst>(RHS);
2233 if (SI && SI->hasOneUse()) {
2234 Value *TV = SI->getTrueValue();
2235 Value *FV = SI->getFalseValue();
2238 // Can we fold the add into the argument of the select?
2239 // We check both true and false select arguments for a matching subtract.
2240 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2241 // Fold the add into the true select value.
2242 return SelectInst::Create(SI->getCondition(), N, A);
2243 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2244 // Fold the add into the false select value.
2245 return SelectInst::Create(SI->getCondition(), A, N);
2249 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2250 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2251 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2252 return ReplaceInstUsesWith(I, LHS);
2254 // Check for (add (sext x), y), see if we can merge this into an
2255 // integer add followed by a sext.
2256 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2257 // (add (sext x), cst) --> (sext (add x, cst'))
2258 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2260 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2261 if (LHSConv->hasOneUse() &&
2262 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2263 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2264 // Insert the new, smaller add.
2265 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2267 InsertNewInstBefore(NewAdd, I);
2268 return new SExtInst(NewAdd, I.getType());
2272 // (add (sext x), (sext y)) --> (sext (add int x, y))
2273 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2274 // Only do this if x/y have the same type, if at last one of them has a
2275 // single use (so we don't increase the number of sexts), and if the
2276 // integer add will not overflow.
2277 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2278 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2279 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2280 RHSConv->getOperand(0))) {
2281 // Insert the new integer add.
2282 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2283 RHSConv->getOperand(0),
2285 InsertNewInstBefore(NewAdd, I);
2286 return new SExtInst(NewAdd, I.getType());
2291 // Check for (add double (sitofp x), y), see if we can merge this into an
2292 // integer add followed by a promotion.
2293 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2294 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2295 // ... if the constant fits in the integer value. This is useful for things
2296 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2297 // requires a constant pool load, and generally allows the add to be better
2299 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2301 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2302 if (LHSConv->hasOneUse() &&
2303 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2304 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2305 // Insert the new integer add.
2306 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2308 InsertNewInstBefore(NewAdd, I);
2309 return new SIToFPInst(NewAdd, I.getType());
2313 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2314 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2315 // Only do this if x/y have the same type, if at last one of them has a
2316 // single use (so we don't increase the number of int->fp conversions),
2317 // and if the integer add will not overflow.
2318 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2319 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2320 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2321 RHSConv->getOperand(0))) {
2322 // Insert the new integer add.
2323 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2324 RHSConv->getOperand(0),
2326 InsertNewInstBefore(NewAdd, I);
2327 return new SIToFPInst(NewAdd, I.getType());
2332 return Changed ? &I : 0;
2335 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2336 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2338 if (Op0 == Op1 && // sub X, X -> 0
2339 !I.getType()->isFPOrFPVector())
2340 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2342 // If this is a 'B = x-(-A)', change to B = x+A...
2343 if (Value *V = dyn_castNegVal(Op1))
2344 return BinaryOperator::CreateAdd(Op0, V);
2346 if (isa<UndefValue>(Op0))
2347 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2348 if (isa<UndefValue>(Op1))
2349 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2351 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2352 // Replace (-1 - A) with (~A)...
2353 if (C->isAllOnesValue())
2354 return BinaryOperator::CreateNot(Op1);
2356 // C - ~X == X + (1+C)
2358 if (match(Op1, m_Not(m_Value(X))))
2359 return BinaryOperator::CreateAdd(X, AddOne(C));
2361 // -(X >>u 31) -> (X >>s 31)
2362 // -(X >>s 31) -> (X >>u 31)
2364 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2365 if (SI->getOpcode() == Instruction::LShr) {
2366 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2367 // Check to see if we are shifting out everything but the sign bit.
2368 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2369 SI->getType()->getPrimitiveSizeInBits()-1) {
2370 // Ok, the transformation is safe. Insert AShr.
2371 return BinaryOperator::Create(Instruction::AShr,
2372 SI->getOperand(0), CU, SI->getName());
2376 else if (SI->getOpcode() == Instruction::AShr) {
2377 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2378 // Check to see if we are shifting out everything but the sign bit.
2379 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2380 SI->getType()->getPrimitiveSizeInBits()-1) {
2381 // Ok, the transformation is safe. Insert LShr.
2382 return BinaryOperator::CreateLShr(
2383 SI->getOperand(0), CU, SI->getName());
2390 // Try to fold constant sub into select arguments.
2391 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2392 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2396 if (I.getType() == Type::Int1Ty)
2397 return BinaryOperator::CreateXor(Op0, Op1);
2399 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2400 if (Op1I->getOpcode() == Instruction::Add &&
2401 !Op0->getType()->isFPOrFPVector()) {
2402 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2403 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2404 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2405 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2406 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2407 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2408 // C1-(X+C2) --> (C1-C2)-X
2409 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
2410 Op1I->getOperand(0));
2414 if (Op1I->hasOneUse()) {
2415 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2416 // is not used by anyone else...
2418 if (Op1I->getOpcode() == Instruction::Sub &&
2419 !Op1I->getType()->isFPOrFPVector()) {
2420 // Swap the two operands of the subexpr...
2421 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2422 Op1I->setOperand(0, IIOp1);
2423 Op1I->setOperand(1, IIOp0);
2425 // Create the new top level add instruction...
2426 return BinaryOperator::CreateAdd(Op0, Op1);
2429 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2431 if (Op1I->getOpcode() == Instruction::And &&
2432 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2433 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2436 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2437 return BinaryOperator::CreateAnd(Op0, NewNot);
2440 // 0 - (X sdiv C) -> (X sdiv -C)
2441 if (Op1I->getOpcode() == Instruction::SDiv)
2442 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2444 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2445 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2446 ConstantExpr::getNeg(DivRHS));
2448 // X - X*C --> X * (1-C)
2449 ConstantInt *C2 = 0;
2450 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2451 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2452 return BinaryOperator::CreateMul(Op0, CP1);
2457 if (!Op0->getType()->isFPOrFPVector())
2458 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2459 if (Op0I->getOpcode() == Instruction::Add) {
2460 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2461 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2462 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2463 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2464 } else if (Op0I->getOpcode() == Instruction::Sub) {
2465 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2466 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2471 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2472 if (X == Op1) // X*C - X --> X * (C-1)
2473 return BinaryOperator::CreateMul(Op1, SubOne(C1));
2475 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2476 if (X == dyn_castFoldableMul(Op1, C2))
2477 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2482 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2483 /// comparison only checks the sign bit. If it only checks the sign bit, set
2484 /// TrueIfSigned if the result of the comparison is true when the input value is
2486 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2487 bool &TrueIfSigned) {
2489 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2490 TrueIfSigned = true;
2491 return RHS->isZero();
2492 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2493 TrueIfSigned = true;
2494 return RHS->isAllOnesValue();
2495 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2496 TrueIfSigned = false;
2497 return RHS->isAllOnesValue();
2498 case ICmpInst::ICMP_UGT:
2499 // True if LHS u> RHS and RHS == high-bit-mask - 1
2500 TrueIfSigned = true;
2501 return RHS->getValue() ==
2502 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2503 case ICmpInst::ICMP_UGE:
2504 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2505 TrueIfSigned = true;
2506 return RHS->getValue().isSignBit();
2512 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2513 bool Changed = SimplifyCommutative(I);
2514 Value *Op0 = I.getOperand(0);
2516 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2517 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2519 // Simplify mul instructions with a constant RHS...
2520 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2521 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2523 // ((X << C1)*C2) == (X * (C2 << C1))
2524 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2525 if (SI->getOpcode() == Instruction::Shl)
2526 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2527 return BinaryOperator::CreateMul(SI->getOperand(0),
2528 ConstantExpr::getShl(CI, ShOp));
2531 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2532 if (CI->equalsInt(1)) // X * 1 == X
2533 return ReplaceInstUsesWith(I, Op0);
2534 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2535 return BinaryOperator::CreateNeg(Op0, I.getName());
2537 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2538 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2539 return BinaryOperator::CreateShl(Op0,
2540 ConstantInt::get(Op0->getType(), Val.logBase2()));
2542 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2543 if (Op1F->isNullValue())
2544 return ReplaceInstUsesWith(I, Op1);
2546 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2547 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2548 if (Op1F->isExactlyValue(1.0))
2549 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2550 } else if (isa<VectorType>(Op1->getType())) {
2551 if (isa<ConstantAggregateZero>(Op1))
2552 return ReplaceInstUsesWith(I, Op1);
2554 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2555 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2556 return BinaryOperator::CreateNeg(Op0, I.getName());
2558 // As above, vector X*splat(1.0) -> X in all defined cases.
2559 if (Constant *Splat = Op1V->getSplatValue()) {
2560 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2561 if (F->isExactlyValue(1.0))
2562 return ReplaceInstUsesWith(I, Op0);
2563 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2564 if (CI->equalsInt(1))
2565 return ReplaceInstUsesWith(I, Op0);
2570 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2571 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2572 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2573 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2574 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2576 InsertNewInstBefore(Add, I);
2577 Value *C1C2 = ConstantExpr::getMul(Op1,
2578 cast<Constant>(Op0I->getOperand(1)));
2579 return BinaryOperator::CreateAdd(Add, C1C2);
2583 // Try to fold constant mul into select arguments.
2584 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2585 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2588 if (isa<PHINode>(Op0))
2589 if (Instruction *NV = FoldOpIntoPhi(I))
2593 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2594 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2595 return BinaryOperator::CreateMul(Op0v, Op1v);
2597 // (X / Y) * Y = X - (X % Y)
2598 // (X / Y) * -Y = (X % Y) - X
2600 Value *Op1 = I.getOperand(1);
2601 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2603 (BO->getOpcode() != Instruction::UDiv &&
2604 BO->getOpcode() != Instruction::SDiv)) {
2606 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2608 Value *Neg = dyn_castNegVal(Op1);
2609 if (BO && BO->hasOneUse() &&
2610 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2611 (BO->getOpcode() == Instruction::UDiv ||
2612 BO->getOpcode() == Instruction::SDiv)) {
2613 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2616 if (BO->getOpcode() == Instruction::UDiv)
2617 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2619 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2621 InsertNewInstBefore(Rem, I);
2625 return BinaryOperator::CreateSub(Op0BO, Rem);
2627 return BinaryOperator::CreateSub(Rem, Op0BO);
2631 if (I.getType() == Type::Int1Ty)
2632 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2634 // If one of the operands of the multiply is a cast from a boolean value, then
2635 // we know the bool is either zero or one, so this is a 'masking' multiply.
2636 // See if we can simplify things based on how the boolean was originally
2638 CastInst *BoolCast = 0;
2639 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2640 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2643 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2644 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2647 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2648 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2649 const Type *SCOpTy = SCIOp0->getType();
2652 // If the icmp is true iff the sign bit of X is set, then convert this
2653 // multiply into a shift/and combination.
2654 if (isa<ConstantInt>(SCIOp1) &&
2655 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2657 // Shift the X value right to turn it into "all signbits".
2658 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2659 SCOpTy->getPrimitiveSizeInBits()-1);
2661 InsertNewInstBefore(
2662 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2663 BoolCast->getOperand(0)->getName()+
2666 // If the multiply type is not the same as the source type, sign extend
2667 // or truncate to the multiply type.
2668 if (I.getType() != V->getType()) {
2669 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2670 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2671 Instruction::CastOps opcode =
2672 (SrcBits == DstBits ? Instruction::BitCast :
2673 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2674 V = InsertCastBefore(opcode, V, I.getType(), I);
2677 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2678 return BinaryOperator::CreateAnd(V, OtherOp);
2683 return Changed ? &I : 0;
2686 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2688 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2689 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2691 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2692 int NonNullOperand = -1;
2693 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2694 if (ST->isNullValue())
2696 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2697 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2698 if (ST->isNullValue())
2701 if (NonNullOperand == -1)
2704 Value *SelectCond = SI->getOperand(0);
2706 // Change the div/rem to use 'Y' instead of the select.
2707 I.setOperand(1, SI->getOperand(NonNullOperand));
2709 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2710 // problem. However, the select, or the condition of the select may have
2711 // multiple uses. Based on our knowledge that the operand must be non-zero,
2712 // propagate the known value for the select into other uses of it, and
2713 // propagate a known value of the condition into its other users.
2715 // If the select and condition only have a single use, don't bother with this,
2717 if (SI->use_empty() && SelectCond->hasOneUse())
2720 // Scan the current block backward, looking for other uses of SI.
2721 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2723 while (BBI != BBFront) {
2725 // If we found a call to a function, we can't assume it will return, so
2726 // information from below it cannot be propagated above it.
2727 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2730 // Replace uses of the select or its condition with the known values.
2731 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2734 *I = SI->getOperand(NonNullOperand);
2736 } else if (*I == SelectCond) {
2737 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2738 ConstantInt::getFalse();
2743 // If we past the instruction, quit looking for it.
2746 if (&*BBI == SelectCond)
2749 // If we ran out of things to eliminate, break out of the loop.
2750 if (SelectCond == 0 && SI == 0)
2758 /// This function implements the transforms on div instructions that work
2759 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2760 /// used by the visitors to those instructions.
2761 /// @brief Transforms common to all three div instructions
2762 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2763 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2765 // undef / X -> 0 for integer.
2766 // undef / X -> undef for FP (the undef could be a snan).
2767 if (isa<UndefValue>(Op0)) {
2768 if (Op0->getType()->isFPOrFPVector())
2769 return ReplaceInstUsesWith(I, Op0);
2770 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2773 // X / undef -> undef
2774 if (isa<UndefValue>(Op1))
2775 return ReplaceInstUsesWith(I, Op1);
2780 /// This function implements the transforms common to both integer division
2781 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2782 /// division instructions.
2783 /// @brief Common integer divide transforms
2784 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2785 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2787 // (sdiv X, X) --> 1 (udiv X, X) --> 1
2789 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2790 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2791 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2792 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2795 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2796 return ReplaceInstUsesWith(I, CI);
2799 if (Instruction *Common = commonDivTransforms(I))
2802 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2803 // This does not apply for fdiv.
2804 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2807 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2809 if (RHS->equalsInt(1))
2810 return ReplaceInstUsesWith(I, Op0);
2812 // (X / C1) / C2 -> X / (C1*C2)
2813 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2814 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2815 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2816 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2817 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2819 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2820 Multiply(RHS, LHSRHS));
2823 if (!RHS->isZero()) { // avoid X udiv 0
2824 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2825 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2827 if (isa<PHINode>(Op0))
2828 if (Instruction *NV = FoldOpIntoPhi(I))
2833 // 0 / X == 0, we don't need to preserve faults!
2834 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2835 if (LHS->equalsInt(0))
2836 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2838 // It can't be division by zero, hence it must be division by one.
2839 if (I.getType() == Type::Int1Ty)
2840 return ReplaceInstUsesWith(I, Op0);
2842 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2843 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2846 return ReplaceInstUsesWith(I, Op0);
2852 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2853 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2855 // Handle the integer div common cases
2856 if (Instruction *Common = commonIDivTransforms(I))
2859 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2860 // X udiv C^2 -> X >> C
2861 // Check to see if this is an unsigned division with an exact power of 2,
2862 // if so, convert to a right shift.
2863 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
2864 return BinaryOperator::CreateLShr(Op0,
2865 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2867 // X udiv C, where C >= signbit
2868 if (C->getValue().isNegative()) {
2869 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2871 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2872 ConstantInt::get(I.getType(), 1));
2876 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2877 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2878 if (RHSI->getOpcode() == Instruction::Shl &&
2879 isa<ConstantInt>(RHSI->getOperand(0))) {
2880 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2881 if (C1.isPowerOf2()) {
2882 Value *N = RHSI->getOperand(1);
2883 const Type *NTy = N->getType();
2884 if (uint32_t C2 = C1.logBase2()) {
2885 Constant *C2V = ConstantInt::get(NTy, C2);
2886 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2888 return BinaryOperator::CreateLShr(Op0, N);
2893 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2894 // where C1&C2 are powers of two.
2895 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2896 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2897 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2898 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2899 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2900 // Compute the shift amounts
2901 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2902 // Construct the "on true" case of the select
2903 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2904 Instruction *TSI = BinaryOperator::CreateLShr(
2905 Op0, TC, SI->getName()+".t");
2906 TSI = InsertNewInstBefore(TSI, I);
2908 // Construct the "on false" case of the select
2909 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2910 Instruction *FSI = BinaryOperator::CreateLShr(
2911 Op0, FC, SI->getName()+".f");
2912 FSI = InsertNewInstBefore(FSI, I);
2914 // construct the select instruction and return it.
2915 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2921 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2922 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2924 // Handle the integer div common cases
2925 if (Instruction *Common = commonIDivTransforms(I))
2928 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2930 if (RHS->isAllOnesValue())
2931 return BinaryOperator::CreateNeg(Op0);
2934 // If the sign bits of both operands are zero (i.e. we can prove they are
2935 // unsigned inputs), turn this into a udiv.
2936 if (I.getType()->isInteger()) {
2937 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2938 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2939 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2940 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2947 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2948 return commonDivTransforms(I);
2951 /// This function implements the transforms on rem instructions that work
2952 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2953 /// is used by the visitors to those instructions.
2954 /// @brief Transforms common to all three rem instructions
2955 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2956 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2958 // 0 % X == 0 for integer, we don't need to preserve faults!
2959 if (Constant *LHS = dyn_cast<Constant>(Op0))
2960 if (LHS->isNullValue())
2961 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2963 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2964 if (I.getType()->isFPOrFPVector())
2965 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
2966 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2968 if (isa<UndefValue>(Op1))
2969 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2971 // Handle cases involving: rem X, (select Cond, Y, Z)
2972 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2978 /// This function implements the transforms common to both integer remainder
2979 /// instructions (urem and srem). It is called by the visitors to those integer
2980 /// remainder instructions.
2981 /// @brief Common integer remainder transforms
2982 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2983 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2985 if (Instruction *common = commonRemTransforms(I))
2988 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2989 // X % 0 == undef, we don't need to preserve faults!
2990 if (RHS->equalsInt(0))
2991 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2993 if (RHS->equalsInt(1)) // X % 1 == 0
2994 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2996 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2997 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2998 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3000 } else if (isa<PHINode>(Op0I)) {
3001 if (Instruction *NV = FoldOpIntoPhi(I))
3005 // See if we can fold away this rem instruction.
3006 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3007 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3008 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3009 KnownZero, KnownOne))
3017 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3018 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3020 if (Instruction *common = commonIRemTransforms(I))
3023 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3024 // X urem C^2 -> X and C
3025 // Check to see if this is an unsigned remainder with an exact power of 2,
3026 // if so, convert to a bitwise and.
3027 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3028 if (C->getValue().isPowerOf2())
3029 return BinaryOperator::CreateAnd(Op0, SubOne(C));
3032 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3033 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3034 if (RHSI->getOpcode() == Instruction::Shl &&
3035 isa<ConstantInt>(RHSI->getOperand(0))) {
3036 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3037 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
3038 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3040 return BinaryOperator::CreateAnd(Op0, Add);
3045 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3046 // where C1&C2 are powers of two.
3047 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3048 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3049 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3050 // STO == 0 and SFO == 0 handled above.
3051 if ((STO->getValue().isPowerOf2()) &&
3052 (SFO->getValue().isPowerOf2())) {
3053 Value *TrueAnd = InsertNewInstBefore(
3054 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
3055 Value *FalseAnd = InsertNewInstBefore(
3056 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
3057 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3065 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3066 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3068 // Handle the integer rem common cases
3069 if (Instruction *common = commonIRemTransforms(I))
3072 if (Value *RHSNeg = dyn_castNegVal(Op1))
3073 if (!isa<Constant>(RHSNeg) ||
3074 (isa<ConstantInt>(RHSNeg) &&
3075 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3077 AddUsesToWorkList(I);
3078 I.setOperand(1, RHSNeg);
3082 // If the sign bits of both operands are zero (i.e. we can prove they are
3083 // unsigned inputs), turn this into a urem.
3084 if (I.getType()->isInteger()) {
3085 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3086 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3087 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3088 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3092 // If it's a constant vector, flip any negative values positive.
3093 if (isa<VectorType>(I.getType())) {
3094 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3095 unsigned VWidth = RHSV->getNumOperands();
3096 std::vector<Constant *> Elts(VWidth);
3098 for (unsigned i = 0; i != VWidth; ++i) {
3099 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3100 if (RHS->getValue().isNegative())
3101 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3107 Constant *NewRHSV = ConstantVector::get(Elts);
3108 if (NewRHSV != RHSV) {
3109 I.setOperand(1, NewRHSV);
3118 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3119 return commonRemTransforms(I);
3122 // isOneBitSet - Return true if there is exactly one bit set in the specified
3124 static bool isOneBitSet(const ConstantInt *CI) {
3125 return CI->getValue().isPowerOf2();
3128 // isHighOnes - Return true if the constant is of the form 1+0+.
3129 // This is the same as lowones(~X).
3130 static bool isHighOnes(const ConstantInt *CI) {
3131 return (~CI->getValue() + 1).isPowerOf2();
3134 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3135 /// are carefully arranged to allow folding of expressions such as:
3137 /// (A < B) | (A > B) --> (A != B)
3139 /// Note that this is only valid if the first and second predicates have the
3140 /// same sign. Is illegal to do: (A u< B) | (A s> B)
3142 /// Three bits are used to represent the condition, as follows:
3147 /// <=> Value Definition
3148 /// 000 0 Always false
3155 /// 111 7 Always true
3157 static unsigned getICmpCode(const ICmpInst *ICI) {
3158 switch (ICI->getPredicate()) {
3160 case ICmpInst::ICMP_UGT: return 1; // 001
3161 case ICmpInst::ICMP_SGT: return 1; // 001
3162 case ICmpInst::ICMP_EQ: return 2; // 010
3163 case ICmpInst::ICMP_UGE: return 3; // 011
3164 case ICmpInst::ICMP_SGE: return 3; // 011
3165 case ICmpInst::ICMP_ULT: return 4; // 100
3166 case ICmpInst::ICMP_SLT: return 4; // 100
3167 case ICmpInst::ICMP_NE: return 5; // 101
3168 case ICmpInst::ICMP_ULE: return 6; // 110
3169 case ICmpInst::ICMP_SLE: return 6; // 110
3172 assert(0 && "Invalid ICmp predicate!");
3177 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3178 /// predicate into a three bit mask. It also returns whether it is an ordered
3179 /// predicate by reference.
3180 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3183 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3184 case FCmpInst::FCMP_UNO: return 0; // 000
3185 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3186 case FCmpInst::FCMP_UGT: return 1; // 001
3187 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3188 case FCmpInst::FCMP_UEQ: return 2; // 010
3189 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3190 case FCmpInst::FCMP_UGE: return 3; // 011
3191 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3192 case FCmpInst::FCMP_ULT: return 4; // 100
3193 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3194 case FCmpInst::FCMP_UNE: return 5; // 101
3195 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3196 case FCmpInst::FCMP_ULE: return 6; // 110
3199 // Not expecting FCMP_FALSE and FCMP_TRUE;
3200 assert(0 && "Unexpected FCmp predicate!");
3205 /// getICmpValue - This is the complement of getICmpCode, which turns an
3206 /// opcode and two operands into either a constant true or false, or a brand
3207 /// new ICmp instruction. The sign is passed in to determine which kind
3208 /// of predicate to use in the new icmp instruction.
3209 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3211 default: assert(0 && "Illegal ICmp code!");
3212 case 0: return ConstantInt::getFalse();
3215 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3217 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3218 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3221 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3223 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3226 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3228 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3229 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3232 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3234 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3235 case 7: return ConstantInt::getTrue();
3239 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3240 /// opcode and two operands into either a FCmp instruction. isordered is passed
3241 /// in to determine which kind of predicate to use in the new fcmp instruction.
3242 static Value *getFCmpValue(bool isordered, unsigned code,
3243 Value *LHS, Value *RHS) {
3245 default: assert(0 && "Illegal FCmp code!");
3248 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3250 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3253 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3255 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3258 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3260 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3263 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3265 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3268 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3270 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3273 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3275 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3278 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3280 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3281 case 7: return ConstantInt::getTrue();
3285 /// PredicatesFoldable - Return true if both predicates match sign or if at
3286 /// least one of them is an equality comparison (which is signless).
3287 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3288 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3289 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3290 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3294 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3295 struct FoldICmpLogical {
3298 ICmpInst::Predicate pred;
3299 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3300 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3301 pred(ICI->getPredicate()) {}
3302 bool shouldApply(Value *V) const {
3303 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3304 if (PredicatesFoldable(pred, ICI->getPredicate()))
3305 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3306 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3309 Instruction *apply(Instruction &Log) const {
3310 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3311 if (ICI->getOperand(0) != LHS) {
3312 assert(ICI->getOperand(1) == LHS);
3313 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3316 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3317 unsigned LHSCode = getICmpCode(ICI);
3318 unsigned RHSCode = getICmpCode(RHSICI);
3320 switch (Log.getOpcode()) {
3321 case Instruction::And: Code = LHSCode & RHSCode; break;
3322 case Instruction::Or: Code = LHSCode | RHSCode; break;
3323 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3324 default: assert(0 && "Illegal logical opcode!"); return 0;
3327 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3328 ICmpInst::isSignedPredicate(ICI->getPredicate());
3330 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3331 if (Instruction *I = dyn_cast<Instruction>(RV))
3333 // Otherwise, it's a constant boolean value...
3334 return IC.ReplaceInstUsesWith(Log, RV);
3337 } // end anonymous namespace
3339 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3340 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3341 // guaranteed to be a binary operator.
3342 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3344 ConstantInt *AndRHS,
3345 BinaryOperator &TheAnd) {
3346 Value *X = Op->getOperand(0);
3347 Constant *Together = 0;
3349 Together = And(AndRHS, OpRHS);
3351 switch (Op->getOpcode()) {
3352 case Instruction::Xor:
3353 if (Op->hasOneUse()) {
3354 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3355 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3356 InsertNewInstBefore(And, TheAnd);
3358 return BinaryOperator::CreateXor(And, Together);
3361 case Instruction::Or:
3362 if (Together == AndRHS) // (X | C) & C --> C
3363 return ReplaceInstUsesWith(TheAnd, AndRHS);
3365 if (Op->hasOneUse() && Together != OpRHS) {
3366 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3367 Instruction *Or = BinaryOperator::CreateOr(X, Together);
3368 InsertNewInstBefore(Or, TheAnd);
3370 return BinaryOperator::CreateAnd(Or, AndRHS);
3373 case Instruction::Add:
3374 if (Op->hasOneUse()) {
3375 // Adding a one to a single bit bit-field should be turned into an XOR
3376 // of the bit. First thing to check is to see if this AND is with a
3377 // single bit constant.
3378 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3380 // If there is only one bit set...
3381 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3382 // Ok, at this point, we know that we are masking the result of the
3383 // ADD down to exactly one bit. If the constant we are adding has
3384 // no bits set below this bit, then we can eliminate the ADD.
3385 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3387 // Check to see if any bits below the one bit set in AndRHSV are set.
3388 if ((AddRHS & (AndRHSV-1)) == 0) {
3389 // If not, the only thing that can effect the output of the AND is
3390 // the bit specified by AndRHSV. If that bit is set, the effect of
3391 // the XOR is to toggle the bit. If it is clear, then the ADD has
3393 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3394 TheAnd.setOperand(0, X);
3397 // Pull the XOR out of the AND.
3398 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3399 InsertNewInstBefore(NewAnd, TheAnd);
3400 NewAnd->takeName(Op);
3401 return BinaryOperator::CreateXor(NewAnd, AndRHS);
3408 case Instruction::Shl: {
3409 // We know that the AND will not produce any of the bits shifted in, so if
3410 // the anded constant includes them, clear them now!
3412 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3413 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3414 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3415 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3417 if (CI->getValue() == ShlMask) {
3418 // Masking out bits that the shift already masks
3419 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3420 } else if (CI != AndRHS) { // Reducing bits set in and.
3421 TheAnd.setOperand(1, CI);
3426 case Instruction::LShr:
3428 // We know that the AND will not produce any of the bits shifted in, so if
3429 // the anded constant includes them, clear them now! This only applies to
3430 // unsigned shifts, because a signed shr may bring in set bits!
3432 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3433 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3434 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3435 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3437 if (CI->getValue() == ShrMask) {
3438 // Masking out bits that the shift already masks.
3439 return ReplaceInstUsesWith(TheAnd, Op);
3440 } else if (CI != AndRHS) {
3441 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3446 case Instruction::AShr:
3448 // See if this is shifting in some sign extension, then masking it out
3450 if (Op->hasOneUse()) {
3451 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3452 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3453 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3454 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3455 if (C == AndRHS) { // Masking out bits shifted in.
3456 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3457 // Make the argument unsigned.
3458 Value *ShVal = Op->getOperand(0);
3459 ShVal = InsertNewInstBefore(
3460 BinaryOperator::CreateLShr(ShVal, OpRHS,
3461 Op->getName()), TheAnd);
3462 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3471 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3472 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3473 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3474 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3475 /// insert new instructions.
3476 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3477 bool isSigned, bool Inside,
3479 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3480 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3481 "Lo is not <= Hi in range emission code!");
3484 if (Lo == Hi) // Trivially false.
3485 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3487 // V >= Min && V < Hi --> V < Hi
3488 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3489 ICmpInst::Predicate pred = (isSigned ?
3490 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3491 return new ICmpInst(pred, V, Hi);
3494 // Emit V-Lo <u Hi-Lo
3495 Constant *NegLo = ConstantExpr::getNeg(Lo);
3496 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3497 InsertNewInstBefore(Add, IB);
3498 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3499 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3502 if (Lo == Hi) // Trivially true.
3503 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3505 // V < Min || V >= Hi -> V > Hi-1
3506 Hi = SubOne(cast<ConstantInt>(Hi));
3507 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3508 ICmpInst::Predicate pred = (isSigned ?
3509 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3510 return new ICmpInst(pred, V, Hi);
3513 // Emit V-Lo >u Hi-1-Lo
3514 // Note that Hi has already had one subtracted from it, above.
3515 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3516 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3517 InsertNewInstBefore(Add, IB);
3518 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3519 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3522 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3523 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3524 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3525 // not, since all 1s are not contiguous.
3526 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3527 const APInt& V = Val->getValue();
3528 uint32_t BitWidth = Val->getType()->getBitWidth();
3529 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3531 // look for the first zero bit after the run of ones
3532 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3533 // look for the first non-zero bit
3534 ME = V.getActiveBits();
3538 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3539 /// where isSub determines whether the operator is a sub. If we can fold one of
3540 /// the following xforms:
3542 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3543 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3544 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3546 /// return (A +/- B).
3548 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3549 ConstantInt *Mask, bool isSub,
3551 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3552 if (!LHSI || LHSI->getNumOperands() != 2 ||
3553 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3555 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3557 switch (LHSI->getOpcode()) {
3559 case Instruction::And:
3560 if (And(N, Mask) == Mask) {
3561 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3562 if ((Mask->getValue().countLeadingZeros() +
3563 Mask->getValue().countPopulation()) ==
3564 Mask->getValue().getBitWidth())
3567 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3568 // part, we don't need any explicit masks to take them out of A. If that
3569 // is all N is, ignore it.
3570 uint32_t MB = 0, ME = 0;
3571 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3572 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3573 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3574 if (MaskedValueIsZero(RHS, Mask))
3579 case Instruction::Or:
3580 case Instruction::Xor:
3581 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3582 if ((Mask->getValue().countLeadingZeros() +
3583 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3584 && And(N, Mask)->isZero())
3591 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3593 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3594 return InsertNewInstBefore(New, I);
3597 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3598 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3599 ICmpInst *LHS, ICmpInst *RHS) {
3601 ConstantInt *LHSCst, *RHSCst;
3602 ICmpInst::Predicate LHSCC, RHSCC;
3604 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3605 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3606 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
3609 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3610 // where C is a power of 2
3611 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3612 LHSCst->getValue().isPowerOf2()) {
3613 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3614 InsertNewInstBefore(NewOr, I);
3615 return new ICmpInst(LHSCC, NewOr, LHSCst);
3618 // From here on, we only handle:
3619 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3620 if (Val != Val2) return 0;
3622 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3623 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3624 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3625 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3626 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3629 // We can't fold (ugt x, C) & (sgt x, C2).
3630 if (!PredicatesFoldable(LHSCC, RHSCC))
3633 // Ensure that the larger constant is on the RHS.
3635 if (ICmpInst::isSignedPredicate(LHSCC) ||
3636 (ICmpInst::isEquality(LHSCC) &&
3637 ICmpInst::isSignedPredicate(RHSCC)))
3638 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3640 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3643 std::swap(LHS, RHS);
3644 std::swap(LHSCst, RHSCst);
3645 std::swap(LHSCC, RHSCC);
3648 // At this point, we know we have have two icmp instructions
3649 // comparing a value against two constants and and'ing the result
3650 // together. Because of the above check, we know that we only have
3651 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3652 // (from the FoldICmpLogical check above), that the two constants
3653 // are not equal and that the larger constant is on the RHS
3654 assert(LHSCst != RHSCst && "Compares not folded above?");
3657 default: assert(0 && "Unknown integer condition code!");
3658 case ICmpInst::ICMP_EQ:
3660 default: assert(0 && "Unknown integer condition code!");
3661 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3662 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3663 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3664 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3665 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3666 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3667 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3668 return ReplaceInstUsesWith(I, LHS);
3670 case ICmpInst::ICMP_NE:
3672 default: assert(0 && "Unknown integer condition code!");
3673 case ICmpInst::ICMP_ULT:
3674 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3675 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3676 break; // (X != 13 & X u< 15) -> no change
3677 case ICmpInst::ICMP_SLT:
3678 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3679 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3680 break; // (X != 13 & X s< 15) -> no change
3681 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3682 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3683 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3684 return ReplaceInstUsesWith(I, RHS);
3685 case ICmpInst::ICMP_NE:
3686 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3687 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3688 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3689 Val->getName()+".off");
3690 InsertNewInstBefore(Add, I);
3691 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3692 ConstantInt::get(Add->getType(), 1));
3694 break; // (X != 13 & X != 15) -> no change
3697 case ICmpInst::ICMP_ULT:
3699 default: assert(0 && "Unknown integer condition code!");
3700 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3701 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3702 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3703 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3705 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3706 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3707 return ReplaceInstUsesWith(I, LHS);
3708 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3712 case ICmpInst::ICMP_SLT:
3714 default: assert(0 && "Unknown integer condition code!");
3715 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3716 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3717 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3718 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3720 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3721 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3722 return ReplaceInstUsesWith(I, LHS);
3723 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3727 case ICmpInst::ICMP_UGT:
3729 default: assert(0 && "Unknown integer condition code!");
3730 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3731 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3732 return ReplaceInstUsesWith(I, RHS);
3733 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3735 case ICmpInst::ICMP_NE:
3736 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3737 return new ICmpInst(LHSCC, Val, RHSCst);
3738 break; // (X u> 13 & X != 15) -> no change
3739 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
3740 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3741 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3745 case ICmpInst::ICMP_SGT:
3747 default: assert(0 && "Unknown integer condition code!");
3748 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3749 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3750 return ReplaceInstUsesWith(I, RHS);
3751 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3753 case ICmpInst::ICMP_NE:
3754 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3755 return new ICmpInst(LHSCC, Val, RHSCst);
3756 break; // (X s> 13 & X != 15) -> no change
3757 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
3758 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3759 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3769 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3770 bool Changed = SimplifyCommutative(I);
3771 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3773 if (isa<UndefValue>(Op1)) // X & undef -> 0
3774 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3778 return ReplaceInstUsesWith(I, Op1);
3780 // See if we can simplify any instructions used by the instruction whose sole
3781 // purpose is to compute bits we don't care about.
3782 if (!isa<VectorType>(I.getType())) {
3783 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3784 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3785 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3786 KnownZero, KnownOne))
3789 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3790 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3791 return ReplaceInstUsesWith(I, I.getOperand(0));
3792 } else if (isa<ConstantAggregateZero>(Op1)) {
3793 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3797 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3798 const APInt& AndRHSMask = AndRHS->getValue();
3799 APInt NotAndRHS(~AndRHSMask);
3801 // Optimize a variety of ((val OP C1) & C2) combinations...
3802 if (isa<BinaryOperator>(Op0)) {
3803 Instruction *Op0I = cast<Instruction>(Op0);
3804 Value *Op0LHS = Op0I->getOperand(0);
3805 Value *Op0RHS = Op0I->getOperand(1);
3806 switch (Op0I->getOpcode()) {
3807 case Instruction::Xor:
3808 case Instruction::Or:
3809 // If the mask is only needed on one incoming arm, push it up.
3810 if (Op0I->hasOneUse()) {
3811 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3812 // Not masking anything out for the LHS, move to RHS.
3813 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3814 Op0RHS->getName()+".masked");
3815 InsertNewInstBefore(NewRHS, I);
3816 return BinaryOperator::Create(
3817 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3819 if (!isa<Constant>(Op0RHS) &&
3820 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3821 // Not masking anything out for the RHS, move to LHS.
3822 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3823 Op0LHS->getName()+".masked");
3824 InsertNewInstBefore(NewLHS, I);
3825 return BinaryOperator::Create(
3826 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3831 case Instruction::Add:
3832 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3833 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3834 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3835 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3836 return BinaryOperator::CreateAnd(V, AndRHS);
3837 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3838 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
3841 case Instruction::Sub:
3842 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3843 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3844 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3845 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3846 return BinaryOperator::CreateAnd(V, AndRHS);
3848 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3849 // has 1's for all bits that the subtraction with A might affect.
3850 if (Op0I->hasOneUse()) {
3851 uint32_t BitWidth = AndRHSMask.getBitWidth();
3852 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3853 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3855 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3856 if (!(A && A->isZero()) && // avoid infinite recursion.
3857 MaskedValueIsZero(Op0LHS, Mask)) {
3858 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3859 InsertNewInstBefore(NewNeg, I);
3860 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3865 case Instruction::Shl:
3866 case Instruction::LShr:
3867 // (1 << x) & 1 --> zext(x == 0)
3868 // (1 >> x) & 1 --> zext(x == 0)
3869 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3870 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3871 Constant::getNullValue(I.getType()));
3872 InsertNewInstBefore(NewICmp, I);
3873 return new ZExtInst(NewICmp, I.getType());
3878 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3879 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3881 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3882 // If this is an integer truncation or change from signed-to-unsigned, and
3883 // if the source is an and/or with immediate, transform it. This
3884 // frequently occurs for bitfield accesses.
3885 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3886 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3887 CastOp->getNumOperands() == 2)
3888 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3889 if (CastOp->getOpcode() == Instruction::And) {
3890 // Change: and (cast (and X, C1) to T), C2
3891 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3892 // This will fold the two constants together, which may allow
3893 // other simplifications.
3894 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3895 CastOp->getOperand(0), I.getType(),
3896 CastOp->getName()+".shrunk");
3897 NewCast = InsertNewInstBefore(NewCast, I);
3898 // trunc_or_bitcast(C1)&C2
3899 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3900 C3 = ConstantExpr::getAnd(C3, AndRHS);
3901 return BinaryOperator::CreateAnd(NewCast, C3);
3902 } else if (CastOp->getOpcode() == Instruction::Or) {
3903 // Change: and (cast (or X, C1) to T), C2
3904 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3905 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3906 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3907 return ReplaceInstUsesWith(I, AndRHS);
3913 // Try to fold constant and into select arguments.
3914 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3915 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3917 if (isa<PHINode>(Op0))
3918 if (Instruction *NV = FoldOpIntoPhi(I))
3922 Value *Op0NotVal = dyn_castNotVal(Op0);
3923 Value *Op1NotVal = dyn_castNotVal(Op1);
3925 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3926 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3928 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3929 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3930 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3931 I.getName()+".demorgan");
3932 InsertNewInstBefore(Or, I);
3933 return BinaryOperator::CreateNot(Or);
3937 Value *A = 0, *B = 0, *C = 0, *D = 0;
3938 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3939 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3940 return ReplaceInstUsesWith(I, Op1);
3942 // (A|B) & ~(A&B) -> A^B
3943 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3944 if ((A == C && B == D) || (A == D && B == C))
3945 return BinaryOperator::CreateXor(A, B);
3949 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3950 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3951 return ReplaceInstUsesWith(I, Op0);
3953 // ~(A&B) & (A|B) -> A^B
3954 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3955 if ((A == C && B == D) || (A == D && B == C))
3956 return BinaryOperator::CreateXor(A, B);
3960 if (Op0->hasOneUse() &&
3961 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3962 if (A == Op1) { // (A^B)&A -> A&(A^B)
3963 I.swapOperands(); // Simplify below
3964 std::swap(Op0, Op1);
3965 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3966 cast<BinaryOperator>(Op0)->swapOperands();
3967 I.swapOperands(); // Simplify below
3968 std::swap(Op0, Op1);
3972 if (Op1->hasOneUse() &&
3973 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3974 if (B == Op0) { // B&(A^B) -> B&(B^A)
3975 cast<BinaryOperator>(Op1)->swapOperands();
3978 if (A == Op0) { // A&(A^B) -> A & ~B
3979 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
3980 InsertNewInstBefore(NotB, I);
3981 return BinaryOperator::CreateAnd(A, NotB);
3985 // (A&((~A)|B)) -> A&B
3986 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
3987 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
3988 return BinaryOperator::CreateAnd(A, Op1);
3989 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
3990 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
3991 return BinaryOperator::CreateAnd(A, Op0);
3994 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3995 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3996 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3999 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4000 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4004 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4005 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4006 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4007 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4008 const Type *SrcTy = Op0C->getOperand(0)->getType();
4009 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4010 // Only do this if the casts both really cause code to be generated.
4011 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4013 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4015 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4016 Op1C->getOperand(0),
4018 InsertNewInstBefore(NewOp, I);
4019 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4023 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4024 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4025 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4026 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4027 SI0->getOperand(1) == SI1->getOperand(1) &&
4028 (SI0->hasOneUse() || SI1->hasOneUse())) {
4029 Instruction *NewOp =
4030 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4032 SI0->getName()), I);
4033 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4034 SI1->getOperand(1));
4038 // If and'ing two fcmp, try combine them into one.
4039 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4040 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4041 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4042 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4043 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4044 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4045 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4046 // If either of the constants are nans, then the whole thing returns
4048 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4049 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4050 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4051 RHS->getOperand(0));
4054 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4055 FCmpInst::Predicate Op0CC, Op1CC;
4056 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4057 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4058 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4059 // Swap RHS operands to match LHS.
4060 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4061 std::swap(Op1LHS, Op1RHS);
4063 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4064 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4066 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4067 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4068 Op1CC == FCmpInst::FCMP_FALSE)
4069 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4070 else if (Op0CC == FCmpInst::FCMP_TRUE)
4071 return ReplaceInstUsesWith(I, Op1);
4072 else if (Op1CC == FCmpInst::FCMP_TRUE)
4073 return ReplaceInstUsesWith(I, Op0);
4076 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4077 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4079 std::swap(Op0, Op1);
4080 std::swap(Op0Pred, Op1Pred);
4081 std::swap(Op0Ordered, Op1Ordered);
4084 // uno && ueq -> uno && (uno || eq) -> ueq
4085 // ord && olt -> ord && (ord && lt) -> olt
4086 if (Op0Ordered == Op1Ordered)
4087 return ReplaceInstUsesWith(I, Op1);
4088 // uno && oeq -> uno && (ord && eq) -> false
4089 // uno && ord -> false
4091 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4092 // ord && ueq -> ord && (uno || eq) -> oeq
4093 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4102 return Changed ? &I : 0;
4105 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4106 /// capable of providing pieces of a bswap. The subexpression provides pieces
4107 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4108 /// the expression came from the corresponding "byte swapped" byte in some other
4109 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4110 /// we know that the expression deposits the low byte of %X into the high byte
4111 /// of the bswap result and that all other bytes are zero. This expression is
4112 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4115 /// This function returns true if the match was unsuccessful and false if so.
4116 /// On entry to the function the "OverallLeftShift" is a signed integer value
4117 /// indicating the number of bytes that the subexpression is later shifted. For
4118 /// example, if the expression is later right shifted by 16 bits, the
4119 /// OverallLeftShift value would be -2 on entry. This is used to specify which
4120 /// byte of ByteValues is actually being set.
4122 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4123 /// byte is masked to zero by a user. For example, in (X & 255), X will be
4124 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4125 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
4126 /// always in the local (OverallLeftShift) coordinate space.
4128 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4129 SmallVector<Value*, 8> &ByteValues) {
4130 if (Instruction *I = dyn_cast<Instruction>(V)) {
4131 // If this is an or instruction, it may be an inner node of the bswap.
4132 if (I->getOpcode() == Instruction::Or) {
4133 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4135 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4139 // If this is a logical shift by a constant multiple of 8, recurse with
4140 // OverallLeftShift and ByteMask adjusted.
4141 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4143 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4144 // Ensure the shift amount is defined and of a byte value.
4145 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4148 unsigned ByteShift = ShAmt >> 3;
4149 if (I->getOpcode() == Instruction::Shl) {
4150 // X << 2 -> collect(X, +2)
4151 OverallLeftShift += ByteShift;
4152 ByteMask >>= ByteShift;
4154 // X >>u 2 -> collect(X, -2)
4155 OverallLeftShift -= ByteShift;
4156 ByteMask <<= ByteShift;
4157 ByteMask &= (~0U >> (32-ByteValues.size()));
4160 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4161 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4163 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4167 // If this is a logical 'and' with a mask that clears bytes, clear the
4168 // corresponding bytes in ByteMask.
4169 if (I->getOpcode() == Instruction::And &&
4170 isa<ConstantInt>(I->getOperand(1))) {
4171 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4172 unsigned NumBytes = ByteValues.size();
4173 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4174 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4176 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4177 // If this byte is masked out by a later operation, we don't care what
4179 if ((ByteMask & (1 << i)) == 0)
4182 // If the AndMask is all zeros for this byte, clear the bit.
4183 APInt MaskB = AndMask & Byte;
4185 ByteMask &= ~(1U << i);
4189 // If the AndMask is not all ones for this byte, it's not a bytezap.
4193 // Otherwise, this byte is kept.
4196 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4201 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4202 // the input value to the bswap. Some observations: 1) if more than one byte
4203 // is demanded from this input, then it could not be successfully assembled
4204 // into a byteswap. At least one of the two bytes would not be aligned with
4205 // their ultimate destination.
4206 if (!isPowerOf2_32(ByteMask)) return true;
4207 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4209 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4210 // is demanded, it needs to go into byte 0 of the result. This means that the
4211 // byte needs to be shifted until it lands in the right byte bucket. The
4212 // shift amount depends on the position: if the byte is coming from the high
4213 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4214 // low part, it must be shifted left.
4215 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4216 if (InputByteNo < ByteValues.size()/2) {
4217 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4220 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4224 // If the destination byte value is already defined, the values are or'd
4225 // together, which isn't a bswap (unless it's an or of the same bits).
4226 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4228 ByteValues[DestByteNo] = V;
4232 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4233 /// If so, insert the new bswap intrinsic and return it.
4234 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4235 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4236 if (!ITy || ITy->getBitWidth() % 16 ||
4237 // ByteMask only allows up to 32-byte values.
4238 ITy->getBitWidth() > 32*8)
4239 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4241 /// ByteValues - For each byte of the result, we keep track of which value
4242 /// defines each byte.
4243 SmallVector<Value*, 8> ByteValues;
4244 ByteValues.resize(ITy->getBitWidth()/8);
4246 // Try to find all the pieces corresponding to the bswap.
4247 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4248 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4251 // Check to see if all of the bytes come from the same value.
4252 Value *V = ByteValues[0];
4253 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4255 // Check to make sure that all of the bytes come from the same value.
4256 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4257 if (ByteValues[i] != V)
4259 const Type *Tys[] = { ITy };
4260 Module *M = I.getParent()->getParent()->getParent();
4261 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4262 return CallInst::Create(F, V);
4265 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4266 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4267 /// we can simplify this expression to "cond ? C : D or B".
4268 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4269 Value *C, Value *D) {
4270 // If A is not a select of -1/0, this cannot match.
4272 if (!match(A, m_SelectCst(m_Value(Cond), -1, 0)))
4275 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4276 if (match(D, m_SelectCst(m_Specific(Cond), 0, -1)))
4277 return SelectInst::Create(Cond, C, B);
4278 if (match(D, m_Not(m_SelectCst(m_Specific(Cond), -1, 0))))
4279 return SelectInst::Create(Cond, C, B);
4280 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4281 if (match(B, m_SelectCst(m_Specific(Cond), 0, -1)))
4282 return SelectInst::Create(Cond, C, D);
4283 if (match(B, m_Not(m_SelectCst(m_Specific(Cond), -1, 0))))
4284 return SelectInst::Create(Cond, C, D);
4288 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4289 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4290 ICmpInst *LHS, ICmpInst *RHS) {
4292 ConstantInt *LHSCst, *RHSCst;
4293 ICmpInst::Predicate LHSCC, RHSCC;
4295 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4296 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4297 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4300 // From here on, we only handle:
4301 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4302 if (Val != Val2) return 0;
4304 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4305 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4306 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4307 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4308 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4311 // We can't fold (ugt x, C) | (sgt x, C2).
4312 if (!PredicatesFoldable(LHSCC, RHSCC))
4315 // Ensure that the larger constant is on the RHS.
4317 if (ICmpInst::isSignedPredicate(LHSCC) ||
4318 (ICmpInst::isEquality(LHSCC) &&
4319 ICmpInst::isSignedPredicate(RHSCC)))
4320 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4322 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4325 std::swap(LHS, RHS);
4326 std::swap(LHSCst, RHSCst);
4327 std::swap(LHSCC, RHSCC);
4330 // At this point, we know we have have two icmp instructions
4331 // comparing a value against two constants and or'ing the result
4332 // together. Because of the above check, we know that we only have
4333 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4334 // FoldICmpLogical check above), that the two constants are not
4336 assert(LHSCst != RHSCst && "Compares not folded above?");
4339 default: assert(0 && "Unknown integer condition code!");
4340 case ICmpInst::ICMP_EQ:
4342 default: assert(0 && "Unknown integer condition code!");
4343 case ICmpInst::ICMP_EQ:
4344 if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4345 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4346 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4347 Val->getName()+".off");
4348 InsertNewInstBefore(Add, I);
4349 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4350 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4352 break; // (X == 13 | X == 15) -> no change
4353 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4354 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4356 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4357 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4358 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4359 return ReplaceInstUsesWith(I, RHS);
4362 case ICmpInst::ICMP_NE:
4364 default: assert(0 && "Unknown integer condition code!");
4365 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4366 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4367 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4368 return ReplaceInstUsesWith(I, LHS);
4369 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4370 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4371 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4372 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4375 case ICmpInst::ICMP_ULT:
4377 default: assert(0 && "Unknown integer condition code!");
4378 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4380 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4381 // If RHSCst is [us]MAXINT, it is always false. Not handling
4382 // this can cause overflow.
4383 if (RHSCst->isMaxValue(false))
4384 return ReplaceInstUsesWith(I, LHS);
4385 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4386 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4388 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4389 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4390 return ReplaceInstUsesWith(I, RHS);
4391 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4395 case ICmpInst::ICMP_SLT:
4397 default: assert(0 && "Unknown integer condition code!");
4398 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4400 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4401 // If RHSCst is [us]MAXINT, it is always false. Not handling
4402 // this can cause overflow.
4403 if (RHSCst->isMaxValue(true))
4404 return ReplaceInstUsesWith(I, LHS);
4405 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4406 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4408 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4409 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4410 return ReplaceInstUsesWith(I, RHS);
4411 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4415 case ICmpInst::ICMP_UGT:
4417 default: assert(0 && "Unknown integer condition code!");
4418 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4419 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4420 return ReplaceInstUsesWith(I, LHS);
4421 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4423 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4424 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4425 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4426 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4430 case ICmpInst::ICMP_SGT:
4432 default: assert(0 && "Unknown integer condition code!");
4433 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4434 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4435 return ReplaceInstUsesWith(I, LHS);
4436 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4438 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4439 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4440 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4441 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4449 /// FoldOrWithConstants - This helper function folds:
4451 /// ((A | B) & C1) | (B & C2)
4457 /// when the XOR of the two constants is "all ones" (-1).
4458 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4459 Value *A, Value *B, Value *C) {
4460 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4464 ConstantInt *CI2 = 0;
4465 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4467 APInt Xor = CI1->getValue() ^ CI2->getValue();
4468 if (!Xor.isAllOnesValue()) return 0;
4470 if (V1 == A || V1 == B) {
4471 Instruction *NewOp =
4472 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4473 return BinaryOperator::CreateOr(NewOp, V1);
4479 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4480 bool Changed = SimplifyCommutative(I);
4481 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4483 if (isa<UndefValue>(Op1)) // X | undef -> -1
4484 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4488 return ReplaceInstUsesWith(I, Op0);
4490 // See if we can simplify any instructions used by the instruction whose sole
4491 // purpose is to compute bits we don't care about.
4492 if (!isa<VectorType>(I.getType())) {
4493 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4494 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4495 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4496 KnownZero, KnownOne))
4498 } else if (isa<ConstantAggregateZero>(Op1)) {
4499 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4500 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4501 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4502 return ReplaceInstUsesWith(I, I.getOperand(1));
4508 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4509 ConstantInt *C1 = 0; Value *X = 0;
4510 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4511 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4512 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4513 InsertNewInstBefore(Or, I);
4515 return BinaryOperator::CreateAnd(Or,
4516 ConstantInt::get(RHS->getValue() | C1->getValue()));
4519 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4520 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4521 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4522 InsertNewInstBefore(Or, I);
4524 return BinaryOperator::CreateXor(Or,
4525 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4528 // Try to fold constant and into select arguments.
4529 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4530 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4532 if (isa<PHINode>(Op0))
4533 if (Instruction *NV = FoldOpIntoPhi(I))
4537 Value *A = 0, *B = 0;
4538 ConstantInt *C1 = 0, *C2 = 0;
4540 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4541 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4542 return ReplaceInstUsesWith(I, Op1);
4543 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4544 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4545 return ReplaceInstUsesWith(I, Op0);
4547 // (A | B) | C and A | (B | C) -> bswap if possible.
4548 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4549 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4550 match(Op1, m_Or(m_Value(), m_Value())) ||
4551 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4552 match(Op1, m_Shift(m_Value(), m_Value())))) {
4553 if (Instruction *BSwap = MatchBSwap(I))
4557 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4558 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4559 MaskedValueIsZero(Op1, C1->getValue())) {
4560 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4561 InsertNewInstBefore(NOr, I);
4563 return BinaryOperator::CreateXor(NOr, C1);
4566 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4567 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4568 MaskedValueIsZero(Op0, C1->getValue())) {
4569 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4570 InsertNewInstBefore(NOr, I);
4572 return BinaryOperator::CreateXor(NOr, C1);
4576 Value *C = 0, *D = 0;
4577 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4578 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4579 Value *V1 = 0, *V2 = 0, *V3 = 0;
4580 C1 = dyn_cast<ConstantInt>(C);
4581 C2 = dyn_cast<ConstantInt>(D);
4582 if (C1 && C2) { // (A & C1)|(B & C2)
4583 // If we have: ((V + N) & C1) | (V & C2)
4584 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4585 // replace with V+N.
4586 if (C1->getValue() == ~C2->getValue()) {
4587 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4588 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4589 // Add commutes, try both ways.
4590 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4591 return ReplaceInstUsesWith(I, A);
4592 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4593 return ReplaceInstUsesWith(I, A);
4595 // Or commutes, try both ways.
4596 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4597 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4598 // Add commutes, try both ways.
4599 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4600 return ReplaceInstUsesWith(I, B);
4601 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4602 return ReplaceInstUsesWith(I, B);
4605 V1 = 0; V2 = 0; V3 = 0;
4608 // Check to see if we have any common things being and'ed. If so, find the
4609 // terms for V1 & (V2|V3).
4610 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4611 if (A == B) // (A & C)|(A & D) == A & (C|D)
4612 V1 = A, V2 = C, V3 = D;
4613 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4614 V1 = A, V2 = B, V3 = C;
4615 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4616 V1 = C, V2 = A, V3 = D;
4617 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4618 V1 = C, V2 = A, V3 = B;
4622 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4623 return BinaryOperator::CreateAnd(V1, Or);
4627 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
4628 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4630 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4632 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4634 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4637 // ((A&~B)|(~A&B)) -> A^B
4638 if ((match(C, m_Not(m_Specific(D))) &&
4639 match(B, m_Not(m_Specific(A)))))
4640 return BinaryOperator::CreateXor(A, D);
4641 // ((~B&A)|(~A&B)) -> A^B
4642 if ((match(A, m_Not(m_Specific(D))) &&
4643 match(B, m_Not(m_Specific(C)))))
4644 return BinaryOperator::CreateXor(C, D);
4645 // ((A&~B)|(B&~A)) -> A^B
4646 if ((match(C, m_Not(m_Specific(B))) &&
4647 match(D, m_Not(m_Specific(A)))))
4648 return BinaryOperator::CreateXor(A, B);
4649 // ((~B&A)|(B&~A)) -> A^B
4650 if ((match(A, m_Not(m_Specific(B))) &&
4651 match(D, m_Not(m_Specific(C)))))
4652 return BinaryOperator::CreateXor(C, B);
4655 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4656 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4657 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4658 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4659 SI0->getOperand(1) == SI1->getOperand(1) &&
4660 (SI0->hasOneUse() || SI1->hasOneUse())) {
4661 Instruction *NewOp =
4662 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4664 SI0->getName()), I);
4665 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4666 SI1->getOperand(1));
4670 // ((A|B)&1)|(B&-2) -> (A&1) | B
4671 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4672 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4673 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4674 if (Ret) return Ret;
4676 // (B&-2)|((A|B)&1) -> (A&1) | B
4677 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4678 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4679 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4680 if (Ret) return Ret;
4683 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4684 if (A == Op1) // ~A | A == -1
4685 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4689 // Note, A is still live here!
4690 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4692 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4694 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4695 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4696 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4697 I.getName()+".demorgan"), I);
4698 return BinaryOperator::CreateNot(And);
4702 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4703 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4704 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4707 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4708 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4712 // fold (or (cast A), (cast B)) -> (cast (or A, B))
4713 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4714 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4715 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4716 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4717 !isa<ICmpInst>(Op1C->getOperand(0))) {
4718 const Type *SrcTy = Op0C->getOperand(0)->getType();
4719 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4720 // Only do this if the casts both really cause code to be
4722 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4724 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4726 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4727 Op1C->getOperand(0),
4729 InsertNewInstBefore(NewOp, I);
4730 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4737 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4738 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4739 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4740 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4741 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4742 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4743 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4744 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4745 // If either of the constants are nans, then the whole thing returns
4747 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4748 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4750 // Otherwise, no need to compare the two constants, compare the
4752 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4753 RHS->getOperand(0));
4756 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4757 FCmpInst::Predicate Op0CC, Op1CC;
4758 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4759 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4760 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4761 // Swap RHS operands to match LHS.
4762 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4763 std::swap(Op1LHS, Op1RHS);
4765 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4766 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4768 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4769 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4770 Op1CC == FCmpInst::FCMP_TRUE)
4771 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4772 else if (Op0CC == FCmpInst::FCMP_FALSE)
4773 return ReplaceInstUsesWith(I, Op1);
4774 else if (Op1CC == FCmpInst::FCMP_FALSE)
4775 return ReplaceInstUsesWith(I, Op0);
4778 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4779 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4780 if (Op0Ordered == Op1Ordered) {
4781 // If both are ordered or unordered, return a new fcmp with
4782 // or'ed predicates.
4783 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4785 if (Instruction *I = dyn_cast<Instruction>(RV))
4787 // Otherwise, it's a constant boolean value...
4788 return ReplaceInstUsesWith(I, RV);
4796 return Changed ? &I : 0;
4801 // XorSelf - Implements: X ^ X --> 0
4804 XorSelf(Value *rhs) : RHS(rhs) {}
4805 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4806 Instruction *apply(BinaryOperator &Xor) const {
4813 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4814 bool Changed = SimplifyCommutative(I);
4815 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4817 if (isa<UndefValue>(Op1)) {
4818 if (isa<UndefValue>(Op0))
4819 // Handle undef ^ undef -> 0 special case. This is a common
4821 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4822 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4825 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4826 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4827 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4828 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4831 // See if we can simplify any instructions used by the instruction whose sole
4832 // purpose is to compute bits we don't care about.
4833 if (!isa<VectorType>(I.getType())) {
4834 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4835 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4836 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4837 KnownZero, KnownOne))
4839 } else if (isa<ConstantAggregateZero>(Op1)) {
4840 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4843 // Is this a ~ operation?
4844 if (Value *NotOp = dyn_castNotVal(&I)) {
4845 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4846 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4847 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4848 if (Op0I->getOpcode() == Instruction::And ||
4849 Op0I->getOpcode() == Instruction::Or) {
4850 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4851 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4853 BinaryOperator::CreateNot(Op0I->getOperand(1),
4854 Op0I->getOperand(1)->getName()+".not");
4855 InsertNewInstBefore(NotY, I);
4856 if (Op0I->getOpcode() == Instruction::And)
4857 return BinaryOperator::CreateOr(Op0NotVal, NotY);
4859 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4866 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4867 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4868 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4869 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4870 return new ICmpInst(ICI->getInversePredicate(),
4871 ICI->getOperand(0), ICI->getOperand(1));
4873 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4874 return new FCmpInst(FCI->getInversePredicate(),
4875 FCI->getOperand(0), FCI->getOperand(1));
4878 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4879 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4880 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4881 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4882 Instruction::CastOps Opcode = Op0C->getOpcode();
4883 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4884 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4885 Op0C->getDestTy())) {
4886 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4887 CI->getOpcode(), CI->getInversePredicate(),
4888 CI->getOperand(0), CI->getOperand(1)), I);
4889 NewCI->takeName(CI);
4890 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4897 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4898 // ~(c-X) == X-c-1 == X+(-c-1)
4899 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4900 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4901 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4902 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4903 ConstantInt::get(I.getType(), 1));
4904 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4907 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4908 if (Op0I->getOpcode() == Instruction::Add) {
4909 // ~(X-c) --> (-c-1)-X
4910 if (RHS->isAllOnesValue()) {
4911 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4912 return BinaryOperator::CreateSub(
4913 ConstantExpr::getSub(NegOp0CI,
4914 ConstantInt::get(I.getType(), 1)),
4915 Op0I->getOperand(0));
4916 } else if (RHS->getValue().isSignBit()) {
4917 // (X + C) ^ signbit -> (X + C + signbit)
4918 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4919 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4922 } else if (Op0I->getOpcode() == Instruction::Or) {
4923 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4924 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4925 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4926 // Anything in both C1 and C2 is known to be zero, remove it from
4928 Constant *CommonBits = And(Op0CI, RHS);
4929 NewRHS = ConstantExpr::getAnd(NewRHS,
4930 ConstantExpr::getNot(CommonBits));
4931 AddToWorkList(Op0I);
4932 I.setOperand(0, Op0I->getOperand(0));
4933 I.setOperand(1, NewRHS);
4940 // Try to fold constant and into select arguments.
4941 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4942 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4944 if (isa<PHINode>(Op0))
4945 if (Instruction *NV = FoldOpIntoPhi(I))
4949 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4951 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4953 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4955 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4958 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4961 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4962 if (A == Op0) { // B^(B|A) == (A|B)^B
4963 Op1I->swapOperands();
4965 std::swap(Op0, Op1);
4966 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4967 I.swapOperands(); // Simplified below.
4968 std::swap(Op0, Op1);
4970 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
4971 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
4972 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
4973 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
4974 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4975 if (A == Op0) { // A^(A&B) -> A^(B&A)
4976 Op1I->swapOperands();
4979 if (B == Op0) { // A^(B&A) -> (B&A)^A
4980 I.swapOperands(); // Simplified below.
4981 std::swap(Op0, Op1);
4986 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4989 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4990 if (A == Op1) // (B|A)^B == (A|B)^B
4992 if (B == Op1) { // (A|B)^B == A & ~B
4994 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4995 return BinaryOperator::CreateAnd(A, NotB);
4997 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
4998 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
4999 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5000 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
5001 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5002 if (A == Op1) // (A&B)^A -> (B&A)^A
5004 if (B == Op1 && // (B&A)^A == ~B & A
5005 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5007 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5008 return BinaryOperator::CreateAnd(N, Op1);
5013 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5014 if (Op0I && Op1I && Op0I->isShift() &&
5015 Op0I->getOpcode() == Op1I->getOpcode() &&
5016 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5017 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5018 Instruction *NewOp =
5019 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5020 Op1I->getOperand(0),
5021 Op0I->getName()), I);
5022 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
5023 Op1I->getOperand(1));
5027 Value *A, *B, *C, *D;
5028 // (A & B)^(A | B) -> A ^ B
5029 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5030 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5031 if ((A == C && B == D) || (A == D && B == C))
5032 return BinaryOperator::CreateXor(A, B);
5034 // (A | B)^(A & B) -> A ^ B
5035 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5036 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5037 if ((A == C && B == D) || (A == D && B == C))
5038 return BinaryOperator::CreateXor(A, B);
5042 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5043 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5044 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5045 // (X & Y)^(X & Y) -> (Y^Z) & X
5046 Value *X = 0, *Y = 0, *Z = 0;
5048 X = A, Y = B, Z = D;
5050 X = A, Y = B, Z = C;
5052 X = B, Y = A, Z = D;
5054 X = B, Y = A, Z = C;
5057 Instruction *NewOp =
5058 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5059 return BinaryOperator::CreateAnd(NewOp, X);
5064 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5065 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5066 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5069 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5070 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5071 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5072 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5073 const Type *SrcTy = Op0C->getOperand(0)->getType();
5074 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5075 // Only do this if the casts both really cause code to be generated.
5076 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5078 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5080 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5081 Op1C->getOperand(0),
5083 InsertNewInstBefore(NewOp, I);
5084 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5089 return Changed ? &I : 0;
5092 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5093 /// overflowed for this type.
5094 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5095 ConstantInt *In2, bool IsSigned = false) {
5096 Result = cast<ConstantInt>(Add(In1, In2));
5099 if (In2->getValue().isNegative())
5100 return Result->getValue().sgt(In1->getValue());
5102 return Result->getValue().slt(In1->getValue());
5104 return Result->getValue().ult(In1->getValue());
5107 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5108 /// overflowed for this type.
5109 static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5110 ConstantInt *In2, bool IsSigned = false) {
5111 Result = cast<ConstantInt>(Subtract(In1, In2));
5114 if (In2->getValue().isNegative())
5115 return Result->getValue().slt(In1->getValue());
5117 return Result->getValue().sgt(In1->getValue());
5119 return Result->getValue().ugt(In1->getValue());
5122 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5123 /// code necessary to compute the offset from the base pointer (without adding
5124 /// in the base pointer). Return the result as a signed integer of intptr size.
5125 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5126 TargetData &TD = IC.getTargetData();
5127 gep_type_iterator GTI = gep_type_begin(GEP);
5128 const Type *IntPtrTy = TD.getIntPtrType();
5129 Value *Result = Constant::getNullValue(IntPtrTy);
5131 // Build a mask for high order bits.
5132 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5133 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5135 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5138 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
5139 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5140 if (OpC->isZero()) continue;
5142 // Handle a struct index, which adds its field offset to the pointer.
5143 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5144 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5146 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5147 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5149 Result = IC.InsertNewInstBefore(
5150 BinaryOperator::CreateAdd(Result,
5151 ConstantInt::get(IntPtrTy, Size),
5152 GEP->getName()+".offs"), I);
5156 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5157 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5158 Scale = ConstantExpr::getMul(OC, Scale);
5159 if (Constant *RC = dyn_cast<Constant>(Result))
5160 Result = ConstantExpr::getAdd(RC, Scale);
5162 // Emit an add instruction.
5163 Result = IC.InsertNewInstBefore(
5164 BinaryOperator::CreateAdd(Result, Scale,
5165 GEP->getName()+".offs"), I);
5169 // Convert to correct type.
5170 if (Op->getType() != IntPtrTy) {
5171 if (Constant *OpC = dyn_cast<Constant>(Op))
5172 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5174 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5175 Op->getName()+".c"), I);
5178 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5179 if (Constant *OpC = dyn_cast<Constant>(Op))
5180 Op = ConstantExpr::getMul(OpC, Scale);
5181 else // We'll let instcombine(mul) convert this to a shl if possible.
5182 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5183 GEP->getName()+".idx"), I);
5186 // Emit an add instruction.
5187 if (isa<Constant>(Op) && isa<Constant>(Result))
5188 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5189 cast<Constant>(Result));
5191 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5192 GEP->getName()+".offs"), I);
5198 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5199 /// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5200 /// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5201 /// complex, and scales are involved. The above expression would also be legal
5202 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5203 /// later form is less amenable to optimization though, and we are allowed to
5204 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5206 /// If we can't emit an optimized form for this expression, this returns null.
5208 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5210 TargetData &TD = IC.getTargetData();
5211 gep_type_iterator GTI = gep_type_begin(GEP);
5213 // Check to see if this gep only has a single variable index. If so, and if
5214 // any constant indices are a multiple of its scale, then we can compute this
5215 // in terms of the scale of the variable index. For example, if the GEP
5216 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5217 // because the expression will cross zero at the same point.
5218 unsigned i, e = GEP->getNumOperands();
5220 for (i = 1; i != e; ++i, ++GTI) {
5221 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5222 // Compute the aggregate offset of constant indices.
5223 if (CI->isZero()) continue;
5225 // Handle a struct index, which adds its field offset to the pointer.
5226 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5227 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5229 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5230 Offset += Size*CI->getSExtValue();
5233 // Found our variable index.
5238 // If there are no variable indices, we must have a constant offset, just
5239 // evaluate it the general way.
5240 if (i == e) return 0;
5242 Value *VariableIdx = GEP->getOperand(i);
5243 // Determine the scale factor of the variable element. For example, this is
5244 // 4 if the variable index is into an array of i32.
5245 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5247 // Verify that there are no other variable indices. If so, emit the hard way.
5248 for (++i, ++GTI; i != e; ++i, ++GTI) {
5249 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5252 // Compute the aggregate offset of constant indices.
5253 if (CI->isZero()) continue;
5255 // Handle a struct index, which adds its field offset to the pointer.
5256 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5257 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5259 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5260 Offset += Size*CI->getSExtValue();
5264 // Okay, we know we have a single variable index, which must be a
5265 // pointer/array/vector index. If there is no offset, life is simple, return
5267 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5269 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5270 // we don't need to bother extending: the extension won't affect where the
5271 // computation crosses zero.
5272 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5273 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5274 VariableIdx->getNameStart(), &I);
5278 // Otherwise, there is an index. The computation we will do will be modulo
5279 // the pointer size, so get it.
5280 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5282 Offset &= PtrSizeMask;
5283 VariableScale &= PtrSizeMask;
5285 // To do this transformation, any constant index must be a multiple of the
5286 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5287 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5288 // multiple of the variable scale.
5289 int64_t NewOffs = Offset / (int64_t)VariableScale;
5290 if (Offset != NewOffs*(int64_t)VariableScale)
5293 // Okay, we can do this evaluation. Start by converting the index to intptr.
5294 const Type *IntPtrTy = TD.getIntPtrType();
5295 if (VariableIdx->getType() != IntPtrTy)
5296 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5298 VariableIdx->getNameStart(), &I);
5299 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5300 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5304 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5305 /// else. At this point we know that the GEP is on the LHS of the comparison.
5306 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5307 ICmpInst::Predicate Cond,
5309 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5311 // Look through bitcasts.
5312 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5313 RHS = BCI->getOperand(0);
5315 Value *PtrBase = GEPLHS->getOperand(0);
5316 if (PtrBase == RHS) {
5317 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
5318 // This transformation (ignoring the base and scales) is valid because we
5319 // know pointers can't overflow. See if we can output an optimized form.
5320 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5322 // If not, synthesize the offset the hard way.
5324 Offset = EmitGEPOffset(GEPLHS, I, *this);
5325 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5326 Constant::getNullValue(Offset->getType()));
5327 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5328 // If the base pointers are different, but the indices are the same, just
5329 // compare the base pointer.
5330 if (PtrBase != GEPRHS->getOperand(0)) {
5331 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5332 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5333 GEPRHS->getOperand(0)->getType();
5335 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5336 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5337 IndicesTheSame = false;
5341 // If all indices are the same, just compare the base pointers.
5343 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5344 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5346 // Otherwise, the base pointers are different and the indices are
5347 // different, bail out.
5351 // If one of the GEPs has all zero indices, recurse.
5352 bool AllZeros = true;
5353 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5354 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5355 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5360 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5361 ICmpInst::getSwappedPredicate(Cond), I);
5363 // If the other GEP has all zero indices, recurse.
5365 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5366 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5367 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5372 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5374 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5375 // If the GEPs only differ by one index, compare it.
5376 unsigned NumDifferences = 0; // Keep track of # differences.
5377 unsigned DiffOperand = 0; // The operand that differs.
5378 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5379 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5380 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5381 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5382 // Irreconcilable differences.
5386 if (NumDifferences++) break;
5391 if (NumDifferences == 0) // SAME GEP?
5392 return ReplaceInstUsesWith(I, // No comparison is needed here.
5393 ConstantInt::get(Type::Int1Ty,
5394 ICmpInst::isTrueWhenEqual(Cond)));
5396 else if (NumDifferences == 1) {
5397 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5398 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5399 // Make sure we do a signed comparison here.
5400 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5404 // Only lower this if the icmp is the only user of the GEP or if we expect
5405 // the result to fold to a constant!
5406 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5407 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5408 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5409 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5410 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5411 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5417 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5419 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5422 if (!isa<ConstantFP>(RHSC)) return 0;
5423 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5425 // Get the width of the mantissa. We don't want to hack on conversions that
5426 // might lose information from the integer, e.g. "i64 -> float"
5427 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5428 if (MantissaWidth == -1) return 0; // Unknown.
5430 // Check to see that the input is converted from an integer type that is small
5431 // enough that preserves all bits. TODO: check here for "known" sign bits.
5432 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5433 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5435 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5436 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5440 // If the conversion would lose info, don't hack on this.
5441 if ((int)InputSize > MantissaWidth)
5444 // Otherwise, we can potentially simplify the comparison. We know that it
5445 // will always come through as an integer value and we know the constant is
5446 // not a NAN (it would have been previously simplified).
5447 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5449 ICmpInst::Predicate Pred;
5450 switch (I.getPredicate()) {
5451 default: assert(0 && "Unexpected predicate!");
5452 case FCmpInst::FCMP_UEQ:
5453 case FCmpInst::FCMP_OEQ:
5454 Pred = ICmpInst::ICMP_EQ;
5456 case FCmpInst::FCMP_UGT:
5457 case FCmpInst::FCMP_OGT:
5458 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5460 case FCmpInst::FCMP_UGE:
5461 case FCmpInst::FCMP_OGE:
5462 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5464 case FCmpInst::FCMP_ULT:
5465 case FCmpInst::FCMP_OLT:
5466 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5468 case FCmpInst::FCMP_ULE:
5469 case FCmpInst::FCMP_OLE:
5470 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5472 case FCmpInst::FCMP_UNE:
5473 case FCmpInst::FCMP_ONE:
5474 Pred = ICmpInst::ICMP_NE;
5476 case FCmpInst::FCMP_ORD:
5477 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5478 case FCmpInst::FCMP_UNO:
5479 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5482 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5484 // Now we know that the APFloat is a normal number, zero or inf.
5486 // See if the FP constant is too large for the integer. For example,
5487 // comparing an i8 to 300.0.
5488 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5491 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5492 // and large values.
5493 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5494 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5495 APFloat::rmNearestTiesToEven);
5496 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5497 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5498 Pred == ICmpInst::ICMP_SLE)
5499 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5500 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5503 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5504 // +INF and large values.
5505 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5506 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5507 APFloat::rmNearestTiesToEven);
5508 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5509 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5510 Pred == ICmpInst::ICMP_ULE)
5511 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5512 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5517 // See if the RHS value is < SignedMin.
5518 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5519 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5520 APFloat::rmNearestTiesToEven);
5521 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5522 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5523 Pred == ICmpInst::ICMP_SGE)
5524 return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5525 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5529 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5530 // [0, UMAX], but it may still be fractional. See if it is fractional by
5531 // casting the FP value to the integer value and back, checking for equality.
5532 // Don't do this for zero, because -0.0 is not fractional.
5533 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5534 if (!RHS.isZero() &&
5535 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5536 // If we had a comparison against a fractional value, we have to adjust the
5537 // compare predicate and sometimes the value. RHSC is rounded towards zero
5540 default: assert(0 && "Unexpected integer comparison!");
5541 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5542 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5543 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5544 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5545 case ICmpInst::ICMP_ULE:
5546 // (float)int <= 4.4 --> int <= 4
5547 // (float)int <= -4.4 --> false
5548 if (RHS.isNegative())
5549 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5551 case ICmpInst::ICMP_SLE:
5552 // (float)int <= 4.4 --> int <= 4
5553 // (float)int <= -4.4 --> int < -4
5554 if (RHS.isNegative())
5555 Pred = ICmpInst::ICMP_SLT;
5557 case ICmpInst::ICMP_ULT:
5558 // (float)int < -4.4 --> false
5559 // (float)int < 4.4 --> int <= 4
5560 if (RHS.isNegative())
5561 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5562 Pred = ICmpInst::ICMP_ULE;
5564 case ICmpInst::ICMP_SLT:
5565 // (float)int < -4.4 --> int < -4
5566 // (float)int < 4.4 --> int <= 4
5567 if (!RHS.isNegative())
5568 Pred = ICmpInst::ICMP_SLE;
5570 case ICmpInst::ICMP_UGT:
5571 // (float)int > 4.4 --> int > 4
5572 // (float)int > -4.4 --> true
5573 if (RHS.isNegative())
5574 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5576 case ICmpInst::ICMP_SGT:
5577 // (float)int > 4.4 --> int > 4
5578 // (float)int > -4.4 --> int >= -4
5579 if (RHS.isNegative())
5580 Pred = ICmpInst::ICMP_SGE;
5582 case ICmpInst::ICMP_UGE:
5583 // (float)int >= -4.4 --> true
5584 // (float)int >= 4.4 --> int > 4
5585 if (!RHS.isNegative())
5586 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5587 Pred = ICmpInst::ICMP_UGT;
5589 case ICmpInst::ICMP_SGE:
5590 // (float)int >= -4.4 --> int >= -4
5591 // (float)int >= 4.4 --> int > 4
5592 if (!RHS.isNegative())
5593 Pred = ICmpInst::ICMP_SGT;
5598 // Lower this FP comparison into an appropriate integer version of the
5600 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5603 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5604 bool Changed = SimplifyCompare(I);
5605 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5607 // Fold trivial predicates.
5608 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5609 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5610 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5611 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5613 // Simplify 'fcmp pred X, X'
5615 switch (I.getPredicate()) {
5616 default: assert(0 && "Unknown predicate!");
5617 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5618 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5619 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5620 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5621 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5622 case FCmpInst::FCMP_OLT: // True if ordered and less than
5623 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5624 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5626 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5627 case FCmpInst::FCMP_ULT: // True if unordered or less than
5628 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5629 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5630 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5631 I.setPredicate(FCmpInst::FCMP_UNO);
5632 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5635 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5636 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5637 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5638 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5639 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5640 I.setPredicate(FCmpInst::FCMP_ORD);
5641 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5646 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5647 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5649 // Handle fcmp with constant RHS
5650 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5651 // If the constant is a nan, see if we can fold the comparison based on it.
5652 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5653 if (CFP->getValueAPF().isNaN()) {
5654 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5655 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5656 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5657 "Comparison must be either ordered or unordered!");
5658 // True if unordered.
5659 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5663 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5664 switch (LHSI->getOpcode()) {
5665 case Instruction::PHI:
5666 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5667 // block. If in the same block, we're encouraging jump threading. If
5668 // not, we are just pessimizing the code by making an i1 phi.
5669 if (LHSI->getParent() == I.getParent())
5670 if (Instruction *NV = FoldOpIntoPhi(I))
5673 case Instruction::SIToFP:
5674 case Instruction::UIToFP:
5675 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5678 case Instruction::Select:
5679 // If either operand of the select is a constant, we can fold the
5680 // comparison into the select arms, which will cause one to be
5681 // constant folded and the select turned into a bitwise or.
5682 Value *Op1 = 0, *Op2 = 0;
5683 if (LHSI->hasOneUse()) {
5684 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5685 // Fold the known value into the constant operand.
5686 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5687 // Insert a new FCmp of the other select operand.
5688 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5689 LHSI->getOperand(2), RHSC,
5691 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5692 // Fold the known value into the constant operand.
5693 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5694 // Insert a new FCmp of the other select operand.
5695 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5696 LHSI->getOperand(1), RHSC,
5702 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5707 return Changed ? &I : 0;
5710 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5711 bool Changed = SimplifyCompare(I);
5712 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5713 const Type *Ty = Op0->getType();
5717 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5718 I.isTrueWhenEqual()));
5720 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5721 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5723 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5724 // addresses never equal each other! We already know that Op0 != Op1.
5725 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5726 isa<ConstantPointerNull>(Op0)) &&
5727 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5728 isa<ConstantPointerNull>(Op1)))
5729 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5730 !I.isTrueWhenEqual()));
5732 // icmp's with boolean values can always be turned into bitwise operations
5733 if (Ty == Type::Int1Ty) {
5734 switch (I.getPredicate()) {
5735 default: assert(0 && "Invalid icmp instruction!");
5736 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
5737 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5738 InsertNewInstBefore(Xor, I);
5739 return BinaryOperator::CreateNot(Xor);
5741 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
5742 return BinaryOperator::CreateXor(Op0, Op1);
5744 case ICmpInst::ICMP_UGT:
5745 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
5747 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
5748 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5749 InsertNewInstBefore(Not, I);
5750 return BinaryOperator::CreateAnd(Not, Op1);
5752 case ICmpInst::ICMP_SGT:
5753 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
5755 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5756 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5757 InsertNewInstBefore(Not, I);
5758 return BinaryOperator::CreateAnd(Not, Op0);
5760 case ICmpInst::ICMP_UGE:
5761 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5763 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
5764 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5765 InsertNewInstBefore(Not, I);
5766 return BinaryOperator::CreateOr(Not, Op1);
5768 case ICmpInst::ICMP_SGE:
5769 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5771 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5772 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5773 InsertNewInstBefore(Not, I);
5774 return BinaryOperator::CreateOr(Not, Op0);
5779 // See if we are doing a comparison with a constant.
5780 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5783 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5784 if (I.isEquality() && CI->isNullValue() &&
5785 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5786 // (icmp cond A B) if cond is equality
5787 return new ICmpInst(I.getPredicate(), A, B);
5790 // If we have an icmp le or icmp ge instruction, turn it into the
5791 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5792 // them being folded in the code below.
5793 switch (I.getPredicate()) {
5795 case ICmpInst::ICMP_ULE:
5796 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5797 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5798 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5799 case ICmpInst::ICMP_SLE:
5800 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5801 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5802 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5803 case ICmpInst::ICMP_UGE:
5804 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5805 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5806 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5807 case ICmpInst::ICMP_SGE:
5808 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5809 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5810 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5813 // See if we can fold the comparison based on range information we can get
5814 // by checking whether bits are known to be zero or one in the input.
5815 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5816 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5818 // If this comparison is a normal comparison, it demands all
5819 // bits, if it is a sign bit comparison, it only demands the sign bit.
5821 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5823 if (SimplifyDemandedBits(Op0,
5824 isSignBit ? APInt::getSignBit(BitWidth)
5825 : APInt::getAllOnesValue(BitWidth),
5826 KnownZero, KnownOne, 0))
5829 // Given the known and unknown bits, compute a range that the LHS could be
5830 // in. Compute the Min, Max and RHS values based on the known bits. For the
5831 // EQ and NE we use unsigned values.
5832 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5833 if (ICmpInst::isSignedPredicate(I.getPredicate()))
5834 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5836 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5838 // If Min and Max are known to be the same, then SimplifyDemandedBits
5839 // figured out that the LHS is a constant. Just constant fold this now so
5840 // that code below can assume that Min != Max.
5842 return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5843 ConstantInt::get(Min),
5846 // Based on the range information we know about the LHS, see if we can
5847 // simplify this comparison. For example, (x&4) < 8 is always true.
5848 const APInt &RHSVal = CI->getValue();
5849 switch (I.getPredicate()) { // LE/GE have been folded already.
5850 default: assert(0 && "Unknown icmp opcode!");
5851 case ICmpInst::ICMP_EQ:
5852 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5853 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5855 case ICmpInst::ICMP_NE:
5856 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5857 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5859 case ICmpInst::ICMP_ULT:
5860 if (Max.ult(RHSVal)) // A <u C -> true iff max(A) < C
5861 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5862 if (Min.uge(RHSVal)) // A <u C -> false iff min(A) >= C
5863 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5864 if (RHSVal == Max) // A <u MAX -> A != MAX
5865 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5866 if (RHSVal == Min+1) // A <u MIN+1 -> A == MIN
5867 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5869 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5870 if (CI->isMinValue(true))
5871 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5872 ConstantInt::getAllOnesValue(Op0->getType()));
5874 case ICmpInst::ICMP_UGT:
5875 if (Min.ugt(RHSVal)) // A >u C -> true iff min(A) > C
5876 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5877 if (Max.ule(RHSVal)) // A >u C -> false iff max(A) <= C
5878 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5880 if (RHSVal == Min) // A >u MIN -> A != MIN
5881 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5882 if (RHSVal == Max-1) // A >u MAX-1 -> A == MAX
5883 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5885 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5886 if (CI->isMaxValue(true))
5887 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5888 ConstantInt::getNullValue(Op0->getType()));
5890 case ICmpInst::ICMP_SLT:
5891 if (Max.slt(RHSVal)) // A <s C -> true iff max(A) < C
5892 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5893 if (Min.sge(RHSVal)) // A <s C -> false iff min(A) >= C
5894 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5895 if (RHSVal == Max) // A <s MAX -> A != MAX
5896 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5897 if (RHSVal == Min+1) // A <s MIN+1 -> A == MIN
5898 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5900 case ICmpInst::ICMP_SGT:
5901 if (Min.sgt(RHSVal)) // A >s C -> true iff min(A) > C
5902 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5903 if (Max.sle(RHSVal)) // A >s C -> false iff max(A) <= C
5904 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5906 if (RHSVal == Min) // A >s MIN -> A != MIN
5907 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5908 if (RHSVal == Max-1) // A >s MAX-1 -> A == MAX
5909 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5914 // Test if the ICmpInst instruction is used exclusively by a select as
5915 // part of a minimum or maximum operation. If so, refrain from doing
5916 // any other folding. This helps out other analyses which understand
5917 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5918 // and CodeGen. And in this case, at least one of the comparison
5919 // operands has at least one user besides the compare (the select),
5920 // which would often largely negate the benefit of folding anyway.
5922 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5923 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5924 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5927 // See if we are doing a comparison between a constant and an instruction that
5928 // can be folded into the comparison.
5929 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5930 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5931 // instruction, see if that instruction also has constants so that the
5932 // instruction can be folded into the icmp
5933 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5934 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5938 // Handle icmp with constant (but not simple integer constant) RHS
5939 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5940 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5941 switch (LHSI->getOpcode()) {
5942 case Instruction::GetElementPtr:
5943 if (RHSC->isNullValue()) {
5944 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5945 bool isAllZeros = true;
5946 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5947 if (!isa<Constant>(LHSI->getOperand(i)) ||
5948 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5953 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5954 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5958 case Instruction::PHI:
5959 // Only fold icmp into the PHI if the phi and fcmp are in the same
5960 // block. If in the same block, we're encouraging jump threading. If
5961 // not, we are just pessimizing the code by making an i1 phi.
5962 if (LHSI->getParent() == I.getParent())
5963 if (Instruction *NV = FoldOpIntoPhi(I))
5966 case Instruction::Select: {
5967 // If either operand of the select is a constant, we can fold the
5968 // comparison into the select arms, which will cause one to be
5969 // constant folded and the select turned into a bitwise or.
5970 Value *Op1 = 0, *Op2 = 0;
5971 if (LHSI->hasOneUse()) {
5972 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5973 // Fold the known value into the constant operand.
5974 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5975 // Insert a new ICmp of the other select operand.
5976 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5977 LHSI->getOperand(2), RHSC,
5979 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5980 // Fold the known value into the constant operand.
5981 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5982 // Insert a new ICmp of the other select operand.
5983 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5984 LHSI->getOperand(1), RHSC,
5990 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5993 case Instruction::Malloc:
5994 // If we have (malloc != null), and if the malloc has a single use, we
5995 // can assume it is successful and remove the malloc.
5996 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5997 AddToWorkList(LHSI);
5998 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5999 !I.isTrueWhenEqual()));
6005 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6006 if (User *GEP = dyn_castGetElementPtr(Op0))
6007 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6009 if (User *GEP = dyn_castGetElementPtr(Op1))
6010 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6011 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6014 // Test to see if the operands of the icmp are casted versions of other
6015 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6017 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6018 if (isa<PointerType>(Op0->getType()) &&
6019 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6020 // We keep moving the cast from the left operand over to the right
6021 // operand, where it can often be eliminated completely.
6022 Op0 = CI->getOperand(0);
6024 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6025 // so eliminate it as well.
6026 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6027 Op1 = CI2->getOperand(0);
6029 // If Op1 is a constant, we can fold the cast into the constant.
6030 if (Op0->getType() != Op1->getType()) {
6031 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6032 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6034 // Otherwise, cast the RHS right before the icmp
6035 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6038 return new ICmpInst(I.getPredicate(), Op0, Op1);
6042 if (isa<CastInst>(Op0)) {
6043 // Handle the special case of: icmp (cast bool to X), <cst>
6044 // This comes up when you have code like
6047 // For generality, we handle any zero-extension of any operand comparison
6048 // with a constant or another cast from the same type.
6049 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6050 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6054 // See if it's the same type of instruction on the left and right.
6055 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6056 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6057 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6058 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
6060 switch (Op0I->getOpcode()) {
6062 case Instruction::Add:
6063 case Instruction::Sub:
6064 case Instruction::Xor:
6065 // a+x icmp eq/ne b+x --> a icmp b
6066 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6067 Op1I->getOperand(0));
6069 case Instruction::Mul:
6070 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6071 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6072 // Mask = -1 >> count-trailing-zeros(Cst).
6073 if (!CI->isZero() && !CI->isOne()) {
6074 const APInt &AP = CI->getValue();
6075 ConstantInt *Mask = ConstantInt::get(
6076 APInt::getLowBitsSet(AP.getBitWidth(),
6078 AP.countTrailingZeros()));
6079 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6081 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6083 InsertNewInstBefore(And1, I);
6084 InsertNewInstBefore(And2, I);
6085 return new ICmpInst(I.getPredicate(), And1, And2);
6094 // ~x < ~y --> y < x
6096 if (match(Op0, m_Not(m_Value(A))) &&
6097 match(Op1, m_Not(m_Value(B))))
6098 return new ICmpInst(I.getPredicate(), B, A);
6101 if (I.isEquality()) {
6102 Value *A, *B, *C, *D;
6104 // -x == -y --> x == y
6105 if (match(Op0, m_Neg(m_Value(A))) &&
6106 match(Op1, m_Neg(m_Value(B))))
6107 return new ICmpInst(I.getPredicate(), A, B);
6109 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6110 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6111 Value *OtherVal = A == Op1 ? B : A;
6112 return new ICmpInst(I.getPredicate(), OtherVal,
6113 Constant::getNullValue(A->getType()));
6116 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6117 // A^c1 == C^c2 --> A == C^(c1^c2)
6118 ConstantInt *C1, *C2;
6119 if (match(B, m_ConstantInt(C1)) &&
6120 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6121 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6122 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6123 return new ICmpInst(I.getPredicate(), A,
6124 InsertNewInstBefore(Xor, I));
6127 // A^B == A^D -> B == D
6128 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6129 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6130 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6131 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6135 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6136 (A == Op0 || B == Op0)) {
6137 // A == (A^B) -> B == 0
6138 Value *OtherVal = A == Op0 ? B : A;
6139 return new ICmpInst(I.getPredicate(), OtherVal,
6140 Constant::getNullValue(A->getType()));
6143 // (A-B) == A -> B == 0
6144 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6145 return new ICmpInst(I.getPredicate(), B,
6146 Constant::getNullValue(B->getType()));
6148 // A == (A-B) -> B == 0
6149 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6150 return new ICmpInst(I.getPredicate(), B,
6151 Constant::getNullValue(B->getType()));
6153 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6154 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6155 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6156 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6157 Value *X = 0, *Y = 0, *Z = 0;
6160 X = B; Y = D; Z = A;
6161 } else if (A == D) {
6162 X = B; Y = C; Z = A;
6163 } else if (B == C) {
6164 X = A; Y = D; Z = B;
6165 } else if (B == D) {
6166 X = A; Y = C; Z = B;
6169 if (X) { // Build (X^Y) & Z
6170 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6171 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6172 I.setOperand(0, Op1);
6173 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6178 return Changed ? &I : 0;
6182 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6183 /// and CmpRHS are both known to be integer constants.
6184 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6185 ConstantInt *DivRHS) {
6186 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6187 const APInt &CmpRHSV = CmpRHS->getValue();
6189 // FIXME: If the operand types don't match the type of the divide
6190 // then don't attempt this transform. The code below doesn't have the
6191 // logic to deal with a signed divide and an unsigned compare (and
6192 // vice versa). This is because (x /s C1) <s C2 produces different
6193 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6194 // (x /u C1) <u C2. Simply casting the operands and result won't
6195 // work. :( The if statement below tests that condition and bails
6197 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6198 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6200 if (DivRHS->isZero())
6201 return 0; // The ProdOV computation fails on divide by zero.
6202 if (DivIsSigned && DivRHS->isAllOnesValue())
6203 return 0; // The overflow computation also screws up here
6204 if (DivRHS->isOne())
6205 return 0; // Not worth bothering, and eliminates some funny cases
6208 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6209 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6210 // C2 (CI). By solving for X we can turn this into a range check
6211 // instead of computing a divide.
6212 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6214 // Determine if the product overflows by seeing if the product is
6215 // not equal to the divide. Make sure we do the same kind of divide
6216 // as in the LHS instruction that we're folding.
6217 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6218 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6220 // Get the ICmp opcode
6221 ICmpInst::Predicate Pred = ICI.getPredicate();
6223 // Figure out the interval that is being checked. For example, a comparison
6224 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6225 // Compute this interval based on the constants involved and the signedness of
6226 // the compare/divide. This computes a half-open interval, keeping track of
6227 // whether either value in the interval overflows. After analysis each
6228 // overflow variable is set to 0 if it's corresponding bound variable is valid
6229 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6230 int LoOverflow = 0, HiOverflow = 0;
6231 ConstantInt *LoBound = 0, *HiBound = 0;
6233 if (!DivIsSigned) { // udiv
6234 // e.g. X/5 op 3 --> [15, 20)
6236 HiOverflow = LoOverflow = ProdOV;
6238 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
6239 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6240 if (CmpRHSV == 0) { // (X / pos) op 0
6241 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
6242 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6244 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
6245 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6246 HiOverflow = LoOverflow = ProdOV;
6248 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6249 } else { // (X / pos) op neg
6250 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
6251 HiBound = AddOne(Prod);
6252 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6254 ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6255 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6259 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6260 if (CmpRHSV == 0) { // (X / neg) op 0
6261 // e.g. X/-5 op 0 --> [-4, 5)
6262 LoBound = AddOne(DivRHS);
6263 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6264 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6265 HiOverflow = 1; // [INTMIN+1, overflow)
6266 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6268 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
6269 // e.g. X/-5 op 3 --> [-19, -14)
6270 HiBound = AddOne(Prod);
6271 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6273 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
6274 } else { // (X / neg) op neg
6275 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6276 LoOverflow = HiOverflow = ProdOV;
6278 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
6281 // Dividing by a negative swaps the condition. LT <-> GT
6282 Pred = ICmpInst::getSwappedPredicate(Pred);
6285 Value *X = DivI->getOperand(0);
6287 default: assert(0 && "Unhandled icmp opcode!");
6288 case ICmpInst::ICMP_EQ:
6289 if (LoOverflow && HiOverflow)
6290 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6291 else if (HiOverflow)
6292 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6293 ICmpInst::ICMP_UGE, X, LoBound);
6294 else if (LoOverflow)
6295 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6296 ICmpInst::ICMP_ULT, X, HiBound);
6298 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6299 case ICmpInst::ICMP_NE:
6300 if (LoOverflow && HiOverflow)
6301 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6302 else if (HiOverflow)
6303 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6304 ICmpInst::ICMP_ULT, X, LoBound);
6305 else if (LoOverflow)
6306 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6307 ICmpInst::ICMP_UGE, X, HiBound);
6309 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6310 case ICmpInst::ICMP_ULT:
6311 case ICmpInst::ICMP_SLT:
6312 if (LoOverflow == +1) // Low bound is greater than input range.
6313 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6314 if (LoOverflow == -1) // Low bound is less than input range.
6315 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6316 return new ICmpInst(Pred, X, LoBound);
6317 case ICmpInst::ICMP_UGT:
6318 case ICmpInst::ICMP_SGT:
6319 if (HiOverflow == +1) // High bound greater than input range.
6320 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6321 else if (HiOverflow == -1) // High bound less than input range.
6322 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6323 if (Pred == ICmpInst::ICMP_UGT)
6324 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6326 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6331 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6333 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6336 const APInt &RHSV = RHS->getValue();
6338 switch (LHSI->getOpcode()) {
6339 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6340 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6341 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6343 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6344 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6345 Value *CompareVal = LHSI->getOperand(0);
6347 // If the sign bit of the XorCST is not set, there is no change to
6348 // the operation, just stop using the Xor.
6349 if (!XorCST->getValue().isNegative()) {
6350 ICI.setOperand(0, CompareVal);
6351 AddToWorkList(LHSI);
6355 // Was the old condition true if the operand is positive?
6356 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6358 // If so, the new one isn't.
6359 isTrueIfPositive ^= true;
6361 if (isTrueIfPositive)
6362 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6364 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6368 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6369 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6370 LHSI->getOperand(0)->hasOneUse()) {
6371 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6373 // If the LHS is an AND of a truncating cast, we can widen the
6374 // and/compare to be the input width without changing the value
6375 // produced, eliminating a cast.
6376 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6377 // We can do this transformation if either the AND constant does not
6378 // have its sign bit set or if it is an equality comparison.
6379 // Extending a relational comparison when we're checking the sign
6380 // bit would not work.
6381 if (Cast->hasOneUse() &&
6382 (ICI.isEquality() ||
6383 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6385 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6386 APInt NewCST = AndCST->getValue();
6387 NewCST.zext(BitWidth);
6389 NewCI.zext(BitWidth);
6390 Instruction *NewAnd =
6391 BinaryOperator::CreateAnd(Cast->getOperand(0),
6392 ConstantInt::get(NewCST),LHSI->getName());
6393 InsertNewInstBefore(NewAnd, ICI);
6394 return new ICmpInst(ICI.getPredicate(), NewAnd,
6395 ConstantInt::get(NewCI));
6399 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6400 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6401 // happens a LOT in code produced by the C front-end, for bitfield
6403 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6404 if (Shift && !Shift->isShift())
6408 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6409 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6410 const Type *AndTy = AndCST->getType(); // Type of the and.
6412 // We can fold this as long as we can't shift unknown bits
6413 // into the mask. This can only happen with signed shift
6414 // rights, as they sign-extend.
6416 bool CanFold = Shift->isLogicalShift();
6418 // To test for the bad case of the signed shr, see if any
6419 // of the bits shifted in could be tested after the mask.
6420 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6421 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6423 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6424 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6425 AndCST->getValue()) == 0)
6431 if (Shift->getOpcode() == Instruction::Shl)
6432 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6434 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6436 // Check to see if we are shifting out any of the bits being
6438 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6439 // If we shifted bits out, the fold is not going to work out.
6440 // As a special case, check to see if this means that the
6441 // result is always true or false now.
6442 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6443 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6444 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6445 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6447 ICI.setOperand(1, NewCst);
6448 Constant *NewAndCST;
6449 if (Shift->getOpcode() == Instruction::Shl)
6450 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6452 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6453 LHSI->setOperand(1, NewAndCST);
6454 LHSI->setOperand(0, Shift->getOperand(0));
6455 AddToWorkList(Shift); // Shift is dead.
6456 AddUsesToWorkList(ICI);
6462 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6463 // preferable because it allows the C<<Y expression to be hoisted out
6464 // of a loop if Y is invariant and X is not.
6465 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6466 ICI.isEquality() && !Shift->isArithmeticShift() &&
6467 isa<Instruction>(Shift->getOperand(0))) {
6470 if (Shift->getOpcode() == Instruction::LShr) {
6471 NS = BinaryOperator::CreateShl(AndCST,
6472 Shift->getOperand(1), "tmp");
6474 // Insert a logical shift.
6475 NS = BinaryOperator::CreateLShr(AndCST,
6476 Shift->getOperand(1), "tmp");
6478 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6480 // Compute X & (C << Y).
6481 Instruction *NewAnd =
6482 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6483 InsertNewInstBefore(NewAnd, ICI);
6485 ICI.setOperand(0, NewAnd);
6491 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6492 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6495 uint32_t TypeBits = RHSV.getBitWidth();
6497 // Check that the shift amount is in range. If not, don't perform
6498 // undefined shifts. When the shift is visited it will be
6500 if (ShAmt->uge(TypeBits))
6503 if (ICI.isEquality()) {
6504 // If we are comparing against bits always shifted out, the
6505 // comparison cannot succeed.
6507 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6508 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6509 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6510 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6511 return ReplaceInstUsesWith(ICI, Cst);
6514 if (LHSI->hasOneUse()) {
6515 // Otherwise strength reduce the shift into an and.
6516 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6518 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6521 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6522 Mask, LHSI->getName()+".mask");
6523 Value *And = InsertNewInstBefore(AndI, ICI);
6524 return new ICmpInst(ICI.getPredicate(), And,
6525 ConstantInt::get(RHSV.lshr(ShAmtVal)));
6529 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6530 bool TrueIfSigned = false;
6531 if (LHSI->hasOneUse() &&
6532 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6533 // (X << 31) <s 0 --> (X&1) != 0
6534 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6535 (TypeBits-ShAmt->getZExtValue()-1));
6537 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6538 Mask, LHSI->getName()+".mask");
6539 Value *And = InsertNewInstBefore(AndI, ICI);
6541 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6542 And, Constant::getNullValue(And->getType()));
6547 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6548 case Instruction::AShr: {
6549 // Only handle equality comparisons of shift-by-constant.
6550 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6551 if (!ShAmt || !ICI.isEquality()) break;
6553 // Check that the shift amount is in range. If not, don't perform
6554 // undefined shifts. When the shift is visited it will be
6556 uint32_t TypeBits = RHSV.getBitWidth();
6557 if (ShAmt->uge(TypeBits))
6560 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6562 // If we are comparing against bits always shifted out, the
6563 // comparison cannot succeed.
6564 APInt Comp = RHSV << ShAmtVal;
6565 if (LHSI->getOpcode() == Instruction::LShr)
6566 Comp = Comp.lshr(ShAmtVal);
6568 Comp = Comp.ashr(ShAmtVal);
6570 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6571 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6572 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6573 return ReplaceInstUsesWith(ICI, Cst);
6576 // Otherwise, check to see if the bits shifted out are known to be zero.
6577 // If so, we can compare against the unshifted value:
6578 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
6579 if (LHSI->hasOneUse() &&
6580 MaskedValueIsZero(LHSI->getOperand(0),
6581 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6582 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6583 ConstantExpr::getShl(RHS, ShAmt));
6586 if (LHSI->hasOneUse()) {
6587 // Otherwise strength reduce the shift into an and.
6588 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6589 Constant *Mask = ConstantInt::get(Val);
6592 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6593 Mask, LHSI->getName()+".mask");
6594 Value *And = InsertNewInstBefore(AndI, ICI);
6595 return new ICmpInst(ICI.getPredicate(), And,
6596 ConstantExpr::getShl(RHS, ShAmt));
6601 case Instruction::SDiv:
6602 case Instruction::UDiv:
6603 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6604 // Fold this div into the comparison, producing a range check.
6605 // Determine, based on the divide type, what the range is being
6606 // checked. If there is an overflow on the low or high side, remember
6607 // it, otherwise compute the range [low, hi) bounding the new value.
6608 // See: InsertRangeTest above for the kinds of replacements possible.
6609 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6610 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6615 case Instruction::Add:
6616 // Fold: icmp pred (add, X, C1), C2
6618 if (!ICI.isEquality()) {
6619 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6621 const APInt &LHSV = LHSC->getValue();
6623 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6626 if (ICI.isSignedPredicate()) {
6627 if (CR.getLower().isSignBit()) {
6628 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6629 ConstantInt::get(CR.getUpper()));
6630 } else if (CR.getUpper().isSignBit()) {
6631 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6632 ConstantInt::get(CR.getLower()));
6635 if (CR.getLower().isMinValue()) {
6636 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6637 ConstantInt::get(CR.getUpper()));
6638 } else if (CR.getUpper().isMinValue()) {
6639 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6640 ConstantInt::get(CR.getLower()));
6647 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6648 if (ICI.isEquality()) {
6649 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6651 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6652 // the second operand is a constant, simplify a bit.
6653 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6654 switch (BO->getOpcode()) {
6655 case Instruction::SRem:
6656 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6657 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6658 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6659 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6660 Instruction *NewRem =
6661 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6663 InsertNewInstBefore(NewRem, ICI);
6664 return new ICmpInst(ICI.getPredicate(), NewRem,
6665 Constant::getNullValue(BO->getType()));
6669 case Instruction::Add:
6670 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6671 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6672 if (BO->hasOneUse())
6673 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6674 Subtract(RHS, BOp1C));
6675 } else if (RHSV == 0) {
6676 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6677 // efficiently invertible, or if the add has just this one use.
6678 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6680 if (Value *NegVal = dyn_castNegVal(BOp1))
6681 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6682 else if (Value *NegVal = dyn_castNegVal(BOp0))
6683 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6684 else if (BO->hasOneUse()) {
6685 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6686 InsertNewInstBefore(Neg, ICI);
6688 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6692 case Instruction::Xor:
6693 // For the xor case, we can xor two constants together, eliminating
6694 // the explicit xor.
6695 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6696 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6697 ConstantExpr::getXor(RHS, BOC));
6700 case Instruction::Sub:
6701 // Replace (([sub|xor] A, B) != 0) with (A != B)
6703 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6707 case Instruction::Or:
6708 // If bits are being or'd in that are not present in the constant we
6709 // are comparing against, then the comparison could never succeed!
6710 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6711 Constant *NotCI = ConstantExpr::getNot(RHS);
6712 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6713 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6718 case Instruction::And:
6719 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6720 // If bits are being compared against that are and'd out, then the
6721 // comparison can never succeed!
6722 if ((RHSV & ~BOC->getValue()) != 0)
6723 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6726 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6727 if (RHS == BOC && RHSV.isPowerOf2())
6728 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6729 ICmpInst::ICMP_NE, LHSI,
6730 Constant::getNullValue(RHS->getType()));
6732 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6733 if (BOC->getValue().isSignBit()) {
6734 Value *X = BO->getOperand(0);
6735 Constant *Zero = Constant::getNullValue(X->getType());
6736 ICmpInst::Predicate pred = isICMP_NE ?
6737 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6738 return new ICmpInst(pred, X, Zero);
6741 // ((X & ~7) == 0) --> X < 8
6742 if (RHSV == 0 && isHighOnes(BOC)) {
6743 Value *X = BO->getOperand(0);
6744 Constant *NegX = ConstantExpr::getNeg(BOC);
6745 ICmpInst::Predicate pred = isICMP_NE ?
6746 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6747 return new ICmpInst(pred, X, NegX);
6752 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6753 // Handle icmp {eq|ne} <intrinsic>, intcst.
6754 if (II->getIntrinsicID() == Intrinsic::bswap) {
6756 ICI.setOperand(0, II->getOperand(1));
6757 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6761 } else { // Not a ICMP_EQ/ICMP_NE
6762 // If the LHS is a cast from an integral value of the same size,
6763 // then since we know the RHS is a constant, try to simlify.
6764 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6765 Value *CastOp = Cast->getOperand(0);
6766 const Type *SrcTy = CastOp->getType();
6767 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6768 if (SrcTy->isInteger() &&
6769 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6770 // If this is an unsigned comparison, try to make the comparison use
6771 // smaller constant values.
6772 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6773 // X u< 128 => X s> -1
6774 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6775 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6776 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6777 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6778 // X u> 127 => X s< 0
6779 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6780 Constant::getNullValue(SrcTy));
6788 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6789 /// We only handle extending casts so far.
6791 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6792 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6793 Value *LHSCIOp = LHSCI->getOperand(0);
6794 const Type *SrcTy = LHSCIOp->getType();
6795 const Type *DestTy = LHSCI->getType();
6798 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6799 // integer type is the same size as the pointer type.
6800 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6801 getTargetData().getPointerSizeInBits() ==
6802 cast<IntegerType>(DestTy)->getBitWidth()) {
6804 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6805 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6806 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6807 RHSOp = RHSC->getOperand(0);
6808 // If the pointer types don't match, insert a bitcast.
6809 if (LHSCIOp->getType() != RHSOp->getType())
6810 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6814 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6817 // The code below only handles extension cast instructions, so far.
6819 if (LHSCI->getOpcode() != Instruction::ZExt &&
6820 LHSCI->getOpcode() != Instruction::SExt)
6823 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6824 bool isSignedCmp = ICI.isSignedPredicate();
6826 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6827 // Not an extension from the same type?
6828 RHSCIOp = CI->getOperand(0);
6829 if (RHSCIOp->getType() != LHSCIOp->getType())
6832 // If the signedness of the two casts doesn't agree (i.e. one is a sext
6833 // and the other is a zext), then we can't handle this.
6834 if (CI->getOpcode() != LHSCI->getOpcode())
6837 // Deal with equality cases early.
6838 if (ICI.isEquality())
6839 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6841 // A signed comparison of sign extended values simplifies into a
6842 // signed comparison.
6843 if (isSignedCmp && isSignedExt)
6844 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6846 // The other three cases all fold into an unsigned comparison.
6847 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6850 // If we aren't dealing with a constant on the RHS, exit early
6851 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6855 // Compute the constant that would happen if we truncated to SrcTy then
6856 // reextended to DestTy.
6857 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6858 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6860 // If the re-extended constant didn't change...
6862 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6863 // For example, we might have:
6864 // %A = sext short %X to uint
6865 // %B = icmp ugt uint %A, 1330
6866 // It is incorrect to transform this into
6867 // %B = icmp ugt short %X, 1330
6868 // because %A may have negative value.
6870 // However, we allow this when the compare is EQ/NE, because they are
6872 if (isSignedExt == isSignedCmp || ICI.isEquality())
6873 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6877 // The re-extended constant changed so the constant cannot be represented
6878 // in the shorter type. Consequently, we cannot emit a simple comparison.
6880 // First, handle some easy cases. We know the result cannot be equal at this
6881 // point so handle the ICI.isEquality() cases
6882 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6883 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6884 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6885 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6887 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6888 // should have been folded away previously and not enter in here.
6891 // We're performing a signed comparison.
6892 if (cast<ConstantInt>(CI)->getValue().isNegative())
6893 Result = ConstantInt::getFalse(); // X < (small) --> false
6895 Result = ConstantInt::getTrue(); // X < (large) --> true
6897 // We're performing an unsigned comparison.
6899 // We're performing an unsigned comp with a sign extended value.
6900 // This is true if the input is >= 0. [aka >s -1]
6901 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6902 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6903 NegOne, ICI.getName()), ICI);
6905 // Unsigned extend & unsigned compare -> always true.
6906 Result = ConstantInt::getTrue();
6910 // Finally, return the value computed.
6911 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6912 ICI.getPredicate() == ICmpInst::ICMP_SLT)
6913 return ReplaceInstUsesWith(ICI, Result);
6915 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6916 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6917 "ICmp should be folded!");
6918 if (Constant *CI = dyn_cast<Constant>(Result))
6919 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6920 return BinaryOperator::CreateNot(Result);
6923 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6924 return commonShiftTransforms(I);
6927 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6928 return commonShiftTransforms(I);
6931 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6932 if (Instruction *R = commonShiftTransforms(I))
6935 Value *Op0 = I.getOperand(0);
6937 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6938 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6939 if (CSI->isAllOnesValue())
6940 return ReplaceInstUsesWith(I, CSI);
6942 // See if we can turn a signed shr into an unsigned shr.
6943 if (!isa<VectorType>(I.getType()) &&
6944 MaskedValueIsZero(Op0,
6945 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6946 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6951 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6952 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6953 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6955 // shl X, 0 == X and shr X, 0 == X
6956 // shl 0, X == 0 and shr 0, X == 0
6957 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6958 Op0 == Constant::getNullValue(Op0->getType()))
6959 return ReplaceInstUsesWith(I, Op0);
6961 if (isa<UndefValue>(Op0)) {
6962 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6963 return ReplaceInstUsesWith(I, Op0);
6964 else // undef << X -> 0, undef >>u X -> 0
6965 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6967 if (isa<UndefValue>(Op1)) {
6968 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6969 return ReplaceInstUsesWith(I, Op0);
6970 else // X << undef, X >>u undef -> 0
6971 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6974 // Try to fold constant and into select arguments.
6975 if (isa<Constant>(Op0))
6976 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6977 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6980 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6981 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6986 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6987 BinaryOperator &I) {
6988 bool isLeftShift = I.getOpcode() == Instruction::Shl;
6990 // See if we can simplify any instructions used by the instruction whose sole
6991 // purpose is to compute bits we don't care about.
6992 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6993 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6994 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6995 KnownZero, KnownOne))
6998 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6999 // of a signed value.
7001 if (Op1->uge(TypeBits)) {
7002 if (I.getOpcode() != Instruction::AShr)
7003 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7005 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7010 // ((X*C1) << C2) == (X * (C1 << C2))
7011 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7012 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7013 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7014 return BinaryOperator::CreateMul(BO->getOperand(0),
7015 ConstantExpr::getShl(BOOp, Op1));
7017 // Try to fold constant and into select arguments.
7018 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7019 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7021 if (isa<PHINode>(Op0))
7022 if (Instruction *NV = FoldOpIntoPhi(I))
7025 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7026 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7027 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7028 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7029 // place. Don't try to do this transformation in this case. Also, we
7030 // require that the input operand is a shift-by-constant so that we have
7031 // confidence that the shifts will get folded together. We could do this
7032 // xform in more cases, but it is unlikely to be profitable.
7033 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7034 isa<ConstantInt>(TrOp->getOperand(1))) {
7035 // Okay, we'll do this xform. Make the shift of shift.
7036 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7037 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7039 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7041 // For logical shifts, the truncation has the effect of making the high
7042 // part of the register be zeros. Emulate this by inserting an AND to
7043 // clear the top bits as needed. This 'and' will usually be zapped by
7044 // other xforms later if dead.
7045 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7046 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7047 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7049 // The mask we constructed says what the trunc would do if occurring
7050 // between the shifts. We want to know the effect *after* the second
7051 // shift. We know that it is a logical shift by a constant, so adjust the
7052 // mask as appropriate.
7053 if (I.getOpcode() == Instruction::Shl)
7054 MaskV <<= Op1->getZExtValue();
7056 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7057 MaskV = MaskV.lshr(Op1->getZExtValue());
7060 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
7062 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7064 // Return the value truncated to the interesting size.
7065 return new TruncInst(And, I.getType());
7069 if (Op0->hasOneUse()) {
7070 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7071 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7074 switch (Op0BO->getOpcode()) {
7076 case Instruction::Add:
7077 case Instruction::And:
7078 case Instruction::Or:
7079 case Instruction::Xor: {
7080 // These operators commute.
7081 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7082 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7083 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
7084 Instruction *YS = BinaryOperator::CreateShl(
7085 Op0BO->getOperand(0), Op1,
7087 InsertNewInstBefore(YS, I); // (Y << C)
7089 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7090 Op0BO->getOperand(1)->getName());
7091 InsertNewInstBefore(X, I); // (X + (Y << C))
7092 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7093 return BinaryOperator::CreateAnd(X, ConstantInt::get(
7094 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7097 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7098 Value *Op0BOOp1 = Op0BO->getOperand(1);
7099 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7101 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7102 m_ConstantInt(CC))) &&
7103 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7104 Instruction *YS = BinaryOperator::CreateShl(
7105 Op0BO->getOperand(0), Op1,
7107 InsertNewInstBefore(YS, I); // (Y << C)
7109 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7110 V1->getName()+".mask");
7111 InsertNewInstBefore(XM, I); // X & (CC << C)
7113 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7118 case Instruction::Sub: {
7119 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7120 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7121 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
7122 Instruction *YS = BinaryOperator::CreateShl(
7123 Op0BO->getOperand(1), Op1,
7125 InsertNewInstBefore(YS, I); // (Y << C)
7127 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7128 Op0BO->getOperand(0)->getName());
7129 InsertNewInstBefore(X, I); // (X + (Y << C))
7130 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7131 return BinaryOperator::CreateAnd(X, ConstantInt::get(
7132 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7135 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7136 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7137 match(Op0BO->getOperand(0),
7138 m_And(m_Shr(m_Value(V1), m_Value(V2)),
7139 m_ConstantInt(CC))) && V2 == Op1 &&
7140 cast<BinaryOperator>(Op0BO->getOperand(0))
7141 ->getOperand(0)->hasOneUse()) {
7142 Instruction *YS = BinaryOperator::CreateShl(
7143 Op0BO->getOperand(1), Op1,
7145 InsertNewInstBefore(YS, I); // (Y << C)
7147 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7148 V1->getName()+".mask");
7149 InsertNewInstBefore(XM, I); // X & (CC << C)
7151 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7159 // If the operand is an bitwise operator with a constant RHS, and the
7160 // shift is the only use, we can pull it out of the shift.
7161 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7162 bool isValid = true; // Valid only for And, Or, Xor
7163 bool highBitSet = false; // Transform if high bit of constant set?
7165 switch (Op0BO->getOpcode()) {
7166 default: isValid = false; break; // Do not perform transform!
7167 case Instruction::Add:
7168 isValid = isLeftShift;
7170 case Instruction::Or:
7171 case Instruction::Xor:
7174 case Instruction::And:
7179 // If this is a signed shift right, and the high bit is modified
7180 // by the logical operation, do not perform the transformation.
7181 // The highBitSet boolean indicates the value of the high bit of
7182 // the constant which would cause it to be modified for this
7185 if (isValid && I.getOpcode() == Instruction::AShr)
7186 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7189 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7191 Instruction *NewShift =
7192 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7193 InsertNewInstBefore(NewShift, I);
7194 NewShift->takeName(Op0BO);
7196 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7203 // Find out if this is a shift of a shift by a constant.
7204 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7205 if (ShiftOp && !ShiftOp->isShift())
7208 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7209 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7210 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7211 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7212 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7213 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7214 Value *X = ShiftOp->getOperand(0);
7216 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
7217 if (AmtSum > TypeBits)
7220 const IntegerType *Ty = cast<IntegerType>(I.getType());
7222 // Check for (X << c1) << c2 and (X >> c1) >> c2
7223 if (I.getOpcode() == ShiftOp->getOpcode()) {
7224 return BinaryOperator::Create(I.getOpcode(), X,
7225 ConstantInt::get(Ty, AmtSum));
7226 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7227 I.getOpcode() == Instruction::AShr) {
7228 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
7229 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7230 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7231 I.getOpcode() == Instruction::LShr) {
7232 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7233 Instruction *Shift =
7234 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7235 InsertNewInstBefore(Shift, I);
7237 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7238 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7241 // Okay, if we get here, one shift must be left, and the other shift must be
7242 // right. See if the amounts are equal.
7243 if (ShiftAmt1 == ShiftAmt2) {
7244 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7245 if (I.getOpcode() == Instruction::Shl) {
7246 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7247 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7249 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7250 if (I.getOpcode() == Instruction::LShr) {
7251 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7252 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
7254 // We can simplify ((X << C) >>s C) into a trunc + sext.
7255 // NOTE: we could do this for any C, but that would make 'unusual' integer
7256 // types. For now, just stick to ones well-supported by the code
7258 const Type *SExtType = 0;
7259 switch (Ty->getBitWidth() - ShiftAmt1) {
7266 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7271 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7272 InsertNewInstBefore(NewTrunc, I);
7273 return new SExtInst(NewTrunc, Ty);
7275 // Otherwise, we can't handle it yet.
7276 } else if (ShiftAmt1 < ShiftAmt2) {
7277 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7279 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7280 if (I.getOpcode() == Instruction::Shl) {
7281 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7282 ShiftOp->getOpcode() == Instruction::AShr);
7283 Instruction *Shift =
7284 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7285 InsertNewInstBefore(Shift, I);
7287 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7288 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7291 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7292 if (I.getOpcode() == Instruction::LShr) {
7293 assert(ShiftOp->getOpcode() == Instruction::Shl);
7294 Instruction *Shift =
7295 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7296 InsertNewInstBefore(Shift, I);
7298 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7299 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7302 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7304 assert(ShiftAmt2 < ShiftAmt1);
7305 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7307 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7308 if (I.getOpcode() == Instruction::Shl) {
7309 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7310 ShiftOp->getOpcode() == Instruction::AShr);
7311 Instruction *Shift =
7312 BinaryOperator::Create(ShiftOp->getOpcode(), X,
7313 ConstantInt::get(Ty, ShiftDiff));
7314 InsertNewInstBefore(Shift, I);
7316 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7317 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7320 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7321 if (I.getOpcode() == Instruction::LShr) {
7322 assert(ShiftOp->getOpcode() == Instruction::Shl);
7323 Instruction *Shift =
7324 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7325 InsertNewInstBefore(Shift, I);
7327 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7328 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
7331 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7338 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7339 /// expression. If so, decompose it, returning some value X, such that Val is
7342 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7344 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7345 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7346 Offset = CI->getZExtValue();
7348 return ConstantInt::get(Type::Int32Ty, 0);
7349 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7350 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7351 if (I->getOpcode() == Instruction::Shl) {
7352 // This is a value scaled by '1 << the shift amt'.
7353 Scale = 1U << RHS->getZExtValue();
7355 return I->getOperand(0);
7356 } else if (I->getOpcode() == Instruction::Mul) {
7357 // This value is scaled by 'RHS'.
7358 Scale = RHS->getZExtValue();
7360 return I->getOperand(0);
7361 } else if (I->getOpcode() == Instruction::Add) {
7362 // We have X+C. Check to see if we really have (X*C2)+C1,
7363 // where C1 is divisible by C2.
7366 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7367 Offset += RHS->getZExtValue();
7374 // Otherwise, we can't look past this.
7381 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7382 /// try to eliminate the cast by moving the type information into the alloc.
7383 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7384 AllocationInst &AI) {
7385 const PointerType *PTy = cast<PointerType>(CI.getType());
7387 // Remove any uses of AI that are dead.
7388 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7390 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7391 Instruction *User = cast<Instruction>(*UI++);
7392 if (isInstructionTriviallyDead(User)) {
7393 while (UI != E && *UI == User)
7394 ++UI; // If this instruction uses AI more than once, don't break UI.
7397 DOUT << "IC: DCE: " << *User;
7398 EraseInstFromFunction(*User);
7402 // Get the type really allocated and the type casted to.
7403 const Type *AllocElTy = AI.getAllocatedType();
7404 const Type *CastElTy = PTy->getElementType();
7405 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7407 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7408 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7409 if (CastElTyAlign < AllocElTyAlign) return 0;
7411 // If the allocation has multiple uses, only promote it if we are strictly
7412 // increasing the alignment of the resultant allocation. If we keep it the
7413 // same, we open the door to infinite loops of various kinds.
7414 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7416 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
7417 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
7418 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7420 // See if we can satisfy the modulus by pulling a scale out of the array
7422 unsigned ArraySizeScale;
7424 Value *NumElements = // See if the array size is a decomposable linear expr.
7425 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7427 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7429 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7430 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7432 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7437 // If the allocation size is constant, form a constant mul expression
7438 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7439 if (isa<ConstantInt>(NumElements))
7440 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7441 // otherwise multiply the amount and the number of elements
7442 else if (Scale != 1) {
7443 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7444 Amt = InsertNewInstBefore(Tmp, AI);
7448 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7449 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
7450 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7451 Amt = InsertNewInstBefore(Tmp, AI);
7454 AllocationInst *New;
7455 if (isa<MallocInst>(AI))
7456 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7458 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7459 InsertNewInstBefore(New, AI);
7462 // If the allocation has multiple uses, insert a cast and change all things
7463 // that used it to use the new cast. This will also hack on CI, but it will
7465 if (!AI.hasOneUse()) {
7466 AddUsesToWorkList(AI);
7467 // New is the allocation instruction, pointer typed. AI is the original
7468 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7469 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7470 InsertNewInstBefore(NewCast, AI);
7471 AI.replaceAllUsesWith(NewCast);
7473 return ReplaceInstUsesWith(CI, New);
7476 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7477 /// and return it as type Ty without inserting any new casts and without
7478 /// changing the computed value. This is used by code that tries to decide
7479 /// whether promoting or shrinking integer operations to wider or smaller types
7480 /// will allow us to eliminate a truncate or extend.
7482 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7483 /// extension operation if Ty is larger.
7485 /// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7486 /// should return true if trunc(V) can be computed by computing V in the smaller
7487 /// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7488 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7489 /// efficiently truncated.
7491 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7492 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7493 /// the final result.
7494 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7496 int &NumCastsRemoved) {
7497 // We can always evaluate constants in another type.
7498 if (isa<ConstantInt>(V))
7501 Instruction *I = dyn_cast<Instruction>(V);
7502 if (!I) return false;
7504 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7506 // If this is an extension or truncate, we can often eliminate it.
7507 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7508 // If this is a cast from the destination type, we can trivially eliminate
7509 // it, and this will remove a cast overall.
7510 if (I->getOperand(0)->getType() == Ty) {
7511 // If the first operand is itself a cast, and is eliminable, do not count
7512 // this as an eliminable cast. We would prefer to eliminate those two
7514 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7520 // We can't extend or shrink something that has multiple uses: doing so would
7521 // require duplicating the instruction in general, which isn't profitable.
7522 if (!I->hasOneUse()) return false;
7524 switch (I->getOpcode()) {
7525 case Instruction::Add:
7526 case Instruction::Sub:
7527 case Instruction::Mul:
7528 case Instruction::And:
7529 case Instruction::Or:
7530 case Instruction::Xor:
7531 // These operators can all arbitrarily be extended or truncated.
7532 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7534 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7537 case Instruction::Shl:
7538 // If we are truncating the result of this SHL, and if it's a shift of a
7539 // constant amount, we can always perform a SHL in a smaller type.
7540 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7541 uint32_t BitWidth = Ty->getBitWidth();
7542 if (BitWidth < OrigTy->getBitWidth() &&
7543 CI->getLimitedValue(BitWidth) < BitWidth)
7544 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7548 case Instruction::LShr:
7549 // If this is a truncate of a logical shr, we can truncate it to a smaller
7550 // lshr iff we know that the bits we would otherwise be shifting in are
7552 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7553 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7554 uint32_t BitWidth = Ty->getBitWidth();
7555 if (BitWidth < OrigBitWidth &&
7556 MaskedValueIsZero(I->getOperand(0),
7557 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7558 CI->getLimitedValue(BitWidth) < BitWidth) {
7559 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7564 case Instruction::ZExt:
7565 case Instruction::SExt:
7566 case Instruction::Trunc:
7567 // If this is the same kind of case as our original (e.g. zext+zext), we
7568 // can safely replace it. Note that replacing it does not reduce the number
7569 // of casts in the input.
7570 if (I->getOpcode() == CastOpc)
7573 case Instruction::Select: {
7574 SelectInst *SI = cast<SelectInst>(I);
7575 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7577 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7580 case Instruction::PHI: {
7581 // We can change a phi if we can change all operands.
7582 PHINode *PN = cast<PHINode>(I);
7583 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7584 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7590 // TODO: Can handle more cases here.
7597 /// EvaluateInDifferentType - Given an expression that
7598 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7599 /// evaluate the expression.
7600 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7602 if (Constant *C = dyn_cast<Constant>(V))
7603 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7605 // Otherwise, it must be an instruction.
7606 Instruction *I = cast<Instruction>(V);
7607 Instruction *Res = 0;
7608 switch (I->getOpcode()) {
7609 case Instruction::Add:
7610 case Instruction::Sub:
7611 case Instruction::Mul:
7612 case Instruction::And:
7613 case Instruction::Or:
7614 case Instruction::Xor:
7615 case Instruction::AShr:
7616 case Instruction::LShr:
7617 case Instruction::Shl: {
7618 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7619 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7620 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
7624 case Instruction::Trunc:
7625 case Instruction::ZExt:
7626 case Instruction::SExt:
7627 // If the source type of the cast is the type we're trying for then we can
7628 // just return the source. There's no need to insert it because it is not
7630 if (I->getOperand(0)->getType() == Ty)
7631 return I->getOperand(0);
7633 // Otherwise, must be the same type of cast, so just reinsert a new one.
7634 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7637 case Instruction::Select: {
7638 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7639 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7640 Res = SelectInst::Create(I->getOperand(0), True, False);
7643 case Instruction::PHI: {
7644 PHINode *OPN = cast<PHINode>(I);
7645 PHINode *NPN = PHINode::Create(Ty);
7646 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7647 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7648 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7654 // TODO: Can handle more cases here.
7655 assert(0 && "Unreachable!");
7660 return InsertNewInstBefore(Res, *I);
7663 /// @brief Implement the transforms common to all CastInst visitors.
7664 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7665 Value *Src = CI.getOperand(0);
7667 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7668 // eliminate it now.
7669 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7670 if (Instruction::CastOps opc =
7671 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7672 // The first cast (CSrc) is eliminable so we need to fix up or replace
7673 // the second cast (CI). CSrc will then have a good chance of being dead.
7674 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7678 // If we are casting a select then fold the cast into the select
7679 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7680 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7683 // If we are casting a PHI then fold the cast into the PHI
7684 if (isa<PHINode>(Src))
7685 if (Instruction *NV = FoldOpIntoPhi(CI))
7691 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7692 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7693 Value *Src = CI.getOperand(0);
7695 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7696 // If casting the result of a getelementptr instruction with no offset, turn
7697 // this into a cast of the original pointer!
7698 if (GEP->hasAllZeroIndices()) {
7699 // Changing the cast operand is usually not a good idea but it is safe
7700 // here because the pointer operand is being replaced with another
7701 // pointer operand so the opcode doesn't need to change.
7703 CI.setOperand(0, GEP->getOperand(0));
7707 // If the GEP has a single use, and the base pointer is a bitcast, and the
7708 // GEP computes a constant offset, see if we can convert these three
7709 // instructions into fewer. This typically happens with unions and other
7710 // non-type-safe code.
7711 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7712 if (GEP->hasAllConstantIndices()) {
7713 // We are guaranteed to get a constant from EmitGEPOffset.
7714 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7715 int64_t Offset = OffsetV->getSExtValue();
7717 // Get the base pointer input of the bitcast, and the type it points to.
7718 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7719 const Type *GEPIdxTy =
7720 cast<PointerType>(OrigBase->getType())->getElementType();
7721 if (GEPIdxTy->isSized()) {
7722 SmallVector<Value*, 8> NewIndices;
7724 // Start with the index over the outer type. Note that the type size
7725 // might be zero (even if the offset isn't zero) if the indexed type
7726 // is something like [0 x {int, int}]
7727 const Type *IntPtrTy = TD->getIntPtrType();
7728 int64_t FirstIdx = 0;
7729 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7730 FirstIdx = Offset/TySize;
7733 // Handle silly modulus not returning values values [0..TySize).
7737 assert(Offset >= 0);
7739 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7742 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7744 // Index into the types. If we fail, set OrigBase to null.
7746 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7747 const StructLayout *SL = TD->getStructLayout(STy);
7748 if (Offset < (int64_t)SL->getSizeInBytes()) {
7749 unsigned Elt = SL->getElementContainingOffset(Offset);
7750 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7752 Offset -= SL->getElementOffset(Elt);
7753 GEPIdxTy = STy->getElementType(Elt);
7755 // Otherwise, we can't index into this, bail out.
7759 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7760 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7761 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7762 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7765 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7767 GEPIdxTy = STy->getElementType();
7769 // Otherwise, we can't index into this, bail out.
7775 // If we were able to index down into an element, create the GEP
7776 // and bitcast the result. This eliminates one bitcast, potentially
7778 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7780 NewIndices.end(), "");
7781 InsertNewInstBefore(NGEP, CI);
7782 NGEP->takeName(GEP);
7784 if (isa<BitCastInst>(CI))
7785 return new BitCastInst(NGEP, CI.getType());
7786 assert(isa<PtrToIntInst>(CI));
7787 return new PtrToIntInst(NGEP, CI.getType());
7794 return commonCastTransforms(CI);
7799 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7800 /// integer types. This function implements the common transforms for all those
7802 /// @brief Implement the transforms common to CastInst with integer operands
7803 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7804 if (Instruction *Result = commonCastTransforms(CI))
7807 Value *Src = CI.getOperand(0);
7808 const Type *SrcTy = Src->getType();
7809 const Type *DestTy = CI.getType();
7810 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7811 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7813 // See if we can simplify any instructions used by the LHS whose sole
7814 // purpose is to compute bits we don't care about.
7815 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7816 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7817 KnownZero, KnownOne))
7820 // If the source isn't an instruction or has more than one use then we
7821 // can't do anything more.
7822 Instruction *SrcI = dyn_cast<Instruction>(Src);
7823 if (!SrcI || !Src->hasOneUse())
7826 // Attempt to propagate the cast into the instruction for int->int casts.
7827 int NumCastsRemoved = 0;
7828 if (!isa<BitCastInst>(CI) &&
7829 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7830 CI.getOpcode(), NumCastsRemoved)) {
7831 // If this cast is a truncate, evaluting in a different type always
7832 // eliminates the cast, so it is always a win. If this is a zero-extension,
7833 // we need to do an AND to maintain the clear top-part of the computation,
7834 // so we require that the input have eliminated at least one cast. If this
7835 // is a sign extension, we insert two new casts (to do the extension) so we
7836 // require that two casts have been eliminated.
7838 switch (CI.getOpcode()) {
7840 // All the others use floating point so we shouldn't actually
7841 // get here because of the check above.
7842 assert(0 && "Unknown cast type");
7843 case Instruction::Trunc:
7846 case Instruction::ZExt:
7847 DoXForm = NumCastsRemoved >= 1;
7849 case Instruction::SExt:
7850 DoXForm = NumCastsRemoved >= 2;
7855 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7856 CI.getOpcode() == Instruction::SExt);
7857 assert(Res->getType() == DestTy);
7858 switch (CI.getOpcode()) {
7859 default: assert(0 && "Unknown cast type!");
7860 case Instruction::Trunc:
7861 case Instruction::BitCast:
7862 // Just replace this cast with the result.
7863 return ReplaceInstUsesWith(CI, Res);
7864 case Instruction::ZExt: {
7865 // We need to emit an AND to clear the high bits.
7866 assert(SrcBitSize < DestBitSize && "Not a zext?");
7867 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7869 return BinaryOperator::CreateAnd(Res, C);
7871 case Instruction::SExt:
7872 // We need to emit a cast to truncate, then a cast to sext.
7873 return CastInst::Create(Instruction::SExt,
7874 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7880 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7881 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7883 switch (SrcI->getOpcode()) {
7884 case Instruction::Add:
7885 case Instruction::Mul:
7886 case Instruction::And:
7887 case Instruction::Or:
7888 case Instruction::Xor:
7889 // If we are discarding information, rewrite.
7890 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7891 // Don't insert two casts if they cannot be eliminated. We allow
7892 // two casts to be inserted if the sizes are the same. This could
7893 // only be converting signedness, which is a noop.
7894 if (DestBitSize == SrcBitSize ||
7895 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7896 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7897 Instruction::CastOps opcode = CI.getOpcode();
7898 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
7899 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
7900 return BinaryOperator::Create(
7901 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7905 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7906 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7907 SrcI->getOpcode() == Instruction::Xor &&
7908 Op1 == ConstantInt::getTrue() &&
7909 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7910 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
7911 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7914 case Instruction::SDiv:
7915 case Instruction::UDiv:
7916 case Instruction::SRem:
7917 case Instruction::URem:
7918 // If we are just changing the sign, rewrite.
7919 if (DestBitSize == SrcBitSize) {
7920 // Don't insert two casts if they cannot be eliminated. We allow
7921 // two casts to be inserted if the sizes are the same. This could
7922 // only be converting signedness, which is a noop.
7923 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7924 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7925 Value *Op0c = InsertCastBefore(Instruction::BitCast,
7926 Op0, DestTy, *SrcI);
7927 Value *Op1c = InsertCastBefore(Instruction::BitCast,
7928 Op1, DestTy, *SrcI);
7929 return BinaryOperator::Create(
7930 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7935 case Instruction::Shl:
7936 // Allow changing the sign of the source operand. Do not allow
7937 // changing the size of the shift, UNLESS the shift amount is a
7938 // constant. We must not change variable sized shifts to a smaller
7939 // size, because it is undefined to shift more bits out than exist
7941 if (DestBitSize == SrcBitSize ||
7942 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7943 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7944 Instruction::BitCast : Instruction::Trunc);
7945 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
7946 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
7947 return BinaryOperator::CreateShl(Op0c, Op1c);
7950 case Instruction::AShr:
7951 // If this is a signed shr, and if all bits shifted in are about to be
7952 // truncated off, turn it into an unsigned shr to allow greater
7954 if (DestBitSize < SrcBitSize &&
7955 isa<ConstantInt>(Op1)) {
7956 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7957 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7958 // Insert the new logical shift right.
7959 return BinaryOperator::CreateLShr(Op0, Op1);
7967 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7968 if (Instruction *Result = commonIntCastTransforms(CI))
7971 Value *Src = CI.getOperand(0);
7972 const Type *Ty = CI.getType();
7973 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7974 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7976 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7977 switch (SrcI->getOpcode()) {
7979 case Instruction::LShr:
7980 // We can shrink lshr to something smaller if we know the bits shifted in
7981 // are already zeros.
7982 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7983 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7985 // Get a mask for the bits shifting in.
7986 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7987 Value* SrcIOp0 = SrcI->getOperand(0);
7988 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7989 if (ShAmt >= DestBitWidth) // All zeros.
7990 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7992 // Okay, we can shrink this. Truncate the input, then return a new
7994 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7995 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7997 return BinaryOperator::CreateLShr(V1, V2);
7999 } else { // This is a variable shr.
8001 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
8002 // more LLVM instructions, but allows '1 << Y' to be hoisted if
8003 // loop-invariant and CSE'd.
8004 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
8005 Value *One = ConstantInt::get(SrcI->getType(), 1);
8007 Value *V = InsertNewInstBefore(
8008 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
8010 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
8011 SrcI->getOperand(0),
8013 Value *Zero = Constant::getNullValue(V->getType());
8014 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
8024 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8025 /// in order to eliminate the icmp.
8026 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8028 // If we are just checking for a icmp eq of a single bit and zext'ing it
8029 // to an integer, then shift the bit to the appropriate place and then
8030 // cast to integer to avoid the comparison.
8031 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8032 const APInt &Op1CV = Op1C->getValue();
8034 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8035 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8036 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8037 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8038 if (!DoXform) return ICI;
8040 Value *In = ICI->getOperand(0);
8041 Value *Sh = ConstantInt::get(In->getType(),
8042 In->getType()->getPrimitiveSizeInBits()-1);
8043 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8044 In->getName()+".lobit"),
8046 if (In->getType() != CI.getType())
8047 In = CastInst::CreateIntegerCast(In, CI.getType(),
8048 false/*ZExt*/, "tmp", &CI);
8050 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8051 Constant *One = ConstantInt::get(In->getType(), 1);
8052 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8053 In->getName()+".not"),
8057 return ReplaceInstUsesWith(CI, In);
8062 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8063 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8064 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8065 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8066 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8067 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8068 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8069 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8070 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8071 // This only works for EQ and NE
8072 ICI->isEquality()) {
8073 // If Op1C some other power of two, convert:
8074 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8075 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8076 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8077 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8079 APInt KnownZeroMask(~KnownZero);
8080 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8081 if (!DoXform) return ICI;
8083 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8084 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8085 // (X&4) == 2 --> false
8086 // (X&4) != 2 --> true
8087 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8088 Res = ConstantExpr::getZExt(Res, CI.getType());
8089 return ReplaceInstUsesWith(CI, Res);
8092 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8093 Value *In = ICI->getOperand(0);
8095 // Perform a logical shr by shiftamt.
8096 // Insert the shift to put the result in the low bit.
8097 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8098 ConstantInt::get(In->getType(), ShiftAmt),
8099 In->getName()+".lobit"), CI);
8102 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8103 Constant *One = ConstantInt::get(In->getType(), 1);
8104 In = BinaryOperator::CreateXor(In, One, "tmp");
8105 InsertNewInstBefore(cast<Instruction>(In), CI);
8108 if (CI.getType() == In->getType())
8109 return ReplaceInstUsesWith(CI, In);
8111 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8119 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8120 // If one of the common conversion will work ..
8121 if (Instruction *Result = commonIntCastTransforms(CI))
8124 Value *Src = CI.getOperand(0);
8126 // If this is a cast of a cast
8127 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8128 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8129 // types and if the sizes are just right we can convert this into a logical
8130 // 'and' which will be much cheaper than the pair of casts.
8131 if (isa<TruncInst>(CSrc)) {
8132 // Get the sizes of the types involved
8133 Value *A = CSrc->getOperand(0);
8134 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8135 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8136 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
8137 // If we're actually extending zero bits and the trunc is a no-op
8138 if (MidSize < DstSize && SrcSize == DstSize) {
8139 // Replace both of the casts with an And of the type mask.
8140 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8141 Constant *AndConst = ConstantInt::get(AndValue);
8143 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
8144 // Unfortunately, if the type changed, we need to cast it back.
8145 if (And->getType() != CI.getType()) {
8146 And->setName(CSrc->getName()+".mask");
8147 InsertNewInstBefore(And, CI);
8148 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
8155 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8156 return transformZExtICmp(ICI, CI);
8158 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8159 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8160 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8161 // of the (zext icmp) will be transformed.
8162 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8163 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8164 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8165 (transformZExtICmp(LHS, CI, false) ||
8166 transformZExtICmp(RHS, CI, false))) {
8167 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8168 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8169 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8176 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8177 if (Instruction *I = commonIntCastTransforms(CI))
8180 Value *Src = CI.getOperand(0);
8182 // Canonicalize sign-extend from i1 to a select.
8183 if (Src->getType() == Type::Int1Ty)
8184 return SelectInst::Create(Src,
8185 ConstantInt::getAllOnesValue(CI.getType()),
8186 Constant::getNullValue(CI.getType()));
8188 // See if the value being truncated is already sign extended. If so, just
8189 // eliminate the trunc/sext pair.
8190 if (getOpcode(Src) == Instruction::Trunc) {
8191 Value *Op = cast<User>(Src)->getOperand(0);
8192 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8193 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8194 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8195 unsigned NumSignBits = ComputeNumSignBits(Op);
8197 if (OpBits == DestBits) {
8198 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8199 // bits, it is already ready.
8200 if (NumSignBits > DestBits-MidBits)
8201 return ReplaceInstUsesWith(CI, Op);
8202 } else if (OpBits < DestBits) {
8203 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8204 // bits, just sext from i32.
8205 if (NumSignBits > OpBits-MidBits)
8206 return new SExtInst(Op, CI.getType(), "tmp");
8208 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8209 // bits, just truncate to i32.
8210 if (NumSignBits > OpBits-MidBits)
8211 return new TruncInst(Op, CI.getType(), "tmp");
8215 // If the input is a shl/ashr pair of a same constant, then this is a sign
8216 // extension from a smaller value. If we could trust arbitrary bitwidth
8217 // integers, we could turn this into a truncate to the smaller bit and then
8218 // use a sext for the whole extension. Since we don't, look deeper and check
8219 // for a truncate. If the source and dest are the same type, eliminate the
8220 // trunc and extend and just do shifts. For example, turn:
8221 // %a = trunc i32 %i to i8
8222 // %b = shl i8 %a, 6
8223 // %c = ashr i8 %b, 6
8224 // %d = sext i8 %c to i32
8226 // %a = shl i32 %i, 30
8227 // %d = ashr i32 %a, 30
8229 ConstantInt *BA = 0, *CA = 0;
8230 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8231 m_ConstantInt(CA))) &&
8232 BA == CA && isa<TruncInst>(A)) {
8233 Value *I = cast<TruncInst>(A)->getOperand(0);
8234 if (I->getType() == CI.getType()) {
8235 unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8236 unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8237 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8238 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8239 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8241 return BinaryOperator::CreateAShr(I, ShAmtV);
8248 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8249 /// in the specified FP type without changing its value.
8250 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
8252 APFloat F = CFP->getValueAPF();
8253 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8255 return ConstantFP::get(F);
8259 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8260 /// through it until we get the source value.
8261 static Value *LookThroughFPExtensions(Value *V) {
8262 if (Instruction *I = dyn_cast<Instruction>(V))
8263 if (I->getOpcode() == Instruction::FPExt)
8264 return LookThroughFPExtensions(I->getOperand(0));
8266 // If this value is a constant, return the constant in the smallest FP type
8267 // that can accurately represent it. This allows us to turn
8268 // (float)((double)X+2.0) into x+2.0f.
8269 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8270 if (CFP->getType() == Type::PPC_FP128Ty)
8271 return V; // No constant folding of this.
8272 // See if the value can be truncated to float and then reextended.
8273 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
8275 if (CFP->getType() == Type::DoubleTy)
8276 return V; // Won't shrink.
8277 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
8279 // Don't try to shrink to various long double types.
8285 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8286 if (Instruction *I = commonCastTransforms(CI))
8289 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8290 // smaller than the destination type, we can eliminate the truncate by doing
8291 // the add as the smaller type. This applies to add/sub/mul/div as well as
8292 // many builtins (sqrt, etc).
8293 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8294 if (OpI && OpI->hasOneUse()) {
8295 switch (OpI->getOpcode()) {
8297 case Instruction::Add:
8298 case Instruction::Sub:
8299 case Instruction::Mul:
8300 case Instruction::FDiv:
8301 case Instruction::FRem:
8302 const Type *SrcTy = OpI->getType();
8303 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8304 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8305 if (LHSTrunc->getType() != SrcTy &&
8306 RHSTrunc->getType() != SrcTy) {
8307 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8308 // If the source types were both smaller than the destination type of
8309 // the cast, do this xform.
8310 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8311 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8312 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8314 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8316 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8325 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8326 return commonCastTransforms(CI);
8329 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8330 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8332 return commonCastTransforms(FI);
8334 // fptoui(uitofp(X)) --> X
8335 // fptoui(sitofp(X)) --> X
8336 // This is safe if the intermediate type has enough bits in its mantissa to
8337 // accurately represent all values of X. For example, do not do this with
8338 // i64->float->i64. This is also safe for sitofp case, because any negative
8339 // 'X' value would cause an undefined result for the fptoui.
8340 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8341 OpI->getOperand(0)->getType() == FI.getType() &&
8342 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8343 OpI->getType()->getFPMantissaWidth())
8344 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8346 return commonCastTransforms(FI);
8349 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8350 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8352 return commonCastTransforms(FI);
8354 // fptosi(sitofp(X)) --> X
8355 // fptosi(uitofp(X)) --> X
8356 // This is safe if the intermediate type has enough bits in its mantissa to
8357 // accurately represent all values of X. For example, do not do this with
8358 // i64->float->i64. This is also safe for sitofp case, because any negative
8359 // 'X' value would cause an undefined result for the fptoui.
8360 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8361 OpI->getOperand(0)->getType() == FI.getType() &&
8362 (int)FI.getType()->getPrimitiveSizeInBits() <=
8363 OpI->getType()->getFPMantissaWidth())
8364 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8366 return commonCastTransforms(FI);
8369 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8370 return commonCastTransforms(CI);
8373 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8374 return commonCastTransforms(CI);
8377 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8378 return commonPointerCastTransforms(CI);
8381 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8382 if (Instruction *I = commonCastTransforms(CI))
8385 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8386 if (!DestPointee->isSized()) return 0;
8388 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8391 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8392 m_ConstantInt(Cst)))) {
8393 // If the source and destination operands have the same type, see if this
8394 // is a single-index GEP.
8395 if (X->getType() == CI.getType()) {
8396 // Get the size of the pointee type.
8397 uint64_t Size = TD->getABITypeSize(DestPointee);
8399 // Convert the constant to intptr type.
8400 APInt Offset = Cst->getValue();
8401 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8403 // If Offset is evenly divisible by Size, we can do this xform.
8404 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8405 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8406 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
8409 // TODO: Could handle other cases, e.g. where add is indexing into field of
8411 } else if (CI.getOperand(0)->hasOneUse() &&
8412 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8413 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8414 // "inttoptr+GEP" instead of "add+intptr".
8416 // Get the size of the pointee type.
8417 uint64_t Size = TD->getABITypeSize(DestPointee);
8419 // Convert the constant to intptr type.
8420 APInt Offset = Cst->getValue();
8421 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8423 // If Offset is evenly divisible by Size, we can do this xform.
8424 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8425 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8427 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8429 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
8435 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8436 // If the operands are integer typed then apply the integer transforms,
8437 // otherwise just apply the common ones.
8438 Value *Src = CI.getOperand(0);
8439 const Type *SrcTy = Src->getType();
8440 const Type *DestTy = CI.getType();
8442 if (SrcTy->isInteger() && DestTy->isInteger()) {
8443 if (Instruction *Result = commonIntCastTransforms(CI))
8445 } else if (isa<PointerType>(SrcTy)) {
8446 if (Instruction *I = commonPointerCastTransforms(CI))
8449 if (Instruction *Result = commonCastTransforms(CI))
8454 // Get rid of casts from one type to the same type. These are useless and can
8455 // be replaced by the operand.
8456 if (DestTy == Src->getType())
8457 return ReplaceInstUsesWith(CI, Src);
8459 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8460 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8461 const Type *DstElTy = DstPTy->getElementType();
8462 const Type *SrcElTy = SrcPTy->getElementType();
8464 // If the address spaces don't match, don't eliminate the bitcast, which is
8465 // required for changing types.
8466 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8469 // If we are casting a malloc or alloca to a pointer to a type of the same
8470 // size, rewrite the allocation instruction to allocate the "right" type.
8471 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8472 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8475 // If the source and destination are pointers, and this cast is equivalent
8476 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8477 // This can enhance SROA and other transforms that want type-safe pointers.
8478 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8479 unsigned NumZeros = 0;
8480 while (SrcElTy != DstElTy &&
8481 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8482 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8483 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8487 // If we found a path from the src to dest, create the getelementptr now.
8488 if (SrcElTy == DstElTy) {
8489 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8490 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8491 ((Instruction*) NULL));
8495 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8496 if (SVI->hasOneUse()) {
8497 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8498 // a bitconvert to a vector with the same # elts.
8499 if (isa<VectorType>(DestTy) &&
8500 cast<VectorType>(DestTy)->getNumElements() ==
8501 SVI->getType()->getNumElements() &&
8502 SVI->getType()->getNumElements() ==
8503 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8505 // If either of the operands is a cast from CI.getType(), then
8506 // evaluating the shuffle in the casted destination's type will allow
8507 // us to eliminate at least one cast.
8508 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8509 Tmp->getOperand(0)->getType() == DestTy) ||
8510 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8511 Tmp->getOperand(0)->getType() == DestTy)) {
8512 Value *LHS = InsertCastBefore(Instruction::BitCast,
8513 SVI->getOperand(0), DestTy, CI);
8514 Value *RHS = InsertCastBefore(Instruction::BitCast,
8515 SVI->getOperand(1), DestTy, CI);
8516 // Return a new shuffle vector. Use the same element ID's, as we
8517 // know the vector types match #elts.
8518 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8526 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8528 /// %D = select %cond, %C, %A
8530 /// %C = select %cond, %B, 0
8533 /// Assuming that the specified instruction is an operand to the select, return
8534 /// a bitmask indicating which operands of this instruction are foldable if they
8535 /// equal the other incoming value of the select.
8537 static unsigned GetSelectFoldableOperands(Instruction *I) {
8538 switch (I->getOpcode()) {
8539 case Instruction::Add:
8540 case Instruction::Mul:
8541 case Instruction::And:
8542 case Instruction::Or:
8543 case Instruction::Xor:
8544 return 3; // Can fold through either operand.
8545 case Instruction::Sub: // Can only fold on the amount subtracted.
8546 case Instruction::Shl: // Can only fold on the shift amount.
8547 case Instruction::LShr:
8548 case Instruction::AShr:
8551 return 0; // Cannot fold
8555 /// GetSelectFoldableConstant - For the same transformation as the previous
8556 /// function, return the identity constant that goes into the select.
8557 static Constant *GetSelectFoldableConstant(Instruction *I) {
8558 switch (I->getOpcode()) {
8559 default: assert(0 && "This cannot happen!"); abort();
8560 case Instruction::Add:
8561 case Instruction::Sub:
8562 case Instruction::Or:
8563 case Instruction::Xor:
8564 case Instruction::Shl:
8565 case Instruction::LShr:
8566 case Instruction::AShr:
8567 return Constant::getNullValue(I->getType());
8568 case Instruction::And:
8569 return Constant::getAllOnesValue(I->getType());
8570 case Instruction::Mul:
8571 return ConstantInt::get(I->getType(), 1);
8575 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8576 /// have the same opcode and only one use each. Try to simplify this.
8577 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8579 if (TI->getNumOperands() == 1) {
8580 // If this is a non-volatile load or a cast from the same type,
8583 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8586 return 0; // unknown unary op.
8589 // Fold this by inserting a select from the input values.
8590 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8591 FI->getOperand(0), SI.getName()+".v");
8592 InsertNewInstBefore(NewSI, SI);
8593 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
8597 // Only handle binary operators here.
8598 if (!isa<BinaryOperator>(TI))
8601 // Figure out if the operations have any operands in common.
8602 Value *MatchOp, *OtherOpT, *OtherOpF;
8604 if (TI->getOperand(0) == FI->getOperand(0)) {
8605 MatchOp = TI->getOperand(0);
8606 OtherOpT = TI->getOperand(1);
8607 OtherOpF = FI->getOperand(1);
8608 MatchIsOpZero = true;
8609 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8610 MatchOp = TI->getOperand(1);
8611 OtherOpT = TI->getOperand(0);
8612 OtherOpF = FI->getOperand(0);
8613 MatchIsOpZero = false;
8614 } else if (!TI->isCommutative()) {
8616 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8617 MatchOp = TI->getOperand(0);
8618 OtherOpT = TI->getOperand(1);
8619 OtherOpF = FI->getOperand(0);
8620 MatchIsOpZero = true;
8621 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8622 MatchOp = TI->getOperand(1);
8623 OtherOpT = TI->getOperand(0);
8624 OtherOpF = FI->getOperand(1);
8625 MatchIsOpZero = true;
8630 // If we reach here, they do have operations in common.
8631 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8632 OtherOpF, SI.getName()+".v");
8633 InsertNewInstBefore(NewSI, SI);
8635 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8637 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8639 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8641 assert(0 && "Shouldn't get here");
8645 /// visitSelectInstWithICmp - Visit a SelectInst that has an
8646 /// ICmpInst as its first operand.
8648 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8650 bool Changed = false;
8651 ICmpInst::Predicate Pred = ICI->getPredicate();
8652 Value *CmpLHS = ICI->getOperand(0);
8653 Value *CmpRHS = ICI->getOperand(1);
8654 Value *TrueVal = SI.getTrueValue();
8655 Value *FalseVal = SI.getFalseValue();
8657 // Check cases where the comparison is with a constant that
8658 // can be adjusted to fit the min/max idiom. We may edit ICI in
8659 // place here, so make sure the select is the only user.
8660 if (ICI->hasOneUse())
8661 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
8664 case ICmpInst::ICMP_ULT:
8665 case ICmpInst::ICMP_SLT: {
8666 // X < MIN ? T : F --> F
8667 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8668 return ReplaceInstUsesWith(SI, FalseVal);
8669 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
8670 Constant *AdjustedRHS = SubOne(CI);
8671 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8672 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8673 Pred = ICmpInst::getSwappedPredicate(Pred);
8674 CmpRHS = AdjustedRHS;
8675 std::swap(FalseVal, TrueVal);
8676 ICI->setPredicate(Pred);
8677 ICI->setOperand(1, CmpRHS);
8678 SI.setOperand(1, TrueVal);
8679 SI.setOperand(2, FalseVal);
8684 case ICmpInst::ICMP_UGT:
8685 case ICmpInst::ICMP_SGT: {
8686 // X > MAX ? T : F --> F
8687 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8688 return ReplaceInstUsesWith(SI, FalseVal);
8689 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
8690 Constant *AdjustedRHS = AddOne(CI);
8691 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8692 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8693 Pred = ICmpInst::getSwappedPredicate(Pred);
8694 CmpRHS = AdjustedRHS;
8695 std::swap(FalseVal, TrueVal);
8696 ICI->setPredicate(Pred);
8697 ICI->setOperand(1, CmpRHS);
8698 SI.setOperand(1, TrueVal);
8699 SI.setOperand(2, FalseVal);
8706 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
8707 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
8708 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
8709 if (match(TrueVal, m_ConstantInt(-1)) &&
8710 match(FalseVal, m_ConstantInt(0)))
8711 Pred = ICI->getPredicate();
8712 else if (match(TrueVal, m_ConstantInt(0)) &&
8713 match(FalseVal, m_ConstantInt(-1)))
8714 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8716 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8717 // If we are just checking for a icmp eq of a single bit and zext'ing it
8718 // to an integer, then shift the bit to the appropriate place and then
8719 // cast to integer to avoid the comparison.
8720 const APInt &Op1CV = CI->getValue();
8722 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8723 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8724 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8725 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
8726 Value *In = ICI->getOperand(0);
8727 Value *Sh = ConstantInt::get(In->getType(),
8728 In->getType()->getPrimitiveSizeInBits()-1);
8729 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8730 In->getName()+".lobit"),
8732 if (In->getType() != SI.getType())
8733 In = CastInst::CreateIntegerCast(In, SI.getType(),
8734 true/*SExt*/, "tmp", ICI);
8736 if (Pred == ICmpInst::ICMP_SGT)
8737 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8738 In->getName()+".not"), *ICI);
8740 return ReplaceInstUsesWith(SI, In);
8745 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8746 // Transform (X == Y) ? X : Y -> Y
8747 if (Pred == ICmpInst::ICMP_EQ)
8748 return ReplaceInstUsesWith(SI, FalseVal);
8749 // Transform (X != Y) ? X : Y -> X
8750 if (Pred == ICmpInst::ICMP_NE)
8751 return ReplaceInstUsesWith(SI, TrueVal);
8752 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8754 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8755 // Transform (X == Y) ? Y : X -> X
8756 if (Pred == ICmpInst::ICMP_EQ)
8757 return ReplaceInstUsesWith(SI, FalseVal);
8758 // Transform (X != Y) ? Y : X -> Y
8759 if (Pred == ICmpInst::ICMP_NE)
8760 return ReplaceInstUsesWith(SI, TrueVal);
8761 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8764 /// NOTE: if we wanted to, this is where to detect integer ABS
8766 return Changed ? &SI : 0;
8769 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8770 Value *CondVal = SI.getCondition();
8771 Value *TrueVal = SI.getTrueValue();
8772 Value *FalseVal = SI.getFalseValue();
8774 // select true, X, Y -> X
8775 // select false, X, Y -> Y
8776 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8777 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8779 // select C, X, X -> X
8780 if (TrueVal == FalseVal)
8781 return ReplaceInstUsesWith(SI, TrueVal);
8783 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8784 return ReplaceInstUsesWith(SI, FalseVal);
8785 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8786 return ReplaceInstUsesWith(SI, TrueVal);
8787 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8788 if (isa<Constant>(TrueVal))
8789 return ReplaceInstUsesWith(SI, TrueVal);
8791 return ReplaceInstUsesWith(SI, FalseVal);
8794 if (SI.getType() == Type::Int1Ty) {
8795 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8796 if (C->getZExtValue()) {
8797 // Change: A = select B, true, C --> A = or B, C
8798 return BinaryOperator::CreateOr(CondVal, FalseVal);
8800 // Change: A = select B, false, C --> A = and !B, C
8802 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8803 "not."+CondVal->getName()), SI);
8804 return BinaryOperator::CreateAnd(NotCond, FalseVal);
8806 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8807 if (C->getZExtValue() == false) {
8808 // Change: A = select B, C, false --> A = and B, C
8809 return BinaryOperator::CreateAnd(CondVal, TrueVal);
8811 // Change: A = select B, C, true --> A = or !B, C
8813 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8814 "not."+CondVal->getName()), SI);
8815 return BinaryOperator::CreateOr(NotCond, TrueVal);
8819 // select a, b, a -> a&b
8820 // select a, a, b -> a|b
8821 if (CondVal == TrueVal)
8822 return BinaryOperator::CreateOr(CondVal, FalseVal);
8823 else if (CondVal == FalseVal)
8824 return BinaryOperator::CreateAnd(CondVal, TrueVal);
8827 // Selecting between two integer constants?
8828 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8829 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8830 // select C, 1, 0 -> zext C to int
8831 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8832 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8833 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8834 // select C, 0, 1 -> zext !C to int
8836 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8837 "not."+CondVal->getName()), SI);
8838 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8841 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8843 // (x <s 0) ? -1 : 0 -> ashr x, 31
8844 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8845 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8846 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8847 // The comparison constant and the result are not neccessarily the
8848 // same width. Make an all-ones value by inserting a AShr.
8849 Value *X = IC->getOperand(0);
8850 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8851 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8852 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8854 InsertNewInstBefore(SRA, SI);
8856 // Then cast to the appropriate width.
8857 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
8862 // If one of the constants is zero (we know they can't both be) and we
8863 // have an icmp instruction with zero, and we have an 'and' with the
8864 // non-constant value, eliminate this whole mess. This corresponds to
8865 // cases like this: ((X & 27) ? 27 : 0)
8866 if (TrueValC->isZero() || FalseValC->isZero())
8867 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8868 cast<Constant>(IC->getOperand(1))->isNullValue())
8869 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8870 if (ICA->getOpcode() == Instruction::And &&
8871 isa<ConstantInt>(ICA->getOperand(1)) &&
8872 (ICA->getOperand(1) == TrueValC ||
8873 ICA->getOperand(1) == FalseValC) &&
8874 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8875 // Okay, now we know that everything is set up, we just don't
8876 // know whether we have a icmp_ne or icmp_eq and whether the
8877 // true or false val is the zero.
8878 bool ShouldNotVal = !TrueValC->isZero();
8879 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8882 V = InsertNewInstBefore(BinaryOperator::Create(
8883 Instruction::Xor, V, ICA->getOperand(1)), SI);
8884 return ReplaceInstUsesWith(SI, V);
8889 // See if we are selecting two values based on a comparison of the two values.
8890 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8891 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8892 // Transform (X == Y) ? X : Y -> Y
8893 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8894 // This is not safe in general for floating point:
8895 // consider X== -0, Y== +0.
8896 // It becomes safe if either operand is a nonzero constant.
8897 ConstantFP *CFPt, *CFPf;
8898 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8899 !CFPt->getValueAPF().isZero()) ||
8900 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8901 !CFPf->getValueAPF().isZero()))
8902 return ReplaceInstUsesWith(SI, FalseVal);
8904 // Transform (X != Y) ? X : Y -> X
8905 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8906 return ReplaceInstUsesWith(SI, TrueVal);
8907 // NOTE: if we wanted to, this is where to detect MIN/MAX
8909 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8910 // Transform (X == Y) ? Y : X -> X
8911 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8912 // This is not safe in general for floating point:
8913 // consider X== -0, Y== +0.
8914 // It becomes safe if either operand is a nonzero constant.
8915 ConstantFP *CFPt, *CFPf;
8916 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8917 !CFPt->getValueAPF().isZero()) ||
8918 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8919 !CFPf->getValueAPF().isZero()))
8920 return ReplaceInstUsesWith(SI, FalseVal);
8922 // Transform (X != Y) ? Y : X -> Y
8923 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8924 return ReplaceInstUsesWith(SI, TrueVal);
8925 // NOTE: if we wanted to, this is where to detect MIN/MAX
8927 // NOTE: if we wanted to, this is where to detect ABS
8930 // See if we are selecting two values based on a comparison of the two values.
8931 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
8932 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
8935 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8936 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8937 if (TI->hasOneUse() && FI->hasOneUse()) {
8938 Instruction *AddOp = 0, *SubOp = 0;
8940 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8941 if (TI->getOpcode() == FI->getOpcode())
8942 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8945 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8946 // even legal for FP.
8947 if (TI->getOpcode() == Instruction::Sub &&
8948 FI->getOpcode() == Instruction::Add) {
8949 AddOp = FI; SubOp = TI;
8950 } else if (FI->getOpcode() == Instruction::Sub &&
8951 TI->getOpcode() == Instruction::Add) {
8952 AddOp = TI; SubOp = FI;
8956 Value *OtherAddOp = 0;
8957 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8958 OtherAddOp = AddOp->getOperand(1);
8959 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8960 OtherAddOp = AddOp->getOperand(0);
8964 // So at this point we know we have (Y -> OtherAddOp):
8965 // select C, (add X, Y), (sub X, Z)
8966 Value *NegVal; // Compute -Z
8967 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8968 NegVal = ConstantExpr::getNeg(C);
8970 NegVal = InsertNewInstBefore(
8971 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8974 Value *NewTrueOp = OtherAddOp;
8975 Value *NewFalseOp = NegVal;
8977 std::swap(NewTrueOp, NewFalseOp);
8978 Instruction *NewSel =
8979 SelectInst::Create(CondVal, NewTrueOp,
8980 NewFalseOp, SI.getName() + ".p");
8982 NewSel = InsertNewInstBefore(NewSel, SI);
8983 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8988 // See if we can fold the select into one of our operands.
8989 if (SI.getType()->isInteger()) {
8990 // See the comment above GetSelectFoldableOperands for a description of the
8991 // transformation we are doing here.
8992 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8993 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8994 !isa<Constant>(FalseVal))
8995 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8996 unsigned OpToFold = 0;
8997 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8999 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9004 Constant *C = GetSelectFoldableConstant(TVI);
9005 Instruction *NewSel =
9006 SelectInst::Create(SI.getCondition(),
9007 TVI->getOperand(2-OpToFold), C);
9008 InsertNewInstBefore(NewSel, SI);
9009 NewSel->takeName(TVI);
9010 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9011 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9013 assert(0 && "Unknown instruction!!");
9018 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
9019 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9020 !isa<Constant>(TrueVal))
9021 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9022 unsigned OpToFold = 0;
9023 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9025 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9030 Constant *C = GetSelectFoldableConstant(FVI);
9031 Instruction *NewSel =
9032 SelectInst::Create(SI.getCondition(), C,
9033 FVI->getOperand(2-OpToFold));
9034 InsertNewInstBefore(NewSel, SI);
9035 NewSel->takeName(FVI);
9036 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9037 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9039 assert(0 && "Unknown instruction!!");
9044 if (BinaryOperator::isNot(CondVal)) {
9045 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9046 SI.setOperand(1, FalseVal);
9047 SI.setOperand(2, TrueVal);
9054 /// EnforceKnownAlignment - If the specified pointer points to an object that
9055 /// we control, modify the object's alignment to PrefAlign. This isn't
9056 /// often possible though. If alignment is important, a more reliable approach
9057 /// is to simply align all global variables and allocation instructions to
9058 /// their preferred alignment from the beginning.
9060 static unsigned EnforceKnownAlignment(Value *V,
9061 unsigned Align, unsigned PrefAlign) {
9063 User *U = dyn_cast<User>(V);
9064 if (!U) return Align;
9066 switch (getOpcode(U)) {
9068 case Instruction::BitCast:
9069 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9070 case Instruction::GetElementPtr: {
9071 // If all indexes are zero, it is just the alignment of the base pointer.
9072 bool AllZeroOperands = true;
9073 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9074 if (!isa<Constant>(*i) ||
9075 !cast<Constant>(*i)->isNullValue()) {
9076 AllZeroOperands = false;
9080 if (AllZeroOperands) {
9081 // Treat this like a bitcast.
9082 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9088 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9089 // If there is a large requested alignment and we can, bump up the alignment
9091 if (!GV->isDeclaration()) {
9092 GV->setAlignment(PrefAlign);
9095 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9096 // If there is a requested alignment and if this is an alloca, round up. We
9097 // don't do this for malloc, because some systems can't respect the request.
9098 if (isa<AllocaInst>(AI)) {
9099 AI->setAlignment(PrefAlign);
9107 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9108 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9109 /// and it is more than the alignment of the ultimate object, see if we can
9110 /// increase the alignment of the ultimate object, making this check succeed.
9111 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9112 unsigned PrefAlign) {
9113 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9114 sizeof(PrefAlign) * CHAR_BIT;
9115 APInt Mask = APInt::getAllOnesValue(BitWidth);
9116 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9117 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9118 unsigned TrailZ = KnownZero.countTrailingOnes();
9119 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9121 if (PrefAlign > Align)
9122 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9124 // We don't need to make any adjustment.
9128 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9129 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9130 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9131 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9132 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
9134 if (CopyAlign < MinAlign) {
9135 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
9139 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9141 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9142 if (MemOpLength == 0) return 0;
9144 // Source and destination pointer types are always "i8*" for intrinsic. See
9145 // if the size is something we can handle with a single primitive load/store.
9146 // A single load+store correctly handles overlapping memory in the memmove
9148 unsigned Size = MemOpLength->getZExtValue();
9149 if (Size == 0) return MI; // Delete this mem transfer.
9151 if (Size > 8 || (Size&(Size-1)))
9152 return 0; // If not 1/2/4/8 bytes, exit.
9154 // Use an integer load+store unless we can find something better.
9155 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
9157 // Memcpy forces the use of i8* for the source and destination. That means
9158 // that if you're using memcpy to move one double around, you'll get a cast
9159 // from double* to i8*. We'd much rather use a double load+store rather than
9160 // an i64 load+store, here because this improves the odds that the source or
9161 // dest address will be promotable. See if we can find a better type than the
9162 // integer datatype.
9163 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9164 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9165 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9166 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9167 // down through these levels if so.
9168 while (!SrcETy->isSingleValueType()) {
9169 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9170 if (STy->getNumElements() == 1)
9171 SrcETy = STy->getElementType(0);
9174 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9175 if (ATy->getNumElements() == 1)
9176 SrcETy = ATy->getElementType();
9183 if (SrcETy->isSingleValueType())
9184 NewPtrTy = PointerType::getUnqual(SrcETy);
9189 // If the memcpy/memmove provides better alignment info than we can
9191 SrcAlign = std::max(SrcAlign, CopyAlign);
9192 DstAlign = std::max(DstAlign, CopyAlign);
9194 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9195 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9196 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9197 InsertNewInstBefore(L, *MI);
9198 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9200 // Set the size of the copy to 0, it will be deleted on the next iteration.
9201 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9205 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9206 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9207 if (MI->getAlignment()->getZExtValue() < Alignment) {
9208 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9212 // Extract the length and alignment and fill if they are constant.
9213 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9214 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9215 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9217 uint64_t Len = LenC->getZExtValue();
9218 Alignment = MI->getAlignment()->getZExtValue();
9220 // If the length is zero, this is a no-op
9221 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9223 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9224 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9225 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9227 Value *Dest = MI->getDest();
9228 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9230 // Alignment 0 is identity for alignment 1 for memset, but not store.
9231 if (Alignment == 0) Alignment = 1;
9233 // Extract the fill value and store.
9234 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9235 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9238 // Set the size of the copy to 0, it will be deleted on the next iteration.
9239 MI->setLength(Constant::getNullValue(LenC->getType()));
9247 /// visitCallInst - CallInst simplification. This mostly only handles folding
9248 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9249 /// the heavy lifting.
9251 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9252 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9253 if (!II) return visitCallSite(&CI);
9255 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9257 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9258 bool Changed = false;
9260 // memmove/cpy/set of zero bytes is a noop.
9261 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9262 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9264 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9265 if (CI->getZExtValue() == 1) {
9266 // Replace the instruction with just byte operations. We would
9267 // transform other cases to loads/stores, but we don't know if
9268 // alignment is sufficient.
9272 // If we have a memmove and the source operation is a constant global,
9273 // then the source and dest pointers can't alias, so we can change this
9274 // into a call to memcpy.
9275 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9276 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9277 if (GVSrc->isConstant()) {
9278 Module *M = CI.getParent()->getParent()->getParent();
9279 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9281 Tys[0] = CI.getOperand(3)->getType();
9283 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9287 // memmove(x,x,size) -> noop.
9288 if (MMI->getSource() == MMI->getDest())
9289 return EraseInstFromFunction(CI);
9292 // If we can determine a pointer alignment that is bigger than currently
9293 // set, update the alignment.
9294 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
9295 if (Instruction *I = SimplifyMemTransfer(MI))
9297 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9298 if (Instruction *I = SimplifyMemSet(MSI))
9302 if (Changed) return II;
9305 switch (II->getIntrinsicID()) {
9307 case Intrinsic::bswap:
9308 // bswap(bswap(x)) -> x
9309 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9310 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9311 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9313 case Intrinsic::ppc_altivec_lvx:
9314 case Intrinsic::ppc_altivec_lvxl:
9315 case Intrinsic::x86_sse_loadu_ps:
9316 case Intrinsic::x86_sse2_loadu_pd:
9317 case Intrinsic::x86_sse2_loadu_dq:
9318 // Turn PPC lvx -> load if the pointer is known aligned.
9319 // Turn X86 loadups -> load if the pointer is known aligned.
9320 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9321 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9322 PointerType::getUnqual(II->getType()),
9324 return new LoadInst(Ptr);
9327 case Intrinsic::ppc_altivec_stvx:
9328 case Intrinsic::ppc_altivec_stvxl:
9329 // Turn stvx -> store if the pointer is known aligned.
9330 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9331 const Type *OpPtrTy =
9332 PointerType::getUnqual(II->getOperand(1)->getType());
9333 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9334 return new StoreInst(II->getOperand(1), Ptr);
9337 case Intrinsic::x86_sse_storeu_ps:
9338 case Intrinsic::x86_sse2_storeu_pd:
9339 case Intrinsic::x86_sse2_storeu_dq:
9340 // Turn X86 storeu -> store if the pointer is known aligned.
9341 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9342 const Type *OpPtrTy =
9343 PointerType::getUnqual(II->getOperand(2)->getType());
9344 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9345 return new StoreInst(II->getOperand(2), Ptr);
9349 case Intrinsic::x86_sse_cvttss2si: {
9350 // These intrinsics only demands the 0th element of its input vector. If
9351 // we can simplify the input based on that, do so now.
9353 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
9355 II->setOperand(1, V);
9361 case Intrinsic::ppc_altivec_vperm:
9362 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9363 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9364 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9366 // Check that all of the elements are integer constants or undefs.
9367 bool AllEltsOk = true;
9368 for (unsigned i = 0; i != 16; ++i) {
9369 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9370 !isa<UndefValue>(Mask->getOperand(i))) {
9377 // Cast the input vectors to byte vectors.
9378 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9379 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9380 Value *Result = UndefValue::get(Op0->getType());
9382 // Only extract each element once.
9383 Value *ExtractedElts[32];
9384 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9386 for (unsigned i = 0; i != 16; ++i) {
9387 if (isa<UndefValue>(Mask->getOperand(i)))
9389 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9390 Idx &= 31; // Match the hardware behavior.
9392 if (ExtractedElts[Idx] == 0) {
9394 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9395 InsertNewInstBefore(Elt, CI);
9396 ExtractedElts[Idx] = Elt;
9399 // Insert this value into the result vector.
9400 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9402 InsertNewInstBefore(cast<Instruction>(Result), CI);
9404 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9409 case Intrinsic::stackrestore: {
9410 // If the save is right next to the restore, remove the restore. This can
9411 // happen when variable allocas are DCE'd.
9412 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9413 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9414 BasicBlock::iterator BI = SS;
9416 return EraseInstFromFunction(CI);
9420 // Scan down this block to see if there is another stack restore in the
9421 // same block without an intervening call/alloca.
9422 BasicBlock::iterator BI = II;
9423 TerminatorInst *TI = II->getParent()->getTerminator();
9424 bool CannotRemove = false;
9425 for (++BI; &*BI != TI; ++BI) {
9426 if (isa<AllocaInst>(BI)) {
9427 CannotRemove = true;
9430 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9431 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9432 // If there is a stackrestore below this one, remove this one.
9433 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9434 return EraseInstFromFunction(CI);
9435 // Otherwise, ignore the intrinsic.
9437 // If we found a non-intrinsic call, we can't remove the stack
9439 CannotRemove = true;
9445 // If the stack restore is in a return/unwind block and if there are no
9446 // allocas or calls between the restore and the return, nuke the restore.
9447 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9448 return EraseInstFromFunction(CI);
9453 return visitCallSite(II);
9456 // InvokeInst simplification
9458 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9459 return visitCallSite(&II);
9462 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
9463 /// passed through the varargs area, we can eliminate the use of the cast.
9464 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9465 const CastInst * const CI,
9466 const TargetData * const TD,
9468 if (!CI->isLosslessCast())
9471 // The size of ByVal arguments is derived from the type, so we
9472 // can't change to a type with a different size. If the size were
9473 // passed explicitly we could avoid this check.
9474 if (!CS.paramHasAttr(ix, Attribute::ByVal))
9478 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9479 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9480 if (!SrcTy->isSized() || !DstTy->isSized())
9482 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
9487 // visitCallSite - Improvements for call and invoke instructions.
9489 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9490 bool Changed = false;
9492 // If the callee is a constexpr cast of a function, attempt to move the cast
9493 // to the arguments of the call/invoke.
9494 if (transformConstExprCastCall(CS)) return 0;
9496 Value *Callee = CS.getCalledValue();
9498 if (Function *CalleeF = dyn_cast<Function>(Callee))
9499 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9500 Instruction *OldCall = CS.getInstruction();
9501 // If the call and callee calling conventions don't match, this call must
9502 // be unreachable, as the call is undefined.
9503 new StoreInst(ConstantInt::getTrue(),
9504 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9506 if (!OldCall->use_empty())
9507 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9508 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9509 return EraseInstFromFunction(*OldCall);
9513 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9514 // This instruction is not reachable, just remove it. We insert a store to
9515 // undef so that we know that this code is not reachable, despite the fact
9516 // that we can't modify the CFG here.
9517 new StoreInst(ConstantInt::getTrue(),
9518 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9519 CS.getInstruction());
9521 if (!CS.getInstruction()->use_empty())
9522 CS.getInstruction()->
9523 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9525 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9526 // Don't break the CFG, insert a dummy cond branch.
9527 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9528 ConstantInt::getTrue(), II);
9530 return EraseInstFromFunction(*CS.getInstruction());
9533 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9534 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9535 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9536 return transformCallThroughTrampoline(CS);
9538 const PointerType *PTy = cast<PointerType>(Callee->getType());
9539 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9540 if (FTy->isVarArg()) {
9541 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9542 // See if we can optimize any arguments passed through the varargs area of
9544 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9545 E = CS.arg_end(); I != E; ++I, ++ix) {
9546 CastInst *CI = dyn_cast<CastInst>(*I);
9547 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9548 *I = CI->getOperand(0);
9554 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9555 // Inline asm calls cannot throw - mark them 'nounwind'.
9556 CS.setDoesNotThrow();
9560 return Changed ? CS.getInstruction() : 0;
9563 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9564 // attempt to move the cast to the arguments of the call/invoke.
9566 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9567 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9568 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9569 if (CE->getOpcode() != Instruction::BitCast ||
9570 !isa<Function>(CE->getOperand(0)))
9572 Function *Callee = cast<Function>(CE->getOperand(0));
9573 Instruction *Caller = CS.getInstruction();
9574 const AttrListPtr &CallerPAL = CS.getAttributes();
9576 // Okay, this is a cast from a function to a different type. Unless doing so
9577 // would cause a type conversion of one of our arguments, change this call to
9578 // be a direct call with arguments casted to the appropriate types.
9580 const FunctionType *FT = Callee->getFunctionType();
9581 const Type *OldRetTy = Caller->getType();
9582 const Type *NewRetTy = FT->getReturnType();
9584 if (isa<StructType>(NewRetTy))
9585 return false; // TODO: Handle multiple return values.
9587 // Check to see if we are changing the return type...
9588 if (OldRetTy != NewRetTy) {
9589 if (Callee->isDeclaration() &&
9590 // Conversion is ok if changing from one pointer type to another or from
9591 // a pointer to an integer of the same size.
9592 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
9593 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
9594 return false; // Cannot transform this return value.
9596 if (!Caller->use_empty() &&
9597 // void -> non-void is handled specially
9598 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
9599 return false; // Cannot transform this return value.
9601 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9602 Attributes RAttrs = CallerPAL.getRetAttributes();
9603 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
9604 return false; // Attribute not compatible with transformed value.
9607 // If the callsite is an invoke instruction, and the return value is used by
9608 // a PHI node in a successor, we cannot change the return type of the call
9609 // because there is no place to put the cast instruction (without breaking
9610 // the critical edge). Bail out in this case.
9611 if (!Caller->use_empty())
9612 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9613 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9615 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9616 if (PN->getParent() == II->getNormalDest() ||
9617 PN->getParent() == II->getUnwindDest())
9621 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9622 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9624 CallSite::arg_iterator AI = CS.arg_begin();
9625 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9626 const Type *ParamTy = FT->getParamType(i);
9627 const Type *ActTy = (*AI)->getType();
9629 if (!CastInst::isCastable(ActTy, ParamTy))
9630 return false; // Cannot transform this parameter value.
9632 if (CallerPAL.getParamAttributes(i + 1)
9633 & Attribute::typeIncompatible(ParamTy))
9634 return false; // Attribute not compatible with transformed value.
9636 // Converting from one pointer type to another or between a pointer and an
9637 // integer of the same size is safe even if we do not have a body.
9638 bool isConvertible = ActTy == ParamTy ||
9639 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9640 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
9641 if (Callee->isDeclaration() && !isConvertible) return false;
9644 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9645 Callee->isDeclaration())
9646 return false; // Do not delete arguments unless we have a function body.
9648 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9649 !CallerPAL.isEmpty())
9650 // In this case we have more arguments than the new function type, but we
9651 // won't be dropping them. Check that these extra arguments have attributes
9652 // that are compatible with being a vararg call argument.
9653 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9654 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
9656 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
9657 if (PAttrs & Attribute::VarArgsIncompatible)
9661 // Okay, we decided that this is a safe thing to do: go ahead and start
9662 // inserting cast instructions as necessary...
9663 std::vector<Value*> Args;
9664 Args.reserve(NumActualArgs);
9665 SmallVector<AttributeWithIndex, 8> attrVec;
9666 attrVec.reserve(NumCommonArgs);
9668 // Get any return attributes.
9669 Attributes RAttrs = CallerPAL.getRetAttributes();
9671 // If the return value is not being used, the type may not be compatible
9672 // with the existing attributes. Wipe out any problematic attributes.
9673 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
9675 // Add the new return attributes.
9677 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
9679 AI = CS.arg_begin();
9680 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9681 const Type *ParamTy = FT->getParamType(i);
9682 if ((*AI)->getType() == ParamTy) {
9683 Args.push_back(*AI);
9685 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9686 false, ParamTy, false);
9687 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
9688 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9691 // Add any parameter attributes.
9692 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9693 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9696 // If the function takes more arguments than the call was taking, add them
9698 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9699 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9701 // If we are removing arguments to the function, emit an obnoxious warning...
9702 if (FT->getNumParams() < NumActualArgs) {
9703 if (!FT->isVarArg()) {
9704 cerr << "WARNING: While resolving call to function '"
9705 << Callee->getName() << "' arguments were dropped!\n";
9707 // Add all of the arguments in their promoted form to the arg list...
9708 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9709 const Type *PTy = getPromotedType((*AI)->getType());
9710 if (PTy != (*AI)->getType()) {
9711 // Must promote to pass through va_arg area!
9712 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9714 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9715 InsertNewInstBefore(Cast, *Caller);
9716 Args.push_back(Cast);
9718 Args.push_back(*AI);
9721 // Add any parameter attributes.
9722 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
9723 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
9728 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
9729 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9731 if (NewRetTy == Type::VoidTy)
9732 Caller->setName(""); // Void type should not have a name.
9734 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
9737 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9738 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9739 Args.begin(), Args.end(),
9740 Caller->getName(), Caller);
9741 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9742 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
9744 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9745 Caller->getName(), Caller);
9746 CallInst *CI = cast<CallInst>(Caller);
9747 if (CI->isTailCall())
9748 cast<CallInst>(NC)->setTailCall();
9749 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9750 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
9753 // Insert a cast of the return type as necessary.
9755 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9756 if (NV->getType() != Type::VoidTy) {
9757 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
9759 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9761 // If this is an invoke instruction, we should insert it after the first
9762 // non-phi, instruction in the normal successor block.
9763 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9764 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9765 InsertNewInstBefore(NC, *I);
9767 // Otherwise, it's a call, just insert cast right after the call instr
9768 InsertNewInstBefore(NC, *Caller);
9770 AddUsersToWorkList(*Caller);
9772 NV = UndefValue::get(Caller->getType());
9776 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9777 Caller->replaceAllUsesWith(NV);
9778 Caller->eraseFromParent();
9779 RemoveFromWorkList(Caller);
9783 // transformCallThroughTrampoline - Turn a call to a function created by the
9784 // init_trampoline intrinsic into a direct call to the underlying function.
9786 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9787 Value *Callee = CS.getCalledValue();
9788 const PointerType *PTy = cast<PointerType>(Callee->getType());
9789 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9790 const AttrListPtr &Attrs = CS.getAttributes();
9792 // If the call already has the 'nest' attribute somewhere then give up -
9793 // otherwise 'nest' would occur twice after splicing in the chain.
9794 if (Attrs.hasAttrSomewhere(Attribute::Nest))
9797 IntrinsicInst *Tramp =
9798 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9800 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9801 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9802 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9804 const AttrListPtr &NestAttrs = NestF->getAttributes();
9805 if (!NestAttrs.isEmpty()) {
9806 unsigned NestIdx = 1;
9807 const Type *NestTy = 0;
9808 Attributes NestAttr = Attribute::None;
9810 // Look for a parameter marked with the 'nest' attribute.
9811 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9812 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9813 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
9814 // Record the parameter type and any other attributes.
9816 NestAttr = NestAttrs.getParamAttributes(NestIdx);
9821 Instruction *Caller = CS.getInstruction();
9822 std::vector<Value*> NewArgs;
9823 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9825 SmallVector<AttributeWithIndex, 8> NewAttrs;
9826 NewAttrs.reserve(Attrs.getNumSlots() + 1);
9828 // Insert the nest argument into the call argument list, which may
9829 // mean appending it. Likewise for attributes.
9831 // Add any result attributes.
9832 if (Attributes Attr = Attrs.getRetAttributes())
9833 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
9837 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9839 if (Idx == NestIdx) {
9840 // Add the chain argument and attributes.
9841 Value *NestVal = Tramp->getOperand(3);
9842 if (NestVal->getType() != NestTy)
9843 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9844 NewArgs.push_back(NestVal);
9845 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
9851 // Add the original argument and attributes.
9852 NewArgs.push_back(*I);
9853 if (Attributes Attr = Attrs.getParamAttributes(Idx))
9855 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9861 // Add any function attributes.
9862 if (Attributes Attr = Attrs.getFnAttributes())
9863 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
9865 // The trampoline may have been bitcast to a bogus type (FTy).
9866 // Handle this by synthesizing a new function type, equal to FTy
9867 // with the chain parameter inserted.
9869 std::vector<const Type*> NewTypes;
9870 NewTypes.reserve(FTy->getNumParams()+1);
9872 // Insert the chain's type into the list of parameter types, which may
9873 // mean appending it.
9876 FunctionType::param_iterator I = FTy->param_begin(),
9877 E = FTy->param_end();
9881 // Add the chain's type.
9882 NewTypes.push_back(NestTy);
9887 // Add the original type.
9888 NewTypes.push_back(*I);
9894 // Replace the trampoline call with a direct call. Let the generic
9895 // code sort out any function type mismatches.
9896 FunctionType *NewFTy =
9897 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9898 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9899 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9900 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
9902 Instruction *NewCaller;
9903 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9904 NewCaller = InvokeInst::Create(NewCallee,
9905 II->getNormalDest(), II->getUnwindDest(),
9906 NewArgs.begin(), NewArgs.end(),
9907 Caller->getName(), Caller);
9908 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9909 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
9911 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9912 Caller->getName(), Caller);
9913 if (cast<CallInst>(Caller)->isTailCall())
9914 cast<CallInst>(NewCaller)->setTailCall();
9915 cast<CallInst>(NewCaller)->
9916 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9917 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
9919 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9920 Caller->replaceAllUsesWith(NewCaller);
9921 Caller->eraseFromParent();
9922 RemoveFromWorkList(Caller);
9927 // Replace the trampoline call with a direct call. Since there is no 'nest'
9928 // parameter, there is no need to adjust the argument list. Let the generic
9929 // code sort out any function type mismatches.
9930 Constant *NewCallee =
9931 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9932 CS.setCalledFunction(NewCallee);
9933 return CS.getInstruction();
9936 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9937 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9938 /// and a single binop.
9939 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9940 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9941 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
9942 unsigned Opc = FirstInst->getOpcode();
9943 Value *LHSVal = FirstInst->getOperand(0);
9944 Value *RHSVal = FirstInst->getOperand(1);
9946 const Type *LHSType = LHSVal->getType();
9947 const Type *RHSType = RHSVal->getType();
9949 // Scan to see if all operands are the same opcode, all have one use, and all
9950 // kill their operands (i.e. the operands have one use).
9951 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
9952 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9953 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9954 // Verify type of the LHS matches so we don't fold cmp's of different
9955 // types or GEP's with different index types.
9956 I->getOperand(0)->getType() != LHSType ||
9957 I->getOperand(1)->getType() != RHSType)
9960 // If they are CmpInst instructions, check their predicates
9961 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9962 if (cast<CmpInst>(I)->getPredicate() !=
9963 cast<CmpInst>(FirstInst)->getPredicate())
9966 // Keep track of which operand needs a phi node.
9967 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9968 if (I->getOperand(1) != RHSVal) RHSVal = 0;
9971 // Otherwise, this is safe to transform!
9973 Value *InLHS = FirstInst->getOperand(0);
9974 Value *InRHS = FirstInst->getOperand(1);
9975 PHINode *NewLHS = 0, *NewRHS = 0;
9977 NewLHS = PHINode::Create(LHSType,
9978 FirstInst->getOperand(0)->getName() + ".pn");
9979 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9980 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9981 InsertNewInstBefore(NewLHS, PN);
9986 NewRHS = PHINode::Create(RHSType,
9987 FirstInst->getOperand(1)->getName() + ".pn");
9988 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9989 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9990 InsertNewInstBefore(NewRHS, PN);
9994 // Add all operands to the new PHIs.
9995 if (NewLHS || NewRHS) {
9996 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9997 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
9999 Value *NewInLHS = InInst->getOperand(0);
10000 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10003 Value *NewInRHS = InInst->getOperand(1);
10004 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10009 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10010 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10011 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10012 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10016 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10017 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10019 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10020 FirstInst->op_end());
10022 // Scan to see if all operands are the same opcode, all have one use, and all
10023 // kill their operands (i.e. the operands have one use).
10024 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10025 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10026 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10027 GEP->getNumOperands() != FirstInst->getNumOperands())
10030 // Compare the operand lists.
10031 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10032 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10035 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10036 // if one of the PHIs has a constant for the index. The index may be
10037 // substantially cheaper to compute for the constants, so making it a
10038 // variable index could pessimize the path. This also handles the case
10039 // for struct indices, which must always be constant.
10040 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10041 isa<ConstantInt>(GEP->getOperand(op)))
10044 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10046 FixedOperands[op] = 0; // Needs a PHI.
10050 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10051 // that is variable.
10052 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10054 bool HasAnyPHIs = false;
10055 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10056 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10057 Value *FirstOp = FirstInst->getOperand(i);
10058 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10059 FirstOp->getName()+".pn");
10060 InsertNewInstBefore(NewPN, PN);
10062 NewPN->reserveOperandSpace(e);
10063 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10064 OperandPhis[i] = NewPN;
10065 FixedOperands[i] = NewPN;
10070 // Add all operands to the new PHIs.
10072 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10073 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10074 BasicBlock *InBB = PN.getIncomingBlock(i);
10076 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10077 if (PHINode *OpPhi = OperandPhis[op])
10078 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10082 Value *Base = FixedOperands[0];
10083 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10084 FixedOperands.end());
10088 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
10089 /// of the block that defines it. This means that it must be obvious the value
10090 /// of the load is not changed from the point of the load to the end of the
10091 /// block it is in.
10093 /// Finally, it is safe, but not profitable, to sink a load targetting a
10094 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
10096 static bool isSafeToSinkLoad(LoadInst *L) {
10097 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10099 for (++BBI; BBI != E; ++BBI)
10100 if (BBI->mayWriteToMemory())
10103 // Check for non-address taken alloca. If not address-taken already, it isn't
10104 // profitable to do this xform.
10105 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10106 bool isAddressTaken = false;
10107 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10109 if (isa<LoadInst>(UI)) continue;
10110 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10111 // If storing TO the alloca, then the address isn't taken.
10112 if (SI->getOperand(1) == AI) continue;
10114 isAddressTaken = true;
10118 if (!isAddressTaken)
10126 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10127 // operator and they all are only used by the PHI, PHI together their
10128 // inputs, and do the operation once, to the result of the PHI.
10129 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10130 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10132 // Scan the instruction, looking for input operations that can be folded away.
10133 // If all input operands to the phi are the same instruction (e.g. a cast from
10134 // the same type or "+42") we can pull the operation through the PHI, reducing
10135 // code size and simplifying code.
10136 Constant *ConstantOp = 0;
10137 const Type *CastSrcTy = 0;
10138 bool isVolatile = false;
10139 if (isa<CastInst>(FirstInst)) {
10140 CastSrcTy = FirstInst->getOperand(0)->getType();
10141 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10142 // Can fold binop, compare or shift here if the RHS is a constant,
10143 // otherwise call FoldPHIArgBinOpIntoPHI.
10144 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10145 if (ConstantOp == 0)
10146 return FoldPHIArgBinOpIntoPHI(PN);
10147 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10148 isVolatile = LI->isVolatile();
10149 // We can't sink the load if the loaded value could be modified between the
10150 // load and the PHI.
10151 if (LI->getParent() != PN.getIncomingBlock(0) ||
10152 !isSafeToSinkLoad(LI))
10155 // If the PHI is of volatile loads and the load block has multiple
10156 // successors, sinking it would remove a load of the volatile value from
10157 // the path through the other successor.
10159 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10162 } else if (isa<GetElementPtrInst>(FirstInst)) {
10163 return FoldPHIArgGEPIntoPHI(PN);
10165 return 0; // Cannot fold this operation.
10168 // Check to see if all arguments are the same operation.
10169 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10170 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10171 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10172 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10175 if (I->getOperand(0)->getType() != CastSrcTy)
10176 return 0; // Cast operation must match.
10177 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10178 // We can't sink the load if the loaded value could be modified between
10179 // the load and the PHI.
10180 if (LI->isVolatile() != isVolatile ||
10181 LI->getParent() != PN.getIncomingBlock(i) ||
10182 !isSafeToSinkLoad(LI))
10185 // If the PHI is of volatile loads and the load block has multiple
10186 // successors, sinking it would remove a load of the volatile value from
10187 // the path through the other successor.
10189 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10193 } else if (I->getOperand(1) != ConstantOp) {
10198 // Okay, they are all the same operation. Create a new PHI node of the
10199 // correct type, and PHI together all of the LHS's of the instructions.
10200 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10201 PN.getName()+".in");
10202 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10204 Value *InVal = FirstInst->getOperand(0);
10205 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10207 // Add all operands to the new PHI.
10208 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10209 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10210 if (NewInVal != InVal)
10212 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10217 // The new PHI unions all of the same values together. This is really
10218 // common, so we handle it intelligently here for compile-time speed.
10222 InsertNewInstBefore(NewPN, PN);
10226 // Insert and return the new operation.
10227 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10228 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10229 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10230 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10231 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10232 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10233 PhiVal, ConstantOp);
10234 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10236 // If this was a volatile load that we are merging, make sure to loop through
10237 // and mark all the input loads as non-volatile. If we don't do this, we will
10238 // insert a new volatile load and the old ones will not be deletable.
10240 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10241 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10243 return new LoadInst(PhiVal, "", isVolatile);
10246 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10248 static bool DeadPHICycle(PHINode *PN,
10249 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10250 if (PN->use_empty()) return true;
10251 if (!PN->hasOneUse()) return false;
10253 // Remember this node, and if we find the cycle, return.
10254 if (!PotentiallyDeadPHIs.insert(PN))
10257 // Don't scan crazily complex things.
10258 if (PotentiallyDeadPHIs.size() == 16)
10261 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10262 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10267 /// PHIsEqualValue - Return true if this phi node is always equal to
10268 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10269 /// z = some value; x = phi (y, z); y = phi (x, z)
10270 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10271 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10272 // See if we already saw this PHI node.
10273 if (!ValueEqualPHIs.insert(PN))
10276 // Don't scan crazily complex things.
10277 if (ValueEqualPHIs.size() == 16)
10280 // Scan the operands to see if they are either phi nodes or are equal to
10282 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10283 Value *Op = PN->getIncomingValue(i);
10284 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10285 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10287 } else if (Op != NonPhiInVal)
10295 // PHINode simplification
10297 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10298 // If LCSSA is around, don't mess with Phi nodes
10299 if (MustPreserveLCSSA) return 0;
10301 if (Value *V = PN.hasConstantValue())
10302 return ReplaceInstUsesWith(PN, V);
10304 // If all PHI operands are the same operation, pull them through the PHI,
10305 // reducing code size.
10306 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10307 isa<Instruction>(PN.getIncomingValue(1)) &&
10308 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10309 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10310 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10311 // than themselves more than once.
10312 PN.getIncomingValue(0)->hasOneUse())
10313 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10316 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10317 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10318 // PHI)... break the cycle.
10319 if (PN.hasOneUse()) {
10320 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10321 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10322 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10323 PotentiallyDeadPHIs.insert(&PN);
10324 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10325 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10328 // If this phi has a single use, and if that use just computes a value for
10329 // the next iteration of a loop, delete the phi. This occurs with unused
10330 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10331 // common case here is good because the only other things that catch this
10332 // are induction variable analysis (sometimes) and ADCE, which is only run
10334 if (PHIUser->hasOneUse() &&
10335 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10336 PHIUser->use_back() == &PN) {
10337 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10341 // We sometimes end up with phi cycles that non-obviously end up being the
10342 // same value, for example:
10343 // z = some value; x = phi (y, z); y = phi (x, z)
10344 // where the phi nodes don't necessarily need to be in the same block. Do a
10345 // quick check to see if the PHI node only contains a single non-phi value, if
10346 // so, scan to see if the phi cycle is actually equal to that value.
10348 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10349 // Scan for the first non-phi operand.
10350 while (InValNo != NumOperandVals &&
10351 isa<PHINode>(PN.getIncomingValue(InValNo)))
10354 if (InValNo != NumOperandVals) {
10355 Value *NonPhiInVal = PN.getOperand(InValNo);
10357 // Scan the rest of the operands to see if there are any conflicts, if so
10358 // there is no need to recursively scan other phis.
10359 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10360 Value *OpVal = PN.getIncomingValue(InValNo);
10361 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10365 // If we scanned over all operands, then we have one unique value plus
10366 // phi values. Scan PHI nodes to see if they all merge in each other or
10368 if (InValNo == NumOperandVals) {
10369 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10370 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10371 return ReplaceInstUsesWith(PN, NonPhiInVal);
10378 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10379 Instruction *InsertPoint,
10380 InstCombiner *IC) {
10381 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10382 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10383 // We must cast correctly to the pointer type. Ensure that we
10384 // sign extend the integer value if it is smaller as this is
10385 // used for address computation.
10386 Instruction::CastOps opcode =
10387 (VTySize < PtrSize ? Instruction::SExt :
10388 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10389 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10393 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10394 Value *PtrOp = GEP.getOperand(0);
10395 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
10396 // If so, eliminate the noop.
10397 if (GEP.getNumOperands() == 1)
10398 return ReplaceInstUsesWith(GEP, PtrOp);
10400 if (isa<UndefValue>(GEP.getOperand(0)))
10401 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10403 bool HasZeroPointerIndex = false;
10404 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10405 HasZeroPointerIndex = C->isNullValue();
10407 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10408 return ReplaceInstUsesWith(GEP, PtrOp);
10410 // Eliminate unneeded casts for indices.
10411 bool MadeChange = false;
10413 gep_type_iterator GTI = gep_type_begin(GEP);
10414 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10415 i != e; ++i, ++GTI) {
10416 if (isa<SequentialType>(*GTI)) {
10417 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
10418 if (CI->getOpcode() == Instruction::ZExt ||
10419 CI->getOpcode() == Instruction::SExt) {
10420 const Type *SrcTy = CI->getOperand(0)->getType();
10421 // We can eliminate a cast from i32 to i64 iff the target
10422 // is a 32-bit pointer target.
10423 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10425 *i = CI->getOperand(0);
10429 // If we are using a wider index than needed for this platform, shrink it
10430 // to what we need. If narrower, sign-extend it to what we need.
10431 // If the incoming value needs a cast instruction,
10432 // insert it. This explicit cast can make subsequent optimizations more
10435 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
10436 if (Constant *C = dyn_cast<Constant>(Op)) {
10437 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
10440 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10445 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10446 if (Constant *C = dyn_cast<Constant>(Op)) {
10447 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10450 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10458 if (MadeChange) return &GEP;
10460 // If this GEP instruction doesn't move the pointer, and if the input operand
10461 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
10462 // real input to the dest type.
10463 if (GEP.hasAllZeroIndices()) {
10464 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
10465 // If the bitcast is of an allocation, and the allocation will be
10466 // converted to match the type of the cast, don't touch this.
10467 if (isa<AllocationInst>(BCI->getOperand(0))) {
10468 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10469 if (Instruction *I = visitBitCast(*BCI)) {
10472 BCI->getParent()->getInstList().insert(BCI, I);
10473 ReplaceInstUsesWith(*BCI, I);
10478 return new BitCastInst(BCI->getOperand(0), GEP.getType());
10482 // Combine Indices - If the source pointer to this getelementptr instruction
10483 // is a getelementptr instruction, combine the indices of the two
10484 // getelementptr instructions into a single instruction.
10486 SmallVector<Value*, 8> SrcGEPOperands;
10487 if (User *Src = dyn_castGetElementPtr(PtrOp))
10488 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10490 if (!SrcGEPOperands.empty()) {
10491 // Note that if our source is a gep chain itself that we wait for that
10492 // chain to be resolved before we perform this transformation. This
10493 // avoids us creating a TON of code in some cases.
10495 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10496 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10497 return 0; // Wait until our source is folded to completion.
10499 SmallVector<Value*, 8> Indices;
10501 // Find out whether the last index in the source GEP is a sequential idx.
10502 bool EndsWithSequential = false;
10503 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10504 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10505 EndsWithSequential = !isa<StructType>(*I);
10507 // Can we combine the two pointer arithmetics offsets?
10508 if (EndsWithSequential) {
10509 // Replace: gep (gep %P, long B), long A, ...
10510 // With: T = long A+B; gep %P, T, ...
10512 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10513 if (SO1 == Constant::getNullValue(SO1->getType())) {
10515 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10518 // If they aren't the same type, convert both to an integer of the
10519 // target's pointer size.
10520 if (SO1->getType() != GO1->getType()) {
10521 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10522 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10523 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10524 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10526 unsigned PS = TD->getPointerSizeInBits();
10527 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
10528 // Convert GO1 to SO1's type.
10529 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10531 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
10532 // Convert SO1 to GO1's type.
10533 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10535 const Type *PT = TD->getIntPtrType();
10536 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10537 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10541 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10542 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10544 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10545 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10549 // Recycle the GEP we already have if possible.
10550 if (SrcGEPOperands.size() == 2) {
10551 GEP.setOperand(0, SrcGEPOperands[0]);
10552 GEP.setOperand(1, Sum);
10555 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10556 SrcGEPOperands.end()-1);
10557 Indices.push_back(Sum);
10558 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10560 } else if (isa<Constant>(*GEP.idx_begin()) &&
10561 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10562 SrcGEPOperands.size() != 1) {
10563 // Otherwise we can do the fold if the first index of the GEP is a zero
10564 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10565 SrcGEPOperands.end());
10566 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10569 if (!Indices.empty())
10570 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10571 Indices.end(), GEP.getName());
10573 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10574 // GEP of global variable. If all of the indices for this GEP are
10575 // constants, we can promote this to a constexpr instead of an instruction.
10577 // Scan for nonconstants...
10578 SmallVector<Constant*, 8> Indices;
10579 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10580 for (; I != E && isa<Constant>(*I); ++I)
10581 Indices.push_back(cast<Constant>(*I));
10583 if (I == E) { // If they are all constants...
10584 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10585 &Indices[0],Indices.size());
10587 // Replace all uses of the GEP with the new constexpr...
10588 return ReplaceInstUsesWith(GEP, CE);
10590 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
10591 if (!isa<PointerType>(X->getType())) {
10592 // Not interesting. Source pointer must be a cast from pointer.
10593 } else if (HasZeroPointerIndex) {
10594 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10595 // into : GEP [10 x i8]* X, i32 0, ...
10597 // This occurs when the program declares an array extern like "int X[];"
10599 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10600 const PointerType *XTy = cast<PointerType>(X->getType());
10601 if (const ArrayType *XATy =
10602 dyn_cast<ArrayType>(XTy->getElementType()))
10603 if (const ArrayType *CATy =
10604 dyn_cast<ArrayType>(CPTy->getElementType()))
10605 if (CATy->getElementType() == XATy->getElementType()) {
10606 // At this point, we know that the cast source type is a pointer
10607 // to an array of the same type as the destination pointer
10608 // array. Because the array type is never stepped over (there
10609 // is a leading zero) we can fold the cast into this GEP.
10610 GEP.setOperand(0, X);
10613 } else if (GEP.getNumOperands() == 2) {
10614 // Transform things like:
10615 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10616 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10617 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10618 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10619 if (isa<ArrayType>(SrcElTy) &&
10620 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10621 TD->getABITypeSize(ResElTy)) {
10623 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10624 Idx[1] = GEP.getOperand(1);
10625 Value *V = InsertNewInstBefore(
10626 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
10627 // V and GEP are both pointer types --> BitCast
10628 return new BitCastInst(V, GEP.getType());
10631 // Transform things like:
10632 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10633 // (where tmp = 8*tmp2) into:
10634 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10636 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
10637 uint64_t ArrayEltSize =
10638 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
10640 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10641 // allow either a mul, shift, or constant here.
10643 ConstantInt *Scale = 0;
10644 if (ArrayEltSize == 1) {
10645 NewIdx = GEP.getOperand(1);
10646 Scale = ConstantInt::get(NewIdx->getType(), 1);
10647 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10648 NewIdx = ConstantInt::get(CI->getType(), 1);
10650 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10651 if (Inst->getOpcode() == Instruction::Shl &&
10652 isa<ConstantInt>(Inst->getOperand(1))) {
10653 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10654 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10655 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10656 NewIdx = Inst->getOperand(0);
10657 } else if (Inst->getOpcode() == Instruction::Mul &&
10658 isa<ConstantInt>(Inst->getOperand(1))) {
10659 Scale = cast<ConstantInt>(Inst->getOperand(1));
10660 NewIdx = Inst->getOperand(0);
10664 // If the index will be to exactly the right offset with the scale taken
10665 // out, perform the transformation. Note, we don't know whether Scale is
10666 // signed or not. We'll use unsigned version of division/modulo
10667 // operation after making sure Scale doesn't have the sign bit set.
10668 if (Scale && Scale->getSExtValue() >= 0LL &&
10669 Scale->getZExtValue() % ArrayEltSize == 0) {
10670 Scale = ConstantInt::get(Scale->getType(),
10671 Scale->getZExtValue() / ArrayEltSize);
10672 if (Scale->getZExtValue() != 1) {
10673 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
10675 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
10676 NewIdx = InsertNewInstBefore(Sc, GEP);
10679 // Insert the new GEP instruction.
10681 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10683 Instruction *NewGEP =
10684 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
10685 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10686 // The NewGEP must be pointer typed, so must the old one -> BitCast
10687 return new BitCastInst(NewGEP, GEP.getType());
10696 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10697 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
10698 if (AI.isArrayAllocation()) { // Check C != 1
10699 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10700 const Type *NewTy =
10701 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10702 AllocationInst *New = 0;
10704 // Create and insert the replacement instruction...
10705 if (isa<MallocInst>(AI))
10706 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10708 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10709 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10712 InsertNewInstBefore(New, AI);
10714 // Scan to the end of the allocation instructions, to skip over a block of
10715 // allocas if possible...
10717 BasicBlock::iterator It = New;
10718 while (isa<AllocationInst>(*It)) ++It;
10720 // Now that I is pointing to the first non-allocation-inst in the block,
10721 // insert our getelementptr instruction...
10723 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
10727 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10728 New->getName()+".sub", It);
10730 // Now make everything use the getelementptr instead of the original
10732 return ReplaceInstUsesWith(AI, V);
10733 } else if (isa<UndefValue>(AI.getArraySize())) {
10734 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10738 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10739 // Note that we only do this for alloca's, because malloc should allocate and
10740 // return a unique pointer, even for a zero byte allocation.
10741 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
10742 TD->getABITypeSize(AI.getAllocatedType()) == 0)
10743 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10748 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10749 Value *Op = FI.getOperand(0);
10751 // free undef -> unreachable.
10752 if (isa<UndefValue>(Op)) {
10753 // Insert a new store to null because we cannot modify the CFG here.
10754 new StoreInst(ConstantInt::getTrue(),
10755 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
10756 return EraseInstFromFunction(FI);
10759 // If we have 'free null' delete the instruction. This can happen in stl code
10760 // when lots of inlining happens.
10761 if (isa<ConstantPointerNull>(Op))
10762 return EraseInstFromFunction(FI);
10764 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10765 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10766 FI.setOperand(0, CI->getOperand(0));
10770 // Change free (gep X, 0,0,0,0) into free(X)
10771 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10772 if (GEPI->hasAllZeroIndices()) {
10773 AddToWorkList(GEPI);
10774 FI.setOperand(0, GEPI->getOperand(0));
10779 // Change free(malloc) into nothing, if the malloc has a single use.
10780 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10781 if (MI->hasOneUse()) {
10782 EraseInstFromFunction(FI);
10783 return EraseInstFromFunction(*MI);
10790 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10791 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10792 const TargetData *TD) {
10793 User *CI = cast<User>(LI.getOperand(0));
10794 Value *CastOp = CI->getOperand(0);
10796 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10797 // Instead of loading constant c string, use corresponding integer value
10798 // directly if string length is small enough.
10800 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
10801 unsigned len = Str.length();
10802 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10803 unsigned numBits = Ty->getPrimitiveSizeInBits();
10804 // Replace LI with immediate integer store.
10805 if ((numBits >> 3) == len + 1) {
10806 APInt StrVal(numBits, 0);
10807 APInt SingleChar(numBits, 0);
10808 if (TD->isLittleEndian()) {
10809 for (signed i = len-1; i >= 0; i--) {
10810 SingleChar = (uint64_t) Str[i];
10811 StrVal = (StrVal << 8) | SingleChar;
10814 for (unsigned i = 0; i < len; i++) {
10815 SingleChar = (uint64_t) Str[i];
10816 StrVal = (StrVal << 8) | SingleChar;
10818 // Append NULL at the end.
10820 StrVal = (StrVal << 8) | SingleChar;
10822 Value *NL = ConstantInt::get(StrVal);
10823 return IC.ReplaceInstUsesWith(LI, NL);
10828 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10829 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10830 const Type *SrcPTy = SrcTy->getElementType();
10832 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
10833 isa<VectorType>(DestPTy)) {
10834 // If the source is an array, the code below will not succeed. Check to
10835 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10837 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10838 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10839 if (ASrcTy->getNumElements() != 0) {
10841 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10842 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10843 SrcTy = cast<PointerType>(CastOp->getType());
10844 SrcPTy = SrcTy->getElementType();
10847 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
10848 isa<VectorType>(SrcPTy)) &&
10849 // Do not allow turning this into a load of an integer, which is then
10850 // casted to a pointer, this pessimizes pointer analysis a lot.
10851 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10852 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10853 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10855 // Okay, we are casting from one integer or pointer type to another of
10856 // the same size. Instead of casting the pointer before the load, cast
10857 // the result of the loaded value.
10858 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10860 LI.isVolatile()),LI);
10861 // Now cast the result of the load.
10862 return new BitCastInst(NewLoad, LI.getType());
10869 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10870 /// from this value cannot trap. If it is not obviously safe to load from the
10871 /// specified pointer, we do a quick local scan of the basic block containing
10872 /// ScanFrom, to determine if the address is already accessed.
10873 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10874 // If it is an alloca it is always safe to load from.
10875 if (isa<AllocaInst>(V)) return true;
10877 // If it is a global variable it is mostly safe to load from.
10878 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10879 // Don't try to evaluate aliases. External weak GV can be null.
10880 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10882 // Otherwise, be a little bit agressive by scanning the local block where we
10883 // want to check to see if the pointer is already being loaded or stored
10884 // from/to. If so, the previous load or store would have already trapped,
10885 // so there is no harm doing an extra load (also, CSE will later eliminate
10886 // the load entirely).
10887 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10892 // If we see a free or a call (which might do a free) the pointer could be
10894 if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10897 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10898 if (LI->getOperand(0) == V) return true;
10899 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
10900 if (SI->getOperand(1) == V) return true;
10907 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10908 Value *Op = LI.getOperand(0);
10910 // Attempt to improve the alignment.
10911 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10913 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10914 LI.getAlignment()))
10915 LI.setAlignment(KnownAlign);
10917 // load (cast X) --> cast (load X) iff safe
10918 if (isa<CastInst>(Op))
10919 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10922 // None of the following transforms are legal for volatile loads.
10923 if (LI.isVolatile()) return 0;
10925 // Do really simple store-to-load forwarding and load CSE, to catch cases
10926 // where there are several consequtive memory accesses to the same location,
10927 // separated by a few arithmetic operations.
10928 BasicBlock::iterator BBI = &LI;
10929 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
10930 return ReplaceInstUsesWith(LI, AvailableVal);
10932 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10933 const Value *GEPI0 = GEPI->getOperand(0);
10934 // TODO: Consider a target hook for valid address spaces for this xform.
10935 if (isa<ConstantPointerNull>(GEPI0) &&
10936 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10937 // Insert a new store to null instruction before the load to indicate
10938 // that this code is not reachable. We do this instead of inserting
10939 // an unreachable instruction directly because we cannot modify the
10941 new StoreInst(UndefValue::get(LI.getType()),
10942 Constant::getNullValue(Op->getType()), &LI);
10943 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10947 if (Constant *C = dyn_cast<Constant>(Op)) {
10948 // load null/undef -> undef
10949 // TODO: Consider a target hook for valid address spaces for this xform.
10950 if (isa<UndefValue>(C) || (C->isNullValue() &&
10951 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10952 // Insert a new store to null instruction before the load to indicate that
10953 // this code is not reachable. We do this instead of inserting an
10954 // unreachable instruction directly because we cannot modify the CFG.
10955 new StoreInst(UndefValue::get(LI.getType()),
10956 Constant::getNullValue(Op->getType()), &LI);
10957 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10960 // Instcombine load (constant global) into the value loaded.
10961 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10962 if (GV->isConstant() && !GV->isDeclaration())
10963 return ReplaceInstUsesWith(LI, GV->getInitializer());
10965 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10966 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10967 if (CE->getOpcode() == Instruction::GetElementPtr) {
10968 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10969 if (GV->isConstant() && !GV->isDeclaration())
10971 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10972 return ReplaceInstUsesWith(LI, V);
10973 if (CE->getOperand(0)->isNullValue()) {
10974 // Insert a new store to null instruction before the load to indicate
10975 // that this code is not reachable. We do this instead of inserting
10976 // an unreachable instruction directly because we cannot modify the
10978 new StoreInst(UndefValue::get(LI.getType()),
10979 Constant::getNullValue(Op->getType()), &LI);
10980 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10983 } else if (CE->isCast()) {
10984 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10990 // If this load comes from anywhere in a constant global, and if the global
10991 // is all undef or zero, we know what it loads.
10992 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
10993 if (GV->isConstant() && GV->hasInitializer()) {
10994 if (GV->getInitializer()->isNullValue())
10995 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10996 else if (isa<UndefValue>(GV->getInitializer()))
10997 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11001 if (Op->hasOneUse()) {
11002 // Change select and PHI nodes to select values instead of addresses: this
11003 // helps alias analysis out a lot, allows many others simplifications, and
11004 // exposes redundancy in the code.
11006 // Note that we cannot do the transformation unless we know that the
11007 // introduced loads cannot trap! Something like this is valid as long as
11008 // the condition is always false: load (select bool %C, int* null, int* %G),
11009 // but it would not be valid if we transformed it to load from null
11010 // unconditionally.
11012 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11013 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11014 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11015 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11016 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11017 SI->getOperand(1)->getName()+".val"), LI);
11018 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11019 SI->getOperand(2)->getName()+".val"), LI);
11020 return SelectInst::Create(SI->getCondition(), V1, V2);
11023 // load (select (cond, null, P)) -> load P
11024 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11025 if (C->isNullValue()) {
11026 LI.setOperand(0, SI->getOperand(2));
11030 // load (select (cond, P, null)) -> load P
11031 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11032 if (C->isNullValue()) {
11033 LI.setOperand(0, SI->getOperand(1));
11041 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11043 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11044 User *CI = cast<User>(SI.getOperand(1));
11045 Value *CastOp = CI->getOperand(0);
11047 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11048 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11049 const Type *SrcPTy = SrcTy->getElementType();
11051 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
11052 // If the source is an array, the code below will not succeed. Check to
11053 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11055 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11056 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11057 if (ASrcTy->getNumElements() != 0) {
11059 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11060 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11061 SrcTy = cast<PointerType>(CastOp->getType());
11062 SrcPTy = SrcTy->getElementType();
11065 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
11066 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11067 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11069 // Okay, we are casting from one integer or pointer type to another of
11070 // the same size. Instead of casting the pointer before
11071 // the store, cast the value to be stored.
11073 Value *SIOp0 = SI.getOperand(0);
11074 Instruction::CastOps opcode = Instruction::BitCast;
11075 const Type* CastSrcTy = SIOp0->getType();
11076 const Type* CastDstTy = SrcPTy;
11077 if (isa<PointerType>(CastDstTy)) {
11078 if (CastSrcTy->isInteger())
11079 opcode = Instruction::IntToPtr;
11080 } else if (isa<IntegerType>(CastDstTy)) {
11081 if (isa<PointerType>(SIOp0->getType()))
11082 opcode = Instruction::PtrToInt;
11084 if (Constant *C = dyn_cast<Constant>(SIOp0))
11085 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11087 NewCast = IC.InsertNewInstBefore(
11088 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11090 return new StoreInst(NewCast, CastOp);
11097 /// equivalentAddressValues - Test if A and B will obviously have the same
11098 /// value. This includes recognizing that %t0 and %t1 will have the same
11099 /// value in code like this:
11100 /// %t0 = getelementptr @a, 0, 3
11101 /// store i32 0, i32* %t0
11102 /// %t1 = getelementptr @a, 0, 3
11103 /// %t2 = load i32* %t1
11105 static bool equivalentAddressValues(Value *A, Value *B) {
11106 // Test if the values are trivially equivalent.
11107 if (A == B) return true;
11109 // Test if the values come form identical arithmetic instructions.
11110 if (isa<BinaryOperator>(A) ||
11111 isa<CastInst>(A) ||
11113 isa<GetElementPtrInst>(A))
11114 if (Instruction *BI = dyn_cast<Instruction>(B))
11115 if (cast<Instruction>(A)->isIdenticalTo(BI))
11118 // Otherwise they may not be equivalent.
11122 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11123 Value *Val = SI.getOperand(0);
11124 Value *Ptr = SI.getOperand(1);
11126 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11127 EraseInstFromFunction(SI);
11132 // If the RHS is an alloca with a single use, zapify the store, making the
11134 if (Ptr->hasOneUse() && !SI.isVolatile()) {
11135 if (isa<AllocaInst>(Ptr)) {
11136 EraseInstFromFunction(SI);
11141 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
11142 if (isa<AllocaInst>(GEP->getOperand(0)) &&
11143 GEP->getOperand(0)->hasOneUse()) {
11144 EraseInstFromFunction(SI);
11150 // Attempt to improve the alignment.
11151 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
11153 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11154 SI.getAlignment()))
11155 SI.setAlignment(KnownAlign);
11157 // Do really simple DSE, to catch cases where there are several consequtive
11158 // stores to the same location, separated by a few arithmetic operations. This
11159 // situation often occurs with bitfield accesses.
11160 BasicBlock::iterator BBI = &SI;
11161 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11165 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11166 // Prev store isn't volatile, and stores to the same location?
11167 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11168 SI.getOperand(1))) {
11171 EraseInstFromFunction(*PrevSI);
11177 // If this is a load, we have to stop. However, if the loaded value is from
11178 // the pointer we're loading and is producing the pointer we're storing,
11179 // then *this* store is dead (X = load P; store X -> P).
11180 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11181 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11182 !SI.isVolatile()) {
11183 EraseInstFromFunction(SI);
11187 // Otherwise, this is a load from some other location. Stores before it
11188 // may not be dead.
11192 // Don't skip over loads or things that can modify memory.
11193 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11198 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11200 // store X, null -> turns into 'unreachable' in SimplifyCFG
11201 if (isa<ConstantPointerNull>(Ptr)) {
11202 if (!isa<UndefValue>(Val)) {
11203 SI.setOperand(0, UndefValue::get(Val->getType()));
11204 if (Instruction *U = dyn_cast<Instruction>(Val))
11205 AddToWorkList(U); // Dropped a use.
11208 return 0; // Do not modify these!
11211 // store undef, Ptr -> noop
11212 if (isa<UndefValue>(Val)) {
11213 EraseInstFromFunction(SI);
11218 // If the pointer destination is a cast, see if we can fold the cast into the
11220 if (isa<CastInst>(Ptr))
11221 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11223 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11225 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11229 // If this store is the last instruction in the basic block, and if the block
11230 // ends with an unconditional branch, try to move it to the successor block.
11232 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11233 if (BI->isUnconditional())
11234 if (SimplifyStoreAtEndOfBlock(SI))
11235 return 0; // xform done!
11240 /// SimplifyStoreAtEndOfBlock - Turn things like:
11241 /// if () { *P = v1; } else { *P = v2 }
11242 /// into a phi node with a store in the successor.
11244 /// Simplify things like:
11245 /// *P = v1; if () { *P = v2; }
11246 /// into a phi node with a store in the successor.
11248 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11249 BasicBlock *StoreBB = SI.getParent();
11251 // Check to see if the successor block has exactly two incoming edges. If
11252 // so, see if the other predecessor contains a store to the same location.
11253 // if so, insert a PHI node (if needed) and move the stores down.
11254 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11256 // Determine whether Dest has exactly two predecessors and, if so, compute
11257 // the other predecessor.
11258 pred_iterator PI = pred_begin(DestBB);
11259 BasicBlock *OtherBB = 0;
11260 if (*PI != StoreBB)
11263 if (PI == pred_end(DestBB))
11266 if (*PI != StoreBB) {
11271 if (++PI != pred_end(DestBB))
11274 // Bail out if all the relevant blocks aren't distinct (this can happen,
11275 // for example, if SI is in an infinite loop)
11276 if (StoreBB == DestBB || OtherBB == DestBB)
11279 // Verify that the other block ends in a branch and is not otherwise empty.
11280 BasicBlock::iterator BBI = OtherBB->getTerminator();
11281 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11282 if (!OtherBr || BBI == OtherBB->begin())
11285 // If the other block ends in an unconditional branch, check for the 'if then
11286 // else' case. there is an instruction before the branch.
11287 StoreInst *OtherStore = 0;
11288 if (OtherBr->isUnconditional()) {
11289 // If this isn't a store, or isn't a store to the same location, bail out.
11291 OtherStore = dyn_cast<StoreInst>(BBI);
11292 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11295 // Otherwise, the other block ended with a conditional branch. If one of the
11296 // destinations is StoreBB, then we have the if/then case.
11297 if (OtherBr->getSuccessor(0) != StoreBB &&
11298 OtherBr->getSuccessor(1) != StoreBB)
11301 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11302 // if/then triangle. See if there is a store to the same ptr as SI that
11303 // lives in OtherBB.
11305 // Check to see if we find the matching store.
11306 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11307 if (OtherStore->getOperand(1) != SI.getOperand(1))
11311 // If we find something that may be using or overwriting the stored
11312 // value, or if we run out of instructions, we can't do the xform.
11313 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11314 BBI == OtherBB->begin())
11318 // In order to eliminate the store in OtherBr, we have to
11319 // make sure nothing reads or overwrites the stored value in
11321 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11322 // FIXME: This should really be AA driven.
11323 if (I->mayReadFromMemory() || I->mayWriteToMemory())
11328 // Insert a PHI node now if we need it.
11329 Value *MergedVal = OtherStore->getOperand(0);
11330 if (MergedVal != SI.getOperand(0)) {
11331 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11332 PN->reserveOperandSpace(2);
11333 PN->addIncoming(SI.getOperand(0), SI.getParent());
11334 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11335 MergedVal = InsertNewInstBefore(PN, DestBB->front());
11338 // Advance to a place where it is safe to insert the new store and
11340 BBI = DestBB->getFirstNonPHI();
11341 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11342 OtherStore->isVolatile()), *BBI);
11344 // Nuke the old stores.
11345 EraseInstFromFunction(SI);
11346 EraseInstFromFunction(*OtherStore);
11352 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11353 // Change br (not X), label True, label False to: br X, label False, True
11355 BasicBlock *TrueDest;
11356 BasicBlock *FalseDest;
11357 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11358 !isa<Constant>(X)) {
11359 // Swap Destinations and condition...
11360 BI.setCondition(X);
11361 BI.setSuccessor(0, FalseDest);
11362 BI.setSuccessor(1, TrueDest);
11366 // Cannonicalize fcmp_one -> fcmp_oeq
11367 FCmpInst::Predicate FPred; Value *Y;
11368 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11369 TrueDest, FalseDest)))
11370 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11371 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11372 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11373 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11374 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11375 NewSCC->takeName(I);
11376 // Swap Destinations and condition...
11377 BI.setCondition(NewSCC);
11378 BI.setSuccessor(0, FalseDest);
11379 BI.setSuccessor(1, TrueDest);
11380 RemoveFromWorkList(I);
11381 I->eraseFromParent();
11382 AddToWorkList(NewSCC);
11386 // Cannonicalize icmp_ne -> icmp_eq
11387 ICmpInst::Predicate IPred;
11388 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11389 TrueDest, FalseDest)))
11390 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11391 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11392 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11393 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11394 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11395 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11396 NewSCC->takeName(I);
11397 // Swap Destinations and condition...
11398 BI.setCondition(NewSCC);
11399 BI.setSuccessor(0, FalseDest);
11400 BI.setSuccessor(1, TrueDest);
11401 RemoveFromWorkList(I);
11402 I->eraseFromParent();;
11403 AddToWorkList(NewSCC);
11410 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11411 Value *Cond = SI.getCondition();
11412 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11413 if (I->getOpcode() == Instruction::Add)
11414 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11415 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11416 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11417 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11419 SI.setOperand(0, I->getOperand(0));
11427 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11428 Value *Agg = EV.getAggregateOperand();
11430 if (!EV.hasIndices())
11431 return ReplaceInstUsesWith(EV, Agg);
11433 if (Constant *C = dyn_cast<Constant>(Agg)) {
11434 if (isa<UndefValue>(C))
11435 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11437 if (isa<ConstantAggregateZero>(C))
11438 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11440 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11441 // Extract the element indexed by the first index out of the constant
11442 Value *V = C->getOperand(*EV.idx_begin());
11443 if (EV.getNumIndices() > 1)
11444 // Extract the remaining indices out of the constant indexed by the
11446 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11448 return ReplaceInstUsesWith(EV, V);
11450 return 0; // Can't handle other constants
11452 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11453 // We're extracting from an insertvalue instruction, compare the indices
11454 const unsigned *exti, *exte, *insi, *inse;
11455 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11456 exte = EV.idx_end(), inse = IV->idx_end();
11457 exti != exte && insi != inse;
11459 if (*insi != *exti)
11460 // The insert and extract both reference distinctly different elements.
11461 // This means the extract is not influenced by the insert, and we can
11462 // replace the aggregate operand of the extract with the aggregate
11463 // operand of the insert. i.e., replace
11464 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11465 // %E = extractvalue { i32, { i32 } } %I, 0
11467 // %E = extractvalue { i32, { i32 } } %A, 0
11468 return ExtractValueInst::Create(IV->getAggregateOperand(),
11469 EV.idx_begin(), EV.idx_end());
11471 if (exti == exte && insi == inse)
11472 // Both iterators are at the end: Index lists are identical. Replace
11473 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11474 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11476 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11477 if (exti == exte) {
11478 // The extract list is a prefix of the insert list. i.e. replace
11479 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11480 // %E = extractvalue { i32, { i32 } } %I, 1
11482 // %X = extractvalue { i32, { i32 } } %A, 1
11483 // %E = insertvalue { i32 } %X, i32 42, 0
11484 // by switching the order of the insert and extract (though the
11485 // insertvalue should be left in, since it may have other uses).
11486 Value *NewEV = InsertNewInstBefore(
11487 ExtractValueInst::Create(IV->getAggregateOperand(),
11488 EV.idx_begin(), EV.idx_end()),
11490 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11494 // The insert list is a prefix of the extract list
11495 // We can simply remove the common indices from the extract and make it
11496 // operate on the inserted value instead of the insertvalue result.
11498 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11499 // %E = extractvalue { i32, { i32 } } %I, 1, 0
11501 // %E extractvalue { i32 } { i32 42 }, 0
11502 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
11505 // Can't simplify extracts from other values. Note that nested extracts are
11506 // already simplified implicitely by the above (extract ( extract (insert) )
11507 // will be translated into extract ( insert ( extract ) ) first and then just
11508 // the value inserted, if appropriate).
11512 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11513 /// is to leave as a vector operation.
11514 static bool CheapToScalarize(Value *V, bool isConstant) {
11515 if (isa<ConstantAggregateZero>(V))
11517 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11518 if (isConstant) return true;
11519 // If all elts are the same, we can extract.
11520 Constant *Op0 = C->getOperand(0);
11521 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11522 if (C->getOperand(i) != Op0)
11526 Instruction *I = dyn_cast<Instruction>(V);
11527 if (!I) return false;
11529 // Insert element gets simplified to the inserted element or is deleted if
11530 // this is constant idx extract element and its a constant idx insertelt.
11531 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11532 isa<ConstantInt>(I->getOperand(2)))
11534 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11536 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11537 if (BO->hasOneUse() &&
11538 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11539 CheapToScalarize(BO->getOperand(1), isConstant)))
11541 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11542 if (CI->hasOneUse() &&
11543 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11544 CheapToScalarize(CI->getOperand(1), isConstant)))
11550 /// Read and decode a shufflevector mask.
11552 /// It turns undef elements into values that are larger than the number of
11553 /// elements in the input.
11554 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11555 unsigned NElts = SVI->getType()->getNumElements();
11556 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11557 return std::vector<unsigned>(NElts, 0);
11558 if (isa<UndefValue>(SVI->getOperand(2)))
11559 return std::vector<unsigned>(NElts, 2*NElts);
11561 std::vector<unsigned> Result;
11562 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
11563 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11564 if (isa<UndefValue>(*i))
11565 Result.push_back(NElts*2); // undef -> 8
11567 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
11571 /// FindScalarElement - Given a vector and an element number, see if the scalar
11572 /// value is already around as a register, for example if it were inserted then
11573 /// extracted from the vector.
11574 static Value *FindScalarElement(Value *V, unsigned EltNo) {
11575 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11576 const VectorType *PTy = cast<VectorType>(V->getType());
11577 unsigned Width = PTy->getNumElements();
11578 if (EltNo >= Width) // Out of range access.
11579 return UndefValue::get(PTy->getElementType());
11581 if (isa<UndefValue>(V))
11582 return UndefValue::get(PTy->getElementType());
11583 else if (isa<ConstantAggregateZero>(V))
11584 return Constant::getNullValue(PTy->getElementType());
11585 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11586 return CP->getOperand(EltNo);
11587 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11588 // If this is an insert to a variable element, we don't know what it is.
11589 if (!isa<ConstantInt>(III->getOperand(2)))
11591 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11593 // If this is an insert to the element we are looking for, return the
11595 if (EltNo == IIElt)
11596 return III->getOperand(1);
11598 // Otherwise, the insertelement doesn't modify the value, recurse on its
11600 return FindScalarElement(III->getOperand(0), EltNo);
11601 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
11602 unsigned LHSWidth =
11603 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11604 unsigned InEl = getShuffleMask(SVI)[EltNo];
11605 if (InEl < LHSWidth)
11606 return FindScalarElement(SVI->getOperand(0), InEl);
11607 else if (InEl < LHSWidth*2)
11608 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
11610 return UndefValue::get(PTy->getElementType());
11613 // Otherwise, we don't know.
11617 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
11618 // If vector val is undef, replace extract with scalar undef.
11619 if (isa<UndefValue>(EI.getOperand(0)))
11620 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11622 // If vector val is constant 0, replace extract with scalar 0.
11623 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11624 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11626 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
11627 // If vector val is constant with all elements the same, replace EI with
11628 // that element. When the elements are not identical, we cannot replace yet
11629 // (we do that below, but only when the index is constant).
11630 Constant *op0 = C->getOperand(0);
11631 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11632 if (C->getOperand(i) != op0) {
11637 return ReplaceInstUsesWith(EI, op0);
11640 // If extracting a specified index from the vector, see if we can recursively
11641 // find a previously computed scalar that was inserted into the vector.
11642 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11643 unsigned IndexVal = IdxC->getZExtValue();
11644 unsigned VectorWidth =
11645 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11647 // If this is extracting an invalid index, turn this into undef, to avoid
11648 // crashing the code below.
11649 if (IndexVal >= VectorWidth)
11650 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11652 // This instruction only demands the single element from the input vector.
11653 // If the input vector has a single use, simplify it based on this use
11655 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11656 uint64_t UndefElts;
11657 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11660 EI.setOperand(0, V);
11665 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11666 return ReplaceInstUsesWith(EI, Elt);
11668 // If the this extractelement is directly using a bitcast from a vector of
11669 // the same number of elements, see if we can find the source element from
11670 // it. In this case, we will end up needing to bitcast the scalars.
11671 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11672 if (const VectorType *VT =
11673 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11674 if (VT->getNumElements() == VectorWidth)
11675 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11676 return new BitCastInst(Elt, EI.getType());
11680 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11681 if (I->hasOneUse()) {
11682 // Push extractelement into predecessor operation if legal and
11683 // profitable to do so
11684 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11685 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11686 if (CheapToScalarize(BO, isConstantElt)) {
11687 ExtractElementInst *newEI0 =
11688 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11689 EI.getName()+".lhs");
11690 ExtractElementInst *newEI1 =
11691 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11692 EI.getName()+".rhs");
11693 InsertNewInstBefore(newEI0, EI);
11694 InsertNewInstBefore(newEI1, EI);
11695 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
11697 } else if (isa<LoadInst>(I)) {
11699 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
11700 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11701 PointerType::get(EI.getType(), AS),EI);
11702 GetElementPtrInst *GEP =
11703 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
11704 InsertNewInstBefore(GEP, EI);
11705 return new LoadInst(GEP);
11708 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11709 // Extracting the inserted element?
11710 if (IE->getOperand(2) == EI.getOperand(1))
11711 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11712 // If the inserted and extracted elements are constants, they must not
11713 // be the same value, extract from the pre-inserted value instead.
11714 if (isa<Constant>(IE->getOperand(2)) &&
11715 isa<Constant>(EI.getOperand(1))) {
11716 AddUsesToWorkList(EI);
11717 EI.setOperand(0, IE->getOperand(0));
11720 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11721 // If this is extracting an element from a shufflevector, figure out where
11722 // it came from and extract from the appropriate input element instead.
11723 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11724 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11726 unsigned LHSWidth =
11727 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11729 if (SrcIdx < LHSWidth)
11730 Src = SVI->getOperand(0);
11731 else if (SrcIdx < LHSWidth*2) {
11732 SrcIdx -= LHSWidth;
11733 Src = SVI->getOperand(1);
11735 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11737 return new ExtractElementInst(Src, SrcIdx);
11744 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11745 /// elements from either LHS or RHS, return the shuffle mask and true.
11746 /// Otherwise, return false.
11747 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11748 std::vector<Constant*> &Mask) {
11749 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11750 "Invalid CollectSingleShuffleElements");
11751 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11753 if (isa<UndefValue>(V)) {
11754 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11756 } else if (V == LHS) {
11757 for (unsigned i = 0; i != NumElts; ++i)
11758 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11760 } else if (V == RHS) {
11761 for (unsigned i = 0; i != NumElts; ++i)
11762 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11764 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11765 // If this is an insert of an extract from some other vector, include it.
11766 Value *VecOp = IEI->getOperand(0);
11767 Value *ScalarOp = IEI->getOperand(1);
11768 Value *IdxOp = IEI->getOperand(2);
11770 if (!isa<ConstantInt>(IdxOp))
11772 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11774 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11775 // Okay, we can handle this if the vector we are insertinting into is
11776 // transitively ok.
11777 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11778 // If so, update the mask to reflect the inserted undef.
11779 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11782 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11783 if (isa<ConstantInt>(EI->getOperand(1)) &&
11784 EI->getOperand(0)->getType() == V->getType()) {
11785 unsigned ExtractedIdx =
11786 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11788 // This must be extracting from either LHS or RHS.
11789 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11790 // Okay, we can handle this if the vector we are insertinting into is
11791 // transitively ok.
11792 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11793 // If so, update the mask to reflect the inserted value.
11794 if (EI->getOperand(0) == LHS) {
11795 Mask[InsertedIdx % NumElts] =
11796 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11798 assert(EI->getOperand(0) == RHS);
11799 Mask[InsertedIdx % NumElts] =
11800 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11809 // TODO: Handle shufflevector here!
11814 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11815 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11816 /// that computes V and the LHS value of the shuffle.
11817 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11819 assert(isa<VectorType>(V->getType()) &&
11820 (RHS == 0 || V->getType() == RHS->getType()) &&
11821 "Invalid shuffle!");
11822 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11824 if (isa<UndefValue>(V)) {
11825 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11827 } else if (isa<ConstantAggregateZero>(V)) {
11828 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11830 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11831 // If this is an insert of an extract from some other vector, include it.
11832 Value *VecOp = IEI->getOperand(0);
11833 Value *ScalarOp = IEI->getOperand(1);
11834 Value *IdxOp = IEI->getOperand(2);
11836 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11837 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11838 EI->getOperand(0)->getType() == V->getType()) {
11839 unsigned ExtractedIdx =
11840 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11841 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11843 // Either the extracted from or inserted into vector must be RHSVec,
11844 // otherwise we'd end up with a shuffle of three inputs.
11845 if (EI->getOperand(0) == RHS || RHS == 0) {
11846 RHS = EI->getOperand(0);
11847 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11848 Mask[InsertedIdx % NumElts] =
11849 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11853 if (VecOp == RHS) {
11854 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11855 // Everything but the extracted element is replaced with the RHS.
11856 for (unsigned i = 0; i != NumElts; ++i) {
11857 if (i != InsertedIdx)
11858 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11863 // If this insertelement is a chain that comes from exactly these two
11864 // vectors, return the vector and the effective shuffle.
11865 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11866 return EI->getOperand(0);
11871 // TODO: Handle shufflevector here!
11873 // Otherwise, can't do anything fancy. Return an identity vector.
11874 for (unsigned i = 0; i != NumElts; ++i)
11875 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11879 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11880 Value *VecOp = IE.getOperand(0);
11881 Value *ScalarOp = IE.getOperand(1);
11882 Value *IdxOp = IE.getOperand(2);
11884 // Inserting an undef or into an undefined place, remove this.
11885 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11886 ReplaceInstUsesWith(IE, VecOp);
11888 // If the inserted element was extracted from some other vector, and if the
11889 // indexes are constant, try to turn this into a shufflevector operation.
11890 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11891 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11892 EI->getOperand(0)->getType() == IE.getType()) {
11893 unsigned NumVectorElts = IE.getType()->getNumElements();
11894 unsigned ExtractedIdx =
11895 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11896 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11898 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11899 return ReplaceInstUsesWith(IE, VecOp);
11901 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11902 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11904 // If we are extracting a value from a vector, then inserting it right
11905 // back into the same place, just use the input vector.
11906 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11907 return ReplaceInstUsesWith(IE, VecOp);
11909 // We could theoretically do this for ANY input. However, doing so could
11910 // turn chains of insertelement instructions into a chain of shufflevector
11911 // instructions, and right now we do not merge shufflevectors. As such,
11912 // only do this in a situation where it is clear that there is benefit.
11913 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11914 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11915 // the values of VecOp, except then one read from EIOp0.
11916 // Build a new shuffle mask.
11917 std::vector<Constant*> Mask;
11918 if (isa<UndefValue>(VecOp))
11919 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11921 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11922 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11925 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11926 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11927 ConstantVector::get(Mask));
11930 // If this insertelement isn't used by some other insertelement, turn it
11931 // (and any insertelements it points to), into one big shuffle.
11932 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11933 std::vector<Constant*> Mask;
11935 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11936 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11937 // We now have a shuffle of LHS, RHS, Mask.
11938 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11947 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11948 Value *LHS = SVI.getOperand(0);
11949 Value *RHS = SVI.getOperand(1);
11950 std::vector<unsigned> Mask = getShuffleMask(&SVI);
11952 bool MadeChange = false;
11954 // Undefined shuffle mask -> undefined value.
11955 if (isa<UndefValue>(SVI.getOperand(2)))
11956 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11958 uint64_t UndefElts;
11959 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
11961 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
11964 uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth);
11965 if (VWidth <= 64 &&
11966 SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
11967 LHS = SVI.getOperand(0);
11968 RHS = SVI.getOperand(1);
11972 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11973 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11974 if (LHS == RHS || isa<UndefValue>(LHS)) {
11975 if (isa<UndefValue>(LHS) && LHS == RHS) {
11976 // shuffle(undef,undef,mask) -> undef.
11977 return ReplaceInstUsesWith(SVI, LHS);
11980 // Remap any references to RHS to use LHS.
11981 std::vector<Constant*> Elts;
11982 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11983 if (Mask[i] >= 2*e)
11984 Elts.push_back(UndefValue::get(Type::Int32Ty));
11986 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11987 (Mask[i] < e && isa<UndefValue>(LHS))) {
11988 Mask[i] = 2*e; // Turn into undef.
11989 Elts.push_back(UndefValue::get(Type::Int32Ty));
11991 Mask[i] = Mask[i] % e; // Force to LHS.
11992 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11996 SVI.setOperand(0, SVI.getOperand(1));
11997 SVI.setOperand(1, UndefValue::get(RHS->getType()));
11998 SVI.setOperand(2, ConstantVector::get(Elts));
11999 LHS = SVI.getOperand(0);
12000 RHS = SVI.getOperand(1);
12004 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12005 bool isLHSID = true, isRHSID = true;
12007 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12008 if (Mask[i] >= e*2) continue; // Ignore undef values.
12009 // Is this an identity shuffle of the LHS value?
12010 isLHSID &= (Mask[i] == i);
12012 // Is this an identity shuffle of the RHS value?
12013 isRHSID &= (Mask[i]-e == i);
12016 // Eliminate identity shuffles.
12017 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12018 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12020 // If the LHS is a shufflevector itself, see if we can combine it with this
12021 // one without producing an unusual shuffle. Here we are really conservative:
12022 // we are absolutely afraid of producing a shuffle mask not in the input
12023 // program, because the code gen may not be smart enough to turn a merged
12024 // shuffle into two specific shuffles: it may produce worse code. As such,
12025 // we only merge two shuffles if the result is one of the two input shuffle
12026 // masks. In this case, merging the shuffles just removes one instruction,
12027 // which we know is safe. This is good for things like turning:
12028 // (splat(splat)) -> splat.
12029 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12030 if (isa<UndefValue>(RHS)) {
12031 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12033 std::vector<unsigned> NewMask;
12034 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12035 if (Mask[i] >= 2*e)
12036 NewMask.push_back(2*e);
12038 NewMask.push_back(LHSMask[Mask[i]]);
12040 // If the result mask is equal to the src shuffle or this shuffle mask, do
12041 // the replacement.
12042 if (NewMask == LHSMask || NewMask == Mask) {
12043 std::vector<Constant*> Elts;
12044 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12045 if (NewMask[i] >= e*2) {
12046 Elts.push_back(UndefValue::get(Type::Int32Ty));
12048 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12051 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12052 LHSSVI->getOperand(1),
12053 ConstantVector::get(Elts));
12058 return MadeChange ? &SVI : 0;
12064 /// TryToSinkInstruction - Try to move the specified instruction from its
12065 /// current block into the beginning of DestBlock, which can only happen if it's
12066 /// safe to move the instruction past all of the instructions between it and the
12067 /// end of its block.
12068 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12069 assert(I->hasOneUse() && "Invariants didn't hold!");
12071 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12072 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
12075 // Do not sink alloca instructions out of the entry block.
12076 if (isa<AllocaInst>(I) && I->getParent() ==
12077 &DestBlock->getParent()->getEntryBlock())
12080 // We can only sink load instructions if there is nothing between the load and
12081 // the end of block that could change the value.
12082 if (I->mayReadFromMemory()) {
12083 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12085 if (Scan->mayWriteToMemory())
12089 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12091 I->moveBefore(InsertPos);
12097 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12098 /// all reachable code to the worklist.
12100 /// This has a couple of tricks to make the code faster and more powerful. In
12101 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12102 /// them to the worklist (this significantly speeds up instcombine on code where
12103 /// many instructions are dead or constant). Additionally, if we find a branch
12104 /// whose condition is a known constant, we only visit the reachable successors.
12106 static void AddReachableCodeToWorklist(BasicBlock *BB,
12107 SmallPtrSet<BasicBlock*, 64> &Visited,
12109 const TargetData *TD) {
12110 SmallVector<BasicBlock*, 256> Worklist;
12111 Worklist.push_back(BB);
12113 while (!Worklist.empty()) {
12114 BB = Worklist.back();
12115 Worklist.pop_back();
12117 // We have now visited this block! If we've already been here, ignore it.
12118 if (!Visited.insert(BB)) continue;
12120 DbgInfoIntrinsic *DBI_Prev = NULL;
12121 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12122 Instruction *Inst = BBI++;
12124 // DCE instruction if trivially dead.
12125 if (isInstructionTriviallyDead(Inst)) {
12127 DOUT << "IC: DCE: " << *Inst;
12128 Inst->eraseFromParent();
12132 // ConstantProp instruction if trivially constant.
12133 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12134 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12135 Inst->replaceAllUsesWith(C);
12137 Inst->eraseFromParent();
12141 // If there are two consecutive llvm.dbg.stoppoint calls then
12142 // it is likely that the optimizer deleted code in between these
12144 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12147 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12148 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12149 IC.RemoveFromWorkList(DBI_Prev);
12150 DBI_Prev->eraseFromParent();
12152 DBI_Prev = DBI_Next;
12155 IC.AddToWorkList(Inst);
12158 // Recursively visit successors. If this is a branch or switch on a
12159 // constant, only visit the reachable successor.
12160 TerminatorInst *TI = BB->getTerminator();
12161 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12162 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12163 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12164 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12165 Worklist.push_back(ReachableBB);
12168 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12169 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12170 // See if this is an explicit destination.
12171 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12172 if (SI->getCaseValue(i) == Cond) {
12173 BasicBlock *ReachableBB = SI->getSuccessor(i);
12174 Worklist.push_back(ReachableBB);
12178 // Otherwise it is the default destination.
12179 Worklist.push_back(SI->getSuccessor(0));
12184 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12185 Worklist.push_back(TI->getSuccessor(i));
12189 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12190 bool Changed = false;
12191 TD = &getAnalysis<TargetData>();
12193 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12194 << F.getNameStr() << "\n");
12197 // Do a depth-first traversal of the function, populate the worklist with
12198 // the reachable instructions. Ignore blocks that are not reachable. Keep
12199 // track of which blocks we visit.
12200 SmallPtrSet<BasicBlock*, 64> Visited;
12201 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12203 // Do a quick scan over the function. If we find any blocks that are
12204 // unreachable, remove any instructions inside of them. This prevents
12205 // the instcombine code from having to deal with some bad special cases.
12206 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12207 if (!Visited.count(BB)) {
12208 Instruction *Term = BB->getTerminator();
12209 while (Term != BB->begin()) { // Remove instrs bottom-up
12210 BasicBlock::iterator I = Term; --I;
12212 DOUT << "IC: DCE: " << *I;
12215 if (!I->use_empty())
12216 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12217 I->eraseFromParent();
12222 while (!Worklist.empty()) {
12223 Instruction *I = RemoveOneFromWorkList();
12224 if (I == 0) continue; // skip null values.
12226 // Check to see if we can DCE the instruction.
12227 if (isInstructionTriviallyDead(I)) {
12228 // Add operands to the worklist.
12229 if (I->getNumOperands() < 4)
12230 AddUsesToWorkList(*I);
12233 DOUT << "IC: DCE: " << *I;
12235 I->eraseFromParent();
12236 RemoveFromWorkList(I);
12240 // Instruction isn't dead, see if we can constant propagate it.
12241 if (Constant *C = ConstantFoldInstruction(I, TD)) {
12242 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12244 // Add operands to the worklist.
12245 AddUsesToWorkList(*I);
12246 ReplaceInstUsesWith(*I, C);
12249 I->eraseFromParent();
12250 RemoveFromWorkList(I);
12254 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12255 // See if we can constant fold its operands.
12256 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
12257 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
12258 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12264 // See if we can trivially sink this instruction to a successor basic block.
12265 if (I->hasOneUse()) {
12266 BasicBlock *BB = I->getParent();
12267 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12268 if (UserParent != BB) {
12269 bool UserIsSuccessor = false;
12270 // See if the user is one of our successors.
12271 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12272 if (*SI == UserParent) {
12273 UserIsSuccessor = true;
12277 // If the user is one of our immediate successors, and if that successor
12278 // only has us as a predecessors (we'd have to split the critical edge
12279 // otherwise), we can keep going.
12280 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12281 next(pred_begin(UserParent)) == pred_end(UserParent))
12282 // Okay, the CFG is simple enough, try to sink this instruction.
12283 Changed |= TryToSinkInstruction(I, UserParent);
12287 // Now that we have an instruction, try combining it to simplify it...
12291 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12292 if (Instruction *Result = visit(*I)) {
12294 // Should we replace the old instruction with a new one?
12296 DOUT << "IC: Old = " << *I
12297 << " New = " << *Result;
12299 // Everything uses the new instruction now.
12300 I->replaceAllUsesWith(Result);
12302 // Push the new instruction and any users onto the worklist.
12303 AddToWorkList(Result);
12304 AddUsersToWorkList(*Result);
12306 // Move the name to the new instruction first.
12307 Result->takeName(I);
12309 // Insert the new instruction into the basic block...
12310 BasicBlock *InstParent = I->getParent();
12311 BasicBlock::iterator InsertPos = I;
12313 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12314 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12317 InstParent->getInstList().insert(InsertPos, Result);
12319 // Make sure that we reprocess all operands now that we reduced their
12321 AddUsesToWorkList(*I);
12323 // Instructions can end up on the worklist more than once. Make sure
12324 // we do not process an instruction that has been deleted.
12325 RemoveFromWorkList(I);
12327 // Erase the old instruction.
12328 InstParent->getInstList().erase(I);
12331 DOUT << "IC: Mod = " << OrigI
12332 << " New = " << *I;
12335 // If the instruction was modified, it's possible that it is now dead.
12336 // if so, remove it.
12337 if (isInstructionTriviallyDead(I)) {
12338 // Make sure we process all operands now that we are reducing their
12340 AddUsesToWorkList(*I);
12342 // Instructions may end up in the worklist more than once. Erase all
12343 // occurrences of this instruction.
12344 RemoveFromWorkList(I);
12345 I->eraseFromParent();
12348 AddUsersToWorkList(*I);
12355 assert(WorklistMap.empty() && "Worklist empty, but map not?");
12357 // Do an explicit clear, this shrinks the map if needed.
12358 WorklistMap.clear();
12363 bool InstCombiner::runOnFunction(Function &F) {
12364 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12366 bool EverMadeChange = false;
12368 // Iterate while there is work to do.
12369 unsigned Iteration = 0;
12370 while (DoOneIteration(F, Iteration++))
12371 EverMadeChange = true;
12372 return EverMadeChange;
12375 FunctionPass *llvm::createInstructionCombiningPass() {
12376 return new InstCombiner();