1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // InstructionCombining - Combine instructions to form fewer, simple
11 // instructions. This pass does not modify the CFG. This pass is where
12 // algebraic simplification happens.
14 // This pass combines things like:
20 // This is a simple worklist driven algorithm.
22 // This pass guarantees that the following canonicalizations are performed on
24 // 1. If a binary operator has a constant operand, it is moved to the RHS
25 // 2. Bitwise operators with constant operands are always grouped so that
26 // shifts are performed first, then or's, then and's, then xor's.
27 // 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All cmp instructions on boolean values are replaced with logical ops
29 // 5. add X, X is represented as (X*2) => (X << 1)
30 // 6. Multiplies with a power-of-two constant argument are transformed into
34 //===----------------------------------------------------------------------===//
36 #define DEBUG_TYPE "instcombine"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/IntrinsicInst.h"
39 #include "llvm/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Analysis/ConstantFolding.h"
43 #include "llvm/Analysis/ValueTracking.h"
44 #include "llvm/Target/TargetData.h"
45 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/Support/CallSite.h"
48 #include "llvm/Support/ConstantRange.h"
49 #include "llvm/Support/Debug.h"
50 #include "llvm/Support/GetElementPtrTypeIterator.h"
51 #include "llvm/Support/InstVisitor.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Support/PatternMatch.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/ADT/DenseMap.h"
56 #include "llvm/ADT/SmallVector.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/Statistic.h"
59 #include "llvm/ADT/STLExtras.h"
64 using namespace llvm::PatternMatch;
66 STATISTIC(NumCombined , "Number of insts combined");
67 STATISTIC(NumConstProp, "Number of constant folds");
68 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70 STATISTIC(NumSunkInst , "Number of instructions sunk");
73 class VISIBILITY_HIDDEN InstCombiner
74 : public FunctionPass,
75 public InstVisitor<InstCombiner, Instruction*> {
76 // Worklist of all of the instructions that need to be simplified.
77 std::vector<Instruction*> Worklist;
78 DenseMap<Instruction*, unsigned> WorklistMap;
80 bool MustPreserveLCSSA;
82 static char ID; // Pass identification, replacement for typeid
83 InstCombiner() : FunctionPass((intptr_t)&ID) {}
85 /// AddToWorkList - Add the specified instruction to the worklist if it
86 /// isn't already in it.
87 void AddToWorkList(Instruction *I) {
88 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
89 Worklist.push_back(I);
92 // RemoveFromWorkList - remove I from the worklist if it exists.
93 void RemoveFromWorkList(Instruction *I) {
94 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95 if (It == WorklistMap.end()) return; // Not in worklist.
97 // Don't bother moving everything down, just null out the slot.
98 Worklist[It->second] = 0;
100 WorklistMap.erase(It);
103 Instruction *RemoveOneFromWorkList() {
104 Instruction *I = Worklist.back();
106 WorklistMap.erase(I);
111 /// AddUsersToWorkList - When an instruction is simplified, add all users of
112 /// the instruction to the work lists because they might get more simplified
115 void AddUsersToWorkList(Value &I) {
116 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
118 AddToWorkList(cast<Instruction>(*UI));
121 /// AddUsesToWorkList - When an instruction is simplified, add operands to
122 /// the work lists because they might get more simplified now.
124 void AddUsesToWorkList(Instruction &I) {
125 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126 if (Instruction *Op = dyn_cast<Instruction>(*i))
130 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131 /// dead. Add all of its operands to the worklist, turning them into
132 /// undef's to reduce the number of uses of those instructions.
134 /// Return the specified operand before it is turned into an undef.
136 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137 Value *R = I.getOperand(op);
139 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
142 // Set the operand to undef to drop the use.
143 *i = UndefValue::get(Op->getType());
150 virtual bool runOnFunction(Function &F);
152 bool DoOneIteration(Function &F, unsigned ItNum);
154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
155 AU.addRequired<TargetData>();
156 AU.addPreservedID(LCSSAID);
157 AU.setPreservesCFG();
160 TargetData &getTargetData() const { return *TD; }
162 // Visitation implementation - Implement instruction combining for different
163 // instruction types. The semantics are as follows:
165 // null - No change was made
166 // I - Change was made, I is still valid, I may be dead though
167 // otherwise - Change was made, replace I with returned instruction
169 Instruction *visitAdd(BinaryOperator &I);
170 Instruction *visitSub(BinaryOperator &I);
171 Instruction *visitMul(BinaryOperator &I);
172 Instruction *visitURem(BinaryOperator &I);
173 Instruction *visitSRem(BinaryOperator &I);
174 Instruction *visitFRem(BinaryOperator &I);
175 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 *visitAnd(BinaryOperator &I);
184 Instruction *visitOr (BinaryOperator &I);
185 Instruction *visitXor(BinaryOperator &I);
186 Instruction *visitShl(BinaryOperator &I);
187 Instruction *visitAShr(BinaryOperator &I);
188 Instruction *visitLShr(BinaryOperator &I);
189 Instruction *commonShiftTransforms(BinaryOperator &I);
190 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
192 Instruction *visitFCmpInst(FCmpInst &I);
193 Instruction *visitICmpInst(ICmpInst &I);
194 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
195 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
198 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
199 ConstantInt *DivRHS);
201 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
202 ICmpInst::Predicate Cond, Instruction &I);
203 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
205 Instruction *commonCastTransforms(CastInst &CI);
206 Instruction *commonIntCastTransforms(CastInst &CI);
207 Instruction *commonPointerCastTransforms(CastInst &CI);
208 Instruction *visitTrunc(TruncInst &CI);
209 Instruction *visitZExt(ZExtInst &CI);
210 Instruction *visitSExt(SExtInst &CI);
211 Instruction *visitFPTrunc(FPTruncInst &CI);
212 Instruction *visitFPExt(CastInst &CI);
213 Instruction *visitFPToUI(FPToUIInst &FI);
214 Instruction *visitFPToSI(FPToSIInst &FI);
215 Instruction *visitUIToFP(CastInst &CI);
216 Instruction *visitSIToFP(CastInst &CI);
217 Instruction *visitPtrToInt(CastInst &CI);
218 Instruction *visitIntToPtr(IntToPtrInst &CI);
219 Instruction *visitBitCast(BitCastInst &CI);
220 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
222 Instruction *visitSelectInst(SelectInst &CI);
223 Instruction *visitCallInst(CallInst &CI);
224 Instruction *visitInvokeInst(InvokeInst &II);
225 Instruction *visitPHINode(PHINode &PN);
226 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
227 Instruction *visitAllocationInst(AllocationInst &AI);
228 Instruction *visitFreeInst(FreeInst &FI);
229 Instruction *visitLoadInst(LoadInst &LI);
230 Instruction *visitStoreInst(StoreInst &SI);
231 Instruction *visitBranchInst(BranchInst &BI);
232 Instruction *visitSwitchInst(SwitchInst &SI);
233 Instruction *visitInsertElementInst(InsertElementInst &IE);
234 Instruction *visitExtractElementInst(ExtractElementInst &EI);
235 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
236 Instruction *visitExtractValueInst(ExtractValueInst &EV);
238 // visitInstruction - Specify what to return for unhandled instructions...
239 Instruction *visitInstruction(Instruction &I) { return 0; }
242 Instruction *visitCallSite(CallSite CS);
243 bool transformConstExprCastCall(CallSite CS);
244 Instruction *transformCallThroughTrampoline(CallSite CS);
245 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
246 bool DoXform = true);
247 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
250 // InsertNewInstBefore - insert an instruction New before instruction Old
251 // in the program. Add the new instruction to the worklist.
253 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
254 assert(New && New->getParent() == 0 &&
255 "New instruction already inserted into a basic block!");
256 BasicBlock *BB = Old.getParent();
257 BB->getInstList().insert(&Old, New); // Insert inst
262 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
263 /// This also adds the cast to the worklist. Finally, this returns the
265 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
267 if (V->getType() == Ty) return V;
269 if (Constant *CV = dyn_cast<Constant>(V))
270 return ConstantExpr::getCast(opc, CV, Ty);
272 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
277 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
278 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
282 // ReplaceInstUsesWith - This method is to be used when an instruction is
283 // found to be dead, replacable with another preexisting expression. Here
284 // we add all uses of I to the worklist, replace all uses of I with the new
285 // value, then return I, so that the inst combiner will know that I was
288 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
289 AddUsersToWorkList(I); // Add all modified instrs to worklist
291 I.replaceAllUsesWith(V);
294 // If we are replacing the instruction with itself, this must be in a
295 // segment of unreachable code, so just clobber the instruction.
296 I.replaceAllUsesWith(UndefValue::get(I.getType()));
301 // UpdateValueUsesWith - This method is to be used when an value is
302 // found to be replacable with another preexisting expression or was
303 // updated. Here we add all uses of I to the worklist, replace all uses of
304 // I with the new value (unless the instruction was just updated), then
305 // return true, so that the inst combiner will know that I was modified.
307 bool UpdateValueUsesWith(Value *Old, Value *New) {
308 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
310 Old->replaceAllUsesWith(New);
311 if (Instruction *I = dyn_cast<Instruction>(Old))
313 if (Instruction *I = dyn_cast<Instruction>(New))
318 // EraseInstFromFunction - When dealing with an instruction that has side
319 // effects or produces a void value, we can't rely on DCE to delete the
320 // instruction. Instead, visit methods should return the value returned by
322 Instruction *EraseInstFromFunction(Instruction &I) {
323 assert(I.use_empty() && "Cannot erase instruction that is used!");
324 AddUsesToWorkList(I);
325 RemoveFromWorkList(&I);
327 return 0; // Don't do anything with FI
330 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
331 APInt &KnownOne, unsigned Depth = 0) const {
332 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
335 bool MaskedValueIsZero(Value *V, const APInt &Mask,
336 unsigned Depth = 0) const {
337 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
339 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
340 return llvm::ComputeNumSignBits(Op, TD, Depth);
344 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
345 /// InsertBefore instruction. This is specialized a bit to avoid inserting
346 /// casts that are known to not do anything...
348 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
349 Value *V, const Type *DestTy,
350 Instruction *InsertBefore);
352 /// SimplifyCommutative - This performs a few simplifications for
353 /// commutative operators.
354 bool SimplifyCommutative(BinaryOperator &I);
356 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
357 /// most-complex to least-complex order.
358 bool SimplifyCompare(CmpInst &I);
360 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
361 /// on the demanded bits.
362 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
363 APInt& KnownZero, APInt& KnownOne,
366 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
367 uint64_t &UndefElts, unsigned Depth = 0);
369 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
370 // PHI node as operand #0, see if we can fold the instruction into the PHI
371 // (which is only possible if all operands to the PHI are constants).
372 Instruction *FoldOpIntoPhi(Instruction &I);
374 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
375 // operator and they all are only used by the PHI, PHI together their
376 // inputs, and do the operation once, to the result of the PHI.
377 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
378 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
381 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
382 ConstantInt *AndRHS, BinaryOperator &TheAnd);
384 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
385 bool isSub, Instruction &I);
386 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
387 bool isSigned, bool Inside, Instruction &IB);
388 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
389 Instruction *MatchBSwap(BinaryOperator &I);
390 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
391 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
392 Instruction *SimplifyMemSet(MemSetInst *MI);
395 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
397 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
399 int &NumCastsRemoved);
400 unsigned GetOrEnforceKnownAlignment(Value *V,
401 unsigned PrefAlign = 0);
406 char InstCombiner::ID = 0;
407 static RegisterPass<InstCombiner>
408 X("instcombine", "Combine redundant instructions");
410 // getComplexity: Assign a complexity or rank value to LLVM Values...
411 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
412 static unsigned getComplexity(Value *V) {
413 if (isa<Instruction>(V)) {
414 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
418 if (isa<Argument>(V)) return 3;
419 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
422 // isOnlyUse - Return true if this instruction will be deleted if we stop using
424 static bool isOnlyUse(Value *V) {
425 return V->hasOneUse() || isa<Constant>(V);
428 // getPromotedType - Return the specified type promoted as it would be to pass
429 // though a va_arg area...
430 static const Type *getPromotedType(const Type *Ty) {
431 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
432 if (ITy->getBitWidth() < 32)
433 return Type::Int32Ty;
438 /// getBitCastOperand - If the specified operand is a CastInst or a constant
439 /// expression bitcast, return the operand value, otherwise return null.
440 static Value *getBitCastOperand(Value *V) {
441 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
442 return I->getOperand(0);
443 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
444 if (CE->getOpcode() == Instruction::BitCast)
445 return CE->getOperand(0);
449 /// This function is a wrapper around CastInst::isEliminableCastPair. It
450 /// simply extracts arguments and returns what that function returns.
451 static Instruction::CastOps
452 isEliminableCastPair(
453 const CastInst *CI, ///< The first cast instruction
454 unsigned opcode, ///< The opcode of the second cast instruction
455 const Type *DstTy, ///< The target type for the second cast instruction
456 TargetData *TD ///< The target data for pointer size
459 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
460 const Type *MidTy = CI->getType(); // B from above
462 // Get the opcodes of the two Cast instructions
463 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
464 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
466 return Instruction::CastOps(
467 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
468 DstTy, TD->getIntPtrType()));
471 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
472 /// in any code being generated. It does not require codegen if V is simple
473 /// enough or if the cast can be folded into other casts.
474 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
475 const Type *Ty, TargetData *TD) {
476 if (V->getType() == Ty || isa<Constant>(V)) return false;
478 // If this is another cast that can be eliminated, it isn't codegen either.
479 if (const CastInst *CI = dyn_cast<CastInst>(V))
480 if (isEliminableCastPair(CI, opcode, Ty, TD))
485 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
486 /// InsertBefore instruction. This is specialized a bit to avoid inserting
487 /// casts that are known to not do anything...
489 Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
490 Value *V, const Type *DestTy,
491 Instruction *InsertBefore) {
492 if (V->getType() == DestTy) return V;
493 if (Constant *C = dyn_cast<Constant>(V))
494 return ConstantExpr::getCast(opcode, C, DestTy);
496 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
499 // SimplifyCommutative - This performs a few simplifications for commutative
502 // 1. Order operands such that they are listed from right (least complex) to
503 // left (most complex). This puts constants before unary operators before
506 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
507 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
509 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
510 bool Changed = false;
511 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
512 Changed = !I.swapOperands();
514 if (!I.isAssociative()) return Changed;
515 Instruction::BinaryOps Opcode = I.getOpcode();
516 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
517 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
518 if (isa<Constant>(I.getOperand(1))) {
519 Constant *Folded = ConstantExpr::get(I.getOpcode(),
520 cast<Constant>(I.getOperand(1)),
521 cast<Constant>(Op->getOperand(1)));
522 I.setOperand(0, Op->getOperand(0));
523 I.setOperand(1, Folded);
525 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
526 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
527 isOnlyUse(Op) && isOnlyUse(Op1)) {
528 Constant *C1 = cast<Constant>(Op->getOperand(1));
529 Constant *C2 = cast<Constant>(Op1->getOperand(1));
531 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
532 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
533 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
537 I.setOperand(0, New);
538 I.setOperand(1, Folded);
545 /// SimplifyCompare - For a CmpInst this function just orders the operands
546 /// so that theyare listed from right (least complex) to left (most complex).
547 /// This puts constants before unary operators before binary operators.
548 bool InstCombiner::SimplifyCompare(CmpInst &I) {
549 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
552 // Compare instructions are not associative so there's nothing else we can do.
556 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
557 // if the LHS is a constant zero (which is the 'negate' form).
559 static inline Value *dyn_castNegVal(Value *V) {
560 if (BinaryOperator::isNeg(V))
561 return BinaryOperator::getNegArgument(V);
563 // Constants can be considered to be negated values if they can be folded.
564 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
565 return ConstantExpr::getNeg(C);
567 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
568 if (C->getType()->getElementType()->isInteger())
569 return ConstantExpr::getNeg(C);
574 static inline Value *dyn_castNotVal(Value *V) {
575 if (BinaryOperator::isNot(V))
576 return BinaryOperator::getNotArgument(V);
578 // Constants can be considered to be not'ed values...
579 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
580 return ConstantInt::get(~C->getValue());
584 // dyn_castFoldableMul - If this value is a multiply that can be folded into
585 // other computations (because it has a constant operand), return the
586 // non-constant operand of the multiply, and set CST to point to the multiplier.
587 // Otherwise, return null.
589 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
590 if (V->hasOneUse() && V->getType()->isInteger())
591 if (Instruction *I = dyn_cast<Instruction>(V)) {
592 if (I->getOpcode() == Instruction::Mul)
593 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
594 return I->getOperand(0);
595 if (I->getOpcode() == Instruction::Shl)
596 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
597 // The multiplier is really 1 << CST.
598 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
599 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
600 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
601 return I->getOperand(0);
607 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
608 /// expression, return it.
609 static User *dyn_castGetElementPtr(Value *V) {
610 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
611 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
612 if (CE->getOpcode() == Instruction::GetElementPtr)
613 return cast<User>(V);
617 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
618 /// opcode value. Otherwise return UserOp1.
619 static unsigned getOpcode(const Value *V) {
620 if (const Instruction *I = dyn_cast<Instruction>(V))
621 return I->getOpcode();
622 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
623 return CE->getOpcode();
624 // Use UserOp1 to mean there's no opcode.
625 return Instruction::UserOp1;
628 /// AddOne - Add one to a ConstantInt
629 static ConstantInt *AddOne(ConstantInt *C) {
630 APInt Val(C->getValue());
631 return ConstantInt::get(++Val);
633 /// SubOne - Subtract one from a ConstantInt
634 static ConstantInt *SubOne(ConstantInt *C) {
635 APInt Val(C->getValue());
636 return ConstantInt::get(--Val);
638 /// Add - Add two ConstantInts together
639 static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
640 return ConstantInt::get(C1->getValue() + C2->getValue());
642 /// And - Bitwise AND two ConstantInts together
643 static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
644 return ConstantInt::get(C1->getValue() & C2->getValue());
646 /// Subtract - Subtract one ConstantInt from another
647 static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
648 return ConstantInt::get(C1->getValue() - C2->getValue());
650 /// Multiply - Multiply two ConstantInts together
651 static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
652 return ConstantInt::get(C1->getValue() * C2->getValue());
654 /// MultiplyOverflows - True if the multiply can not be expressed in an int
656 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
657 uint32_t W = C1->getBitWidth();
658 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
667 APInt MulExt = LHSExt * RHSExt;
670 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
671 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
672 return MulExt.slt(Min) || MulExt.sgt(Max);
674 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
678 /// ShrinkDemandedConstant - Check to see if the specified operand of the
679 /// specified instruction is a constant integer. If so, check to see if there
680 /// are any bits set in the constant that are not demanded. If so, shrink the
681 /// constant and return true.
682 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
684 assert(I && "No instruction?");
685 assert(OpNo < I->getNumOperands() && "Operand index too large");
687 // If the operand is not a constant integer, nothing to do.
688 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
689 if (!OpC) return false;
691 // If there are no bits set that aren't demanded, nothing to do.
692 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
693 if ((~Demanded & OpC->getValue()) == 0)
696 // This instruction is producing bits that are not demanded. Shrink the RHS.
697 Demanded &= OpC->getValue();
698 I->setOperand(OpNo, ConstantInt::get(Demanded));
702 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
703 // set of known zero and one bits, compute the maximum and minimum values that
704 // could have the specified known zero and known one bits, returning them in
706 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
707 const APInt& KnownZero,
708 const APInt& KnownOne,
709 APInt& Min, APInt& Max) {
710 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
711 assert(KnownZero.getBitWidth() == BitWidth &&
712 KnownOne.getBitWidth() == BitWidth &&
713 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
714 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
715 APInt UnknownBits = ~(KnownZero|KnownOne);
717 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
718 // bit if it is unknown.
720 Max = KnownOne|UnknownBits;
722 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
724 Max.clear(BitWidth-1);
728 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
729 // a set of known zero and one bits, compute the maximum and minimum values that
730 // could have the specified known zero and known one bits, returning them in
732 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
733 const APInt &KnownZero,
734 const APInt &KnownOne,
735 APInt &Min, APInt &Max) {
736 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
737 assert(KnownZero.getBitWidth() == BitWidth &&
738 KnownOne.getBitWidth() == BitWidth &&
739 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
740 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
741 APInt UnknownBits = ~(KnownZero|KnownOne);
743 // The minimum value is when the unknown bits are all zeros.
745 // The maximum value is when the unknown bits are all ones.
746 Max = KnownOne|UnknownBits;
749 /// SimplifyDemandedBits - This function attempts to replace V with a simpler
750 /// value based on the demanded bits. When this function is called, it is known
751 /// that only the bits set in DemandedMask of the result of V are ever used
752 /// downstream. Consequently, depending on the mask and V, it may be possible
753 /// to replace V with a constant or one of its operands. In such cases, this
754 /// function does the replacement and returns true. In all other cases, it
755 /// returns false after analyzing the expression and setting KnownOne and known
756 /// to be one in the expression. KnownZero contains all the bits that are known
757 /// to be zero in the expression. These are provided to potentially allow the
758 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
759 /// the expression. KnownOne and KnownZero always follow the invariant that
760 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
761 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
762 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
763 /// and KnownOne must all be the same.
764 bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
765 APInt& KnownZero, APInt& KnownOne,
767 assert(V != 0 && "Null pointer of Value???");
768 assert(Depth <= 6 && "Limit Search Depth");
769 uint32_t BitWidth = DemandedMask.getBitWidth();
770 const IntegerType *VTy = cast<IntegerType>(V->getType());
771 assert(VTy->getBitWidth() == BitWidth &&
772 KnownZero.getBitWidth() == BitWidth &&
773 KnownOne.getBitWidth() == BitWidth &&
774 "Value *V, DemandedMask, KnownZero and KnownOne \
775 must have same BitWidth");
776 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
777 // We know all of the bits for a constant!
778 KnownOne = CI->getValue() & DemandedMask;
779 KnownZero = ~KnownOne & DemandedMask;
785 if (!V->hasOneUse()) { // Other users may use these bits.
786 if (Depth != 0) { // Not at the root.
787 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
788 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
791 // If this is the root being simplified, allow it to have multiple uses,
792 // just set the DemandedMask to all bits.
793 DemandedMask = APInt::getAllOnesValue(BitWidth);
794 } else if (DemandedMask == 0) { // Not demanding any bits from V.
795 if (V != UndefValue::get(VTy))
796 return UpdateValueUsesWith(V, UndefValue::get(VTy));
798 } else if (Depth == 6) { // Limit search depth.
802 Instruction *I = dyn_cast<Instruction>(V);
803 if (!I) return false; // Only analyze instructions.
805 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
806 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
807 switch (I->getOpcode()) {
809 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
811 case Instruction::And:
812 // If either the LHS or the RHS are Zero, the result is zero.
813 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
814 RHSKnownZero, RHSKnownOne, Depth+1))
816 assert((RHSKnownZero & RHSKnownOne) == 0 &&
817 "Bits known to be one AND zero?");
819 // If something is known zero on the RHS, the bits aren't demanded on the
821 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
822 LHSKnownZero, LHSKnownOne, Depth+1))
824 assert((LHSKnownZero & LHSKnownOne) == 0 &&
825 "Bits known to be one AND zero?");
827 // If all of the demanded bits are known 1 on one side, return the other.
828 // These bits cannot contribute to the result of the 'and'.
829 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
830 (DemandedMask & ~LHSKnownZero))
831 return UpdateValueUsesWith(I, I->getOperand(0));
832 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
833 (DemandedMask & ~RHSKnownZero))
834 return UpdateValueUsesWith(I, I->getOperand(1));
836 // If all of the demanded bits in the inputs are known zeros, return zero.
837 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
838 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
840 // If the RHS is a constant, see if we can simplify it.
841 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
842 return UpdateValueUsesWith(I, I);
844 // Output known-1 bits are only known if set in both the LHS & RHS.
845 RHSKnownOne &= LHSKnownOne;
846 // Output known-0 are known to be clear if zero in either the LHS | RHS.
847 RHSKnownZero |= LHSKnownZero;
849 case Instruction::Or:
850 // If either the LHS or the RHS are One, the result is One.
851 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
852 RHSKnownZero, RHSKnownOne, Depth+1))
854 assert((RHSKnownZero & RHSKnownOne) == 0 &&
855 "Bits known to be one AND zero?");
856 // If something is known one on the RHS, the bits aren't demanded on the
858 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
859 LHSKnownZero, LHSKnownOne, Depth+1))
861 assert((LHSKnownZero & LHSKnownOne) == 0 &&
862 "Bits known to be one AND zero?");
864 // If all of the demanded bits are known zero on one side, return the other.
865 // These bits cannot contribute to the result of the 'or'.
866 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
867 (DemandedMask & ~LHSKnownOne))
868 return UpdateValueUsesWith(I, I->getOperand(0));
869 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
870 (DemandedMask & ~RHSKnownOne))
871 return UpdateValueUsesWith(I, I->getOperand(1));
873 // If all of the potentially set bits on one side are known to be set on
874 // the other side, just use the 'other' side.
875 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
876 (DemandedMask & (~RHSKnownZero)))
877 return UpdateValueUsesWith(I, I->getOperand(0));
878 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
879 (DemandedMask & (~LHSKnownZero)))
880 return UpdateValueUsesWith(I, I->getOperand(1));
882 // If the RHS is a constant, see if we can simplify it.
883 if (ShrinkDemandedConstant(I, 1, DemandedMask))
884 return UpdateValueUsesWith(I, I);
886 // Output known-0 bits are only known if clear in both the LHS & RHS.
887 RHSKnownZero &= LHSKnownZero;
888 // Output known-1 are known to be set if set in either the LHS | RHS.
889 RHSKnownOne |= LHSKnownOne;
891 case Instruction::Xor: {
892 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
893 RHSKnownZero, RHSKnownOne, Depth+1))
895 assert((RHSKnownZero & RHSKnownOne) == 0 &&
896 "Bits known to be one AND zero?");
897 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
898 LHSKnownZero, LHSKnownOne, Depth+1))
900 assert((LHSKnownZero & LHSKnownOne) == 0 &&
901 "Bits known to be one AND zero?");
903 // If all of the demanded bits are known zero on one side, return the other.
904 // These bits cannot contribute to the result of the 'xor'.
905 if ((DemandedMask & RHSKnownZero) == DemandedMask)
906 return UpdateValueUsesWith(I, I->getOperand(0));
907 if ((DemandedMask & LHSKnownZero) == DemandedMask)
908 return UpdateValueUsesWith(I, I->getOperand(1));
910 // Output known-0 bits are known if clear or set in both the LHS & RHS.
911 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
912 (RHSKnownOne & LHSKnownOne);
913 // Output known-1 are known to be set if set in only one of the LHS, RHS.
914 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
915 (RHSKnownOne & LHSKnownZero);
917 // If all of the demanded bits are known to be zero on one side or the
918 // other, turn this into an *inclusive* or.
919 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
920 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
922 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
924 InsertNewInstBefore(Or, *I);
925 return UpdateValueUsesWith(I, Or);
928 // If all of the demanded bits on one side are known, and all of the set
929 // bits on that side are also known to be set on the other side, turn this
930 // into an AND, as we know the bits will be cleared.
931 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
932 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
934 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
935 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
937 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
938 InsertNewInstBefore(And, *I);
939 return UpdateValueUsesWith(I, And);
943 // If the RHS is a constant, see if we can simplify it.
944 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
945 if (ShrinkDemandedConstant(I, 1, DemandedMask))
946 return UpdateValueUsesWith(I, I);
948 RHSKnownZero = KnownZeroOut;
949 RHSKnownOne = KnownOneOut;
952 case Instruction::Select:
953 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
954 RHSKnownZero, RHSKnownOne, Depth+1))
956 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
957 LHSKnownZero, LHSKnownOne, Depth+1))
959 assert((RHSKnownZero & RHSKnownOne) == 0 &&
960 "Bits known to be one AND zero?");
961 assert((LHSKnownZero & LHSKnownOne) == 0 &&
962 "Bits known to be one AND zero?");
964 // If the operands are constants, see if we can simplify them.
965 if (ShrinkDemandedConstant(I, 1, DemandedMask))
966 return UpdateValueUsesWith(I, I);
967 if (ShrinkDemandedConstant(I, 2, DemandedMask))
968 return UpdateValueUsesWith(I, I);
970 // Only known if known in both the LHS and RHS.
971 RHSKnownOne &= LHSKnownOne;
972 RHSKnownZero &= LHSKnownZero;
974 case Instruction::Trunc: {
976 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
977 DemandedMask.zext(truncBf);
978 RHSKnownZero.zext(truncBf);
979 RHSKnownOne.zext(truncBf);
980 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
981 RHSKnownZero, RHSKnownOne, Depth+1))
983 DemandedMask.trunc(BitWidth);
984 RHSKnownZero.trunc(BitWidth);
985 RHSKnownOne.trunc(BitWidth);
986 assert((RHSKnownZero & RHSKnownOne) == 0 &&
987 "Bits known to be one AND zero?");
990 case Instruction::BitCast:
991 if (!I->getOperand(0)->getType()->isInteger())
994 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
995 RHSKnownZero, RHSKnownOne, Depth+1))
997 assert((RHSKnownZero & RHSKnownOne) == 0 &&
998 "Bits known to be one AND zero?");
1000 case Instruction::ZExt: {
1001 // Compute the bits in the result that are not present in the input.
1002 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1003 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1005 DemandedMask.trunc(SrcBitWidth);
1006 RHSKnownZero.trunc(SrcBitWidth);
1007 RHSKnownOne.trunc(SrcBitWidth);
1008 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1009 RHSKnownZero, RHSKnownOne, Depth+1))
1011 DemandedMask.zext(BitWidth);
1012 RHSKnownZero.zext(BitWidth);
1013 RHSKnownOne.zext(BitWidth);
1014 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1015 "Bits known to be one AND zero?");
1016 // The top bits are known to be zero.
1017 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1020 case Instruction::SExt: {
1021 // Compute the bits in the result that are not present in the input.
1022 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1023 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1025 APInt InputDemandedBits = DemandedMask &
1026 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1028 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1029 // If any of the sign extended bits are demanded, we know that the sign
1031 if ((NewBits & DemandedMask) != 0)
1032 InputDemandedBits.set(SrcBitWidth-1);
1034 InputDemandedBits.trunc(SrcBitWidth);
1035 RHSKnownZero.trunc(SrcBitWidth);
1036 RHSKnownOne.trunc(SrcBitWidth);
1037 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1038 RHSKnownZero, RHSKnownOne, Depth+1))
1040 InputDemandedBits.zext(BitWidth);
1041 RHSKnownZero.zext(BitWidth);
1042 RHSKnownOne.zext(BitWidth);
1043 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1044 "Bits known to be one AND zero?");
1046 // If the sign bit of the input is known set or clear, then we know the
1047 // top bits of the result.
1049 // If the input sign bit is known zero, or if the NewBits are not demanded
1050 // convert this into a zero extension.
1051 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1053 // Convert to ZExt cast
1054 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1055 return UpdateValueUsesWith(I, NewCast);
1056 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1057 RHSKnownOne |= NewBits;
1061 case Instruction::Add: {
1062 // Figure out what the input bits are. If the top bits of the and result
1063 // are not demanded, then the add doesn't demand them from its input
1065 uint32_t NLZ = DemandedMask.countLeadingZeros();
1067 // If there is a constant on the RHS, there are a variety of xformations
1069 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1070 // If null, this should be simplified elsewhere. Some of the xforms here
1071 // won't work if the RHS is zero.
1075 // If the top bit of the output is demanded, demand everything from the
1076 // input. Otherwise, we demand all the input bits except NLZ top bits.
1077 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1079 // Find information about known zero/one bits in the input.
1080 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1081 LHSKnownZero, LHSKnownOne, Depth+1))
1084 // If the RHS of the add has bits set that can't affect the input, reduce
1086 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1087 return UpdateValueUsesWith(I, I);
1089 // Avoid excess work.
1090 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1093 // Turn it into OR if input bits are zero.
1094 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1096 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1098 InsertNewInstBefore(Or, *I);
1099 return UpdateValueUsesWith(I, Or);
1102 // We can say something about the output known-zero and known-one bits,
1103 // depending on potential carries from the input constant and the
1104 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1105 // bits set and the RHS constant is 0x01001, then we know we have a known
1106 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1108 // To compute this, we first compute the potential carry bits. These are
1109 // the bits which may be modified. I'm not aware of a better way to do
1111 const APInt& RHSVal = RHS->getValue();
1112 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1114 // Now that we know which bits have carries, compute the known-1/0 sets.
1116 // Bits are known one if they are known zero in one operand and one in the
1117 // other, and there is no input carry.
1118 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1119 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1121 // Bits are known zero if they are known zero in both operands and there
1122 // is no input carry.
1123 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1125 // If the high-bits of this ADD are not demanded, then it does not demand
1126 // the high bits of its LHS or RHS.
1127 if (DemandedMask[BitWidth-1] == 0) {
1128 // Right fill the mask of bits for this ADD to demand the most
1129 // significant bit and all those below it.
1130 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1131 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1132 LHSKnownZero, LHSKnownOne, Depth+1))
1134 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1135 LHSKnownZero, LHSKnownOne, Depth+1))
1141 case Instruction::Sub:
1142 // If the high-bits of this SUB are not demanded, then it does not demand
1143 // the high bits of its LHS or RHS.
1144 if (DemandedMask[BitWidth-1] == 0) {
1145 // Right fill the mask of bits for this SUB to demand the most
1146 // significant bit and all those below it.
1147 uint32_t NLZ = DemandedMask.countLeadingZeros();
1148 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1149 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1150 LHSKnownZero, LHSKnownOne, Depth+1))
1152 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1153 LHSKnownZero, LHSKnownOne, Depth+1))
1156 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1157 // the known zeros and ones.
1158 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1160 case Instruction::Shl:
1161 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1162 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1163 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1164 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1165 RHSKnownZero, RHSKnownOne, Depth+1))
1167 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1168 "Bits known to be one AND zero?");
1169 RHSKnownZero <<= ShiftAmt;
1170 RHSKnownOne <<= ShiftAmt;
1171 // low bits known zero.
1173 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1176 case Instruction::LShr:
1177 // For a logical shift right
1178 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1179 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1181 // Unsigned shift right.
1182 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1183 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1184 RHSKnownZero, RHSKnownOne, Depth+1))
1186 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1187 "Bits known to be one AND zero?");
1188 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1189 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1191 // Compute the new bits that are at the top now.
1192 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1193 RHSKnownZero |= HighBits; // high bits known zero.
1197 case Instruction::AShr:
1198 // If this is an arithmetic shift right and only the low-bit is set, we can
1199 // always convert this into a logical shr, even if the shift amount is
1200 // variable. The low bit of the shift cannot be an input sign bit unless
1201 // the shift amount is >= the size of the datatype, which is undefined.
1202 if (DemandedMask == 1) {
1203 // Perform the logical shift right.
1204 Value *NewVal = BinaryOperator::CreateLShr(
1205 I->getOperand(0), I->getOperand(1), I->getName());
1206 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1207 return UpdateValueUsesWith(I, NewVal);
1210 // If the sign bit is the only bit demanded by this ashr, then there is no
1211 // need to do it, the shift doesn't change the high bit.
1212 if (DemandedMask.isSignBit())
1213 return UpdateValueUsesWith(I, I->getOperand(0));
1215 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1216 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1218 // Signed shift right.
1219 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1220 // If any of the "high bits" are demanded, we should set the sign bit as
1222 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1223 DemandedMaskIn.set(BitWidth-1);
1224 if (SimplifyDemandedBits(I->getOperand(0),
1226 RHSKnownZero, RHSKnownOne, Depth+1))
1228 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1229 "Bits known to be one AND zero?");
1230 // Compute the new bits that are at the top now.
1231 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1232 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1233 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1235 // Handle the sign bits.
1236 APInt SignBit(APInt::getSignBit(BitWidth));
1237 // Adjust to where it is now in the mask.
1238 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1240 // If the input sign bit is known to be zero, or if none of the top bits
1241 // are demanded, turn this into an unsigned shift right.
1242 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
1243 (HighBits & ~DemandedMask) == HighBits) {
1244 // Perform the logical shift right.
1245 Value *NewVal = BinaryOperator::CreateLShr(
1246 I->getOperand(0), SA, I->getName());
1247 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1248 return UpdateValueUsesWith(I, NewVal);
1249 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1250 RHSKnownOne |= HighBits;
1254 case Instruction::SRem:
1255 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1256 APInt RA = Rem->getValue();
1257 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
1258 if (DemandedMask.ule(RA)) // srem won't affect demanded bits
1259 return UpdateValueUsesWith(I, I->getOperand(0));
1261 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
1262 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1263 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1264 LHSKnownZero, LHSKnownOne, Depth+1))
1267 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1268 LHSKnownZero |= ~LowBits;
1269 else if (LHSKnownOne[BitWidth-1])
1270 LHSKnownOne |= ~LowBits;
1272 KnownZero |= LHSKnownZero & DemandedMask;
1273 KnownOne |= LHSKnownOne & DemandedMask;
1275 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1279 case Instruction::URem: {
1280 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1281 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1282 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1283 KnownZero2, KnownOne2, Depth+1))
1286 uint32_t Leaders = KnownZero2.countLeadingOnes();
1287 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
1288 KnownZero2, KnownOne2, Depth+1))
1291 Leaders = std::max(Leaders,
1292 KnownZero2.countLeadingOnes());
1293 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1296 case Instruction::Call:
1297 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1298 switch (II->getIntrinsicID()) {
1300 case Intrinsic::bswap: {
1301 // If the only bits demanded come from one byte of the bswap result,
1302 // just shift the input byte into position to eliminate the bswap.
1303 unsigned NLZ = DemandedMask.countLeadingZeros();
1304 unsigned NTZ = DemandedMask.countTrailingZeros();
1306 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1307 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1308 // have 14 leading zeros, round to 8.
1311 // If we need exactly one byte, we can do this transformation.
1312 if (BitWidth-NLZ-NTZ == 8) {
1313 unsigned ResultBit = NTZ;
1314 unsigned InputBit = BitWidth-NTZ-8;
1316 // Replace this with either a left or right shift to get the byte into
1318 Instruction *NewVal;
1319 if (InputBit > ResultBit)
1320 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1321 ConstantInt::get(I->getType(), InputBit-ResultBit));
1323 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1324 ConstantInt::get(I->getType(), ResultBit-InputBit));
1325 NewVal->takeName(I);
1326 InsertNewInstBefore(NewVal, *I);
1327 return UpdateValueUsesWith(I, NewVal);
1330 // TODO: Could compute known zero/one bits based on the input.
1335 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1339 // If the client is only demanding bits that we know, return the known
1341 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1342 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1347 /// SimplifyDemandedVectorElts - The specified value producecs a vector with
1348 /// 64 or fewer elements. DemandedElts contains the set of elements that are
1349 /// actually used by the caller. This method analyzes which elements of the
1350 /// operand are undef and returns that information in UndefElts.
1352 /// If the information about demanded elements can be used to simplify the
1353 /// operation, the operation is simplified, then the resultant value is
1354 /// returned. This returns null if no change was made.
1355 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1356 uint64_t &UndefElts,
1358 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1359 assert(VWidth <= 64 && "Vector too wide to analyze!");
1360 uint64_t EltMask = ~0ULL >> (64-VWidth);
1361 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1362 "Invalid DemandedElts!");
1364 if (isa<UndefValue>(V)) {
1365 // If the entire vector is undefined, just return this info.
1366 UndefElts = EltMask;
1368 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1369 UndefElts = EltMask;
1370 return UndefValue::get(V->getType());
1374 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1375 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1376 Constant *Undef = UndefValue::get(EltTy);
1378 std::vector<Constant*> Elts;
1379 for (unsigned i = 0; i != VWidth; ++i)
1380 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1381 Elts.push_back(Undef);
1382 UndefElts |= (1ULL << i);
1383 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1384 Elts.push_back(Undef);
1385 UndefElts |= (1ULL << i);
1386 } else { // Otherwise, defined.
1387 Elts.push_back(CP->getOperand(i));
1390 // If we changed the constant, return it.
1391 Constant *NewCP = ConstantVector::get(Elts);
1392 return NewCP != CP ? NewCP : 0;
1393 } else if (isa<ConstantAggregateZero>(V)) {
1394 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1396 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1397 Constant *Zero = Constant::getNullValue(EltTy);
1398 Constant *Undef = UndefValue::get(EltTy);
1399 std::vector<Constant*> Elts;
1400 for (unsigned i = 0; i != VWidth; ++i)
1401 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1402 UndefElts = DemandedElts ^ EltMask;
1403 return ConstantVector::get(Elts);
1406 if (!V->hasOneUse()) { // Other users may use these bits.
1407 if (Depth != 0) { // Not at the root.
1408 // TODO: Just compute the UndefElts information recursively.
1412 } else if (Depth == 10) { // Limit search depth.
1416 Instruction *I = dyn_cast<Instruction>(V);
1417 if (!I) return false; // Only analyze instructions.
1419 bool MadeChange = false;
1420 uint64_t UndefElts2;
1422 switch (I->getOpcode()) {
1425 case Instruction::InsertElement: {
1426 // If this is a variable index, we don't know which element it overwrites.
1427 // demand exactly the same input as we produce.
1428 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1430 // Note that we can't propagate undef elt info, because we don't know
1431 // which elt is getting updated.
1432 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1433 UndefElts2, Depth+1);
1434 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1438 // If this is inserting an element that isn't demanded, remove this
1440 unsigned IdxNo = Idx->getZExtValue();
1441 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1442 return AddSoonDeadInstToWorklist(*I, 0);
1444 // Otherwise, the element inserted overwrites whatever was there, so the
1445 // input demanded set is simpler than the output set.
1446 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1447 DemandedElts & ~(1ULL << IdxNo),
1448 UndefElts, Depth+1);
1449 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1451 // The inserted element is defined.
1452 UndefElts |= 1ULL << IdxNo;
1455 case Instruction::BitCast: {
1456 // Vector->vector casts only.
1457 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1459 unsigned InVWidth = VTy->getNumElements();
1460 uint64_t InputDemandedElts = 0;
1463 if (VWidth == InVWidth) {
1464 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1465 // elements as are demanded of us.
1467 InputDemandedElts = DemandedElts;
1468 } else if (VWidth > InVWidth) {
1472 // If there are more elements in the result than there are in the source,
1473 // then an input element is live if any of the corresponding output
1474 // elements are live.
1475 Ratio = VWidth/InVWidth;
1476 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1477 if (DemandedElts & (1ULL << OutIdx))
1478 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1484 // If there are more elements in the source than there are in the result,
1485 // then an input element is live if the corresponding output element is
1487 Ratio = InVWidth/VWidth;
1488 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1489 if (DemandedElts & (1ULL << InIdx/Ratio))
1490 InputDemandedElts |= 1ULL << InIdx;
1493 // div/rem demand all inputs, because they don't want divide by zero.
1494 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1495 UndefElts2, Depth+1);
1497 I->setOperand(0, TmpV);
1501 UndefElts = UndefElts2;
1502 if (VWidth > InVWidth) {
1503 assert(0 && "Unimp");
1504 // If there are more elements in the result than there are in the source,
1505 // then an output element is undef if the corresponding input element is
1507 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1508 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1509 UndefElts |= 1ULL << OutIdx;
1510 } else if (VWidth < InVWidth) {
1511 assert(0 && "Unimp");
1512 // If there are more elements in the source than there are in the result,
1513 // then a result element is undef if all of the corresponding input
1514 // elements are undef.
1515 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1516 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1517 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1518 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1522 case Instruction::And:
1523 case Instruction::Or:
1524 case Instruction::Xor:
1525 case Instruction::Add:
1526 case Instruction::Sub:
1527 case Instruction::Mul:
1528 // div/rem demand all inputs, because they don't want divide by zero.
1529 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1530 UndefElts, Depth+1);
1531 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1532 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1533 UndefElts2, Depth+1);
1534 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1536 // Output elements are undefined if both are undefined. Consider things
1537 // like undef&0. The result is known zero, not undef.
1538 UndefElts &= UndefElts2;
1541 case Instruction::Call: {
1542 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1544 switch (II->getIntrinsicID()) {
1547 // Binary vector operations that work column-wise. A dest element is a
1548 // function of the corresponding input elements from the two inputs.
1549 case Intrinsic::x86_sse_sub_ss:
1550 case Intrinsic::x86_sse_mul_ss:
1551 case Intrinsic::x86_sse_min_ss:
1552 case Intrinsic::x86_sse_max_ss:
1553 case Intrinsic::x86_sse2_sub_sd:
1554 case Intrinsic::x86_sse2_mul_sd:
1555 case Intrinsic::x86_sse2_min_sd:
1556 case Intrinsic::x86_sse2_max_sd:
1557 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1558 UndefElts, Depth+1);
1559 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1560 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1561 UndefElts2, Depth+1);
1562 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1564 // If only the low elt is demanded and this is a scalarizable intrinsic,
1565 // scalarize it now.
1566 if (DemandedElts == 1) {
1567 switch (II->getIntrinsicID()) {
1569 case Intrinsic::x86_sse_sub_ss:
1570 case Intrinsic::x86_sse_mul_ss:
1571 case Intrinsic::x86_sse2_sub_sd:
1572 case Intrinsic::x86_sse2_mul_sd:
1573 // TODO: Lower MIN/MAX/ABS/etc
1574 Value *LHS = II->getOperand(1);
1575 Value *RHS = II->getOperand(2);
1576 // Extract the element as scalars.
1577 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1578 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1580 switch (II->getIntrinsicID()) {
1581 default: assert(0 && "Case stmts out of sync!");
1582 case Intrinsic::x86_sse_sub_ss:
1583 case Intrinsic::x86_sse2_sub_sd:
1584 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
1585 II->getName()), *II);
1587 case Intrinsic::x86_sse_mul_ss:
1588 case Intrinsic::x86_sse2_mul_sd:
1589 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
1590 II->getName()), *II);
1595 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1597 InsertNewInstBefore(New, *II);
1598 AddSoonDeadInstToWorklist(*II, 0);
1603 // Output elements are undefined if both are undefined. Consider things
1604 // like undef&0. The result is known zero, not undef.
1605 UndefElts &= UndefElts2;
1611 return MadeChange ? I : 0;
1615 /// AssociativeOpt - Perform an optimization on an associative operator. This
1616 /// function is designed to check a chain of associative operators for a
1617 /// potential to apply a certain optimization. Since the optimization may be
1618 /// applicable if the expression was reassociated, this checks the chain, then
1619 /// reassociates the expression as necessary to expose the optimization
1620 /// opportunity. This makes use of a special Functor, which must define
1621 /// 'shouldApply' and 'apply' methods.
1623 template<typename Functor>
1624 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1625 unsigned Opcode = Root.getOpcode();
1626 Value *LHS = Root.getOperand(0);
1628 // Quick check, see if the immediate LHS matches...
1629 if (F.shouldApply(LHS))
1630 return F.apply(Root);
1632 // Otherwise, if the LHS is not of the same opcode as the root, return.
1633 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1634 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1635 // Should we apply this transform to the RHS?
1636 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1638 // If not to the RHS, check to see if we should apply to the LHS...
1639 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1640 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1644 // If the functor wants to apply the optimization to the RHS of LHSI,
1645 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1647 // Now all of the instructions are in the current basic block, go ahead
1648 // and perform the reassociation.
1649 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1651 // First move the selected RHS to the LHS of the root...
1652 Root.setOperand(0, LHSI->getOperand(1));
1654 // Make what used to be the LHS of the root be the user of the root...
1655 Value *ExtraOperand = TmpLHSI->getOperand(1);
1656 if (&Root == TmpLHSI) {
1657 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1660 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1661 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1662 BasicBlock::iterator ARI = &Root; ++ARI;
1663 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
1666 // Now propagate the ExtraOperand down the chain of instructions until we
1668 while (TmpLHSI != LHSI) {
1669 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1670 // Move the instruction to immediately before the chain we are
1671 // constructing to avoid breaking dominance properties.
1672 NextLHSI->moveBefore(ARI);
1675 Value *NextOp = NextLHSI->getOperand(1);
1676 NextLHSI->setOperand(1, ExtraOperand);
1678 ExtraOperand = NextOp;
1681 // Now that the instructions are reassociated, have the functor perform
1682 // the transformation...
1683 return F.apply(Root);
1686 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1693 // AddRHS - Implements: X + X --> X << 1
1696 AddRHS(Value *rhs) : RHS(rhs) {}
1697 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1698 Instruction *apply(BinaryOperator &Add) const {
1699 return BinaryOperator::CreateShl(Add.getOperand(0),
1700 ConstantInt::get(Add.getType(), 1));
1704 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1706 struct AddMaskingAnd {
1708 AddMaskingAnd(Constant *c) : C2(c) {}
1709 bool shouldApply(Value *LHS) const {
1711 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1712 ConstantExpr::getAnd(C1, C2)->isNullValue();
1714 Instruction *apply(BinaryOperator &Add) const {
1715 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1721 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1723 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1724 if (Constant *SOC = dyn_cast<Constant>(SO))
1725 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1727 return IC->InsertNewInstBefore(CastInst::Create(
1728 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1731 // Figure out if the constant is the left or the right argument.
1732 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1733 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1735 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1737 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1738 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1741 Value *Op0 = SO, *Op1 = ConstOperand;
1743 std::swap(Op0, Op1);
1745 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1746 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1747 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1748 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1749 SO->getName()+".cmp");
1751 assert(0 && "Unknown binary instruction type!");
1754 return IC->InsertNewInstBefore(New, I);
1757 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1758 // constant as the other operand, try to fold the binary operator into the
1759 // select arguments. This also works for Cast instructions, which obviously do
1760 // not have a second operand.
1761 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1763 // Don't modify shared select instructions
1764 if (!SI->hasOneUse()) return 0;
1765 Value *TV = SI->getOperand(1);
1766 Value *FV = SI->getOperand(2);
1768 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1769 // Bool selects with constant operands can be folded to logical ops.
1770 if (SI->getType() == Type::Int1Ty) return 0;
1772 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1773 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1775 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1782 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1783 /// node as operand #0, see if we can fold the instruction into the PHI (which
1784 /// is only possible if all operands to the PHI are constants).
1785 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1786 PHINode *PN = cast<PHINode>(I.getOperand(0));
1787 unsigned NumPHIValues = PN->getNumIncomingValues();
1788 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1790 // Check to see if all of the operands of the PHI are constants. If there is
1791 // one non-constant value, remember the BB it is. If there is more than one
1792 // or if *it* is a PHI, bail out.
1793 BasicBlock *NonConstBB = 0;
1794 for (unsigned i = 0; i != NumPHIValues; ++i)
1795 if (!isa<Constant>(PN->getIncomingValue(i))) {
1796 if (NonConstBB) return 0; // More than one non-const value.
1797 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1798 NonConstBB = PN->getIncomingBlock(i);
1800 // If the incoming non-constant value is in I's block, we have an infinite
1802 if (NonConstBB == I.getParent())
1806 // If there is exactly one non-constant value, we can insert a copy of the
1807 // operation in that block. However, if this is a critical edge, we would be
1808 // inserting the computation one some other paths (e.g. inside a loop). Only
1809 // do this if the pred block is unconditionally branching into the phi block.
1811 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1812 if (!BI || !BI->isUnconditional()) return 0;
1815 // Okay, we can do the transformation: create the new PHI node.
1816 PHINode *NewPN = PHINode::Create(I.getType(), "");
1817 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1818 InsertNewInstBefore(NewPN, *PN);
1819 NewPN->takeName(PN);
1821 // Next, add all of the operands to the PHI.
1822 if (I.getNumOperands() == 2) {
1823 Constant *C = cast<Constant>(I.getOperand(1));
1824 for (unsigned i = 0; i != NumPHIValues; ++i) {
1826 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1827 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1828 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1830 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1832 assert(PN->getIncomingBlock(i) == NonConstBB);
1833 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1834 InV = BinaryOperator::Create(BO->getOpcode(),
1835 PN->getIncomingValue(i), C, "phitmp",
1836 NonConstBB->getTerminator());
1837 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1838 InV = CmpInst::Create(CI->getOpcode(),
1840 PN->getIncomingValue(i), C, "phitmp",
1841 NonConstBB->getTerminator());
1843 assert(0 && "Unknown binop!");
1845 AddToWorkList(cast<Instruction>(InV));
1847 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1850 CastInst *CI = cast<CastInst>(&I);
1851 const Type *RetTy = CI->getType();
1852 for (unsigned i = 0; i != NumPHIValues; ++i) {
1854 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1855 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1857 assert(PN->getIncomingBlock(i) == NonConstBB);
1858 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
1859 I.getType(), "phitmp",
1860 NonConstBB->getTerminator());
1861 AddToWorkList(cast<Instruction>(InV));
1863 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1866 return ReplaceInstUsesWith(I, NewPN);
1870 /// WillNotOverflowSignedAdd - Return true if we can prove that:
1871 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1872 /// This basically requires proving that the add in the original type would not
1873 /// overflow to change the sign bit or have a carry out.
1874 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1875 // There are different heuristics we can use for this. Here are some simple
1878 // Add has the property that adding any two 2's complement numbers can only
1879 // have one carry bit which can change a sign. As such, if LHS and RHS each
1880 // have at least two sign bits, we know that the addition of the two values will
1881 // sign extend fine.
1882 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1886 // If one of the operands only has one non-zero bit, and if the other operand
1887 // has a known-zero bit in a more significant place than it (not including the
1888 // sign bit) the ripple may go up to and fill the zero, but won't change the
1889 // sign. For example, (X & ~4) + 1.
1897 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1898 bool Changed = SimplifyCommutative(I);
1899 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1901 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1902 // X + undef -> undef
1903 if (isa<UndefValue>(RHS))
1904 return ReplaceInstUsesWith(I, RHS);
1907 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1908 if (RHSC->isNullValue())
1909 return ReplaceInstUsesWith(I, LHS);
1910 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1911 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1912 (I.getType())->getValueAPF()))
1913 return ReplaceInstUsesWith(I, LHS);
1916 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1917 // X + (signbit) --> X ^ signbit
1918 const APInt& Val = CI->getValue();
1919 uint32_t BitWidth = Val.getBitWidth();
1920 if (Val == APInt::getSignBit(BitWidth))
1921 return BinaryOperator::CreateXor(LHS, RHS);
1923 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1924 // (X & 254)+1 -> (X&254)|1
1925 if (!isa<VectorType>(I.getType())) {
1926 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1927 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1928 KnownZero, KnownOne))
1933 if (isa<PHINode>(LHS))
1934 if (Instruction *NV = FoldOpIntoPhi(I))
1937 ConstantInt *XorRHS = 0;
1939 if (isa<ConstantInt>(RHSC) &&
1940 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1941 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
1942 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
1944 uint32_t Size = TySizeBits / 2;
1945 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1946 APInt CFF80Val(-C0080Val);
1948 if (TySizeBits > Size) {
1949 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1950 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1951 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1952 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
1953 // This is a sign extend if the top bits are known zero.
1954 if (!MaskedValueIsZero(XorLHS,
1955 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
1956 Size = 0; // Not a sign ext, but can't be any others either.
1961 C0080Val = APIntOps::lshr(C0080Val, Size);
1962 CFF80Val = APIntOps::ashr(CFF80Val, Size);
1963 } while (Size >= 1);
1965 // FIXME: This shouldn't be necessary. When the backends can handle types
1966 // with funny bit widths then this switch statement should be removed. It
1967 // is just here to get the size of the "middle" type back up to something
1968 // that the back ends can handle.
1969 const Type *MiddleType = 0;
1972 case 32: MiddleType = Type::Int32Ty; break;
1973 case 16: MiddleType = Type::Int16Ty; break;
1974 case 8: MiddleType = Type::Int8Ty; break;
1977 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
1978 InsertNewInstBefore(NewTrunc, I);
1979 return new SExtInst(NewTrunc, I.getType(), I.getName());
1984 if (I.getType() == Type::Int1Ty)
1985 return BinaryOperator::CreateXor(LHS, RHS);
1988 if (I.getType()->isInteger()) {
1989 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1991 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1992 if (RHSI->getOpcode() == Instruction::Sub)
1993 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1994 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1996 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1997 if (LHSI->getOpcode() == Instruction::Sub)
1998 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1999 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2004 // -A + -B --> -(A + B)
2005 if (Value *LHSV = dyn_castNegVal(LHS)) {
2006 if (LHS->getType()->isIntOrIntVector()) {
2007 if (Value *RHSV = dyn_castNegVal(RHS)) {
2008 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2009 InsertNewInstBefore(NewAdd, I);
2010 return BinaryOperator::CreateNeg(NewAdd);
2014 return BinaryOperator::CreateSub(RHS, LHSV);
2018 if (!isa<Constant>(RHS))
2019 if (Value *V = dyn_castNegVal(RHS))
2020 return BinaryOperator::CreateSub(LHS, V);
2024 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2025 if (X == RHS) // X*C + X --> X * (C+1)
2026 return BinaryOperator::CreateMul(RHS, AddOne(C2));
2028 // X*C1 + X*C2 --> X * (C1+C2)
2030 if (X == dyn_castFoldableMul(RHS, C1))
2031 return BinaryOperator::CreateMul(X, Add(C1, C2));
2034 // X + X*C --> X * (C+1)
2035 if (dyn_castFoldableMul(RHS, C2) == LHS)
2036 return BinaryOperator::CreateMul(LHS, AddOne(C2));
2038 // X + ~X --> -1 since ~X = -X-1
2039 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2040 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2043 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2044 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2045 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2048 // A+B --> A|B iff A and B have no bits set in common.
2049 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2050 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2051 APInt LHSKnownOne(IT->getBitWidth(), 0);
2052 APInt LHSKnownZero(IT->getBitWidth(), 0);
2053 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2054 if (LHSKnownZero != 0) {
2055 APInt RHSKnownOne(IT->getBitWidth(), 0);
2056 APInt RHSKnownZero(IT->getBitWidth(), 0);
2057 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2059 // No bits in common -> bitwise or.
2060 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2061 return BinaryOperator::CreateOr(LHS, RHS);
2065 // W*X + Y*Z --> W * (X+Z) iff W == Y
2066 if (I.getType()->isIntOrIntVector()) {
2067 Value *W, *X, *Y, *Z;
2068 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2069 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2073 } else if (Y == X) {
2075 } else if (X == Z) {
2082 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2083 LHS->getName()), I);
2084 return BinaryOperator::CreateMul(W, NewAdd);
2089 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2091 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2092 return BinaryOperator::CreateSub(SubOne(CRHS), X);
2094 // (X & FF00) + xx00 -> (X+xx00) & FF00
2095 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2096 Constant *Anded = And(CRHS, C2);
2097 if (Anded == CRHS) {
2098 // See if all bits from the first bit set in the Add RHS up are included
2099 // in the mask. First, get the rightmost bit.
2100 const APInt& AddRHSV = CRHS->getValue();
2102 // Form a mask of all bits from the lowest bit added through the top.
2103 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2105 // See if the and mask includes all of these bits.
2106 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2108 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2109 // Okay, the xform is safe. Insert the new add pronto.
2110 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2111 LHS->getName()), I);
2112 return BinaryOperator::CreateAnd(NewAdd, C2);
2117 // Try to fold constant add into select arguments.
2118 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2119 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2123 // add (cast *A to intptrtype) B ->
2124 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
2126 CastInst *CI = dyn_cast<CastInst>(LHS);
2129 CI = dyn_cast<CastInst>(RHS);
2132 if (CI && CI->getType()->isSized() &&
2133 (CI->getType()->getPrimitiveSizeInBits() ==
2134 TD->getIntPtrType()->getPrimitiveSizeInBits())
2135 && isa<PointerType>(CI->getOperand(0)->getType())) {
2137 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2138 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2139 PointerType::get(Type::Int8Ty, AS), I);
2140 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2141 return new PtrToIntInst(I2, CI->getType());
2145 // add (select X 0 (sub n A)) A --> select X A n
2147 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2150 SI = dyn_cast<SelectInst>(RHS);
2153 if (SI && SI->hasOneUse()) {
2154 Value *TV = SI->getTrueValue();
2155 Value *FV = SI->getFalseValue();
2158 // Can we fold the add into the argument of the select?
2159 // We check both true and false select arguments for a matching subtract.
2160 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2161 A == Other) // Fold the add into the true select value.
2162 return SelectInst::Create(SI->getCondition(), N, A);
2163 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2164 A == Other) // Fold the add into the false select value.
2165 return SelectInst::Create(SI->getCondition(), A, N);
2169 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2170 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2171 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2172 return ReplaceInstUsesWith(I, LHS);
2174 // Check for (add (sext x), y), see if we can merge this into an
2175 // integer add followed by a sext.
2176 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2177 // (add (sext x), cst) --> (sext (add x, cst'))
2178 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2180 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2181 if (LHSConv->hasOneUse() &&
2182 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2183 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2184 // Insert the new, smaller add.
2185 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2187 InsertNewInstBefore(NewAdd, I);
2188 return new SExtInst(NewAdd, I.getType());
2192 // (add (sext x), (sext y)) --> (sext (add int x, y))
2193 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2194 // Only do this if x/y have the same type, if at last one of them has a
2195 // single use (so we don't increase the number of sexts), and if the
2196 // integer add will not overflow.
2197 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2198 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2199 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2200 RHSConv->getOperand(0))) {
2201 // Insert the new integer add.
2202 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2203 RHSConv->getOperand(0),
2205 InsertNewInstBefore(NewAdd, I);
2206 return new SExtInst(NewAdd, I.getType());
2211 // Check for (add double (sitofp x), y), see if we can merge this into an
2212 // integer add followed by a promotion.
2213 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2214 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2215 // ... if the constant fits in the integer value. This is useful for things
2216 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2217 // requires a constant pool load, and generally allows the add to be better
2219 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2221 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2222 if (LHSConv->hasOneUse() &&
2223 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2224 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2225 // Insert the new integer add.
2226 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2228 InsertNewInstBefore(NewAdd, I);
2229 return new SIToFPInst(NewAdd, I.getType());
2233 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2234 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2235 // Only do this if x/y have the same type, if at last one of them has a
2236 // single use (so we don't increase the number of int->fp conversions),
2237 // and if the integer add will not overflow.
2238 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2239 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2240 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2241 RHSConv->getOperand(0))) {
2242 // Insert the new integer add.
2243 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2244 RHSConv->getOperand(0),
2246 InsertNewInstBefore(NewAdd, I);
2247 return new SIToFPInst(NewAdd, I.getType());
2252 return Changed ? &I : 0;
2255 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2256 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2258 if (Op0 == Op1) // sub X, X -> 0
2259 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2261 // If this is a 'B = x-(-A)', change to B = x+A...
2262 if (Value *V = dyn_castNegVal(Op1))
2263 return BinaryOperator::CreateAdd(Op0, V);
2265 if (isa<UndefValue>(Op0))
2266 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2267 if (isa<UndefValue>(Op1))
2268 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2270 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2271 // Replace (-1 - A) with (~A)...
2272 if (C->isAllOnesValue())
2273 return BinaryOperator::CreateNot(Op1);
2275 // C - ~X == X + (1+C)
2277 if (match(Op1, m_Not(m_Value(X))))
2278 return BinaryOperator::CreateAdd(X, AddOne(C));
2280 // -(X >>u 31) -> (X >>s 31)
2281 // -(X >>s 31) -> (X >>u 31)
2283 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2284 if (SI->getOpcode() == Instruction::LShr) {
2285 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2286 // Check to see if we are shifting out everything but the sign bit.
2287 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2288 SI->getType()->getPrimitiveSizeInBits()-1) {
2289 // Ok, the transformation is safe. Insert AShr.
2290 return BinaryOperator::Create(Instruction::AShr,
2291 SI->getOperand(0), CU, SI->getName());
2295 else if (SI->getOpcode() == Instruction::AShr) {
2296 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2297 // Check to see if we are shifting out everything but the sign bit.
2298 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2299 SI->getType()->getPrimitiveSizeInBits()-1) {
2300 // Ok, the transformation is safe. Insert LShr.
2301 return BinaryOperator::CreateLShr(
2302 SI->getOperand(0), CU, SI->getName());
2309 // Try to fold constant sub into select arguments.
2310 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2311 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2314 if (isa<PHINode>(Op0))
2315 if (Instruction *NV = FoldOpIntoPhi(I))
2319 if (I.getType() == Type::Int1Ty)
2320 return BinaryOperator::CreateXor(Op0, Op1);
2322 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2323 if (Op1I->getOpcode() == Instruction::Add &&
2324 !Op0->getType()->isFPOrFPVector()) {
2325 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2326 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2327 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2328 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2329 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2330 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2331 // C1-(X+C2) --> (C1-C2)-X
2332 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
2333 Op1I->getOperand(0));
2337 if (Op1I->hasOneUse()) {
2338 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2339 // is not used by anyone else...
2341 if (Op1I->getOpcode() == Instruction::Sub &&
2342 !Op1I->getType()->isFPOrFPVector()) {
2343 // Swap the two operands of the subexpr...
2344 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2345 Op1I->setOperand(0, IIOp1);
2346 Op1I->setOperand(1, IIOp0);
2348 // Create the new top level add instruction...
2349 return BinaryOperator::CreateAdd(Op0, Op1);
2352 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2354 if (Op1I->getOpcode() == Instruction::And &&
2355 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2356 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2359 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2360 return BinaryOperator::CreateAnd(Op0, NewNot);
2363 // 0 - (X sdiv C) -> (X sdiv -C)
2364 if (Op1I->getOpcode() == Instruction::SDiv)
2365 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2367 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2368 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2369 ConstantExpr::getNeg(DivRHS));
2371 // X - X*C --> X * (1-C)
2372 ConstantInt *C2 = 0;
2373 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2374 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2375 return BinaryOperator::CreateMul(Op0, CP1);
2378 // X - ((X / Y) * Y) --> X % Y
2379 if (Op1I->getOpcode() == Instruction::Mul)
2380 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2381 if (Op0 == I->getOperand(0) &&
2382 Op1I->getOperand(1) == I->getOperand(1)) {
2383 if (I->getOpcode() == Instruction::SDiv)
2384 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
2385 if (I->getOpcode() == Instruction::UDiv)
2386 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
2391 if (!Op0->getType()->isFPOrFPVector())
2392 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2393 if (Op0I->getOpcode() == Instruction::Add) {
2394 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2395 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2396 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2397 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2398 } else if (Op0I->getOpcode() == Instruction::Sub) {
2399 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2400 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2405 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2406 if (X == Op1) // X*C - X --> X * (C-1)
2407 return BinaryOperator::CreateMul(Op1, SubOne(C1));
2409 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2410 if (X == dyn_castFoldableMul(Op1, C2))
2411 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
2416 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2417 /// comparison only checks the sign bit. If it only checks the sign bit, set
2418 /// TrueIfSigned if the result of the comparison is true when the input value is
2420 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2421 bool &TrueIfSigned) {
2423 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2424 TrueIfSigned = true;
2425 return RHS->isZero();
2426 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2427 TrueIfSigned = true;
2428 return RHS->isAllOnesValue();
2429 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2430 TrueIfSigned = false;
2431 return RHS->isAllOnesValue();
2432 case ICmpInst::ICMP_UGT:
2433 // True if LHS u> RHS and RHS == high-bit-mask - 1
2434 TrueIfSigned = true;
2435 return RHS->getValue() ==
2436 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2437 case ICmpInst::ICMP_UGE:
2438 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2439 TrueIfSigned = true;
2440 return RHS->getValue().isSignBit();
2446 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2447 bool Changed = SimplifyCommutative(I);
2448 Value *Op0 = I.getOperand(0);
2450 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2451 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2453 // Simplify mul instructions with a constant RHS...
2454 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2455 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2457 // ((X << C1)*C2) == (X * (C2 << C1))
2458 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2459 if (SI->getOpcode() == Instruction::Shl)
2460 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2461 return BinaryOperator::CreateMul(SI->getOperand(0),
2462 ConstantExpr::getShl(CI, ShOp));
2465 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2466 if (CI->equalsInt(1)) // X * 1 == X
2467 return ReplaceInstUsesWith(I, Op0);
2468 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2469 return BinaryOperator::CreateNeg(Op0, I.getName());
2471 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2472 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2473 return BinaryOperator::CreateShl(Op0,
2474 ConstantInt::get(Op0->getType(), Val.logBase2()));
2476 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2477 if (Op1F->isNullValue())
2478 return ReplaceInstUsesWith(I, Op1);
2480 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2481 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2482 // We need a better interface for long double here.
2483 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2484 if (Op1F->isExactlyValue(1.0))
2485 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2488 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2489 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2490 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2491 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2492 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2494 InsertNewInstBefore(Add, I);
2495 Value *C1C2 = ConstantExpr::getMul(Op1,
2496 cast<Constant>(Op0I->getOperand(1)));
2497 return BinaryOperator::CreateAdd(Add, C1C2);
2501 // Try to fold constant mul into select arguments.
2502 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2503 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2506 if (isa<PHINode>(Op0))
2507 if (Instruction *NV = FoldOpIntoPhi(I))
2511 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2512 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2513 return BinaryOperator::CreateMul(Op0v, Op1v);
2515 if (I.getType() == Type::Int1Ty)
2516 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2518 // If one of the operands of the multiply is a cast from a boolean value, then
2519 // we know the bool is either zero or one, so this is a 'masking' multiply.
2520 // See if we can simplify things based on how the boolean was originally
2522 CastInst *BoolCast = 0;
2523 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2524 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2527 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2528 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2531 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2532 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2533 const Type *SCOpTy = SCIOp0->getType();
2536 // If the icmp is true iff the sign bit of X is set, then convert this
2537 // multiply into a shift/and combination.
2538 if (isa<ConstantInt>(SCIOp1) &&
2539 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2541 // Shift the X value right to turn it into "all signbits".
2542 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2543 SCOpTy->getPrimitiveSizeInBits()-1);
2545 InsertNewInstBefore(
2546 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2547 BoolCast->getOperand(0)->getName()+
2550 // If the multiply type is not the same as the source type, sign extend
2551 // or truncate to the multiply type.
2552 if (I.getType() != V->getType()) {
2553 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2554 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2555 Instruction::CastOps opcode =
2556 (SrcBits == DstBits ? Instruction::BitCast :
2557 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2558 V = InsertCastBefore(opcode, V, I.getType(), I);
2561 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2562 return BinaryOperator::CreateAnd(V, OtherOp);
2567 return Changed ? &I : 0;
2570 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2572 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2573 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2575 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2576 int NonNullOperand = -1;
2577 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2578 if (ST->isNullValue())
2580 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2581 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2582 if (ST->isNullValue())
2585 if (NonNullOperand == -1)
2588 Value *SelectCond = SI->getOperand(0);
2590 // Change the div/rem to use 'Y' instead of the select.
2591 I.setOperand(1, SI->getOperand(NonNullOperand));
2593 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2594 // problem. However, the select, or the condition of the select may have
2595 // multiple uses. Based on our knowledge that the operand must be non-zero,
2596 // propagate the known value for the select into other uses of it, and
2597 // propagate a known value of the condition into its other users.
2599 // If the select and condition only have a single use, don't bother with this,
2601 if (SI->use_empty() && SelectCond->hasOneUse())
2604 // Scan the current block backward, looking for other uses of SI.
2605 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2607 while (BBI != BBFront) {
2609 // If we found a call to a function, we can't assume it will return, so
2610 // information from below it cannot be propagated above it.
2611 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2614 // Replace uses of the select or its condition with the known values.
2615 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2618 *I = SI->getOperand(NonNullOperand);
2620 } else if (*I == SelectCond) {
2621 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2622 ConstantInt::getFalse();
2627 // If we past the instruction, quit looking for it.
2630 if (&*BBI == SelectCond)
2633 // If we ran out of things to eliminate, break out of the loop.
2634 if (SelectCond == 0 && SI == 0)
2642 /// This function implements the transforms on div instructions that work
2643 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2644 /// used by the visitors to those instructions.
2645 /// @brief Transforms common to all three div instructions
2646 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2647 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2649 // undef / X -> 0 for integer.
2650 // undef / X -> undef for FP (the undef could be a snan).
2651 if (isa<UndefValue>(Op0)) {
2652 if (Op0->getType()->isFPOrFPVector())
2653 return ReplaceInstUsesWith(I, Op0);
2654 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2657 // X / undef -> undef
2658 if (isa<UndefValue>(Op1))
2659 return ReplaceInstUsesWith(I, Op1);
2664 /// This function implements the transforms common to both integer division
2665 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2666 /// division instructions.
2667 /// @brief Common integer divide transforms
2668 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2669 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2671 // (sdiv X, X) --> 1 (udiv X, X) --> 1
2673 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2674 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2675 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2676 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2679 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2680 return ReplaceInstUsesWith(I, CI);
2683 if (Instruction *Common = commonDivTransforms(I))
2686 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2687 // This does not apply for fdiv.
2688 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2691 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2693 if (RHS->equalsInt(1))
2694 return ReplaceInstUsesWith(I, Op0);
2696 // (X / C1) / C2 -> X / (C1*C2)
2697 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2698 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2699 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2700 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2701 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2703 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2704 Multiply(RHS, LHSRHS));
2707 if (!RHS->isZero()) { // avoid X udiv 0
2708 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2709 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2711 if (isa<PHINode>(Op0))
2712 if (Instruction *NV = FoldOpIntoPhi(I))
2717 // 0 / X == 0, we don't need to preserve faults!
2718 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2719 if (LHS->equalsInt(0))
2720 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2722 // It can't be division by zero, hence it must be division by one.
2723 if (I.getType() == Type::Int1Ty)
2724 return ReplaceInstUsesWith(I, Op0);
2729 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2730 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2732 // Handle the integer div common cases
2733 if (Instruction *Common = commonIDivTransforms(I))
2736 // X udiv C^2 -> X >> C
2737 // Check to see if this is an unsigned division with an exact power of 2,
2738 // if so, convert to a right shift.
2739 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2740 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
2741 return BinaryOperator::CreateLShr(Op0,
2742 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2745 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2746 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2747 if (RHSI->getOpcode() == Instruction::Shl &&
2748 isa<ConstantInt>(RHSI->getOperand(0))) {
2749 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2750 if (C1.isPowerOf2()) {
2751 Value *N = RHSI->getOperand(1);
2752 const Type *NTy = N->getType();
2753 if (uint32_t C2 = C1.logBase2()) {
2754 Constant *C2V = ConstantInt::get(NTy, C2);
2755 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
2757 return BinaryOperator::CreateLShr(Op0, N);
2762 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2763 // where C1&C2 are powers of two.
2764 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2765 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2766 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2767 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2768 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2769 // Compute the shift amounts
2770 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2771 // Construct the "on true" case of the select
2772 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2773 Instruction *TSI = BinaryOperator::CreateLShr(
2774 Op0, TC, SI->getName()+".t");
2775 TSI = InsertNewInstBefore(TSI, I);
2777 // Construct the "on false" case of the select
2778 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2779 Instruction *FSI = BinaryOperator::CreateLShr(
2780 Op0, FC, SI->getName()+".f");
2781 FSI = InsertNewInstBefore(FSI, I);
2783 // construct the select instruction and return it.
2784 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
2790 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2791 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2793 // Handle the integer div common cases
2794 if (Instruction *Common = commonIDivTransforms(I))
2797 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2799 if (RHS->isAllOnesValue())
2800 return BinaryOperator::CreateNeg(Op0);
2803 if (Value *LHSNeg = dyn_castNegVal(Op0))
2804 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2807 // If the sign bits of both operands are zero (i.e. we can prove they are
2808 // unsigned inputs), turn this into a udiv.
2809 if (I.getType()->isInteger()) {
2810 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2811 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2812 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
2813 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
2820 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2821 return commonDivTransforms(I);
2824 /// This function implements the transforms on rem instructions that work
2825 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2826 /// is used by the visitors to those instructions.
2827 /// @brief Transforms common to all three rem instructions
2828 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2829 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2831 // 0 % X == 0 for integer, we don't need to preserve faults!
2832 if (Constant *LHS = dyn_cast<Constant>(Op0))
2833 if (LHS->isNullValue())
2834 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2836 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2837 if (I.getType()->isFPOrFPVector())
2838 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
2839 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2841 if (isa<UndefValue>(Op1))
2842 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2844 // Handle cases involving: rem X, (select Cond, Y, Z)
2845 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2851 /// This function implements the transforms common to both integer remainder
2852 /// instructions (urem and srem). It is called by the visitors to those integer
2853 /// remainder instructions.
2854 /// @brief Common integer remainder transforms
2855 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2856 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2858 if (Instruction *common = commonRemTransforms(I))
2861 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2862 // X % 0 == undef, we don't need to preserve faults!
2863 if (RHS->equalsInt(0))
2864 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2866 if (RHS->equalsInt(1)) // X % 1 == 0
2867 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2869 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2870 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2871 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2873 } else if (isa<PHINode>(Op0I)) {
2874 if (Instruction *NV = FoldOpIntoPhi(I))
2878 // See if we can fold away this rem instruction.
2879 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
2880 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2881 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2882 KnownZero, KnownOne))
2890 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2891 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2893 if (Instruction *common = commonIRemTransforms(I))
2896 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2897 // X urem C^2 -> X and C
2898 // Check to see if this is an unsigned remainder with an exact power of 2,
2899 // if so, convert to a bitwise and.
2900 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2901 if (C->getValue().isPowerOf2())
2902 return BinaryOperator::CreateAnd(Op0, SubOne(C));
2905 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2906 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2907 if (RHSI->getOpcode() == Instruction::Shl &&
2908 isa<ConstantInt>(RHSI->getOperand(0))) {
2909 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2910 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2911 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
2913 return BinaryOperator::CreateAnd(Op0, Add);
2918 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2919 // where C1&C2 are powers of two.
2920 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2921 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2922 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2923 // STO == 0 and SFO == 0 handled above.
2924 if ((STO->getValue().isPowerOf2()) &&
2925 (SFO->getValue().isPowerOf2())) {
2926 Value *TrueAnd = InsertNewInstBefore(
2927 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2928 Value *FalseAnd = InsertNewInstBefore(
2929 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2930 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
2938 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2939 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2941 // Handle the integer rem common cases
2942 if (Instruction *common = commonIRemTransforms(I))
2945 if (Value *RHSNeg = dyn_castNegVal(Op1))
2946 if (!isa<ConstantInt>(RHSNeg) ||
2947 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2949 AddUsesToWorkList(I);
2950 I.setOperand(1, RHSNeg);
2954 // If the sign bits of both operands are zero (i.e. we can prove they are
2955 // unsigned inputs), turn this into a urem.
2956 if (I.getType()->isInteger()) {
2957 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2958 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2959 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2960 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
2967 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2968 return commonRemTransforms(I);
2971 // isOneBitSet - Return true if there is exactly one bit set in the specified
2973 static bool isOneBitSet(const ConstantInt *CI) {
2974 return CI->getValue().isPowerOf2();
2977 // isHighOnes - Return true if the constant is of the form 1+0+.
2978 // This is the same as lowones(~X).
2979 static bool isHighOnes(const ConstantInt *CI) {
2980 return (~CI->getValue() + 1).isPowerOf2();
2983 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
2984 /// are carefully arranged to allow folding of expressions such as:
2986 /// (A < B) | (A > B) --> (A != B)
2988 /// Note that this is only valid if the first and second predicates have the
2989 /// same sign. Is illegal to do: (A u< B) | (A s> B)
2991 /// Three bits are used to represent the condition, as follows:
2996 /// <=> Value Definition
2997 /// 000 0 Always false
3004 /// 111 7 Always true
3006 static unsigned getICmpCode(const ICmpInst *ICI) {
3007 switch (ICI->getPredicate()) {
3009 case ICmpInst::ICMP_UGT: return 1; // 001
3010 case ICmpInst::ICMP_SGT: return 1; // 001
3011 case ICmpInst::ICMP_EQ: return 2; // 010
3012 case ICmpInst::ICMP_UGE: return 3; // 011
3013 case ICmpInst::ICMP_SGE: return 3; // 011
3014 case ICmpInst::ICMP_ULT: return 4; // 100
3015 case ICmpInst::ICMP_SLT: return 4; // 100
3016 case ICmpInst::ICMP_NE: return 5; // 101
3017 case ICmpInst::ICMP_ULE: return 6; // 110
3018 case ICmpInst::ICMP_SLE: return 6; // 110
3021 assert(0 && "Invalid ICmp predicate!");
3026 /// getICmpValue - This is the complement of getICmpCode, which turns an
3027 /// opcode and two operands into either a constant true or false, or a brand
3028 /// new ICmp instruction. The sign is passed in to determine which kind
3029 /// of predicate to use in new icmp instructions.
3030 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3032 default: assert(0 && "Illegal ICmp code!");
3033 case 0: return ConstantInt::getFalse();
3036 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3038 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3039 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3042 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3044 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3047 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3049 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3050 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3053 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3055 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3056 case 7: return ConstantInt::getTrue();
3060 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3061 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3062 (ICmpInst::isSignedPredicate(p1) &&
3063 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3064 (ICmpInst::isSignedPredicate(p2) &&
3065 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3069 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3070 struct FoldICmpLogical {
3073 ICmpInst::Predicate pred;
3074 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3075 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3076 pred(ICI->getPredicate()) {}
3077 bool shouldApply(Value *V) const {
3078 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3079 if (PredicatesFoldable(pred, ICI->getPredicate()))
3080 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3081 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3084 Instruction *apply(Instruction &Log) const {
3085 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3086 if (ICI->getOperand(0) != LHS) {
3087 assert(ICI->getOperand(1) == LHS);
3088 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3091 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3092 unsigned LHSCode = getICmpCode(ICI);
3093 unsigned RHSCode = getICmpCode(RHSICI);
3095 switch (Log.getOpcode()) {
3096 case Instruction::And: Code = LHSCode & RHSCode; break;
3097 case Instruction::Or: Code = LHSCode | RHSCode; break;
3098 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3099 default: assert(0 && "Illegal logical opcode!"); return 0;
3102 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3103 ICmpInst::isSignedPredicate(ICI->getPredicate());
3105 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3106 if (Instruction *I = dyn_cast<Instruction>(RV))
3108 // Otherwise, it's a constant boolean value...
3109 return IC.ReplaceInstUsesWith(Log, RV);
3112 } // end anonymous namespace
3114 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3115 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3116 // guaranteed to be a binary operator.
3117 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3119 ConstantInt *AndRHS,
3120 BinaryOperator &TheAnd) {
3121 Value *X = Op->getOperand(0);
3122 Constant *Together = 0;
3124 Together = And(AndRHS, OpRHS);
3126 switch (Op->getOpcode()) {
3127 case Instruction::Xor:
3128 if (Op->hasOneUse()) {
3129 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3130 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3131 InsertNewInstBefore(And, TheAnd);
3133 return BinaryOperator::CreateXor(And, Together);
3136 case Instruction::Or:
3137 if (Together == AndRHS) // (X | C) & C --> C
3138 return ReplaceInstUsesWith(TheAnd, AndRHS);
3140 if (Op->hasOneUse() && Together != OpRHS) {
3141 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3142 Instruction *Or = BinaryOperator::CreateOr(X, Together);
3143 InsertNewInstBefore(Or, TheAnd);
3145 return BinaryOperator::CreateAnd(Or, AndRHS);
3148 case Instruction::Add:
3149 if (Op->hasOneUse()) {
3150 // Adding a one to a single bit bit-field should be turned into an XOR
3151 // of the bit. First thing to check is to see if this AND is with a
3152 // single bit constant.
3153 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3155 // If there is only one bit set...
3156 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3157 // Ok, at this point, we know that we are masking the result of the
3158 // ADD down to exactly one bit. If the constant we are adding has
3159 // no bits set below this bit, then we can eliminate the ADD.
3160 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3162 // Check to see if any bits below the one bit set in AndRHSV are set.
3163 if ((AddRHS & (AndRHSV-1)) == 0) {
3164 // If not, the only thing that can effect the output of the AND is
3165 // the bit specified by AndRHSV. If that bit is set, the effect of
3166 // the XOR is to toggle the bit. If it is clear, then the ADD has
3168 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3169 TheAnd.setOperand(0, X);
3172 // Pull the XOR out of the AND.
3173 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3174 InsertNewInstBefore(NewAnd, TheAnd);
3175 NewAnd->takeName(Op);
3176 return BinaryOperator::CreateXor(NewAnd, AndRHS);
3183 case Instruction::Shl: {
3184 // We know that the AND will not produce any of the bits shifted in, so if
3185 // the anded constant includes them, clear them now!
3187 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3188 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3189 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3190 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3192 if (CI->getValue() == ShlMask) {
3193 // Masking out bits that the shift already masks
3194 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3195 } else if (CI != AndRHS) { // Reducing bits set in and.
3196 TheAnd.setOperand(1, CI);
3201 case Instruction::LShr:
3203 // We know that the AND will not produce any of the bits shifted in, so if
3204 // the anded constant includes them, clear them now! This only applies to
3205 // unsigned shifts, because a signed shr may bring in set bits!
3207 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3208 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3209 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3210 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3212 if (CI->getValue() == ShrMask) {
3213 // Masking out bits that the shift already masks.
3214 return ReplaceInstUsesWith(TheAnd, Op);
3215 } else if (CI != AndRHS) {
3216 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3221 case Instruction::AShr:
3223 // See if this is shifting in some sign extension, then masking it out
3225 if (Op->hasOneUse()) {
3226 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3227 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3228 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3229 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3230 if (C == AndRHS) { // Masking out bits shifted in.
3231 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3232 // Make the argument unsigned.
3233 Value *ShVal = Op->getOperand(0);
3234 ShVal = InsertNewInstBefore(
3235 BinaryOperator::CreateLShr(ShVal, OpRHS,
3236 Op->getName()), TheAnd);
3237 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3246 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3247 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3248 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3249 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3250 /// insert new instructions.
3251 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3252 bool isSigned, bool Inside,
3254 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3255 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3256 "Lo is not <= Hi in range emission code!");
3259 if (Lo == Hi) // Trivially false.
3260 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3262 // V >= Min && V < Hi --> V < Hi
3263 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3264 ICmpInst::Predicate pred = (isSigned ?
3265 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3266 return new ICmpInst(pred, V, Hi);
3269 // Emit V-Lo <u Hi-Lo
3270 Constant *NegLo = ConstantExpr::getNeg(Lo);
3271 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3272 InsertNewInstBefore(Add, IB);
3273 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3274 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3277 if (Lo == Hi) // Trivially true.
3278 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3280 // V < Min || V >= Hi -> V > Hi-1
3281 Hi = SubOne(cast<ConstantInt>(Hi));
3282 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3283 ICmpInst::Predicate pred = (isSigned ?
3284 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3285 return new ICmpInst(pred, V, Hi);
3288 // Emit V-Lo >u Hi-1-Lo
3289 // Note that Hi has already had one subtracted from it, above.
3290 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3291 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3292 InsertNewInstBefore(Add, IB);
3293 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3294 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3297 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3298 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3299 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3300 // not, since all 1s are not contiguous.
3301 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3302 const APInt& V = Val->getValue();
3303 uint32_t BitWidth = Val->getType()->getBitWidth();
3304 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3306 // look for the first zero bit after the run of ones
3307 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3308 // look for the first non-zero bit
3309 ME = V.getActiveBits();
3313 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3314 /// where isSub determines whether the operator is a sub. If we can fold one of
3315 /// the following xforms:
3317 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3318 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3319 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3321 /// return (A +/- B).
3323 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3324 ConstantInt *Mask, bool isSub,
3326 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3327 if (!LHSI || LHSI->getNumOperands() != 2 ||
3328 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3330 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3332 switch (LHSI->getOpcode()) {
3334 case Instruction::And:
3335 if (And(N, Mask) == Mask) {
3336 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3337 if ((Mask->getValue().countLeadingZeros() +
3338 Mask->getValue().countPopulation()) ==
3339 Mask->getValue().getBitWidth())
3342 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3343 // part, we don't need any explicit masks to take them out of A. If that
3344 // is all N is, ignore it.
3345 uint32_t MB = 0, ME = 0;
3346 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3347 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3348 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3349 if (MaskedValueIsZero(RHS, Mask))
3354 case Instruction::Or:
3355 case Instruction::Xor:
3356 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3357 if ((Mask->getValue().countLeadingZeros() +
3358 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3359 && And(N, Mask)->isZero())
3366 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3368 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3369 return InsertNewInstBefore(New, I);
3372 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3373 bool Changed = SimplifyCommutative(I);
3374 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3376 if (isa<UndefValue>(Op1)) // X & undef -> 0
3377 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3381 return ReplaceInstUsesWith(I, Op1);
3383 // See if we can simplify any instructions used by the instruction whose sole
3384 // purpose is to compute bits we don't care about.
3385 if (!isa<VectorType>(I.getType())) {
3386 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3387 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3388 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3389 KnownZero, KnownOne))
3392 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3393 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3394 return ReplaceInstUsesWith(I, I.getOperand(0));
3395 } else if (isa<ConstantAggregateZero>(Op1)) {
3396 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3400 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3401 const APInt& AndRHSMask = AndRHS->getValue();
3402 APInt NotAndRHS(~AndRHSMask);
3404 // Optimize a variety of ((val OP C1) & C2) combinations...
3405 if (isa<BinaryOperator>(Op0)) {
3406 Instruction *Op0I = cast<Instruction>(Op0);
3407 Value *Op0LHS = Op0I->getOperand(0);
3408 Value *Op0RHS = Op0I->getOperand(1);
3409 switch (Op0I->getOpcode()) {
3410 case Instruction::Xor:
3411 case Instruction::Or:
3412 // If the mask is only needed on one incoming arm, push it up.
3413 if (Op0I->hasOneUse()) {
3414 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3415 // Not masking anything out for the LHS, move to RHS.
3416 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3417 Op0RHS->getName()+".masked");
3418 InsertNewInstBefore(NewRHS, I);
3419 return BinaryOperator::Create(
3420 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3422 if (!isa<Constant>(Op0RHS) &&
3423 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3424 // Not masking anything out for the RHS, move to LHS.
3425 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
3426 Op0LHS->getName()+".masked");
3427 InsertNewInstBefore(NewLHS, I);
3428 return BinaryOperator::Create(
3429 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3434 case Instruction::Add:
3435 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3436 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3437 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3438 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3439 return BinaryOperator::CreateAnd(V, AndRHS);
3440 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3441 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
3444 case Instruction::Sub:
3445 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3446 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3447 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3448 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3449 return BinaryOperator::CreateAnd(V, AndRHS);
3451 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3452 // has 1's for all bits that the subtraction with A might affect.
3453 if (Op0I->hasOneUse()) {
3454 uint32_t BitWidth = AndRHSMask.getBitWidth();
3455 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3456 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3458 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
3459 if (!(A && A->isZero()) && // avoid infinite recursion.
3460 MaskedValueIsZero(Op0LHS, Mask)) {
3461 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3462 InsertNewInstBefore(NewNeg, I);
3463 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3468 case Instruction::Shl:
3469 case Instruction::LShr:
3470 // (1 << x) & 1 --> zext(x == 0)
3471 // (1 >> x) & 1 --> zext(x == 0)
3472 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
3473 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3474 Constant::getNullValue(I.getType()));
3475 InsertNewInstBefore(NewICmp, I);
3476 return new ZExtInst(NewICmp, I.getType());
3481 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3482 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3484 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3485 // If this is an integer truncation or change from signed-to-unsigned, and
3486 // if the source is an and/or with immediate, transform it. This
3487 // frequently occurs for bitfield accesses.
3488 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3489 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3490 CastOp->getNumOperands() == 2)
3491 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
3492 if (CastOp->getOpcode() == Instruction::And) {
3493 // Change: and (cast (and X, C1) to T), C2
3494 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3495 // This will fold the two constants together, which may allow
3496 // other simplifications.
3497 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
3498 CastOp->getOperand(0), I.getType(),
3499 CastOp->getName()+".shrunk");
3500 NewCast = InsertNewInstBefore(NewCast, I);
3501 // trunc_or_bitcast(C1)&C2
3502 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3503 C3 = ConstantExpr::getAnd(C3, AndRHS);
3504 return BinaryOperator::CreateAnd(NewCast, C3);
3505 } else if (CastOp->getOpcode() == Instruction::Or) {
3506 // Change: and (cast (or X, C1) to T), C2
3507 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3508 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3509 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3510 return ReplaceInstUsesWith(I, AndRHS);
3516 // Try to fold constant and into select arguments.
3517 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3518 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3520 if (isa<PHINode>(Op0))
3521 if (Instruction *NV = FoldOpIntoPhi(I))
3525 Value *Op0NotVal = dyn_castNotVal(Op0);
3526 Value *Op1NotVal = dyn_castNotVal(Op1);
3528 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3529 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3531 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3532 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3533 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
3534 I.getName()+".demorgan");
3535 InsertNewInstBefore(Or, I);
3536 return BinaryOperator::CreateNot(Or);
3540 Value *A = 0, *B = 0, *C = 0, *D = 0;
3541 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3542 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3543 return ReplaceInstUsesWith(I, Op1);
3545 // (A|B) & ~(A&B) -> A^B
3546 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3547 if ((A == C && B == D) || (A == D && B == C))
3548 return BinaryOperator::CreateXor(A, B);
3552 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3553 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3554 return ReplaceInstUsesWith(I, Op0);
3556 // ~(A&B) & (A|B) -> A^B
3557 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3558 if ((A == C && B == D) || (A == D && B == C))
3559 return BinaryOperator::CreateXor(A, B);
3563 if (Op0->hasOneUse() &&
3564 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3565 if (A == Op1) { // (A^B)&A -> A&(A^B)
3566 I.swapOperands(); // Simplify below
3567 std::swap(Op0, Op1);
3568 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3569 cast<BinaryOperator>(Op0)->swapOperands();
3570 I.swapOperands(); // Simplify below
3571 std::swap(Op0, Op1);
3574 if (Op1->hasOneUse() &&
3575 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3576 if (B == Op0) { // B&(A^B) -> B&(B^A)
3577 cast<BinaryOperator>(Op1)->swapOperands();
3580 if (A == Op0) { // A&(A^B) -> A & ~B
3581 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
3582 InsertNewInstBefore(NotB, I);
3583 return BinaryOperator::CreateAnd(A, NotB);
3589 { // (icmp ugt/ult A, C) & (icmp B, C) --> (icmp (A|B), C)
3590 // where C is a power of 2
3592 ConstantInt *C1, *C2;
3593 ICmpInst::Predicate LHSCC, RHSCC;
3594 if (match(&I, m_And(m_ICmp(LHSCC, m_Value(A), m_ConstantInt(C1)),
3595 m_ICmp(RHSCC, m_Value(B), m_ConstantInt(C2)))))
3596 if (C1 == C2 && LHSCC == RHSCC && C1->getValue().isPowerOf2() &&
3597 (LHSCC == ICmpInst::ICMP_ULT || LHSCC == ICmpInst::ICMP_UGT)) {
3598 Instruction *NewOr = BinaryOperator::CreateOr(A, B);
3599 InsertNewInstBefore(NewOr, I);
3600 return new ICmpInst(LHSCC, NewOr, C1);
3604 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3605 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3606 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3609 Value *LHSVal, *RHSVal;
3610 ConstantInt *LHSCst, *RHSCst;
3611 ICmpInst::Predicate LHSCC, RHSCC;
3612 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3613 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3614 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3615 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3616 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3617 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3618 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3619 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3621 // Don't try to fold ICMP_SLT + ICMP_ULT.
3622 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3623 ICmpInst::isSignedPredicate(LHSCC) ==
3624 ICmpInst::isSignedPredicate(RHSCC))) {
3625 // Ensure that the larger constant is on the RHS.
3626 ICmpInst::Predicate GT;
3627 if (ICmpInst::isSignedPredicate(LHSCC) ||
3628 (ICmpInst::isEquality(LHSCC) &&
3629 ICmpInst::isSignedPredicate(RHSCC)))
3630 GT = ICmpInst::ICMP_SGT;
3632 GT = ICmpInst::ICMP_UGT;
3634 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3635 ICmpInst *LHS = cast<ICmpInst>(Op0);
3636 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3637 std::swap(LHS, RHS);
3638 std::swap(LHSCst, RHSCst);
3639 std::swap(LHSCC, RHSCC);
3642 // At this point, we know we have have two icmp instructions
3643 // comparing a value against two constants and and'ing the result
3644 // together. Because of the above check, we know that we only have
3645 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3646 // (from the FoldICmpLogical check above), that the two constants
3647 // are not equal and that the larger constant is on the RHS
3648 assert(LHSCst != RHSCst && "Compares not folded above?");
3651 default: assert(0 && "Unknown integer condition code!");
3652 case ICmpInst::ICMP_EQ:
3654 default: assert(0 && "Unknown integer condition code!");
3655 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3656 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3657 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3658 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3659 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3660 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3661 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3662 return ReplaceInstUsesWith(I, LHS);
3664 case ICmpInst::ICMP_NE:
3666 default: assert(0 && "Unknown integer condition code!");
3667 case ICmpInst::ICMP_ULT:
3668 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3669 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3670 break; // (X != 13 & X u< 15) -> no change
3671 case ICmpInst::ICMP_SLT:
3672 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3673 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3674 break; // (X != 13 & X s< 15) -> no change
3675 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3676 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3677 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3678 return ReplaceInstUsesWith(I, RHS);
3679 case ICmpInst::ICMP_NE:
3680 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3681 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3682 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
3683 LHSVal->getName()+".off");
3684 InsertNewInstBefore(Add, I);
3685 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3686 ConstantInt::get(Add->getType(), 1));
3688 break; // (X != 13 & X != 15) -> no change
3691 case ICmpInst::ICMP_ULT:
3693 default: assert(0 && "Unknown integer condition code!");
3694 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3695 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3696 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3697 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3699 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3700 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3701 return ReplaceInstUsesWith(I, LHS);
3702 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3706 case ICmpInst::ICMP_SLT:
3708 default: assert(0 && "Unknown integer condition code!");
3709 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3710 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3711 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3712 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3714 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3715 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3716 return ReplaceInstUsesWith(I, LHS);
3717 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3721 case ICmpInst::ICMP_UGT:
3723 default: assert(0 && "Unknown integer condition code!");
3724 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3725 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3726 return ReplaceInstUsesWith(I, RHS);
3727 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3729 case ICmpInst::ICMP_NE:
3730 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3731 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3732 break; // (X u> 13 & X != 15) -> no change
3733 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3734 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3736 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3740 case ICmpInst::ICMP_SGT:
3742 default: assert(0 && "Unknown integer condition code!");
3743 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3744 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3745 return ReplaceInstUsesWith(I, RHS);
3746 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3748 case ICmpInst::ICMP_NE:
3749 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3750 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3751 break; // (X s> 13 & X != 15) -> no change
3752 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3753 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3755 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3763 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3764 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3765 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3766 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3767 const Type *SrcTy = Op0C->getOperand(0)->getType();
3768 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3769 // Only do this if the casts both really cause code to be generated.
3770 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3772 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3774 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
3775 Op1C->getOperand(0),
3777 InsertNewInstBefore(NewOp, I);
3778 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
3782 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3783 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3784 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3785 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
3786 SI0->getOperand(1) == SI1->getOperand(1) &&
3787 (SI0->hasOneUse() || SI1->hasOneUse())) {
3788 Instruction *NewOp =
3789 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
3791 SI0->getName()), I);
3792 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
3793 SI1->getOperand(1));
3797 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3798 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3799 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3800 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3801 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3802 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3803 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3804 // If either of the constants are nans, then the whole thing returns
3806 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3807 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3808 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3809 RHS->getOperand(0));
3814 return Changed ? &I : 0;
3817 /// CollectBSwapParts - Look to see if the specified value defines a single byte
3818 /// in the result. If it does, and if the specified byte hasn't been filled in
3819 /// yet, fill it in and return false.
3820 static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3821 Instruction *I = dyn_cast<Instruction>(V);
3822 if (I == 0) return true;
3824 // If this is an or instruction, it is an inner node of the bswap.
3825 if (I->getOpcode() == Instruction::Or)
3826 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3827 CollectBSwapParts(I->getOperand(1), ByteValues);
3829 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3830 // If this is a shift by a constant int, and it is "24", then its operand
3831 // defines a byte. We only handle unsigned types here.
3832 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3833 // Not shifting the entire input by N-1 bytes?
3834 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3835 8*(ByteValues.size()-1))
3839 if (I->getOpcode() == Instruction::Shl) {
3840 // X << 24 defines the top byte with the lowest of the input bytes.
3841 DestNo = ByteValues.size()-1;
3843 // X >>u 24 defines the low byte with the highest of the input bytes.
3847 // If the destination byte value is already defined, the values are or'd
3848 // together, which isn't a bswap (unless it's an or of the same bits).
3849 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3851 ByteValues[DestNo] = I->getOperand(0);
3855 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3857 Value *Shift = 0, *ShiftLHS = 0;
3858 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3859 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3860 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3862 Instruction *SI = cast<Instruction>(Shift);
3864 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3865 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3866 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3869 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3871 if (AndAmt->getValue().getActiveBits() > 64)
3873 uint64_t AndAmtVal = AndAmt->getZExtValue();
3874 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3875 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3877 // Unknown mask for bswap.
3878 if (DestByte == ByteValues.size()) return true;
3880 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3882 if (SI->getOpcode() == Instruction::Shl)
3883 SrcByte = DestByte - ShiftBytes;
3885 SrcByte = DestByte + ShiftBytes;
3887 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3888 if (SrcByte != ByteValues.size()-DestByte-1)
3891 // If the destination byte value is already defined, the values are or'd
3892 // together, which isn't a bswap (unless it's an or of the same bits).
3893 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3895 ByteValues[DestByte] = SI->getOperand(0);
3899 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3900 /// If so, insert the new bswap intrinsic and return it.
3901 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3902 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3903 if (!ITy || ITy->getBitWidth() % 16)
3904 return 0; // Can only bswap pairs of bytes. Can't do vectors.
3906 /// ByteValues - For each byte of the result, we keep track of which value
3907 /// defines each byte.
3908 SmallVector<Value*, 8> ByteValues;
3909 ByteValues.resize(ITy->getBitWidth()/8);
3911 // Try to find all the pieces corresponding to the bswap.
3912 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3913 CollectBSwapParts(I.getOperand(1), ByteValues))
3916 // Check to see if all of the bytes come from the same value.
3917 Value *V = ByteValues[0];
3918 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3920 // Check to make sure that all of the bytes come from the same value.
3921 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3922 if (ByteValues[i] != V)
3924 const Type *Tys[] = { ITy };
3925 Module *M = I.getParent()->getParent()->getParent();
3926 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
3927 return CallInst::Create(F, V);
3931 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3932 bool Changed = SimplifyCommutative(I);
3933 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3935 if (isa<UndefValue>(Op1)) // X | undef -> -1
3936 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3940 return ReplaceInstUsesWith(I, Op0);
3942 // See if we can simplify any instructions used by the instruction whose sole
3943 // purpose is to compute bits we don't care about.
3944 if (!isa<VectorType>(I.getType())) {
3945 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3946 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3947 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3948 KnownZero, KnownOne))
3950 } else if (isa<ConstantAggregateZero>(Op1)) {
3951 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3952 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3953 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3954 return ReplaceInstUsesWith(I, I.getOperand(1));
3960 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3961 ConstantInt *C1 = 0; Value *X = 0;
3962 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3963 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3964 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3965 InsertNewInstBefore(Or, I);
3967 return BinaryOperator::CreateAnd(Or,
3968 ConstantInt::get(RHS->getValue() | C1->getValue()));
3971 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3972 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3973 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
3974 InsertNewInstBefore(Or, I);
3976 return BinaryOperator::CreateXor(Or,
3977 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3980 // Try to fold constant and into select arguments.
3981 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3982 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3984 if (isa<PHINode>(Op0))
3985 if (Instruction *NV = FoldOpIntoPhi(I))
3989 Value *A = 0, *B = 0;
3990 ConstantInt *C1 = 0, *C2 = 0;
3992 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3993 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3994 return ReplaceInstUsesWith(I, Op1);
3995 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3996 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3997 return ReplaceInstUsesWith(I, Op0);
3999 // (A | B) | C and A | (B | C) -> bswap if possible.
4000 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4001 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4002 match(Op1, m_Or(m_Value(), m_Value())) ||
4003 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4004 match(Op1, m_Shift(m_Value(), m_Value())))) {
4005 if (Instruction *BSwap = MatchBSwap(I))
4009 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4010 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4011 MaskedValueIsZero(Op1, C1->getValue())) {
4012 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4013 InsertNewInstBefore(NOr, I);
4015 return BinaryOperator::CreateXor(NOr, C1);
4018 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4019 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4020 MaskedValueIsZero(Op0, C1->getValue())) {
4021 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4022 InsertNewInstBefore(NOr, I);
4024 return BinaryOperator::CreateXor(NOr, C1);
4028 Value *C = 0, *D = 0;
4029 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4030 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4031 Value *V1 = 0, *V2 = 0, *V3 = 0;
4032 C1 = dyn_cast<ConstantInt>(C);
4033 C2 = dyn_cast<ConstantInt>(D);
4034 if (C1 && C2) { // (A & C1)|(B & C2)
4035 // If we have: ((V + N) & C1) | (V & C2)
4036 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4037 // replace with V+N.
4038 if (C1->getValue() == ~C2->getValue()) {
4039 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4040 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4041 // Add commutes, try both ways.
4042 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4043 return ReplaceInstUsesWith(I, A);
4044 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4045 return ReplaceInstUsesWith(I, A);
4047 // Or commutes, try both ways.
4048 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4049 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4050 // Add commutes, try both ways.
4051 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4052 return ReplaceInstUsesWith(I, B);
4053 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4054 return ReplaceInstUsesWith(I, B);
4057 V1 = 0; V2 = 0; V3 = 0;
4060 // Check to see if we have any common things being and'ed. If so, find the
4061 // terms for V1 & (V2|V3).
4062 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4063 if (A == B) // (A & C)|(A & D) == A & (C|D)
4064 V1 = A, V2 = C, V3 = D;
4065 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4066 V1 = A, V2 = B, V3 = C;
4067 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4068 V1 = C, V2 = A, V3 = D;
4069 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4070 V1 = C, V2 = A, V3 = B;
4074 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4075 return BinaryOperator::CreateAnd(V1, Or);
4080 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4081 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4082 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4083 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4084 SI0->getOperand(1) == SI1->getOperand(1) &&
4085 (SI0->hasOneUse() || SI1->hasOneUse())) {
4086 Instruction *NewOp =
4087 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4089 SI0->getName()), I);
4090 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4091 SI1->getOperand(1));
4095 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4096 if (A == Op1) // ~A | A == -1
4097 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4101 // Note, A is still live here!
4102 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4104 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4106 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4107 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4108 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4109 I.getName()+".demorgan"), I);
4110 return BinaryOperator::CreateNot(And);
4114 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4115 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4116 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4119 Value *LHSVal, *RHSVal;
4120 ConstantInt *LHSCst, *RHSCst;
4121 ICmpInst::Predicate LHSCC, RHSCC;
4122 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4123 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4124 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4125 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4126 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4127 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4128 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4129 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4130 // We can't fold (ugt x, C) | (sgt x, C2).
4131 PredicatesFoldable(LHSCC, RHSCC)) {
4132 // Ensure that the larger constant is on the RHS.
4133 ICmpInst *LHS = cast<ICmpInst>(Op0);
4135 if (ICmpInst::isSignedPredicate(LHSCC))
4136 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4138 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4141 std::swap(LHS, RHS);
4142 std::swap(LHSCst, RHSCst);
4143 std::swap(LHSCC, RHSCC);
4146 // At this point, we know we have have two icmp instructions
4147 // comparing a value against two constants and or'ing the result
4148 // together. Because of the above check, we know that we only have
4149 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4150 // FoldICmpLogical check above), that the two constants are not
4152 assert(LHSCst != RHSCst && "Compares not folded above?");
4155 default: assert(0 && "Unknown integer condition code!");
4156 case ICmpInst::ICMP_EQ:
4158 default: assert(0 && "Unknown integer condition code!");
4159 case ICmpInst::ICMP_EQ:
4160 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4161 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4162 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
4163 LHSVal->getName()+".off");
4164 InsertNewInstBefore(Add, I);
4165 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4166 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4168 break; // (X == 13 | X == 15) -> no change
4169 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4170 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4172 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4173 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4174 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4175 return ReplaceInstUsesWith(I, RHS);
4178 case ICmpInst::ICMP_NE:
4180 default: assert(0 && "Unknown integer condition code!");
4181 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4182 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4183 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4184 return ReplaceInstUsesWith(I, LHS);
4185 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4186 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4187 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4188 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4191 case ICmpInst::ICMP_ULT:
4193 default: assert(0 && "Unknown integer condition code!");
4194 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4196 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
4197 // If RHSCst is [us]MAXINT, it is always false. Not handling
4198 // this can cause overflow.
4199 if (RHSCst->isMaxValue(false))
4200 return ReplaceInstUsesWith(I, LHS);
4201 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4203 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4205 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4206 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4207 return ReplaceInstUsesWith(I, RHS);
4208 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4212 case ICmpInst::ICMP_SLT:
4214 default: assert(0 && "Unknown integer condition code!");
4215 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4217 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
4218 // If RHSCst is [us]MAXINT, it is always false. Not handling
4219 // this can cause overflow.
4220 if (RHSCst->isMaxValue(true))
4221 return ReplaceInstUsesWith(I, LHS);
4222 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4224 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4226 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4227 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4228 return ReplaceInstUsesWith(I, RHS);
4229 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4233 case ICmpInst::ICMP_UGT:
4235 default: assert(0 && "Unknown integer condition code!");
4236 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4237 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4238 return ReplaceInstUsesWith(I, LHS);
4239 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4241 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4242 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4243 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4244 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4248 case ICmpInst::ICMP_SGT:
4250 default: assert(0 && "Unknown integer condition code!");
4251 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4252 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4253 return ReplaceInstUsesWith(I, LHS);
4254 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4256 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4257 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4258 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4259 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4267 // fold (or (cast A), (cast B)) -> (cast (or A, B))
4268 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4269 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4270 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4271 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4272 !isa<ICmpInst>(Op1C->getOperand(0))) {
4273 const Type *SrcTy = Op0C->getOperand(0)->getType();
4274 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4275 // Only do this if the casts both really cause code to be
4277 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4279 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4281 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4282 Op1C->getOperand(0),
4284 InsertNewInstBefore(NewOp, I);
4285 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4292 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4293 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4294 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4295 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4296 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4297 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
4298 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4299 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4300 // If either of the constants are nans, then the whole thing returns
4302 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4303 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4305 // Otherwise, no need to compare the two constants, compare the
4307 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4308 RHS->getOperand(0));
4313 return Changed ? &I : 0;
4318 // XorSelf - Implements: X ^ X --> 0
4321 XorSelf(Value *rhs) : RHS(rhs) {}
4322 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4323 Instruction *apply(BinaryOperator &Xor) const {
4330 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4331 bool Changed = SimplifyCommutative(I);
4332 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4334 if (isa<UndefValue>(Op1)) {
4335 if (isa<UndefValue>(Op0))
4336 // Handle undef ^ undef -> 0 special case. This is a common
4338 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4339 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4342 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4343 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4344 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4345 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4348 // See if we can simplify any instructions used by the instruction whose sole
4349 // purpose is to compute bits we don't care about.
4350 if (!isa<VectorType>(I.getType())) {
4351 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4352 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4353 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4354 KnownZero, KnownOne))
4356 } else if (isa<ConstantAggregateZero>(Op1)) {
4357 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4360 // Is this a ~ operation?
4361 if (Value *NotOp = dyn_castNotVal(&I)) {
4362 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4363 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4364 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4365 if (Op0I->getOpcode() == Instruction::And ||
4366 Op0I->getOpcode() == Instruction::Or) {
4367 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4368 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4370 BinaryOperator::CreateNot(Op0I->getOperand(1),
4371 Op0I->getOperand(1)->getName()+".not");
4372 InsertNewInstBefore(NotY, I);
4373 if (Op0I->getOpcode() == Instruction::And)
4374 return BinaryOperator::CreateOr(Op0NotVal, NotY);
4376 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
4383 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4384 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4385 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4386 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
4387 return new ICmpInst(ICI->getInversePredicate(),
4388 ICI->getOperand(0), ICI->getOperand(1));
4390 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4391 return new FCmpInst(FCI->getInversePredicate(),
4392 FCI->getOperand(0), FCI->getOperand(1));
4395 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4396 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4397 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4398 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4399 Instruction::CastOps Opcode = Op0C->getOpcode();
4400 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4401 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4402 Op0C->getDestTy())) {
4403 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4404 CI->getOpcode(), CI->getInversePredicate(),
4405 CI->getOperand(0), CI->getOperand(1)), I);
4406 NewCI->takeName(CI);
4407 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4414 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4415 // ~(c-X) == X-c-1 == X+(-c-1)
4416 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4417 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4418 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4419 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4420 ConstantInt::get(I.getType(), 1));
4421 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
4424 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
4425 if (Op0I->getOpcode() == Instruction::Add) {
4426 // ~(X-c) --> (-c-1)-X
4427 if (RHS->isAllOnesValue()) {
4428 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4429 return BinaryOperator::CreateSub(
4430 ConstantExpr::getSub(NegOp0CI,
4431 ConstantInt::get(I.getType(), 1)),
4432 Op0I->getOperand(0));
4433 } else if (RHS->getValue().isSignBit()) {
4434 // (X + C) ^ signbit -> (X + C + signbit)
4435 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4436 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
4439 } else if (Op0I->getOpcode() == Instruction::Or) {
4440 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4441 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4442 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4443 // Anything in both C1 and C2 is known to be zero, remove it from
4445 Constant *CommonBits = And(Op0CI, RHS);
4446 NewRHS = ConstantExpr::getAnd(NewRHS,
4447 ConstantExpr::getNot(CommonBits));
4448 AddToWorkList(Op0I);
4449 I.setOperand(0, Op0I->getOperand(0));
4450 I.setOperand(1, NewRHS);
4457 // Try to fold constant and into select arguments.
4458 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4459 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4461 if (isa<PHINode>(Op0))
4462 if (Instruction *NV = FoldOpIntoPhi(I))
4466 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4468 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4470 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4472 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4475 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4478 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4479 if (A == Op0) { // B^(B|A) == (A|B)^B
4480 Op1I->swapOperands();
4482 std::swap(Op0, Op1);
4483 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4484 I.swapOperands(); // Simplified below.
4485 std::swap(Op0, Op1);
4487 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4488 if (Op0 == A) // A^(A^B) == B
4489 return ReplaceInstUsesWith(I, B);
4490 else if (Op0 == B) // A^(B^A) == B
4491 return ReplaceInstUsesWith(I, A);
4492 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4493 if (A == Op0) { // A^(A&B) -> A^(B&A)
4494 Op1I->swapOperands();
4497 if (B == Op0) { // A^(B&A) -> (B&A)^A
4498 I.swapOperands(); // Simplified below.
4499 std::swap(Op0, Op1);
4504 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4507 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4508 if (A == Op1) // (B|A)^B == (A|B)^B
4510 if (B == Op1) { // (A|B)^B == A & ~B
4512 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4513 return BinaryOperator::CreateAnd(A, NotB);
4515 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4516 if (Op1 == A) // (A^B)^A == B
4517 return ReplaceInstUsesWith(I, B);
4518 else if (Op1 == B) // (B^A)^A == B
4519 return ReplaceInstUsesWith(I, A);
4520 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4521 if (A == Op1) // (A&B)^A -> (B&A)^A
4523 if (B == Op1 && // (B&A)^A == ~B & A
4524 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
4526 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4527 return BinaryOperator::CreateAnd(N, Op1);
4532 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4533 if (Op0I && Op1I && Op0I->isShift() &&
4534 Op0I->getOpcode() == Op1I->getOpcode() &&
4535 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4536 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4537 Instruction *NewOp =
4538 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
4539 Op1I->getOperand(0),
4540 Op0I->getName()), I);
4541 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
4542 Op1I->getOperand(1));
4546 Value *A, *B, *C, *D;
4547 // (A & B)^(A | B) -> A ^ B
4548 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4549 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4550 if ((A == C && B == D) || (A == D && B == C))
4551 return BinaryOperator::CreateXor(A, B);
4553 // (A | B)^(A & B) -> A ^ B
4554 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4555 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4556 if ((A == C && B == D) || (A == D && B == C))
4557 return BinaryOperator::CreateXor(A, B);
4561 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4562 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4563 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4564 // (X & Y)^(X & Y) -> (Y^Z) & X
4565 Value *X = 0, *Y = 0, *Z = 0;
4567 X = A, Y = B, Z = D;
4569 X = A, Y = B, Z = C;
4571 X = B, Y = A, Z = D;
4573 X = B, Y = A, Z = C;
4576 Instruction *NewOp =
4577 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4578 return BinaryOperator::CreateAnd(NewOp, X);
4583 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4584 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4585 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4588 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4589 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4590 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4591 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4592 const Type *SrcTy = Op0C->getOperand(0)->getType();
4593 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4594 // Only do this if the casts both really cause code to be generated.
4595 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4597 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4599 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
4600 Op1C->getOperand(0),
4602 InsertNewInstBefore(NewOp, I);
4603 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4608 return Changed ? &I : 0;
4611 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4612 /// overflowed for this type.
4613 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4614 ConstantInt *In2, bool IsSigned = false) {
4615 Result = cast<ConstantInt>(Add(In1, In2));
4618 if (In2->getValue().isNegative())
4619 return Result->getValue().sgt(In1->getValue());
4621 return Result->getValue().slt(In1->getValue());
4623 return Result->getValue().ult(In1->getValue());
4626 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4627 /// code necessary to compute the offset from the base pointer (without adding
4628 /// in the base pointer). Return the result as a signed integer of intptr size.
4629 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4630 TargetData &TD = IC.getTargetData();
4631 gep_type_iterator GTI = gep_type_begin(GEP);
4632 const Type *IntPtrTy = TD.getIntPtrType();
4633 Value *Result = Constant::getNullValue(IntPtrTy);
4635 // Build a mask for high order bits.
4636 unsigned IntPtrWidth = TD.getPointerSizeInBits();
4637 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4639 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
4642 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
4643 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4644 if (OpC->isZero()) continue;
4646 // Handle a struct index, which adds its field offset to the pointer.
4647 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4648 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4650 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4651 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4653 Result = IC.InsertNewInstBefore(
4654 BinaryOperator::CreateAdd(Result,
4655 ConstantInt::get(IntPtrTy, Size),
4656 GEP->getName()+".offs"), I);
4660 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4661 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4662 Scale = ConstantExpr::getMul(OC, Scale);
4663 if (Constant *RC = dyn_cast<Constant>(Result))
4664 Result = ConstantExpr::getAdd(RC, Scale);
4666 // Emit an add instruction.
4667 Result = IC.InsertNewInstBefore(
4668 BinaryOperator::CreateAdd(Result, Scale,
4669 GEP->getName()+".offs"), I);
4673 // Convert to correct type.
4674 if (Op->getType() != IntPtrTy) {
4675 if (Constant *OpC = dyn_cast<Constant>(Op))
4676 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4678 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4679 Op->getName()+".c"), I);
4682 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4683 if (Constant *OpC = dyn_cast<Constant>(Op))
4684 Op = ConstantExpr::getMul(OpC, Scale);
4685 else // We'll let instcombine(mul) convert this to a shl if possible.
4686 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
4687 GEP->getName()+".idx"), I);
4690 // Emit an add instruction.
4691 if (isa<Constant>(Op) && isa<Constant>(Result))
4692 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4693 cast<Constant>(Result));
4695 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
4696 GEP->getName()+".offs"), I);
4702 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
4703 /// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
4704 /// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
4705 /// complex, and scales are involved. The above expression would also be legal
4706 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
4707 /// later form is less amenable to optimization though, and we are allowed to
4708 /// generate the first by knowing that pointer arithmetic doesn't overflow.
4710 /// If we can't emit an optimized form for this expression, this returns null.
4712 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
4714 TargetData &TD = IC.getTargetData();
4715 gep_type_iterator GTI = gep_type_begin(GEP);
4717 // Check to see if this gep only has a single variable index. If so, and if
4718 // any constant indices are a multiple of its scale, then we can compute this
4719 // in terms of the scale of the variable index. For example, if the GEP
4720 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
4721 // because the expression will cross zero at the same point.
4722 unsigned i, e = GEP->getNumOperands();
4724 for (i = 1; i != e; ++i, ++GTI) {
4725 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
4726 // Compute the aggregate offset of constant indices.
4727 if (CI->isZero()) continue;
4729 // Handle a struct index, which adds its field offset to the pointer.
4730 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4731 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4733 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4734 Offset += Size*CI->getSExtValue();
4737 // Found our variable index.
4742 // If there are no variable indices, we must have a constant offset, just
4743 // evaluate it the general way.
4744 if (i == e) return 0;
4746 Value *VariableIdx = GEP->getOperand(i);
4747 // Determine the scale factor of the variable element. For example, this is
4748 // 4 if the variable index is into an array of i32.
4749 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
4751 // Verify that there are no other variable indices. If so, emit the hard way.
4752 for (++i, ++GTI; i != e; ++i, ++GTI) {
4753 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
4756 // Compute the aggregate offset of constant indices.
4757 if (CI->isZero()) continue;
4759 // Handle a struct index, which adds its field offset to the pointer.
4760 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4761 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
4763 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
4764 Offset += Size*CI->getSExtValue();
4768 // Okay, we know we have a single variable index, which must be a
4769 // pointer/array/vector index. If there is no offset, life is simple, return
4771 unsigned IntPtrWidth = TD.getPointerSizeInBits();
4773 // Cast to intptrty in case a truncation occurs. If an extension is needed,
4774 // we don't need to bother extending: the extension won't affect where the
4775 // computation crosses zero.
4776 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
4777 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
4778 VariableIdx->getNameStart(), &I);
4782 // Otherwise, there is an index. The computation we will do will be modulo
4783 // the pointer size, so get it.
4784 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4786 Offset &= PtrSizeMask;
4787 VariableScale &= PtrSizeMask;
4789 // To do this transformation, any constant index must be a multiple of the
4790 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
4791 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
4792 // multiple of the variable scale.
4793 int64_t NewOffs = Offset / (int64_t)VariableScale;
4794 if (Offset != NewOffs*(int64_t)VariableScale)
4797 // Okay, we can do this evaluation. Start by converting the index to intptr.
4798 const Type *IntPtrTy = TD.getIntPtrType();
4799 if (VariableIdx->getType() != IntPtrTy)
4800 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
4802 VariableIdx->getNameStart(), &I);
4803 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
4804 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
4808 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4809 /// else. At this point we know that the GEP is on the LHS of the comparison.
4810 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4811 ICmpInst::Predicate Cond,
4813 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4815 // Look through bitcasts.
4816 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
4817 RHS = BCI->getOperand(0);
4819 Value *PtrBase = GEPLHS->getOperand(0);
4820 if (PtrBase == RHS) {
4821 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4822 // This transformation (ignoring the base and scales) is valid because we
4823 // know pointers can't overflow. See if we can output an optimized form.
4824 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
4826 // If not, synthesize the offset the hard way.
4828 Offset = EmitGEPOffset(GEPLHS, I, *this);
4829 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4830 Constant::getNullValue(Offset->getType()));
4831 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4832 // If the base pointers are different, but the indices are the same, just
4833 // compare the base pointer.
4834 if (PtrBase != GEPRHS->getOperand(0)) {
4835 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4836 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4837 GEPRHS->getOperand(0)->getType();
4839 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4840 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4841 IndicesTheSame = false;
4845 // If all indices are the same, just compare the base pointers.
4847 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4848 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4850 // Otherwise, the base pointers are different and the indices are
4851 // different, bail out.
4855 // If one of the GEPs has all zero indices, recurse.
4856 bool AllZeros = true;
4857 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4858 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4859 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4864 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4865 ICmpInst::getSwappedPredicate(Cond), I);
4867 // If the other GEP has all zero indices, recurse.
4869 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4870 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4871 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4876 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4878 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4879 // If the GEPs only differ by one index, compare it.
4880 unsigned NumDifferences = 0; // Keep track of # differences.
4881 unsigned DiffOperand = 0; // The operand that differs.
4882 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4883 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4884 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4885 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4886 // Irreconcilable differences.
4890 if (NumDifferences++) break;
4895 if (NumDifferences == 0) // SAME GEP?
4896 return ReplaceInstUsesWith(I, // No comparison is needed here.
4897 ConstantInt::get(Type::Int1Ty,
4898 ICmpInst::isTrueWhenEqual(Cond)));
4900 else if (NumDifferences == 1) {
4901 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4902 Value *RHSV = GEPRHS->getOperand(DiffOperand);
4903 // Make sure we do a signed comparison here.
4904 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4908 // Only lower this if the icmp is the only user of the GEP or if we expect
4909 // the result to fold to a constant!
4910 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4911 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4912 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4913 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4914 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4915 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4921 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
4923 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
4926 if (!isa<ConstantFP>(RHSC)) return 0;
4927 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
4929 // Get the width of the mantissa. We don't want to hack on conversions that
4930 // might lose information from the integer, e.g. "i64 -> float"
4931 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
4932 if (MantissaWidth == -1) return 0; // Unknown.
4934 // Check to see that the input is converted from an integer type that is small
4935 // enough that preserves all bits. TODO: check here for "known" sign bits.
4936 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
4937 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
4939 // If this is a uitofp instruction, we need an extra bit to hold the sign.
4940 if (isa<UIToFPInst>(LHSI))
4943 // If the conversion would lose info, don't hack on this.
4944 if ((int)InputSize > MantissaWidth)
4947 // Otherwise, we can potentially simplify the comparison. We know that it
4948 // will always come through as an integer value and we know the constant is
4949 // not a NAN (it would have been previously simplified).
4950 assert(!RHS.isNaN() && "NaN comparison not already folded!");
4952 ICmpInst::Predicate Pred;
4953 switch (I.getPredicate()) {
4954 default: assert(0 && "Unexpected predicate!");
4955 case FCmpInst::FCMP_UEQ:
4956 case FCmpInst::FCMP_OEQ: Pred = ICmpInst::ICMP_EQ; break;
4957 case FCmpInst::FCMP_UGT:
4958 case FCmpInst::FCMP_OGT: Pred = ICmpInst::ICMP_SGT; break;
4959 case FCmpInst::FCMP_UGE:
4960 case FCmpInst::FCMP_OGE: Pred = ICmpInst::ICMP_SGE; break;
4961 case FCmpInst::FCMP_ULT:
4962 case FCmpInst::FCMP_OLT: Pred = ICmpInst::ICMP_SLT; break;
4963 case FCmpInst::FCMP_ULE:
4964 case FCmpInst::FCMP_OLE: Pred = ICmpInst::ICMP_SLE; break;
4965 case FCmpInst::FCMP_UNE:
4966 case FCmpInst::FCMP_ONE: Pred = ICmpInst::ICMP_NE; break;
4967 case FCmpInst::FCMP_ORD:
4968 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4969 case FCmpInst::FCMP_UNO:
4970 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4973 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
4975 // Now we know that the APFloat is a normal number, zero or inf.
4977 // See if the FP constant is too large for the integer. For example,
4978 // comparing an i8 to 300.0.
4979 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
4981 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
4982 // and large values.
4983 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
4984 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
4985 APFloat::rmNearestTiesToEven);
4986 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
4987 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
4988 Pred == ICmpInst::ICMP_SLE)
4989 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4990 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4993 // See if the RHS value is < SignedMin.
4994 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
4995 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
4996 APFloat::rmNearestTiesToEven);
4997 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
4998 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
4999 Pred == ICmpInst::ICMP_SGE)
5000 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5001 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5004 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] but
5005 // it may still be fractional. See if it is fractional by casting the FP
5006 // value to the integer value and back, checking for equality. Don't do this
5007 // for zero, because -0.0 is not fractional.
5008 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5009 if (!RHS.isZero() &&
5010 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
5011 // If we had a comparison against a fractional value, we have to adjust
5012 // the compare predicate and sometimes the value. RHSC is rounded towards
5013 // zero at this point.
5015 default: assert(0 && "Unexpected integer comparison!");
5016 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5017 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5018 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5019 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5020 case ICmpInst::ICMP_SLE:
5021 // (float)int <= 4.4 --> int <= 4
5022 // (float)int <= -4.4 --> int < -4
5023 if (RHS.isNegative())
5024 Pred = ICmpInst::ICMP_SLT;
5026 case ICmpInst::ICMP_SLT:
5027 // (float)int < -4.4 --> int < -4
5028 // (float)int < 4.4 --> int <= 4
5029 if (!RHS.isNegative())
5030 Pred = ICmpInst::ICMP_SLE;
5032 case ICmpInst::ICMP_SGT:
5033 // (float)int > 4.4 --> int > 4
5034 // (float)int > -4.4 --> int >= -4
5035 if (RHS.isNegative())
5036 Pred = ICmpInst::ICMP_SGE;
5038 case ICmpInst::ICMP_SGE:
5039 // (float)int >= -4.4 --> int >= -4
5040 // (float)int >= 4.4 --> int > 4
5041 if (!RHS.isNegative())
5042 Pred = ICmpInst::ICMP_SGT;
5047 // Lower this FP comparison into an appropriate integer version of the
5049 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5052 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5053 bool Changed = SimplifyCompare(I);
5054 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5056 // Fold trivial predicates.
5057 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5058 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5059 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5060 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5062 // Simplify 'fcmp pred X, X'
5064 switch (I.getPredicate()) {
5065 default: assert(0 && "Unknown predicate!");
5066 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5067 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5068 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5069 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5070 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5071 case FCmpInst::FCMP_OLT: // True if ordered and less than
5072 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5073 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5075 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5076 case FCmpInst::FCMP_ULT: // True if unordered or less than
5077 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5078 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5079 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5080 I.setPredicate(FCmpInst::FCMP_UNO);
5081 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5084 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5085 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5086 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5087 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5088 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5089 I.setPredicate(FCmpInst::FCMP_ORD);
5090 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5095 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5096 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5098 // Handle fcmp with constant RHS
5099 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5100 // If the constant is a nan, see if we can fold the comparison based on it.
5101 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5102 if (CFP->getValueAPF().isNaN()) {
5103 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5104 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5105 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5106 "Comparison must be either ordered or unordered!");
5107 // True if unordered.
5108 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5112 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5113 switch (LHSI->getOpcode()) {
5114 case Instruction::PHI:
5115 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5116 // block. If in the same block, we're encouraging jump threading. If
5117 // not, we are just pessimizing the code by making an i1 phi.
5118 if (LHSI->getParent() == I.getParent())
5119 if (Instruction *NV = FoldOpIntoPhi(I))
5122 case Instruction::SIToFP:
5123 case Instruction::UIToFP:
5124 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5127 case Instruction::Select:
5128 // If either operand of the select is a constant, we can fold the
5129 // comparison into the select arms, which will cause one to be
5130 // constant folded and the select turned into a bitwise or.
5131 Value *Op1 = 0, *Op2 = 0;
5132 if (LHSI->hasOneUse()) {
5133 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5134 // Fold the known value into the constant operand.
5135 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5136 // Insert a new FCmp of the other select operand.
5137 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5138 LHSI->getOperand(2), RHSC,
5140 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5141 // Fold the known value into the constant operand.
5142 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5143 // Insert a new FCmp of the other select operand.
5144 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5145 LHSI->getOperand(1), RHSC,
5151 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5156 return Changed ? &I : 0;
5159 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5160 bool Changed = SimplifyCompare(I);
5161 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5162 const Type *Ty = Op0->getType();
5166 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5167 I.isTrueWhenEqual()));
5169 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5170 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5172 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5173 // addresses never equal each other! We already know that Op0 != Op1.
5174 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5175 isa<ConstantPointerNull>(Op0)) &&
5176 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5177 isa<ConstantPointerNull>(Op1)))
5178 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5179 !I.isTrueWhenEqual()));
5181 // icmp's with boolean values can always be turned into bitwise operations
5182 if (Ty == Type::Int1Ty) {
5183 switch (I.getPredicate()) {
5184 default: assert(0 && "Invalid icmp instruction!");
5185 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
5186 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5187 InsertNewInstBefore(Xor, I);
5188 return BinaryOperator::CreateNot(Xor);
5190 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
5191 return BinaryOperator::CreateXor(Op0, Op1);
5193 case ICmpInst::ICMP_UGT:
5194 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
5196 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
5197 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5198 InsertNewInstBefore(Not, I);
5199 return BinaryOperator::CreateAnd(Not, Op1);
5201 case ICmpInst::ICMP_SGT:
5202 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
5204 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5205 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5206 InsertNewInstBefore(Not, I);
5207 return BinaryOperator::CreateAnd(Not, Op0);
5209 case ICmpInst::ICMP_UGE:
5210 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5212 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
5213 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5214 InsertNewInstBefore(Not, I);
5215 return BinaryOperator::CreateOr(Not, Op1);
5217 case ICmpInst::ICMP_SGE:
5218 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5220 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5221 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5222 InsertNewInstBefore(Not, I);
5223 return BinaryOperator::CreateOr(Not, Op0);
5228 // See if we are doing a comparison between a constant and an instruction that
5229 // can be folded into the comparison.
5230 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5233 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5234 if (I.isEquality() && CI->isNullValue() &&
5235 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5236 // (icmp cond A B) if cond is equality
5237 return new ICmpInst(I.getPredicate(), A, B);
5240 // If we have a icmp le or icmp ge instruction, turn it into the appropriate
5241 // icmp lt or icmp gt instruction. This allows us to rely on them being
5242 // folded in the code below.
5243 switch (I.getPredicate()) {
5245 case ICmpInst::ICMP_ULE:
5246 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5247 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5248 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5249 case ICmpInst::ICMP_SLE:
5250 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5251 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5252 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5253 case ICmpInst::ICMP_UGE:
5254 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5255 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5256 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5257 case ICmpInst::ICMP_SGE:
5258 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5259 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5260 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5263 // See if we can fold the comparison based on range information we can get
5264 // by checking whether bits are known to be zero or one in the input.
5265 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5266 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5268 // If this comparison is a normal comparison, it demands all
5269 // bits, if it is a sign bit comparison, it only demands the sign bit.
5271 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5273 if (SimplifyDemandedBits(Op0,
5274 isSignBit ? APInt::getSignBit(BitWidth)
5275 : APInt::getAllOnesValue(BitWidth),
5276 KnownZero, KnownOne, 0))
5279 // Given the known and unknown bits, compute a range that the LHS could be
5280 // in. Compute the Min, Max and RHS values based on the known bits. For the
5281 // EQ and NE we use unsigned values.
5282 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5283 if (ICmpInst::isSignedPredicate(I.getPredicate()))
5284 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5286 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5288 // If Min and Max are known to be the same, then SimplifyDemandedBits
5289 // figured out that the LHS is a constant. Just constant fold this now so
5290 // that code below can assume that Min != Max.
5292 return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5293 ConstantInt::get(Min),
5296 // Based on the range information we know about the LHS, see if we can
5297 // simplify this comparison. For example, (x&4) < 8 is always true.
5298 const APInt &RHSVal = CI->getValue();
5299 switch (I.getPredicate()) { // LE/GE have been folded already.
5300 default: assert(0 && "Unknown icmp opcode!");
5301 case ICmpInst::ICMP_EQ:
5302 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5303 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5305 case ICmpInst::ICMP_NE:
5306 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5307 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5309 case ICmpInst::ICMP_ULT:
5310 if (Max.ult(RHSVal)) // A <u C -> true iff max(A) < C
5311 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5312 if (Min.uge(RHSVal)) // A <u C -> false iff min(A) >= C
5313 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5314 if (RHSVal == Max) // A <u MAX -> A != MAX
5315 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5316 if (RHSVal == Min+1) // A <u MIN+1 -> A == MIN
5317 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5319 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5320 if (CI->isMinValue(true))
5321 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5322 ConstantInt::getAllOnesValue(Op0->getType()));
5324 case ICmpInst::ICMP_UGT:
5325 if (Min.ugt(RHSVal)) // A >u C -> true iff min(A) > C
5326 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5327 if (Max.ule(RHSVal)) // A >u C -> false iff max(A) <= C
5328 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5330 if (RHSVal == Min) // A >u MIN -> A != MIN
5331 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5332 if (RHSVal == Max-1) // A >u MAX-1 -> A == MAX
5333 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5335 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5336 if (CI->isMaxValue(true))
5337 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5338 ConstantInt::getNullValue(Op0->getType()));
5340 case ICmpInst::ICMP_SLT:
5341 if (Max.slt(RHSVal)) // A <s C -> true iff max(A) < C
5342 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5343 if (Min.sge(RHSVal)) // A <s C -> false iff min(A) >= C
5344 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5345 if (RHSVal == Max) // A <s MAX -> A != MAX
5346 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5347 if (RHSVal == Min+1) // A <s MIN+1 -> A == MIN
5348 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5350 case ICmpInst::ICMP_SGT:
5351 if (Min.sgt(RHSVal)) // A >s C -> true iff min(A) > C
5352 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5353 if (Max.sle(RHSVal)) // A >s C -> false iff max(A) <= C
5354 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5356 if (RHSVal == Min) // A >s MIN -> A != MIN
5357 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5358 if (RHSVal == Max-1) // A >s MAX-1 -> A == MAX
5359 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5363 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5364 // instruction, see if that instruction also has constants so that the
5365 // instruction can be folded into the icmp
5366 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5367 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5371 // Handle icmp with constant (but not simple integer constant) RHS
5372 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5373 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5374 switch (LHSI->getOpcode()) {
5375 case Instruction::GetElementPtr:
5376 if (RHSC->isNullValue()) {
5377 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5378 bool isAllZeros = true;
5379 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5380 if (!isa<Constant>(LHSI->getOperand(i)) ||
5381 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5386 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5387 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5391 case Instruction::PHI:
5392 // Only fold icmp into the PHI if the phi and fcmp are in the same
5393 // block. If in the same block, we're encouraging jump threading. If
5394 // not, we are just pessimizing the code by making an i1 phi.
5395 if (LHSI->getParent() == I.getParent())
5396 if (Instruction *NV = FoldOpIntoPhi(I))
5399 case Instruction::Select: {
5400 // If either operand of the select is a constant, we can fold the
5401 // comparison into the select arms, which will cause one to be
5402 // constant folded and the select turned into a bitwise or.
5403 Value *Op1 = 0, *Op2 = 0;
5404 if (LHSI->hasOneUse()) {
5405 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5406 // Fold the known value into the constant operand.
5407 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5408 // Insert a new ICmp of the other select operand.
5409 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5410 LHSI->getOperand(2), RHSC,
5412 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5413 // Fold the known value into the constant operand.
5414 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5415 // Insert a new ICmp of the other select operand.
5416 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5417 LHSI->getOperand(1), RHSC,
5423 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5426 case Instruction::Malloc:
5427 // If we have (malloc != null), and if the malloc has a single use, we
5428 // can assume it is successful and remove the malloc.
5429 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5430 AddToWorkList(LHSI);
5431 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5432 !I.isTrueWhenEqual()));
5438 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5439 if (User *GEP = dyn_castGetElementPtr(Op0))
5440 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5442 if (User *GEP = dyn_castGetElementPtr(Op1))
5443 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5444 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5447 // Test to see if the operands of the icmp are casted versions of other
5448 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5450 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5451 if (isa<PointerType>(Op0->getType()) &&
5452 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
5453 // We keep moving the cast from the left operand over to the right
5454 // operand, where it can often be eliminated completely.
5455 Op0 = CI->getOperand(0);
5457 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5458 // so eliminate it as well.
5459 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5460 Op1 = CI2->getOperand(0);
5462 // If Op1 is a constant, we can fold the cast into the constant.
5463 if (Op0->getType() != Op1->getType()) {
5464 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5465 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5467 // Otherwise, cast the RHS right before the icmp
5468 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
5471 return new ICmpInst(I.getPredicate(), Op0, Op1);
5475 if (isa<CastInst>(Op0)) {
5476 // Handle the special case of: icmp (cast bool to X), <cst>
5477 // This comes up when you have code like
5480 // For generality, we handle any zero-extension of any operand comparison
5481 // with a constant or another cast from the same type.
5482 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5483 if (Instruction *R = visitICmpInstWithCastAndCast(I))
5487 // See if it's the same type of instruction on the left and right.
5488 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5489 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
5490 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
5491 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
5493 switch (Op0I->getOpcode()) {
5495 case Instruction::Add:
5496 case Instruction::Sub:
5497 case Instruction::Xor:
5498 // a+x icmp eq/ne b+x --> a icmp b
5499 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
5500 Op1I->getOperand(0));
5502 case Instruction::Mul:
5503 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5504 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
5505 // Mask = -1 >> count-trailing-zeros(Cst).
5506 if (!CI->isZero() && !CI->isOne()) {
5507 const APInt &AP = CI->getValue();
5508 ConstantInt *Mask = ConstantInt::get(
5509 APInt::getLowBitsSet(AP.getBitWidth(),
5511 AP.countTrailingZeros()));
5512 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
5514 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
5516 InsertNewInstBefore(And1, I);
5517 InsertNewInstBefore(And2, I);
5518 return new ICmpInst(I.getPredicate(), And1, And2);
5527 // ~x < ~y --> y < x
5529 if (match(Op0, m_Not(m_Value(A))) &&
5530 match(Op1, m_Not(m_Value(B))))
5531 return new ICmpInst(I.getPredicate(), B, A);
5534 if (I.isEquality()) {
5535 Value *A, *B, *C, *D;
5537 // -x == -y --> x == y
5538 if (match(Op0, m_Neg(m_Value(A))) &&
5539 match(Op1, m_Neg(m_Value(B))))
5540 return new ICmpInst(I.getPredicate(), A, B);
5542 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5543 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5544 Value *OtherVal = A == Op1 ? B : A;
5545 return new ICmpInst(I.getPredicate(), OtherVal,
5546 Constant::getNullValue(A->getType()));
5549 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5550 // A^c1 == C^c2 --> A == C^(c1^c2)
5551 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5552 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5553 if (Op1->hasOneUse()) {
5554 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5555 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
5556 return new ICmpInst(I.getPredicate(), A,
5557 InsertNewInstBefore(Xor, I));
5560 // A^B == A^D -> B == D
5561 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5562 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5563 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5564 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5568 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5569 (A == Op0 || B == Op0)) {
5570 // A == (A^B) -> B == 0
5571 Value *OtherVal = A == Op0 ? B : A;
5572 return new ICmpInst(I.getPredicate(), OtherVal,
5573 Constant::getNullValue(A->getType()));
5575 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5576 // (A-B) == A -> B == 0
5577 return new ICmpInst(I.getPredicate(), B,
5578 Constant::getNullValue(B->getType()));
5580 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5581 // A == (A-B) -> B == 0
5582 return new ICmpInst(I.getPredicate(), B,
5583 Constant::getNullValue(B->getType()));
5586 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5587 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5588 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5589 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5590 Value *X = 0, *Y = 0, *Z = 0;
5593 X = B; Y = D; Z = A;
5594 } else if (A == D) {
5595 X = B; Y = C; Z = A;
5596 } else if (B == C) {
5597 X = A; Y = D; Z = B;
5598 } else if (B == D) {
5599 X = A; Y = C; Z = B;
5602 if (X) { // Build (X^Y) & Z
5603 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5604 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
5605 I.setOperand(0, Op1);
5606 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5611 return Changed ? &I : 0;
5615 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5616 /// and CmpRHS are both known to be integer constants.
5617 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5618 ConstantInt *DivRHS) {
5619 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5620 const APInt &CmpRHSV = CmpRHS->getValue();
5622 // FIXME: If the operand types don't match the type of the divide
5623 // then don't attempt this transform. The code below doesn't have the
5624 // logic to deal with a signed divide and an unsigned compare (and
5625 // vice versa). This is because (x /s C1) <s C2 produces different
5626 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5627 // (x /u C1) <u C2. Simply casting the operands and result won't
5628 // work. :( The if statement below tests that condition and bails
5630 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5631 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5633 if (DivRHS->isZero())
5634 return 0; // The ProdOV computation fails on divide by zero.
5636 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5637 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5638 // C2 (CI). By solving for X we can turn this into a range check
5639 // instead of computing a divide.
5640 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5642 // Determine if the product overflows by seeing if the product is
5643 // not equal to the divide. Make sure we do the same kind of divide
5644 // as in the LHS instruction that we're folding.
5645 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5646 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5648 // Get the ICmp opcode
5649 ICmpInst::Predicate Pred = ICI.getPredicate();
5651 // Figure out the interval that is being checked. For example, a comparison
5652 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5653 // Compute this interval based on the constants involved and the signedness of
5654 // the compare/divide. This computes a half-open interval, keeping track of
5655 // whether either value in the interval overflows. After analysis each
5656 // overflow variable is set to 0 if it's corresponding bound variable is valid
5657 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5658 int LoOverflow = 0, HiOverflow = 0;
5659 ConstantInt *LoBound = 0, *HiBound = 0;
5662 if (!DivIsSigned) { // udiv
5663 // e.g. X/5 op 3 --> [15, 20)
5665 HiOverflow = LoOverflow = ProdOV;
5667 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5668 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
5669 if (CmpRHSV == 0) { // (X / pos) op 0
5670 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
5671 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5673 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
5674 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5675 HiOverflow = LoOverflow = ProdOV;
5677 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5678 } else { // (X / pos) op neg
5679 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
5680 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5681 LoOverflow = AddWithOverflow(LoBound, Prod,
5682 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5683 HiBound = AddOne(Prod);
5684 HiOverflow = ProdOV ? -1 : 0;
5686 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
5687 if (CmpRHSV == 0) { // (X / neg) op 0
5688 // e.g. X/-5 op 0 --> [-4, 5)
5689 LoBound = AddOne(DivRHS);
5690 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5691 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5692 HiOverflow = 1; // [INTMIN+1, overflow)
5693 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5695 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
5696 // e.g. X/-5 op 3 --> [-19, -14)
5697 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5699 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5700 HiBound = AddOne(Prod);
5701 } else { // (X / neg) op neg
5702 // e.g. X/-5 op -3 --> [15, 20)
5704 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5705 HiBound = Subtract(Prod, DivRHS);
5708 // Dividing by a negative swaps the condition. LT <-> GT
5709 Pred = ICmpInst::getSwappedPredicate(Pred);
5712 Value *X = DivI->getOperand(0);
5714 default: assert(0 && "Unhandled icmp opcode!");
5715 case ICmpInst::ICMP_EQ:
5716 if (LoOverflow && HiOverflow)
5717 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5718 else if (HiOverflow)
5719 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5720 ICmpInst::ICMP_UGE, X, LoBound);
5721 else if (LoOverflow)
5722 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5723 ICmpInst::ICMP_ULT, X, HiBound);
5725 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5726 case ICmpInst::ICMP_NE:
5727 if (LoOverflow && HiOverflow)
5728 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5729 else if (HiOverflow)
5730 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5731 ICmpInst::ICMP_ULT, X, LoBound);
5732 else if (LoOverflow)
5733 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5734 ICmpInst::ICMP_UGE, X, HiBound);
5736 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5737 case ICmpInst::ICMP_ULT:
5738 case ICmpInst::ICMP_SLT:
5739 if (LoOverflow == +1) // Low bound is greater than input range.
5740 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5741 if (LoOverflow == -1) // Low bound is less than input range.
5742 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5743 return new ICmpInst(Pred, X, LoBound);
5744 case ICmpInst::ICMP_UGT:
5745 case ICmpInst::ICMP_SGT:
5746 if (HiOverflow == +1) // High bound greater than input range.
5747 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5748 else if (HiOverflow == -1) // High bound less than input range.
5749 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5750 if (Pred == ICmpInst::ICMP_UGT)
5751 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5753 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5758 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5760 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5763 const APInt &RHSV = RHS->getValue();
5765 switch (LHSI->getOpcode()) {
5766 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
5767 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5768 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5770 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5771 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
5772 Value *CompareVal = LHSI->getOperand(0);
5774 // If the sign bit of the XorCST is not set, there is no change to
5775 // the operation, just stop using the Xor.
5776 if (!XorCST->getValue().isNegative()) {
5777 ICI.setOperand(0, CompareVal);
5778 AddToWorkList(LHSI);
5782 // Was the old condition true if the operand is positive?
5783 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5785 // If so, the new one isn't.
5786 isTrueIfPositive ^= true;
5788 if (isTrueIfPositive)
5789 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5791 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5795 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5796 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5797 LHSI->getOperand(0)->hasOneUse()) {
5798 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5800 // If the LHS is an AND of a truncating cast, we can widen the
5801 // and/compare to be the input width without changing the value
5802 // produced, eliminating a cast.
5803 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5804 // We can do this transformation if either the AND constant does not
5805 // have its sign bit set or if it is an equality comparison.
5806 // Extending a relational comparison when we're checking the sign
5807 // bit would not work.
5808 if (Cast->hasOneUse() &&
5809 (ICI.isEquality() ||
5810 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
5812 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5813 APInt NewCST = AndCST->getValue();
5814 NewCST.zext(BitWidth);
5816 NewCI.zext(BitWidth);
5817 Instruction *NewAnd =
5818 BinaryOperator::CreateAnd(Cast->getOperand(0),
5819 ConstantInt::get(NewCST),LHSI->getName());
5820 InsertNewInstBefore(NewAnd, ICI);
5821 return new ICmpInst(ICI.getPredicate(), NewAnd,
5822 ConstantInt::get(NewCI));
5826 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5827 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5828 // happens a LOT in code produced by the C front-end, for bitfield
5830 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5831 if (Shift && !Shift->isShift())
5835 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5836 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5837 const Type *AndTy = AndCST->getType(); // Type of the and.
5839 // We can fold this as long as we can't shift unknown bits
5840 // into the mask. This can only happen with signed shift
5841 // rights, as they sign-extend.
5843 bool CanFold = Shift->isLogicalShift();
5845 // To test for the bad case of the signed shr, see if any
5846 // of the bits shifted in could be tested after the mask.
5847 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5848 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5850 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5851 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5852 AndCST->getValue()) == 0)
5858 if (Shift->getOpcode() == Instruction::Shl)
5859 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5861 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5863 // Check to see if we are shifting out any of the bits being
5865 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5866 // If we shifted bits out, the fold is not going to work out.
5867 // As a special case, check to see if this means that the
5868 // result is always true or false now.
5869 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5870 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5871 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5872 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5874 ICI.setOperand(1, NewCst);
5875 Constant *NewAndCST;
5876 if (Shift->getOpcode() == Instruction::Shl)
5877 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5879 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5880 LHSI->setOperand(1, NewAndCST);
5881 LHSI->setOperand(0, Shift->getOperand(0));
5882 AddToWorkList(Shift); // Shift is dead.
5883 AddUsesToWorkList(ICI);
5889 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5890 // preferable because it allows the C<<Y expression to be hoisted out
5891 // of a loop if Y is invariant and X is not.
5892 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5893 ICI.isEquality() && !Shift->isArithmeticShift() &&
5894 isa<Instruction>(Shift->getOperand(0))) {
5897 if (Shift->getOpcode() == Instruction::LShr) {
5898 NS = BinaryOperator::CreateShl(AndCST,
5899 Shift->getOperand(1), "tmp");
5901 // Insert a logical shift.
5902 NS = BinaryOperator::CreateLShr(AndCST,
5903 Shift->getOperand(1), "tmp");
5905 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5907 // Compute X & (C << Y).
5908 Instruction *NewAnd =
5909 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
5910 InsertNewInstBefore(NewAnd, ICI);
5912 ICI.setOperand(0, NewAnd);
5918 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5919 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5922 uint32_t TypeBits = RHSV.getBitWidth();
5924 // Check that the shift amount is in range. If not, don't perform
5925 // undefined shifts. When the shift is visited it will be
5927 if (ShAmt->uge(TypeBits))
5930 if (ICI.isEquality()) {
5931 // If we are comparing against bits always shifted out, the
5932 // comparison cannot succeed.
5934 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5935 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5936 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5937 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5938 return ReplaceInstUsesWith(ICI, Cst);
5941 if (LHSI->hasOneUse()) {
5942 // Otherwise strength reduce the shift into an and.
5943 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5945 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5948 BinaryOperator::CreateAnd(LHSI->getOperand(0),
5949 Mask, LHSI->getName()+".mask");
5950 Value *And = InsertNewInstBefore(AndI, ICI);
5951 return new ICmpInst(ICI.getPredicate(), And,
5952 ConstantInt::get(RHSV.lshr(ShAmtVal)));
5956 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5957 bool TrueIfSigned = false;
5958 if (LHSI->hasOneUse() &&
5959 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5960 // (X << 31) <s 0 --> (X&1) != 0
5961 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5962 (TypeBits-ShAmt->getZExtValue()-1));
5964 BinaryOperator::CreateAnd(LHSI->getOperand(0),
5965 Mask, LHSI->getName()+".mask");
5966 Value *And = InsertNewInstBefore(AndI, ICI);
5968 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5969 And, Constant::getNullValue(And->getType()));
5974 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
5975 case Instruction::AShr: {
5976 // Only handle equality comparisons of shift-by-constant.
5977 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5978 if (!ShAmt || !ICI.isEquality()) break;
5980 // Check that the shift amount is in range. If not, don't perform
5981 // undefined shifts. When the shift is visited it will be
5983 uint32_t TypeBits = RHSV.getBitWidth();
5984 if (ShAmt->uge(TypeBits))
5987 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5989 // If we are comparing against bits always shifted out, the
5990 // comparison cannot succeed.
5991 APInt Comp = RHSV << ShAmtVal;
5992 if (LHSI->getOpcode() == Instruction::LShr)
5993 Comp = Comp.lshr(ShAmtVal);
5995 Comp = Comp.ashr(ShAmtVal);
5997 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5998 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5999 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6000 return ReplaceInstUsesWith(ICI, Cst);
6003 // Otherwise, check to see if the bits shifted out are known to be zero.
6004 // If so, we can compare against the unshifted value:
6005 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
6006 if (LHSI->hasOneUse() &&
6007 MaskedValueIsZero(LHSI->getOperand(0),
6008 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6009 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6010 ConstantExpr::getShl(RHS, ShAmt));
6013 if (LHSI->hasOneUse()) {
6014 // Otherwise strength reduce the shift into an and.
6015 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6016 Constant *Mask = ConstantInt::get(Val);
6019 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6020 Mask, LHSI->getName()+".mask");
6021 Value *And = InsertNewInstBefore(AndI, ICI);
6022 return new ICmpInst(ICI.getPredicate(), And,
6023 ConstantExpr::getShl(RHS, ShAmt));
6028 case Instruction::SDiv:
6029 case Instruction::UDiv:
6030 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6031 // Fold this div into the comparison, producing a range check.
6032 // Determine, based on the divide type, what the range is being
6033 // checked. If there is an overflow on the low or high side, remember
6034 // it, otherwise compute the range [low, hi) bounding the new value.
6035 // See: InsertRangeTest above for the kinds of replacements possible.
6036 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6037 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6042 case Instruction::Add:
6043 // Fold: icmp pred (add, X, C1), C2
6045 if (!ICI.isEquality()) {
6046 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6048 const APInt &LHSV = LHSC->getValue();
6050 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6053 if (ICI.isSignedPredicate()) {
6054 if (CR.getLower().isSignBit()) {
6055 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6056 ConstantInt::get(CR.getUpper()));
6057 } else if (CR.getUpper().isSignBit()) {
6058 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6059 ConstantInt::get(CR.getLower()));
6062 if (CR.getLower().isMinValue()) {
6063 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6064 ConstantInt::get(CR.getUpper()));
6065 } else if (CR.getUpper().isMinValue()) {
6066 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6067 ConstantInt::get(CR.getLower()));
6074 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6075 if (ICI.isEquality()) {
6076 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6078 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6079 // the second operand is a constant, simplify a bit.
6080 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6081 switch (BO->getOpcode()) {
6082 case Instruction::SRem:
6083 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6084 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6085 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6086 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6087 Instruction *NewRem =
6088 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
6090 InsertNewInstBefore(NewRem, ICI);
6091 return new ICmpInst(ICI.getPredicate(), NewRem,
6092 Constant::getNullValue(BO->getType()));
6096 case Instruction::Add:
6097 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6098 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6099 if (BO->hasOneUse())
6100 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6101 Subtract(RHS, BOp1C));
6102 } else if (RHSV == 0) {
6103 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6104 // efficiently invertible, or if the add has just this one use.
6105 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6107 if (Value *NegVal = dyn_castNegVal(BOp1))
6108 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6109 else if (Value *NegVal = dyn_castNegVal(BOp0))
6110 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6111 else if (BO->hasOneUse()) {
6112 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
6113 InsertNewInstBefore(Neg, ICI);
6115 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6119 case Instruction::Xor:
6120 // For the xor case, we can xor two constants together, eliminating
6121 // the explicit xor.
6122 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6123 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6124 ConstantExpr::getXor(RHS, BOC));
6127 case Instruction::Sub:
6128 // Replace (([sub|xor] A, B) != 0) with (A != B)
6130 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6134 case Instruction::Or:
6135 // If bits are being or'd in that are not present in the constant we
6136 // are comparing against, then the comparison could never succeed!
6137 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6138 Constant *NotCI = ConstantExpr::getNot(RHS);
6139 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6140 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6145 case Instruction::And:
6146 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6147 // If bits are being compared against that are and'd out, then the
6148 // comparison can never succeed!
6149 if ((RHSV & ~BOC->getValue()) != 0)
6150 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6153 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6154 if (RHS == BOC && RHSV.isPowerOf2())
6155 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6156 ICmpInst::ICMP_NE, LHSI,
6157 Constant::getNullValue(RHS->getType()));
6159 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6160 if (BOC->getValue().isSignBit()) {
6161 Value *X = BO->getOperand(0);
6162 Constant *Zero = Constant::getNullValue(X->getType());
6163 ICmpInst::Predicate pred = isICMP_NE ?
6164 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6165 return new ICmpInst(pred, X, Zero);
6168 // ((X & ~7) == 0) --> X < 8
6169 if (RHSV == 0 && isHighOnes(BOC)) {
6170 Value *X = BO->getOperand(0);
6171 Constant *NegX = ConstantExpr::getNeg(BOC);
6172 ICmpInst::Predicate pred = isICMP_NE ?
6173 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6174 return new ICmpInst(pred, X, NegX);
6179 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6180 // Handle icmp {eq|ne} <intrinsic>, intcst.
6181 if (II->getIntrinsicID() == Intrinsic::bswap) {
6183 ICI.setOperand(0, II->getOperand(1));
6184 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6188 } else { // Not a ICMP_EQ/ICMP_NE
6189 // If the LHS is a cast from an integral value of the same size,
6190 // then since we know the RHS is a constant, try to simlify.
6191 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6192 Value *CastOp = Cast->getOperand(0);
6193 const Type *SrcTy = CastOp->getType();
6194 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6195 if (SrcTy->isInteger() &&
6196 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6197 // If this is an unsigned comparison, try to make the comparison use
6198 // smaller constant values.
6199 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6200 // X u< 128 => X s> -1
6201 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6202 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6203 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6204 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6205 // X u> 127 => X s< 0
6206 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6207 Constant::getNullValue(SrcTy));
6215 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6216 /// We only handle extending casts so far.
6218 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6219 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6220 Value *LHSCIOp = LHSCI->getOperand(0);
6221 const Type *SrcTy = LHSCIOp->getType();
6222 const Type *DestTy = LHSCI->getType();
6225 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6226 // integer type is the same size as the pointer type.
6227 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6228 getTargetData().getPointerSizeInBits() ==
6229 cast<IntegerType>(DestTy)->getBitWidth()) {
6231 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6232 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6233 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6234 RHSOp = RHSC->getOperand(0);
6235 // If the pointer types don't match, insert a bitcast.
6236 if (LHSCIOp->getType() != RHSOp->getType())
6237 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
6241 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6244 // The code below only handles extension cast instructions, so far.
6246 if (LHSCI->getOpcode() != Instruction::ZExt &&
6247 LHSCI->getOpcode() != Instruction::SExt)
6250 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6251 bool isSignedCmp = ICI.isSignedPredicate();
6253 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6254 // Not an extension from the same type?
6255 RHSCIOp = CI->getOperand(0);
6256 if (RHSCIOp->getType() != LHSCIOp->getType())
6259 // If the signedness of the two casts doesn't agree (i.e. one is a sext
6260 // and the other is a zext), then we can't handle this.
6261 if (CI->getOpcode() != LHSCI->getOpcode())
6264 // Deal with equality cases early.
6265 if (ICI.isEquality())
6266 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6268 // A signed comparison of sign extended values simplifies into a
6269 // signed comparison.
6270 if (isSignedCmp && isSignedExt)
6271 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6273 // The other three cases all fold into an unsigned comparison.
6274 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
6277 // If we aren't dealing with a constant on the RHS, exit early
6278 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6282 // Compute the constant that would happen if we truncated to SrcTy then
6283 // reextended to DestTy.
6284 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6285 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6287 // If the re-extended constant didn't change...
6289 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6290 // For example, we might have:
6291 // %A = sext short %X to uint
6292 // %B = icmp ugt uint %A, 1330
6293 // It is incorrect to transform this into
6294 // %B = icmp ugt short %X, 1330
6295 // because %A may have negative value.
6297 // However, we allow this when the compare is EQ/NE, because they are
6299 if (isSignedExt == isSignedCmp || ICI.isEquality())
6300 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6304 // The re-extended constant changed so the constant cannot be represented
6305 // in the shorter type. Consequently, we cannot emit a simple comparison.
6307 // First, handle some easy cases. We know the result cannot be equal at this
6308 // point so handle the ICI.isEquality() cases
6309 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6310 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6311 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6312 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6314 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6315 // should have been folded away previously and not enter in here.
6318 // We're performing a signed comparison.
6319 if (cast<ConstantInt>(CI)->getValue().isNegative())
6320 Result = ConstantInt::getFalse(); // X < (small) --> false
6322 Result = ConstantInt::getTrue(); // X < (large) --> true
6324 // We're performing an unsigned comparison.
6326 // We're performing an unsigned comp with a sign extended value.
6327 // This is true if the input is >= 0. [aka >s -1]
6328 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6329 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6330 NegOne, ICI.getName()), ICI);
6332 // Unsigned extend & unsigned compare -> always true.
6333 Result = ConstantInt::getTrue();
6337 // Finally, return the value computed.
6338 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6339 ICI.getPredicate() == ICmpInst::ICMP_SLT)
6340 return ReplaceInstUsesWith(ICI, Result);
6342 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6343 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6344 "ICmp should be folded!");
6345 if (Constant *CI = dyn_cast<Constant>(Result))
6346 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6347 return BinaryOperator::CreateNot(Result);
6350 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6351 return commonShiftTransforms(I);
6354 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6355 return commonShiftTransforms(I);
6358 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
6359 if (Instruction *R = commonShiftTransforms(I))
6362 Value *Op0 = I.getOperand(0);
6364 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6365 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6366 if (CSI->isAllOnesValue())
6367 return ReplaceInstUsesWith(I, CSI);
6369 // See if we can turn a signed shr into an unsigned shr.
6370 if (MaskedValueIsZero(Op0,
6371 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6372 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
6377 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6378 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6379 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6381 // shl X, 0 == X and shr X, 0 == X
6382 // shl 0, X == 0 and shr 0, X == 0
6383 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6384 Op0 == Constant::getNullValue(Op0->getType()))
6385 return ReplaceInstUsesWith(I, Op0);
6387 if (isa<UndefValue>(Op0)) {
6388 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6389 return ReplaceInstUsesWith(I, Op0);
6390 else // undef << X -> 0, undef >>u X -> 0
6391 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6393 if (isa<UndefValue>(Op1)) {
6394 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6395 return ReplaceInstUsesWith(I, Op0);
6396 else // X << undef, X >>u undef -> 0
6397 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6400 // Try to fold constant and into select arguments.
6401 if (isa<Constant>(Op0))
6402 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6403 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6406 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6407 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6412 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6413 BinaryOperator &I) {
6414 bool isLeftShift = I.getOpcode() == Instruction::Shl;
6416 // See if we can simplify any instructions used by the instruction whose sole
6417 // purpose is to compute bits we don't care about.
6418 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6419 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6420 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6421 KnownZero, KnownOne))
6424 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6425 // of a signed value.
6427 if (Op1->uge(TypeBits)) {
6428 if (I.getOpcode() != Instruction::AShr)
6429 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6431 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6436 // ((X*C1) << C2) == (X * (C1 << C2))
6437 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6438 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6439 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6440 return BinaryOperator::CreateMul(BO->getOperand(0),
6441 ConstantExpr::getShl(BOOp, Op1));
6443 // Try to fold constant and into select arguments.
6444 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6445 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6447 if (isa<PHINode>(Op0))
6448 if (Instruction *NV = FoldOpIntoPhi(I))
6451 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6452 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6453 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6454 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6455 // place. Don't try to do this transformation in this case. Also, we
6456 // require that the input operand is a shift-by-constant so that we have
6457 // confidence that the shifts will get folded together. We could do this
6458 // xform in more cases, but it is unlikely to be profitable.
6459 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6460 isa<ConstantInt>(TrOp->getOperand(1))) {
6461 // Okay, we'll do this xform. Make the shift of shift.
6462 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6463 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
6465 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6467 // For logical shifts, the truncation has the effect of making the high
6468 // part of the register be zeros. Emulate this by inserting an AND to
6469 // clear the top bits as needed. This 'and' will usually be zapped by
6470 // other xforms later if dead.
6471 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6472 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6473 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6475 // The mask we constructed says what the trunc would do if occurring
6476 // between the shifts. We want to know the effect *after* the second
6477 // shift. We know that it is a logical shift by a constant, so adjust the
6478 // mask as appropriate.
6479 if (I.getOpcode() == Instruction::Shl)
6480 MaskV <<= Op1->getZExtValue();
6482 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6483 MaskV = MaskV.lshr(Op1->getZExtValue());
6486 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
6488 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6490 // Return the value truncated to the interesting size.
6491 return new TruncInst(And, I.getType());
6495 if (Op0->hasOneUse()) {
6496 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6497 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6500 switch (Op0BO->getOpcode()) {
6502 case Instruction::Add:
6503 case Instruction::And:
6504 case Instruction::Or:
6505 case Instruction::Xor: {
6506 // These operators commute.
6507 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
6508 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6509 match(Op0BO->getOperand(1),
6510 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6511 Instruction *YS = BinaryOperator::CreateShl(
6512 Op0BO->getOperand(0), Op1,
6514 InsertNewInstBefore(YS, I); // (Y << C)
6516 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
6517 Op0BO->getOperand(1)->getName());
6518 InsertNewInstBefore(X, I); // (X + (Y << C))
6519 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6520 return BinaryOperator::CreateAnd(X, ConstantInt::get(
6521 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6524 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
6525 Value *Op0BOOp1 = Op0BO->getOperand(1);
6526 if (isLeftShift && Op0BOOp1->hasOneUse() &&
6528 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6529 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6531 Instruction *YS = BinaryOperator::CreateShl(
6532 Op0BO->getOperand(0), Op1,
6534 InsertNewInstBefore(YS, I); // (Y << C)
6536 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6537 V1->getName()+".mask");
6538 InsertNewInstBefore(XM, I); // X & (CC << C)
6540 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
6545 case Instruction::Sub: {
6546 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6547 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6548 match(Op0BO->getOperand(0),
6549 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6550 Instruction *YS = BinaryOperator::CreateShl(
6551 Op0BO->getOperand(1), Op1,
6553 InsertNewInstBefore(YS, I); // (Y << C)
6555 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
6556 Op0BO->getOperand(0)->getName());
6557 InsertNewInstBefore(X, I); // (X + (Y << C))
6558 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6559 return BinaryOperator::CreateAnd(X, ConstantInt::get(
6560 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6563 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
6564 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6565 match(Op0BO->getOperand(0),
6566 m_And(m_Shr(m_Value(V1), m_Value(V2)),
6567 m_ConstantInt(CC))) && V2 == Op1 &&
6568 cast<BinaryOperator>(Op0BO->getOperand(0))
6569 ->getOperand(0)->hasOneUse()) {
6570 Instruction *YS = BinaryOperator::CreateShl(
6571 Op0BO->getOperand(1), Op1,
6573 InsertNewInstBefore(YS, I); // (Y << C)
6575 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
6576 V1->getName()+".mask");
6577 InsertNewInstBefore(XM, I); // X & (CC << C)
6579 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
6587 // If the operand is an bitwise operator with a constant RHS, and the
6588 // shift is the only use, we can pull it out of the shift.
6589 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6590 bool isValid = true; // Valid only for And, Or, Xor
6591 bool highBitSet = false; // Transform if high bit of constant set?
6593 switch (Op0BO->getOpcode()) {
6594 default: isValid = false; break; // Do not perform transform!
6595 case Instruction::Add:
6596 isValid = isLeftShift;
6598 case Instruction::Or:
6599 case Instruction::Xor:
6602 case Instruction::And:
6607 // If this is a signed shift right, and the high bit is modified
6608 // by the logical operation, do not perform the transformation.
6609 // The highBitSet boolean indicates the value of the high bit of
6610 // the constant which would cause it to be modified for this
6613 if (isValid && I.getOpcode() == Instruction::AShr)
6614 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6617 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6619 Instruction *NewShift =
6620 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6621 InsertNewInstBefore(NewShift, I);
6622 NewShift->takeName(Op0BO);
6624 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
6631 // Find out if this is a shift of a shift by a constant.
6632 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6633 if (ShiftOp && !ShiftOp->isShift())
6636 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6637 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6638 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6639 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6640 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6641 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6642 Value *X = ShiftOp->getOperand(0);
6644 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
6645 if (AmtSum > TypeBits)
6648 const IntegerType *Ty = cast<IntegerType>(I.getType());
6650 // Check for (X << c1) << c2 and (X >> c1) >> c2
6651 if (I.getOpcode() == ShiftOp->getOpcode()) {
6652 return BinaryOperator::Create(I.getOpcode(), X,
6653 ConstantInt::get(Ty, AmtSum));
6654 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6655 I.getOpcode() == Instruction::AShr) {
6656 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6657 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
6658 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6659 I.getOpcode() == Instruction::LShr) {
6660 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6661 Instruction *Shift =
6662 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
6663 InsertNewInstBefore(Shift, I);
6665 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6666 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6669 // Okay, if we get here, one shift must be left, and the other shift must be
6670 // right. See if the amounts are equal.
6671 if (ShiftAmt1 == ShiftAmt2) {
6672 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6673 if (I.getOpcode() == Instruction::Shl) {
6674 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6675 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6677 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6678 if (I.getOpcode() == Instruction::LShr) {
6679 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6680 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
6682 // We can simplify ((X << C) >>s C) into a trunc + sext.
6683 // NOTE: we could do this for any C, but that would make 'unusual' integer
6684 // types. For now, just stick to ones well-supported by the code
6686 const Type *SExtType = 0;
6687 switch (Ty->getBitWidth() - ShiftAmt1) {
6694 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6699 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6700 InsertNewInstBefore(NewTrunc, I);
6701 return new SExtInst(NewTrunc, Ty);
6703 // Otherwise, we can't handle it yet.
6704 } else if (ShiftAmt1 < ShiftAmt2) {
6705 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6707 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6708 if (I.getOpcode() == Instruction::Shl) {
6709 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6710 ShiftOp->getOpcode() == Instruction::AShr);
6711 Instruction *Shift =
6712 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6713 InsertNewInstBefore(Shift, I);
6715 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6716 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6719 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
6720 if (I.getOpcode() == Instruction::LShr) {
6721 assert(ShiftOp->getOpcode() == Instruction::Shl);
6722 Instruction *Shift =
6723 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
6724 InsertNewInstBefore(Shift, I);
6726 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6727 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6730 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6732 assert(ShiftAmt2 < ShiftAmt1);
6733 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6735 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6736 if (I.getOpcode() == Instruction::Shl) {
6737 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6738 ShiftOp->getOpcode() == Instruction::AShr);
6739 Instruction *Shift =
6740 BinaryOperator::Create(ShiftOp->getOpcode(), X,
6741 ConstantInt::get(Ty, ShiftDiff));
6742 InsertNewInstBefore(Shift, I);
6744 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6745 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6748 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
6749 if (I.getOpcode() == Instruction::LShr) {
6750 assert(ShiftOp->getOpcode() == Instruction::Shl);
6751 Instruction *Shift =
6752 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
6753 InsertNewInstBefore(Shift, I);
6755 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6756 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
6759 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6766 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6767 /// expression. If so, decompose it, returning some value X, such that Val is
6770 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6772 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6773 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6774 Offset = CI->getZExtValue();
6776 return ConstantInt::get(Type::Int32Ty, 0);
6777 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6778 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6779 if (I->getOpcode() == Instruction::Shl) {
6780 // This is a value scaled by '1 << the shift amt'.
6781 Scale = 1U << RHS->getZExtValue();
6783 return I->getOperand(0);
6784 } else if (I->getOpcode() == Instruction::Mul) {
6785 // This value is scaled by 'RHS'.
6786 Scale = RHS->getZExtValue();
6788 return I->getOperand(0);
6789 } else if (I->getOpcode() == Instruction::Add) {
6790 // We have X+C. Check to see if we really have (X*C2)+C1,
6791 // where C1 is divisible by C2.
6794 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6795 Offset += RHS->getZExtValue();
6802 // Otherwise, we can't look past this.
6809 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6810 /// try to eliminate the cast by moving the type information into the alloc.
6811 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6812 AllocationInst &AI) {
6813 const PointerType *PTy = cast<PointerType>(CI.getType());
6815 // Remove any uses of AI that are dead.
6816 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6818 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6819 Instruction *User = cast<Instruction>(*UI++);
6820 if (isInstructionTriviallyDead(User)) {
6821 while (UI != E && *UI == User)
6822 ++UI; // If this instruction uses AI more than once, don't break UI.
6825 DOUT << "IC: DCE: " << *User;
6826 EraseInstFromFunction(*User);
6830 // Get the type really allocated and the type casted to.
6831 const Type *AllocElTy = AI.getAllocatedType();
6832 const Type *CastElTy = PTy->getElementType();
6833 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6835 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6836 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6837 if (CastElTyAlign < AllocElTyAlign) return 0;
6839 // If the allocation has multiple uses, only promote it if we are strictly
6840 // increasing the alignment of the resultant allocation. If we keep it the
6841 // same, we open the door to infinite loops of various kinds.
6842 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6844 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6845 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
6846 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6848 // See if we can satisfy the modulus by pulling a scale out of the array
6850 unsigned ArraySizeScale;
6852 Value *NumElements = // See if the array size is a decomposable linear expr.
6853 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6855 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6857 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6858 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
6860 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6865 // If the allocation size is constant, form a constant mul expression
6866 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6867 if (isa<ConstantInt>(NumElements))
6868 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6869 // otherwise multiply the amount and the number of elements
6870 else if (Scale != 1) {
6871 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
6872 Amt = InsertNewInstBefore(Tmp, AI);
6876 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6877 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6878 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
6879 Amt = InsertNewInstBefore(Tmp, AI);
6882 AllocationInst *New;
6883 if (isa<MallocInst>(AI))
6884 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6886 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6887 InsertNewInstBefore(New, AI);
6890 // If the allocation has multiple uses, insert a cast and change all things
6891 // that used it to use the new cast. This will also hack on CI, but it will
6893 if (!AI.hasOneUse()) {
6894 AddUsesToWorkList(AI);
6895 // New is the allocation instruction, pointer typed. AI is the original
6896 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6897 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6898 InsertNewInstBefore(NewCast, AI);
6899 AI.replaceAllUsesWith(NewCast);
6901 return ReplaceInstUsesWith(CI, New);
6904 /// CanEvaluateInDifferentType - Return true if we can take the specified value
6905 /// and return it as type Ty without inserting any new casts and without
6906 /// changing the computed value. This is used by code that tries to decide
6907 /// whether promoting or shrinking integer operations to wider or smaller types
6908 /// will allow us to eliminate a truncate or extend.
6910 /// This is a truncation operation if Ty is smaller than V->getType(), or an
6911 /// extension operation if Ty is larger.
6913 /// If CastOpc is a truncation, then Ty will be a type smaller than V. We
6914 /// should return true if trunc(V) can be computed by computing V in the smaller
6915 /// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
6916 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
6917 /// efficiently truncated.
6919 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
6920 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
6921 /// the final result.
6922 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
6924 int &NumCastsRemoved) {
6925 // We can always evaluate constants in another type.
6926 if (isa<ConstantInt>(V))
6929 Instruction *I = dyn_cast<Instruction>(V);
6930 if (!I) return false;
6932 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6934 // If this is an extension or truncate, we can often eliminate it.
6935 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6936 // If this is a cast from the destination type, we can trivially eliminate
6937 // it, and this will remove a cast overall.
6938 if (I->getOperand(0)->getType() == Ty) {
6939 // If the first operand is itself a cast, and is eliminable, do not count
6940 // this as an eliminable cast. We would prefer to eliminate those two
6942 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
6948 // We can't extend or shrink something that has multiple uses: doing so would
6949 // require duplicating the instruction in general, which isn't profitable.
6950 if (!I->hasOneUse()) return false;
6952 switch (I->getOpcode()) {
6953 case Instruction::Add:
6954 case Instruction::Sub:
6955 case Instruction::Mul:
6956 case Instruction::And:
6957 case Instruction::Or:
6958 case Instruction::Xor:
6959 // These operators can all arbitrarily be extended or truncated.
6960 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6962 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6965 case Instruction::Shl:
6966 // If we are truncating the result of this SHL, and if it's a shift of a
6967 // constant amount, we can always perform a SHL in a smaller type.
6968 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6969 uint32_t BitWidth = Ty->getBitWidth();
6970 if (BitWidth < OrigTy->getBitWidth() &&
6971 CI->getLimitedValue(BitWidth) < BitWidth)
6972 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6976 case Instruction::LShr:
6977 // If this is a truncate of a logical shr, we can truncate it to a smaller
6978 // lshr iff we know that the bits we would otherwise be shifting in are
6980 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6981 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6982 uint32_t BitWidth = Ty->getBitWidth();
6983 if (BitWidth < OrigBitWidth &&
6984 MaskedValueIsZero(I->getOperand(0),
6985 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6986 CI->getLimitedValue(BitWidth) < BitWidth) {
6987 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6992 case Instruction::ZExt:
6993 case Instruction::SExt:
6994 case Instruction::Trunc:
6995 // If this is the same kind of case as our original (e.g. zext+zext), we
6996 // can safely replace it. Note that replacing it does not reduce the number
6997 // of casts in the input.
6998 if (I->getOpcode() == CastOpc)
7001 case Instruction::Select: {
7002 SelectInst *SI = cast<SelectInst>(I);
7003 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7005 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7008 case Instruction::PHI: {
7009 // We can change a phi if we can change all operands.
7010 PHINode *PN = cast<PHINode>(I);
7011 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7012 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7018 // TODO: Can handle more cases here.
7025 /// EvaluateInDifferentType - Given an expression that
7026 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7027 /// evaluate the expression.
7028 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7030 if (Constant *C = dyn_cast<Constant>(V))
7031 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7033 // Otherwise, it must be an instruction.
7034 Instruction *I = cast<Instruction>(V);
7035 Instruction *Res = 0;
7036 switch (I->getOpcode()) {
7037 case Instruction::Add:
7038 case Instruction::Sub:
7039 case Instruction::Mul:
7040 case Instruction::And:
7041 case Instruction::Or:
7042 case Instruction::Xor:
7043 case Instruction::AShr:
7044 case Instruction::LShr:
7045 case Instruction::Shl: {
7046 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7047 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7048 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
7052 case Instruction::Trunc:
7053 case Instruction::ZExt:
7054 case Instruction::SExt:
7055 // If the source type of the cast is the type we're trying for then we can
7056 // just return the source. There's no need to insert it because it is not
7058 if (I->getOperand(0)->getType() == Ty)
7059 return I->getOperand(0);
7061 // Otherwise, must be the same type of cast, so just reinsert a new one.
7062 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7065 case Instruction::Select: {
7066 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7067 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7068 Res = SelectInst::Create(I->getOperand(0), True, False);
7071 case Instruction::PHI: {
7072 PHINode *OPN = cast<PHINode>(I);
7073 PHINode *NPN = PHINode::Create(Ty);
7074 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7075 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7076 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7082 // TODO: Can handle more cases here.
7083 assert(0 && "Unreachable!");
7088 return InsertNewInstBefore(Res, *I);
7091 /// @brief Implement the transforms common to all CastInst visitors.
7092 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7093 Value *Src = CI.getOperand(0);
7095 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7096 // eliminate it now.
7097 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7098 if (Instruction::CastOps opc =
7099 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7100 // The first cast (CSrc) is eliminable so we need to fix up or replace
7101 // the second cast (CI). CSrc will then have a good chance of being dead.
7102 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7106 // If we are casting a select then fold the cast into the select
7107 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7108 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7111 // If we are casting a PHI then fold the cast into the PHI
7112 if (isa<PHINode>(Src))
7113 if (Instruction *NV = FoldOpIntoPhi(CI))
7119 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7120 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7121 Value *Src = CI.getOperand(0);
7123 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7124 // If casting the result of a getelementptr instruction with no offset, turn
7125 // this into a cast of the original pointer!
7126 if (GEP->hasAllZeroIndices()) {
7127 // Changing the cast operand is usually not a good idea but it is safe
7128 // here because the pointer operand is being replaced with another
7129 // pointer operand so the opcode doesn't need to change.
7131 CI.setOperand(0, GEP->getOperand(0));
7135 // If the GEP has a single use, and the base pointer is a bitcast, and the
7136 // GEP computes a constant offset, see if we can convert these three
7137 // instructions into fewer. This typically happens with unions and other
7138 // non-type-safe code.
7139 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7140 if (GEP->hasAllConstantIndices()) {
7141 // We are guaranteed to get a constant from EmitGEPOffset.
7142 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7143 int64_t Offset = OffsetV->getSExtValue();
7145 // Get the base pointer input of the bitcast, and the type it points to.
7146 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7147 const Type *GEPIdxTy =
7148 cast<PointerType>(OrigBase->getType())->getElementType();
7149 if (GEPIdxTy->isSized()) {
7150 SmallVector<Value*, 8> NewIndices;
7152 // Start with the index over the outer type. Note that the type size
7153 // might be zero (even if the offset isn't zero) if the indexed type
7154 // is something like [0 x {int, int}]
7155 const Type *IntPtrTy = TD->getIntPtrType();
7156 int64_t FirstIdx = 0;
7157 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
7158 FirstIdx = Offset/TySize;
7161 // Handle silly modulus not returning values values [0..TySize).
7165 assert(Offset >= 0);
7167 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7170 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7172 // Index into the types. If we fail, set OrigBase to null.
7174 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7175 const StructLayout *SL = TD->getStructLayout(STy);
7176 if (Offset < (int64_t)SL->getSizeInBytes()) {
7177 unsigned Elt = SL->getElementContainingOffset(Offset);
7178 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7180 Offset -= SL->getElementOffset(Elt);
7181 GEPIdxTy = STy->getElementType(Elt);
7183 // Otherwise, we can't index into this, bail out.
7187 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7188 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
7189 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
7190 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7193 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7195 GEPIdxTy = STy->getElementType();
7197 // Otherwise, we can't index into this, bail out.
7203 // If we were able to index down into an element, create the GEP
7204 // and bitcast the result. This eliminates one bitcast, potentially
7206 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7208 NewIndices.end(), "");
7209 InsertNewInstBefore(NGEP, CI);
7210 NGEP->takeName(GEP);
7212 if (isa<BitCastInst>(CI))
7213 return new BitCastInst(NGEP, CI.getType());
7214 assert(isa<PtrToIntInst>(CI));
7215 return new PtrToIntInst(NGEP, CI.getType());
7222 return commonCastTransforms(CI);
7227 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7228 /// integer types. This function implements the common transforms for all those
7230 /// @brief Implement the transforms common to CastInst with integer operands
7231 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7232 if (Instruction *Result = commonCastTransforms(CI))
7235 Value *Src = CI.getOperand(0);
7236 const Type *SrcTy = Src->getType();
7237 const Type *DestTy = CI.getType();
7238 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7239 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7241 // See if we can simplify any instructions used by the LHS whose sole
7242 // purpose is to compute bits we don't care about.
7243 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7244 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7245 KnownZero, KnownOne))
7248 // If the source isn't an instruction or has more than one use then we
7249 // can't do anything more.
7250 Instruction *SrcI = dyn_cast<Instruction>(Src);
7251 if (!SrcI || !Src->hasOneUse())
7254 // Attempt to propagate the cast into the instruction for int->int casts.
7255 int NumCastsRemoved = 0;
7256 if (!isa<BitCastInst>(CI) &&
7257 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
7258 CI.getOpcode(), NumCastsRemoved)) {
7259 // If this cast is a truncate, evaluting in a different type always
7260 // eliminates the cast, so it is always a win. If this is a zero-extension,
7261 // we need to do an AND to maintain the clear top-part of the computation,
7262 // so we require that the input have eliminated at least one cast. If this
7263 // is a sign extension, we insert two new casts (to do the extension) so we
7264 // require that two casts have been eliminated.
7266 switch (CI.getOpcode()) {
7268 // All the others use floating point so we shouldn't actually
7269 // get here because of the check above.
7270 assert(0 && "Unknown cast type");
7271 case Instruction::Trunc:
7274 case Instruction::ZExt:
7275 DoXForm = NumCastsRemoved >= 1;
7277 case Instruction::SExt:
7278 DoXForm = NumCastsRemoved >= 2;
7283 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7284 CI.getOpcode() == Instruction::SExt);
7285 assert(Res->getType() == DestTy);
7286 switch (CI.getOpcode()) {
7287 default: assert(0 && "Unknown cast type!");
7288 case Instruction::Trunc:
7289 case Instruction::BitCast:
7290 // Just replace this cast with the result.
7291 return ReplaceInstUsesWith(CI, Res);
7292 case Instruction::ZExt: {
7293 // We need to emit an AND to clear the high bits.
7294 assert(SrcBitSize < DestBitSize && "Not a zext?");
7295 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7297 return BinaryOperator::CreateAnd(Res, C);
7299 case Instruction::SExt:
7300 // We need to emit a cast to truncate, then a cast to sext.
7301 return CastInst::Create(Instruction::SExt,
7302 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7308 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7309 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7311 switch (SrcI->getOpcode()) {
7312 case Instruction::Add:
7313 case Instruction::Mul:
7314 case Instruction::And:
7315 case Instruction::Or:
7316 case Instruction::Xor:
7317 // If we are discarding information, rewrite.
7318 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7319 // Don't insert two casts if they cannot be eliminated. We allow
7320 // two casts to be inserted if the sizes are the same. This could
7321 // only be converting signedness, which is a noop.
7322 if (DestBitSize == SrcBitSize ||
7323 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7324 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7325 Instruction::CastOps opcode = CI.getOpcode();
7326 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7327 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7328 return BinaryOperator::Create(
7329 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7333 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7334 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7335 SrcI->getOpcode() == Instruction::Xor &&
7336 Op1 == ConstantInt::getTrue() &&
7337 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7338 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
7339 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
7342 case Instruction::SDiv:
7343 case Instruction::UDiv:
7344 case Instruction::SRem:
7345 case Instruction::URem:
7346 // If we are just changing the sign, rewrite.
7347 if (DestBitSize == SrcBitSize) {
7348 // Don't insert two casts if they cannot be eliminated. We allow
7349 // two casts to be inserted if the sizes are the same. This could
7350 // only be converting signedness, which is a noop.
7351 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7352 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7353 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7355 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7357 return BinaryOperator::Create(
7358 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7363 case Instruction::Shl:
7364 // Allow changing the sign of the source operand. Do not allow
7365 // changing the size of the shift, UNLESS the shift amount is a
7366 // constant. We must not change variable sized shifts to a smaller
7367 // size, because it is undefined to shift more bits out than exist
7369 if (DestBitSize == SrcBitSize ||
7370 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7371 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7372 Instruction::BitCast : Instruction::Trunc);
7373 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7374 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
7375 return BinaryOperator::CreateShl(Op0c, Op1c);
7378 case Instruction::AShr:
7379 // If this is a signed shr, and if all bits shifted in are about to be
7380 // truncated off, turn it into an unsigned shr to allow greater
7382 if (DestBitSize < SrcBitSize &&
7383 isa<ConstantInt>(Op1)) {
7384 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7385 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7386 // Insert the new logical shift right.
7387 return BinaryOperator::CreateLShr(Op0, Op1);
7395 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7396 if (Instruction *Result = commonIntCastTransforms(CI))
7399 Value *Src = CI.getOperand(0);
7400 const Type *Ty = CI.getType();
7401 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7402 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7404 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7405 switch (SrcI->getOpcode()) {
7407 case Instruction::LShr:
7408 // We can shrink lshr to something smaller if we know the bits shifted in
7409 // are already zeros.
7410 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7411 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7413 // Get a mask for the bits shifting in.
7414 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7415 Value* SrcIOp0 = SrcI->getOperand(0);
7416 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7417 if (ShAmt >= DestBitWidth) // All zeros.
7418 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7420 // Okay, we can shrink this. Truncate the input, then return a new
7422 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7423 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7425 return BinaryOperator::CreateLShr(V1, V2);
7427 } else { // This is a variable shr.
7429 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7430 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7431 // loop-invariant and CSE'd.
7432 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7433 Value *One = ConstantInt::get(SrcI->getType(), 1);
7435 Value *V = InsertNewInstBefore(
7436 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
7438 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
7439 SrcI->getOperand(0),
7441 Value *Zero = Constant::getNullValue(V->getType());
7442 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7452 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7453 /// in order to eliminate the icmp.
7454 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7456 // If we are just checking for a icmp eq of a single bit and zext'ing it
7457 // to an integer, then shift the bit to the appropriate place and then
7458 // cast to integer to avoid the comparison.
7459 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7460 const APInt &Op1CV = Op1C->getValue();
7462 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7463 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7464 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7465 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7466 if (!DoXform) return ICI;
7468 Value *In = ICI->getOperand(0);
7469 Value *Sh = ConstantInt::get(In->getType(),
7470 In->getType()->getPrimitiveSizeInBits()-1);
7471 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
7472 In->getName()+".lobit"),
7474 if (In->getType() != CI.getType())
7475 In = CastInst::CreateIntegerCast(In, CI.getType(),
7476 false/*ZExt*/, "tmp", &CI);
7478 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7479 Constant *One = ConstantInt::get(In->getType(), 1);
7480 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
7481 In->getName()+".not"),
7485 return ReplaceInstUsesWith(CI, In);
7490 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7491 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7492 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7493 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7494 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7495 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7496 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7497 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7498 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7499 // This only works for EQ and NE
7500 ICI->isEquality()) {
7501 // If Op1C some other power of two, convert:
7502 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7503 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7504 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7505 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7507 APInt KnownZeroMask(~KnownZero);
7508 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7509 if (!DoXform) return ICI;
7511 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7512 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7513 // (X&4) == 2 --> false
7514 // (X&4) != 2 --> true
7515 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7516 Res = ConstantExpr::getZExt(Res, CI.getType());
7517 return ReplaceInstUsesWith(CI, Res);
7520 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7521 Value *In = ICI->getOperand(0);
7523 // Perform a logical shr by shiftamt.
7524 // Insert the shift to put the result in the low bit.
7525 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
7526 ConstantInt::get(In->getType(), ShiftAmt),
7527 In->getName()+".lobit"), CI);
7530 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7531 Constant *One = ConstantInt::get(In->getType(), 1);
7532 In = BinaryOperator::CreateXor(In, One, "tmp");
7533 InsertNewInstBefore(cast<Instruction>(In), CI);
7536 if (CI.getType() == In->getType())
7537 return ReplaceInstUsesWith(CI, In);
7539 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
7547 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7548 // If one of the common conversion will work ..
7549 if (Instruction *Result = commonIntCastTransforms(CI))
7552 Value *Src = CI.getOperand(0);
7554 // If this is a cast of a cast
7555 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7556 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7557 // types and if the sizes are just right we can convert this into a logical
7558 // 'and' which will be much cheaper than the pair of casts.
7559 if (isa<TruncInst>(CSrc)) {
7560 // Get the sizes of the types involved
7561 Value *A = CSrc->getOperand(0);
7562 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7563 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7564 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7565 // If we're actually extending zero bits and the trunc is a no-op
7566 if (MidSize < DstSize && SrcSize == DstSize) {
7567 // Replace both of the casts with an And of the type mask.
7568 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7569 Constant *AndConst = ConstantInt::get(AndValue);
7571 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
7572 // Unfortunately, if the type changed, we need to cast it back.
7573 if (And->getType() != CI.getType()) {
7574 And->setName(CSrc->getName()+".mask");
7575 InsertNewInstBefore(And, CI);
7576 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
7583 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7584 return transformZExtICmp(ICI, CI);
7586 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7587 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7588 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7589 // of the (zext icmp) will be transformed.
7590 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7591 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7592 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7593 (transformZExtICmp(LHS, CI, false) ||
7594 transformZExtICmp(RHS, CI, false))) {
7595 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7596 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
7597 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
7604 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7605 if (Instruction *I = commonIntCastTransforms(CI))
7608 Value *Src = CI.getOperand(0);
7610 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7611 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7612 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7613 // If we are just checking for a icmp eq of a single bit and zext'ing it
7614 // to an integer, then shift the bit to the appropriate place and then
7615 // cast to integer to avoid the comparison.
7616 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7617 const APInt &Op1CV = Op1C->getValue();
7619 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7620 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7621 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7622 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7623 Value *In = ICI->getOperand(0);
7624 Value *Sh = ConstantInt::get(In->getType(),
7625 In->getType()->getPrimitiveSizeInBits()-1);
7626 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
7627 In->getName()+".lobit"),
7629 if (In->getType() != CI.getType())
7630 In = CastInst::CreateIntegerCast(In, CI.getType(),
7631 true/*SExt*/, "tmp", &CI);
7633 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7634 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
7635 In->getName()+".not"), CI);
7637 return ReplaceInstUsesWith(CI, In);
7642 // See if the value being truncated is already sign extended. If so, just
7643 // eliminate the trunc/sext pair.
7644 if (getOpcode(Src) == Instruction::Trunc) {
7645 Value *Op = cast<User>(Src)->getOperand(0);
7646 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
7647 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
7648 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
7649 unsigned NumSignBits = ComputeNumSignBits(Op);
7651 if (OpBits == DestBits) {
7652 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
7653 // bits, it is already ready.
7654 if (NumSignBits > DestBits-MidBits)
7655 return ReplaceInstUsesWith(CI, Op);
7656 } else if (OpBits < DestBits) {
7657 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
7658 // bits, just sext from i32.
7659 if (NumSignBits > OpBits-MidBits)
7660 return new SExtInst(Op, CI.getType(), "tmp");
7662 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
7663 // bits, just truncate to i32.
7664 if (NumSignBits > OpBits-MidBits)
7665 return new TruncInst(Op, CI.getType(), "tmp");
7672 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7673 /// in the specified FP type without changing its value.
7674 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
7675 APFloat F = CFP->getValueAPF();
7676 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7677 return ConstantFP::get(F);
7681 /// LookThroughFPExtensions - If this is an fp extension instruction, look
7682 /// through it until we get the source value.
7683 static Value *LookThroughFPExtensions(Value *V) {
7684 if (Instruction *I = dyn_cast<Instruction>(V))
7685 if (I->getOpcode() == Instruction::FPExt)
7686 return LookThroughFPExtensions(I->getOperand(0));
7688 // If this value is a constant, return the constant in the smallest FP type
7689 // that can accurately represent it. This allows us to turn
7690 // (float)((double)X+2.0) into x+2.0f.
7691 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7692 if (CFP->getType() == Type::PPC_FP128Ty)
7693 return V; // No constant folding of this.
7694 // See if the value can be truncated to float and then reextended.
7695 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
7697 if (CFP->getType() == Type::DoubleTy)
7698 return V; // Won't shrink.
7699 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
7701 // Don't try to shrink to various long double types.
7707 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7708 if (Instruction *I = commonCastTransforms(CI))
7711 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7712 // smaller than the destination type, we can eliminate the truncate by doing
7713 // the add as the smaller type. This applies to add/sub/mul/div as well as
7714 // many builtins (sqrt, etc).
7715 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7716 if (OpI && OpI->hasOneUse()) {
7717 switch (OpI->getOpcode()) {
7719 case Instruction::Add:
7720 case Instruction::Sub:
7721 case Instruction::Mul:
7722 case Instruction::FDiv:
7723 case Instruction::FRem:
7724 const Type *SrcTy = OpI->getType();
7725 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7726 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7727 if (LHSTrunc->getType() != SrcTy &&
7728 RHSTrunc->getType() != SrcTy) {
7729 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7730 // If the source types were both smaller than the destination type of
7731 // the cast, do this xform.
7732 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7733 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7734 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7736 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7738 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7747 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7748 return commonCastTransforms(CI);
7751 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
7752 // fptoui(uitofp(X)) --> X if the intermediate type has enough bits in its
7753 // mantissa to accurately represent all values of X. For example, do not
7754 // do this with i64->float->i64.
7755 if (UIToFPInst *SrcI = dyn_cast<UIToFPInst>(FI.getOperand(0)))
7756 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7757 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
7758 SrcI->getType()->getFPMantissaWidth())
7759 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7761 return commonCastTransforms(FI);
7764 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
7765 // fptosi(sitofp(X)) --> X if the intermediate type has enough bits in its
7766 // mantissa to accurately represent all values of X. For example, do not
7767 // do this with i64->float->i64.
7768 if (SIToFPInst *SrcI = dyn_cast<SIToFPInst>(FI.getOperand(0)))
7769 if (SrcI->getOperand(0)->getType() == FI.getType() &&
7770 (int)FI.getType()->getPrimitiveSizeInBits() <=
7771 SrcI->getType()->getFPMantissaWidth())
7772 return ReplaceInstUsesWith(FI, SrcI->getOperand(0));
7774 return commonCastTransforms(FI);
7777 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7778 return commonCastTransforms(CI);
7781 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7782 return commonCastTransforms(CI);
7785 Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7786 return commonPointerCastTransforms(CI);
7789 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7790 if (Instruction *I = commonCastTransforms(CI))
7793 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7794 if (!DestPointee->isSized()) return 0;
7796 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7799 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7800 m_ConstantInt(Cst)))) {
7801 // If the source and destination operands have the same type, see if this
7802 // is a single-index GEP.
7803 if (X->getType() == CI.getType()) {
7804 // Get the size of the pointee type.
7805 uint64_t Size = TD->getABITypeSize(DestPointee);
7807 // Convert the constant to intptr type.
7808 APInt Offset = Cst->getValue();
7809 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7811 // If Offset is evenly divisible by Size, we can do this xform.
7812 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7813 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7814 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
7817 // TODO: Could handle other cases, e.g. where add is indexing into field of
7819 } else if (CI.getOperand(0)->hasOneUse() &&
7820 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7821 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7822 // "inttoptr+GEP" instead of "add+intptr".
7824 // Get the size of the pointee type.
7825 uint64_t Size = TD->getABITypeSize(DestPointee);
7827 // Convert the constant to intptr type.
7828 APInt Offset = Cst->getValue();
7829 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7831 // If Offset is evenly divisible by Size, we can do this xform.
7832 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7833 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7835 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7837 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
7843 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7844 // If the operands are integer typed then apply the integer transforms,
7845 // otherwise just apply the common ones.
7846 Value *Src = CI.getOperand(0);
7847 const Type *SrcTy = Src->getType();
7848 const Type *DestTy = CI.getType();
7850 if (SrcTy->isInteger() && DestTy->isInteger()) {
7851 if (Instruction *Result = commonIntCastTransforms(CI))
7853 } else if (isa<PointerType>(SrcTy)) {
7854 if (Instruction *I = commonPointerCastTransforms(CI))
7857 if (Instruction *Result = commonCastTransforms(CI))
7862 // Get rid of casts from one type to the same type. These are useless and can
7863 // be replaced by the operand.
7864 if (DestTy == Src->getType())
7865 return ReplaceInstUsesWith(CI, Src);
7867 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7868 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7869 const Type *DstElTy = DstPTy->getElementType();
7870 const Type *SrcElTy = SrcPTy->getElementType();
7872 // If the address spaces don't match, don't eliminate the bitcast, which is
7873 // required for changing types.
7874 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7877 // If we are casting a malloc or alloca to a pointer to a type of the same
7878 // size, rewrite the allocation instruction to allocate the "right" type.
7879 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7880 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7883 // If the source and destination are pointers, and this cast is equivalent
7884 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
7885 // This can enhance SROA and other transforms that want type-safe pointers.
7886 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7887 unsigned NumZeros = 0;
7888 while (SrcElTy != DstElTy &&
7889 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7890 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7891 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7895 // If we found a path from the src to dest, create the getelementptr now.
7896 if (SrcElTy == DstElTy) {
7897 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
7898 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
7899 ((Instruction*) NULL));
7903 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7904 if (SVI->hasOneUse()) {
7905 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7906 // a bitconvert to a vector with the same # elts.
7907 if (isa<VectorType>(DestTy) &&
7908 cast<VectorType>(DestTy)->getNumElements() ==
7909 SVI->getType()->getNumElements()) {
7911 // If either of the operands is a cast from CI.getType(), then
7912 // evaluating the shuffle in the casted destination's type will allow
7913 // us to eliminate at least one cast.
7914 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7915 Tmp->getOperand(0)->getType() == DestTy) ||
7916 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7917 Tmp->getOperand(0)->getType() == DestTy)) {
7918 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7919 SVI->getOperand(0), DestTy, &CI);
7920 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7921 SVI->getOperand(1), DestTy, &CI);
7922 // Return a new shuffle vector. Use the same element ID's, as we
7923 // know the vector types match #elts.
7924 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7932 /// GetSelectFoldableOperands - We want to turn code that looks like this:
7934 /// %D = select %cond, %C, %A
7936 /// %C = select %cond, %B, 0
7939 /// Assuming that the specified instruction is an operand to the select, return
7940 /// a bitmask indicating which operands of this instruction are foldable if they
7941 /// equal the other incoming value of the select.
7943 static unsigned GetSelectFoldableOperands(Instruction *I) {
7944 switch (I->getOpcode()) {
7945 case Instruction::Add:
7946 case Instruction::Mul:
7947 case Instruction::And:
7948 case Instruction::Or:
7949 case Instruction::Xor:
7950 return 3; // Can fold through either operand.
7951 case Instruction::Sub: // Can only fold on the amount subtracted.
7952 case Instruction::Shl: // Can only fold on the shift amount.
7953 case Instruction::LShr:
7954 case Instruction::AShr:
7957 return 0; // Cannot fold
7961 /// GetSelectFoldableConstant - For the same transformation as the previous
7962 /// function, return the identity constant that goes into the select.
7963 static Constant *GetSelectFoldableConstant(Instruction *I) {
7964 switch (I->getOpcode()) {
7965 default: assert(0 && "This cannot happen!"); abort();
7966 case Instruction::Add:
7967 case Instruction::Sub:
7968 case Instruction::Or:
7969 case Instruction::Xor:
7970 case Instruction::Shl:
7971 case Instruction::LShr:
7972 case Instruction::AShr:
7973 return Constant::getNullValue(I->getType());
7974 case Instruction::And:
7975 return Constant::getAllOnesValue(I->getType());
7976 case Instruction::Mul:
7977 return ConstantInt::get(I->getType(), 1);
7981 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7982 /// have the same opcode and only one use each. Try to simplify this.
7983 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7985 if (TI->getNumOperands() == 1) {
7986 // If this is a non-volatile load or a cast from the same type,
7989 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7992 return 0; // unknown unary op.
7995 // Fold this by inserting a select from the input values.
7996 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
7997 FI->getOperand(0), SI.getName()+".v");
7998 InsertNewInstBefore(NewSI, SI);
7999 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
8003 // Only handle binary operators here.
8004 if (!isa<BinaryOperator>(TI))
8007 // Figure out if the operations have any operands in common.
8008 Value *MatchOp, *OtherOpT, *OtherOpF;
8010 if (TI->getOperand(0) == FI->getOperand(0)) {
8011 MatchOp = TI->getOperand(0);
8012 OtherOpT = TI->getOperand(1);
8013 OtherOpF = FI->getOperand(1);
8014 MatchIsOpZero = true;
8015 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8016 MatchOp = TI->getOperand(1);
8017 OtherOpT = TI->getOperand(0);
8018 OtherOpF = FI->getOperand(0);
8019 MatchIsOpZero = false;
8020 } else if (!TI->isCommutative()) {
8022 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8023 MatchOp = TI->getOperand(0);
8024 OtherOpT = TI->getOperand(1);
8025 OtherOpF = FI->getOperand(0);
8026 MatchIsOpZero = true;
8027 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8028 MatchOp = TI->getOperand(1);
8029 OtherOpT = TI->getOperand(0);
8030 OtherOpF = FI->getOperand(1);
8031 MatchIsOpZero = true;
8036 // If we reach here, they do have operations in common.
8037 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8038 OtherOpF, SI.getName()+".v");
8039 InsertNewInstBefore(NewSI, SI);
8041 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8043 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8045 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8047 assert(0 && "Shouldn't get here");
8051 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8052 Value *CondVal = SI.getCondition();
8053 Value *TrueVal = SI.getTrueValue();
8054 Value *FalseVal = SI.getFalseValue();
8056 // select true, X, Y -> X
8057 // select false, X, Y -> Y
8058 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8059 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8061 // select C, X, X -> X
8062 if (TrueVal == FalseVal)
8063 return ReplaceInstUsesWith(SI, TrueVal);
8065 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8066 return ReplaceInstUsesWith(SI, FalseVal);
8067 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8068 return ReplaceInstUsesWith(SI, TrueVal);
8069 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8070 if (isa<Constant>(TrueVal))
8071 return ReplaceInstUsesWith(SI, TrueVal);
8073 return ReplaceInstUsesWith(SI, FalseVal);
8076 if (SI.getType() == Type::Int1Ty) {
8077 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8078 if (C->getZExtValue()) {
8079 // Change: A = select B, true, C --> A = or B, C
8080 return BinaryOperator::CreateOr(CondVal, FalseVal);
8082 // Change: A = select B, false, C --> A = and !B, C
8084 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8085 "not."+CondVal->getName()), SI);
8086 return BinaryOperator::CreateAnd(NotCond, FalseVal);
8088 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8089 if (C->getZExtValue() == false) {
8090 // Change: A = select B, C, false --> A = and B, C
8091 return BinaryOperator::CreateAnd(CondVal, TrueVal);
8093 // Change: A = select B, C, true --> A = or !B, C
8095 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8096 "not."+CondVal->getName()), SI);
8097 return BinaryOperator::CreateOr(NotCond, TrueVal);
8101 // select a, b, a -> a&b
8102 // select a, a, b -> a|b
8103 if (CondVal == TrueVal)
8104 return BinaryOperator::CreateOr(CondVal, FalseVal);
8105 else if (CondVal == FalseVal)
8106 return BinaryOperator::CreateAnd(CondVal, TrueVal);
8109 // Selecting between two integer constants?
8110 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8111 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8112 // select C, 1, 0 -> zext C to int
8113 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
8114 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
8115 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8116 // select C, 0, 1 -> zext !C to int
8118 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
8119 "not."+CondVal->getName()), SI);
8120 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
8123 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8125 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8127 // (x <s 0) ? -1 : 0 -> ashr x, 31
8128 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8129 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8130 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8131 // The comparison constant and the result are not neccessarily the
8132 // same width. Make an all-ones value by inserting a AShr.
8133 Value *X = IC->getOperand(0);
8134 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8135 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
8136 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
8138 InsertNewInstBefore(SRA, SI);
8140 // Finally, convert to the type of the select RHS. We figure out
8141 // if this requires a SExt, Trunc or BitCast based on the sizes.
8142 Instruction::CastOps opc = Instruction::BitCast;
8143 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8144 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
8145 if (SRASize < SISize)
8146 opc = Instruction::SExt;
8147 else if (SRASize > SISize)
8148 opc = Instruction::Trunc;
8149 return CastInst::Create(opc, SRA, SI.getType());
8154 // If one of the constants is zero (we know they can't both be) and we
8155 // have an icmp instruction with zero, and we have an 'and' with the
8156 // non-constant value, eliminate this whole mess. This corresponds to
8157 // cases like this: ((X & 27) ? 27 : 0)
8158 if (TrueValC->isZero() || FalseValC->isZero())
8159 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8160 cast<Constant>(IC->getOperand(1))->isNullValue())
8161 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8162 if (ICA->getOpcode() == Instruction::And &&
8163 isa<ConstantInt>(ICA->getOperand(1)) &&
8164 (ICA->getOperand(1) == TrueValC ||
8165 ICA->getOperand(1) == FalseValC) &&
8166 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8167 // Okay, now we know that everything is set up, we just don't
8168 // know whether we have a icmp_ne or icmp_eq and whether the
8169 // true or false val is the zero.
8170 bool ShouldNotVal = !TrueValC->isZero();
8171 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8174 V = InsertNewInstBefore(BinaryOperator::Create(
8175 Instruction::Xor, V, ICA->getOperand(1)), SI);
8176 return ReplaceInstUsesWith(SI, V);
8181 // See if we are selecting two values based on a comparison of the two values.
8182 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8183 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8184 // Transform (X == Y) ? X : Y -> Y
8185 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8186 // This is not safe in general for floating point:
8187 // consider X== -0, Y== +0.
8188 // It becomes safe if either operand is a nonzero constant.
8189 ConstantFP *CFPt, *CFPf;
8190 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8191 !CFPt->getValueAPF().isZero()) ||
8192 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8193 !CFPf->getValueAPF().isZero()))
8194 return ReplaceInstUsesWith(SI, FalseVal);
8196 // Transform (X != Y) ? X : Y -> X
8197 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8198 return ReplaceInstUsesWith(SI, TrueVal);
8199 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8201 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8202 // Transform (X == Y) ? Y : X -> X
8203 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8204 // This is not safe in general for floating point:
8205 // consider X== -0, Y== +0.
8206 // It becomes safe if either operand is a nonzero constant.
8207 ConstantFP *CFPt, *CFPf;
8208 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8209 !CFPt->getValueAPF().isZero()) ||
8210 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8211 !CFPf->getValueAPF().isZero()))
8212 return ReplaceInstUsesWith(SI, FalseVal);
8214 // Transform (X != Y) ? Y : X -> Y
8215 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8216 return ReplaceInstUsesWith(SI, TrueVal);
8217 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8221 // See if we are selecting two values based on a comparison of the two values.
8222 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8223 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8224 // Transform (X == Y) ? X : Y -> Y
8225 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8226 return ReplaceInstUsesWith(SI, FalseVal);
8227 // Transform (X != Y) ? X : Y -> X
8228 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8229 return ReplaceInstUsesWith(SI, TrueVal);
8230 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8232 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8233 // Transform (X == Y) ? Y : X -> X
8234 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8235 return ReplaceInstUsesWith(SI, FalseVal);
8236 // Transform (X != Y) ? Y : X -> Y
8237 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8238 return ReplaceInstUsesWith(SI, TrueVal);
8239 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8243 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8244 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8245 if (TI->hasOneUse() && FI->hasOneUse()) {
8246 Instruction *AddOp = 0, *SubOp = 0;
8248 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8249 if (TI->getOpcode() == FI->getOpcode())
8250 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8253 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8254 // even legal for FP.
8255 if (TI->getOpcode() == Instruction::Sub &&
8256 FI->getOpcode() == Instruction::Add) {
8257 AddOp = FI; SubOp = TI;
8258 } else if (FI->getOpcode() == Instruction::Sub &&
8259 TI->getOpcode() == Instruction::Add) {
8260 AddOp = TI; SubOp = FI;
8264 Value *OtherAddOp = 0;
8265 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8266 OtherAddOp = AddOp->getOperand(1);
8267 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8268 OtherAddOp = AddOp->getOperand(0);
8272 // So at this point we know we have (Y -> OtherAddOp):
8273 // select C, (add X, Y), (sub X, Z)
8274 Value *NegVal; // Compute -Z
8275 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8276 NegVal = ConstantExpr::getNeg(C);
8278 NegVal = InsertNewInstBefore(
8279 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
8282 Value *NewTrueOp = OtherAddOp;
8283 Value *NewFalseOp = NegVal;
8285 std::swap(NewTrueOp, NewFalseOp);
8286 Instruction *NewSel =
8287 SelectInst::Create(CondVal, NewTrueOp,
8288 NewFalseOp, SI.getName() + ".p");
8290 NewSel = InsertNewInstBefore(NewSel, SI);
8291 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
8296 // See if we can fold the select into one of our operands.
8297 if (SI.getType()->isInteger()) {
8298 // See the comment above GetSelectFoldableOperands for a description of the
8299 // transformation we are doing here.
8300 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8301 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8302 !isa<Constant>(FalseVal))
8303 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8304 unsigned OpToFold = 0;
8305 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8307 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8312 Constant *C = GetSelectFoldableConstant(TVI);
8313 Instruction *NewSel =
8314 SelectInst::Create(SI.getCondition(),
8315 TVI->getOperand(2-OpToFold), C);
8316 InsertNewInstBefore(NewSel, SI);
8317 NewSel->takeName(TVI);
8318 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
8319 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
8321 assert(0 && "Unknown instruction!!");
8326 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8327 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8328 !isa<Constant>(TrueVal))
8329 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8330 unsigned OpToFold = 0;
8331 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8333 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8338 Constant *C = GetSelectFoldableConstant(FVI);
8339 Instruction *NewSel =
8340 SelectInst::Create(SI.getCondition(), C,
8341 FVI->getOperand(2-OpToFold));
8342 InsertNewInstBefore(NewSel, SI);
8343 NewSel->takeName(FVI);
8344 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
8345 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
8347 assert(0 && "Unknown instruction!!");
8352 if (BinaryOperator::isNot(CondVal)) {
8353 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8354 SI.setOperand(1, FalseVal);
8355 SI.setOperand(2, TrueVal);
8362 /// EnforceKnownAlignment - If the specified pointer points to an object that
8363 /// we control, modify the object's alignment to PrefAlign. This isn't
8364 /// often possible though. If alignment is important, a more reliable approach
8365 /// is to simply align all global variables and allocation instructions to
8366 /// their preferred alignment from the beginning.
8368 static unsigned EnforceKnownAlignment(Value *V,
8369 unsigned Align, unsigned PrefAlign) {
8371 User *U = dyn_cast<User>(V);
8372 if (!U) return Align;
8374 switch (getOpcode(U)) {
8376 case Instruction::BitCast:
8377 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8378 case Instruction::GetElementPtr: {
8379 // If all indexes are zero, it is just the alignment of the base pointer.
8380 bool AllZeroOperands = true;
8381 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
8382 if (!isa<Constant>(*i) ||
8383 !cast<Constant>(*i)->isNullValue()) {
8384 AllZeroOperands = false;
8388 if (AllZeroOperands) {
8389 // Treat this like a bitcast.
8390 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8396 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8397 // If there is a large requested alignment and we can, bump up the alignment
8399 if (!GV->isDeclaration()) {
8400 GV->setAlignment(PrefAlign);
8403 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8404 // If there is a requested alignment and if this is an alloca, round up. We
8405 // don't do this for malloc, because some systems can't respect the request.
8406 if (isa<AllocaInst>(AI)) {
8407 AI->setAlignment(PrefAlign);
8415 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8416 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8417 /// and it is more than the alignment of the ultimate object, see if we can
8418 /// increase the alignment of the ultimate object, making this check succeed.
8419 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8420 unsigned PrefAlign) {
8421 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8422 sizeof(PrefAlign) * CHAR_BIT;
8423 APInt Mask = APInt::getAllOnesValue(BitWidth);
8424 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8425 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8426 unsigned TrailZ = KnownZero.countTrailingOnes();
8427 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8429 if (PrefAlign > Align)
8430 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8432 // We don't need to make any adjustment.
8436 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8437 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8438 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
8439 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8440 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8442 if (CopyAlign < MinAlign) {
8443 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8447 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8449 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8450 if (MemOpLength == 0) return 0;
8452 // Source and destination pointer types are always "i8*" for intrinsic. See
8453 // if the size is something we can handle with a single primitive load/store.
8454 // A single load+store correctly handles overlapping memory in the memmove
8456 unsigned Size = MemOpLength->getZExtValue();
8457 if (Size == 0) return MI; // Delete this mem transfer.
8459 if (Size > 8 || (Size&(Size-1)))
8460 return 0; // If not 1/2/4/8 bytes, exit.
8462 // Use an integer load+store unless we can find something better.
8463 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
8465 // Memcpy forces the use of i8* for the source and destination. That means
8466 // that if you're using memcpy to move one double around, you'll get a cast
8467 // from double* to i8*. We'd much rather use a double load+store rather than
8468 // an i64 load+store, here because this improves the odds that the source or
8469 // dest address will be promotable. See if we can find a better type than the
8470 // integer datatype.
8471 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8472 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8473 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8474 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8475 // down through these levels if so.
8476 while (!SrcETy->isSingleValueType()) {
8477 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8478 if (STy->getNumElements() == 1)
8479 SrcETy = STy->getElementType(0);
8482 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8483 if (ATy->getNumElements() == 1)
8484 SrcETy = ATy->getElementType();
8491 if (SrcETy->isSingleValueType())
8492 NewPtrTy = PointerType::getUnqual(SrcETy);
8497 // If the memcpy/memmove provides better alignment info than we can
8499 SrcAlign = std::max(SrcAlign, CopyAlign);
8500 DstAlign = std::max(DstAlign, CopyAlign);
8502 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8503 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
8504 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8505 InsertNewInstBefore(L, *MI);
8506 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8508 // Set the size of the copy to 0, it will be deleted on the next iteration.
8509 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8513 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8514 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8515 if (MI->getAlignment()->getZExtValue() < Alignment) {
8516 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8520 // Extract the length and alignment and fill if they are constant.
8521 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8522 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8523 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8525 uint64_t Len = LenC->getZExtValue();
8526 Alignment = MI->getAlignment()->getZExtValue();
8528 // If the length is zero, this is a no-op
8529 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8531 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8532 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8533 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8535 Value *Dest = MI->getDest();
8536 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8538 // Alignment 0 is identity for alignment 1 for memset, but not store.
8539 if (Alignment == 0) Alignment = 1;
8541 // Extract the fill value and store.
8542 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8543 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8546 // Set the size of the copy to 0, it will be deleted on the next iteration.
8547 MI->setLength(Constant::getNullValue(LenC->getType()));
8555 /// visitCallInst - CallInst simplification. This mostly only handles folding
8556 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8557 /// the heavy lifting.
8559 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8560 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8561 if (!II) return visitCallSite(&CI);
8563 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8565 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8566 bool Changed = false;
8568 // memmove/cpy/set of zero bytes is a noop.
8569 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8570 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8572 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8573 if (CI->getZExtValue() == 1) {
8574 // Replace the instruction with just byte operations. We would
8575 // transform other cases to loads/stores, but we don't know if
8576 // alignment is sufficient.
8580 // If we have a memmove and the source operation is a constant global,
8581 // then the source and dest pointers can't alias, so we can change this
8582 // into a call to memcpy.
8583 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
8584 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8585 if (GVSrc->isConstant()) {
8586 Module *M = CI.getParent()->getParent()->getParent();
8587 Intrinsic::ID MemCpyID;
8588 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8589 MemCpyID = Intrinsic::memcpy_i32;
8591 MemCpyID = Intrinsic::memcpy_i64;
8592 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
8596 // memmove(x,x,size) -> noop.
8597 if (MMI->getSource() == MMI->getDest())
8598 return EraseInstFromFunction(CI);
8601 // If we can determine a pointer alignment that is bigger than currently
8602 // set, update the alignment.
8603 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
8604 if (Instruction *I = SimplifyMemTransfer(MI))
8606 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8607 if (Instruction *I = SimplifyMemSet(MSI))
8611 if (Changed) return II;
8614 switch (II->getIntrinsicID()) {
8616 case Intrinsic::bswap:
8617 // bswap(bswap(x)) -> x
8618 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
8619 if (Operand->getIntrinsicID() == Intrinsic::bswap)
8620 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
8622 case Intrinsic::ppc_altivec_lvx:
8623 case Intrinsic::ppc_altivec_lvxl:
8624 case Intrinsic::x86_sse_loadu_ps:
8625 case Intrinsic::x86_sse2_loadu_pd:
8626 case Intrinsic::x86_sse2_loadu_dq:
8627 // Turn PPC lvx -> load if the pointer is known aligned.
8628 // Turn X86 loadups -> load if the pointer is known aligned.
8629 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8630 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8631 PointerType::getUnqual(II->getType()),
8633 return new LoadInst(Ptr);
8636 case Intrinsic::ppc_altivec_stvx:
8637 case Intrinsic::ppc_altivec_stvxl:
8638 // Turn stvx -> store if the pointer is known aligned.
8639 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
8640 const Type *OpPtrTy =
8641 PointerType::getUnqual(II->getOperand(1)->getType());
8642 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
8643 return new StoreInst(II->getOperand(1), Ptr);
8646 case Intrinsic::x86_sse_storeu_ps:
8647 case Intrinsic::x86_sse2_storeu_pd:
8648 case Intrinsic::x86_sse2_storeu_dq:
8649 case Intrinsic::x86_sse2_storel_dq:
8650 // Turn X86 storeu -> store if the pointer is known aligned.
8651 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
8652 const Type *OpPtrTy =
8653 PointerType::getUnqual(II->getOperand(2)->getType());
8654 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
8655 return new StoreInst(II->getOperand(2), Ptr);
8659 case Intrinsic::x86_sse_cvttss2si: {
8660 // These intrinsics only demands the 0th element of its input vector. If
8661 // we can simplify the input based on that, do so now.
8663 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8665 II->setOperand(1, V);
8671 case Intrinsic::ppc_altivec_vperm:
8672 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8673 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8674 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8676 // Check that all of the elements are integer constants or undefs.
8677 bool AllEltsOk = true;
8678 for (unsigned i = 0; i != 16; ++i) {
8679 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8680 !isa<UndefValue>(Mask->getOperand(i))) {
8687 // Cast the input vectors to byte vectors.
8688 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8689 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
8690 Value *Result = UndefValue::get(Op0->getType());
8692 // Only extract each element once.
8693 Value *ExtractedElts[32];
8694 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8696 for (unsigned i = 0; i != 16; ++i) {
8697 if (isa<UndefValue>(Mask->getOperand(i)))
8699 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8700 Idx &= 31; // Match the hardware behavior.
8702 if (ExtractedElts[Idx] == 0) {
8704 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8705 InsertNewInstBefore(Elt, CI);
8706 ExtractedElts[Idx] = Elt;
8709 // Insert this value into the result vector.
8710 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8712 InsertNewInstBefore(cast<Instruction>(Result), CI);
8714 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
8719 case Intrinsic::stackrestore: {
8720 // If the save is right next to the restore, remove the restore. This can
8721 // happen when variable allocas are DCE'd.
8722 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8723 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8724 BasicBlock::iterator BI = SS;
8726 return EraseInstFromFunction(CI);
8730 // Scan down this block to see if there is another stack restore in the
8731 // same block without an intervening call/alloca.
8732 BasicBlock::iterator BI = II;
8733 TerminatorInst *TI = II->getParent()->getTerminator();
8734 bool CannotRemove = false;
8735 for (++BI; &*BI != TI; ++BI) {
8736 if (isa<AllocaInst>(BI)) {
8737 CannotRemove = true;
8740 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
8741 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
8742 // If there is a stackrestore below this one, remove this one.
8743 if (II->getIntrinsicID() == Intrinsic::stackrestore)
8744 return EraseInstFromFunction(CI);
8745 // Otherwise, ignore the intrinsic.
8747 // If we found a non-intrinsic call, we can't remove the stack
8749 CannotRemove = true;
8755 // If the stack restore is in a return/unwind block and if there are no
8756 // allocas or calls between the restore and the return, nuke the restore.
8757 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8758 return EraseInstFromFunction(CI);
8763 return visitCallSite(II);
8766 // InvokeInst simplification
8768 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8769 return visitCallSite(&II);
8772 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
8773 /// passed through the varargs area, we can eliminate the use of the cast.
8774 static bool isSafeToEliminateVarargsCast(const CallSite CS,
8775 const CastInst * const CI,
8776 const TargetData * const TD,
8778 if (!CI->isLosslessCast())
8781 // The size of ByVal arguments is derived from the type, so we
8782 // can't change to a type with a different size. If the size were
8783 // passed explicitly we could avoid this check.
8784 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8788 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8789 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8790 if (!SrcTy->isSized() || !DstTy->isSized())
8792 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8797 // visitCallSite - Improvements for call and invoke instructions.
8799 Instruction *InstCombiner::visitCallSite(CallSite CS) {
8800 bool Changed = false;
8802 // If the callee is a constexpr cast of a function, attempt to move the cast
8803 // to the arguments of the call/invoke.
8804 if (transformConstExprCastCall(CS)) return 0;
8806 Value *Callee = CS.getCalledValue();
8808 if (Function *CalleeF = dyn_cast<Function>(Callee))
8809 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8810 Instruction *OldCall = CS.getInstruction();
8811 // If the call and callee calling conventions don't match, this call must
8812 // be unreachable, as the call is undefined.
8813 new StoreInst(ConstantInt::getTrue(),
8814 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8816 if (!OldCall->use_empty())
8817 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8818 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8819 return EraseInstFromFunction(*OldCall);
8823 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8824 // This instruction is not reachable, just remove it. We insert a store to
8825 // undef so that we know that this code is not reachable, despite the fact
8826 // that we can't modify the CFG here.
8827 new StoreInst(ConstantInt::getTrue(),
8828 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8829 CS.getInstruction());
8831 if (!CS.getInstruction()->use_empty())
8832 CS.getInstruction()->
8833 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8835 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8836 // Don't break the CFG, insert a dummy cond branch.
8837 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8838 ConstantInt::getTrue(), II);
8840 return EraseInstFromFunction(*CS.getInstruction());
8843 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8844 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8845 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8846 return transformCallThroughTrampoline(CS);
8848 const PointerType *PTy = cast<PointerType>(Callee->getType());
8849 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8850 if (FTy->isVarArg()) {
8851 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
8852 // See if we can optimize any arguments passed through the varargs area of
8854 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8855 E = CS.arg_end(); I != E; ++I, ++ix) {
8856 CastInst *CI = dyn_cast<CastInst>(*I);
8857 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8858 *I = CI->getOperand(0);
8864 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
8865 // Inline asm calls cannot throw - mark them 'nounwind'.
8866 CS.setDoesNotThrow();
8870 return Changed ? CS.getInstruction() : 0;
8873 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
8874 // attempt to move the cast to the arguments of the call/invoke.
8876 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8877 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8878 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8879 if (CE->getOpcode() != Instruction::BitCast ||
8880 !isa<Function>(CE->getOperand(0)))
8882 Function *Callee = cast<Function>(CE->getOperand(0));
8883 Instruction *Caller = CS.getInstruction();
8884 const PAListPtr &CallerPAL = CS.getParamAttrs();
8886 // Okay, this is a cast from a function to a different type. Unless doing so
8887 // would cause a type conversion of one of our arguments, change this call to
8888 // be a direct call with arguments casted to the appropriate types.
8890 const FunctionType *FT = Callee->getFunctionType();
8891 const Type *OldRetTy = Caller->getType();
8892 const Type *NewRetTy = FT->getReturnType();
8894 if (isa<StructType>(NewRetTy))
8895 return false; // TODO: Handle multiple return values.
8897 // Check to see if we are changing the return type...
8898 if (OldRetTy != NewRetTy) {
8899 if (Callee->isDeclaration() &&
8900 // Conversion is ok if changing from one pointer type to another or from
8901 // a pointer to an integer of the same size.
8902 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
8903 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
8904 return false; // Cannot transform this return value.
8906 if (!Caller->use_empty() &&
8907 // void -> non-void is handled specially
8908 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
8909 return false; // Cannot transform this return value.
8911 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8912 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8913 if (RAttrs & ParamAttr::typeIncompatible(NewRetTy))
8914 return false; // Attribute not compatible with transformed value.
8917 // If the callsite is an invoke instruction, and the return value is used by
8918 // a PHI node in a successor, we cannot change the return type of the call
8919 // because there is no place to put the cast instruction (without breaking
8920 // the critical edge). Bail out in this case.
8921 if (!Caller->use_empty())
8922 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8923 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8925 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8926 if (PN->getParent() == II->getNormalDest() ||
8927 PN->getParent() == II->getUnwindDest())
8931 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8932 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8934 CallSite::arg_iterator AI = CS.arg_begin();
8935 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8936 const Type *ParamTy = FT->getParamType(i);
8937 const Type *ActTy = (*AI)->getType();
8939 if (!CastInst::isCastable(ActTy, ParamTy))
8940 return false; // Cannot transform this parameter value.
8942 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8943 return false; // Attribute not compatible with transformed value.
8945 // Converting from one pointer type to another or between a pointer and an
8946 // integer of the same size is safe even if we do not have a body.
8947 bool isConvertible = ActTy == ParamTy ||
8948 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
8949 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
8950 if (Callee->isDeclaration() && !isConvertible) return false;
8953 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8954 Callee->isDeclaration())
8955 return false; // Do not delete arguments unless we have a function body.
8957 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
8958 !CallerPAL.isEmpty())
8959 // In this case we have more arguments than the new function type, but we
8960 // won't be dropping them. Check that these extra arguments have attributes
8961 // that are compatible with being a vararg call argument.
8962 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
8963 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
8965 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
8966 if (PAttrs & ParamAttr::VarArgsIncompatible)
8970 // Okay, we decided that this is a safe thing to do: go ahead and start
8971 // inserting cast instructions as necessary...
8972 std::vector<Value*> Args;
8973 Args.reserve(NumActualArgs);
8974 SmallVector<ParamAttrsWithIndex, 8> attrVec;
8975 attrVec.reserve(NumCommonArgs);
8977 // Get any return attributes.
8978 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
8980 // If the return value is not being used, the type may not be compatible
8981 // with the existing attributes. Wipe out any problematic attributes.
8982 RAttrs &= ~ParamAttr::typeIncompatible(NewRetTy);
8984 // Add the new return attributes.
8986 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
8988 AI = CS.arg_begin();
8989 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8990 const Type *ParamTy = FT->getParamType(i);
8991 if ((*AI)->getType() == ParamTy) {
8992 Args.push_back(*AI);
8994 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8995 false, ParamTy, false);
8996 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
8997 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9000 // Add any parameter attributes.
9001 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9002 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9005 // If the function takes more arguments than the call was taking, add them
9007 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9008 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9010 // If we are removing arguments to the function, emit an obnoxious warning...
9011 if (FT->getNumParams() < NumActualArgs) {
9012 if (!FT->isVarArg()) {
9013 cerr << "WARNING: While resolving call to function '"
9014 << Callee->getName() << "' arguments were dropped!\n";
9016 // Add all of the arguments in their promoted form to the arg list...
9017 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9018 const Type *PTy = getPromotedType((*AI)->getType());
9019 if (PTy != (*AI)->getType()) {
9020 // Must promote to pass through va_arg area!
9021 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9023 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
9024 InsertNewInstBefore(Cast, *Caller);
9025 Args.push_back(Cast);
9027 Args.push_back(*AI);
9030 // Add any parameter attributes.
9031 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
9032 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9037 if (NewRetTy == Type::VoidTy)
9038 Caller->setName(""); // Void type should not have a name.
9040 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
9043 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9044 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
9045 Args.begin(), Args.end(),
9046 Caller->getName(), Caller);
9047 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
9048 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
9050 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9051 Caller->getName(), Caller);
9052 CallInst *CI = cast<CallInst>(Caller);
9053 if (CI->isTailCall())
9054 cast<CallInst>(NC)->setTailCall();
9055 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
9056 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
9059 // Insert a cast of the return type as necessary.
9061 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
9062 if (NV->getType() != Type::VoidTy) {
9063 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
9065 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
9067 // If this is an invoke instruction, we should insert it after the first
9068 // non-phi, instruction in the normal successor block.
9069 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9070 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
9071 InsertNewInstBefore(NC, *I);
9073 // Otherwise, it's a call, just insert cast right after the call instr
9074 InsertNewInstBefore(NC, *Caller);
9076 AddUsersToWorkList(*Caller);
9078 NV = UndefValue::get(Caller->getType());
9082 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9083 Caller->replaceAllUsesWith(NV);
9084 Caller->eraseFromParent();
9085 RemoveFromWorkList(Caller);
9089 // transformCallThroughTrampoline - Turn a call to a function created by the
9090 // init_trampoline intrinsic into a direct call to the underlying function.
9092 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9093 Value *Callee = CS.getCalledValue();
9094 const PointerType *PTy = cast<PointerType>(Callee->getType());
9095 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9096 const PAListPtr &Attrs = CS.getParamAttrs();
9098 // If the call already has the 'nest' attribute somewhere then give up -
9099 // otherwise 'nest' would occur twice after splicing in the chain.
9100 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
9103 IntrinsicInst *Tramp =
9104 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9106 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
9107 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9108 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9110 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9111 if (!NestAttrs.isEmpty()) {
9112 unsigned NestIdx = 1;
9113 const Type *NestTy = 0;
9114 ParameterAttributes NestAttr = ParamAttr::None;
9116 // Look for a parameter marked with the 'nest' attribute.
9117 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9118 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
9119 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
9120 // Record the parameter type and any other attributes.
9122 NestAttr = NestAttrs.getParamAttrs(NestIdx);
9127 Instruction *Caller = CS.getInstruction();
9128 std::vector<Value*> NewArgs;
9129 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9131 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9132 NewAttrs.reserve(Attrs.getNumSlots() + 1);
9134 // Insert the nest argument into the call argument list, which may
9135 // mean appending it. Likewise for attributes.
9137 // Add any function result attributes.
9138 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9139 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
9143 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9145 if (Idx == NestIdx) {
9146 // Add the chain argument and attributes.
9147 Value *NestVal = Tramp->getOperand(3);
9148 if (NestVal->getType() != NestTy)
9149 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9150 NewArgs.push_back(NestVal);
9151 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
9157 // Add the original argument and attributes.
9158 NewArgs.push_back(*I);
9159 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
9161 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
9167 // The trampoline may have been bitcast to a bogus type (FTy).
9168 // Handle this by synthesizing a new function type, equal to FTy
9169 // with the chain parameter inserted.
9171 std::vector<const Type*> NewTypes;
9172 NewTypes.reserve(FTy->getNumParams()+1);
9174 // Insert the chain's type into the list of parameter types, which may
9175 // mean appending it.
9178 FunctionType::param_iterator I = FTy->param_begin(),
9179 E = FTy->param_end();
9183 // Add the chain's type.
9184 NewTypes.push_back(NestTy);
9189 // Add the original type.
9190 NewTypes.push_back(*I);
9196 // Replace the trampoline call with a direct call. Let the generic
9197 // code sort out any function type mismatches.
9198 FunctionType *NewFTy =
9199 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
9200 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9201 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
9202 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
9204 Instruction *NewCaller;
9205 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9206 NewCaller = InvokeInst::Create(NewCallee,
9207 II->getNormalDest(), II->getUnwindDest(),
9208 NewArgs.begin(), NewArgs.end(),
9209 Caller->getName(), Caller);
9210 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
9211 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
9213 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9214 Caller->getName(), Caller);
9215 if (cast<CallInst>(Caller)->isTailCall())
9216 cast<CallInst>(NewCaller)->setTailCall();
9217 cast<CallInst>(NewCaller)->
9218 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
9219 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
9221 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9222 Caller->replaceAllUsesWith(NewCaller);
9223 Caller->eraseFromParent();
9224 RemoveFromWorkList(Caller);
9229 // Replace the trampoline call with a direct call. Since there is no 'nest'
9230 // parameter, there is no need to adjust the argument list. Let the generic
9231 // code sort out any function type mismatches.
9232 Constant *NewCallee =
9233 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9234 CS.setCalledFunction(NewCallee);
9235 return CS.getInstruction();
9238 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9239 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9240 /// and a single binop.
9241 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9242 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9243 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9244 isa<CmpInst>(FirstInst));
9245 unsigned Opc = FirstInst->getOpcode();
9246 Value *LHSVal = FirstInst->getOperand(0);
9247 Value *RHSVal = FirstInst->getOperand(1);
9249 const Type *LHSType = LHSVal->getType();
9250 const Type *RHSType = RHSVal->getType();
9252 // Scan to see if all operands are the same opcode, all have one use, and all
9253 // kill their operands (i.e. the operands have one use).
9254 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9255 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9256 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9257 // Verify type of the LHS matches so we don't fold cmp's of different
9258 // types or GEP's with different index types.
9259 I->getOperand(0)->getType() != LHSType ||
9260 I->getOperand(1)->getType() != RHSType)
9263 // If they are CmpInst instructions, check their predicates
9264 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9265 if (cast<CmpInst>(I)->getPredicate() !=
9266 cast<CmpInst>(FirstInst)->getPredicate())
9269 // Keep track of which operand needs a phi node.
9270 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9271 if (I->getOperand(1) != RHSVal) RHSVal = 0;
9274 // Otherwise, this is safe to transform, determine if it is profitable.
9276 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9277 // Indexes are often folded into load/store instructions, so we don't want to
9278 // hide them behind a phi.
9279 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9282 Value *InLHS = FirstInst->getOperand(0);
9283 Value *InRHS = FirstInst->getOperand(1);
9284 PHINode *NewLHS = 0, *NewRHS = 0;
9286 NewLHS = PHINode::Create(LHSType,
9287 FirstInst->getOperand(0)->getName() + ".pn");
9288 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9289 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9290 InsertNewInstBefore(NewLHS, PN);
9295 NewRHS = PHINode::Create(RHSType,
9296 FirstInst->getOperand(1)->getName() + ".pn");
9297 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9298 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9299 InsertNewInstBefore(NewRHS, PN);
9303 // Add all operands to the new PHIs.
9304 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9306 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9307 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9310 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9311 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9315 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9316 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
9317 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9318 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
9321 assert(isa<GetElementPtrInst>(FirstInst));
9322 return GetElementPtrInst::Create(LHSVal, RHSVal);
9326 /// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9327 /// of the block that defines it. This means that it must be obvious the value
9328 /// of the load is not changed from the point of the load to the end of the
9331 /// Finally, it is safe, but not profitable, to sink a load targetting a
9332 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
9334 static bool isSafeToSinkLoad(LoadInst *L) {
9335 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9337 for (++BBI; BBI != E; ++BBI)
9338 if (BBI->mayWriteToMemory())
9341 // Check for non-address taken alloca. If not address-taken already, it isn't
9342 // profitable to do this xform.
9343 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9344 bool isAddressTaken = false;
9345 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9347 if (isa<LoadInst>(UI)) continue;
9348 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9349 // If storing TO the alloca, then the address isn't taken.
9350 if (SI->getOperand(1) == AI) continue;
9352 isAddressTaken = true;
9356 if (!isAddressTaken)
9364 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9365 // operator and they all are only used by the PHI, PHI together their
9366 // inputs, and do the operation once, to the result of the PHI.
9367 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9368 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9370 // Scan the instruction, looking for input operations that can be folded away.
9371 // If all input operands to the phi are the same instruction (e.g. a cast from
9372 // the same type or "+42") we can pull the operation through the PHI, reducing
9373 // code size and simplifying code.
9374 Constant *ConstantOp = 0;
9375 const Type *CastSrcTy = 0;
9376 bool isVolatile = false;
9377 if (isa<CastInst>(FirstInst)) {
9378 CastSrcTy = FirstInst->getOperand(0)->getType();
9379 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9380 // Can fold binop, compare or shift here if the RHS is a constant,
9381 // otherwise call FoldPHIArgBinOpIntoPHI.
9382 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9383 if (ConstantOp == 0)
9384 return FoldPHIArgBinOpIntoPHI(PN);
9385 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9386 isVolatile = LI->isVolatile();
9387 // We can't sink the load if the loaded value could be modified between the
9388 // load and the PHI.
9389 if (LI->getParent() != PN.getIncomingBlock(0) ||
9390 !isSafeToSinkLoad(LI))
9393 // If the PHI is of volatile loads and the load block has multiple
9394 // successors, sinking it would remove a load of the volatile value from
9395 // the path through the other successor.
9397 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9400 } else if (isa<GetElementPtrInst>(FirstInst)) {
9401 if (FirstInst->getNumOperands() == 2)
9402 return FoldPHIArgBinOpIntoPHI(PN);
9403 // Can't handle general GEPs yet.
9406 return 0; // Cannot fold this operation.
9409 // Check to see if all arguments are the same operation.
9410 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9411 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9412 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9413 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9416 if (I->getOperand(0)->getType() != CastSrcTy)
9417 return 0; // Cast operation must match.
9418 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9419 // We can't sink the load if the loaded value could be modified between
9420 // the load and the PHI.
9421 if (LI->isVolatile() != isVolatile ||
9422 LI->getParent() != PN.getIncomingBlock(i) ||
9423 !isSafeToSinkLoad(LI))
9426 // If the PHI is of volatile loads and the load block has multiple
9427 // successors, sinking it would remove a load of the volatile value from
9428 // the path through the other successor.
9430 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9434 } else if (I->getOperand(1) != ConstantOp) {
9439 // Okay, they are all the same operation. Create a new PHI node of the
9440 // correct type, and PHI together all of the LHS's of the instructions.
9441 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9442 PN.getName()+".in");
9443 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9445 Value *InVal = FirstInst->getOperand(0);
9446 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9448 // Add all operands to the new PHI.
9449 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9450 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9451 if (NewInVal != InVal)
9453 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9458 // The new PHI unions all of the same values together. This is really
9459 // common, so we handle it intelligently here for compile-time speed.
9463 InsertNewInstBefore(NewPN, PN);
9467 // Insert and return the new operation.
9468 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
9469 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
9470 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
9471 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
9472 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
9473 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
9474 PhiVal, ConstantOp);
9475 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9477 // If this was a volatile load that we are merging, make sure to loop through
9478 // and mark all the input loads as non-volatile. If we don't do this, we will
9479 // insert a new volatile load and the old ones will not be deletable.
9481 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9482 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9484 return new LoadInst(PhiVal, "", isVolatile);
9487 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9489 static bool DeadPHICycle(PHINode *PN,
9490 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9491 if (PN->use_empty()) return true;
9492 if (!PN->hasOneUse()) return false;
9494 // Remember this node, and if we find the cycle, return.
9495 if (!PotentiallyDeadPHIs.insert(PN))
9498 // Don't scan crazily complex things.
9499 if (PotentiallyDeadPHIs.size() == 16)
9502 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9503 return DeadPHICycle(PU, PotentiallyDeadPHIs);
9508 /// PHIsEqualValue - Return true if this phi node is always equal to
9509 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9510 /// z = some value; x = phi (y, z); y = phi (x, z)
9511 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9512 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9513 // See if we already saw this PHI node.
9514 if (!ValueEqualPHIs.insert(PN))
9517 // Don't scan crazily complex things.
9518 if (ValueEqualPHIs.size() == 16)
9521 // Scan the operands to see if they are either phi nodes or are equal to
9523 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9524 Value *Op = PN->getIncomingValue(i);
9525 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9526 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9528 } else if (Op != NonPhiInVal)
9536 // PHINode simplification
9538 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9539 // If LCSSA is around, don't mess with Phi nodes
9540 if (MustPreserveLCSSA) return 0;
9542 if (Value *V = PN.hasConstantValue())
9543 return ReplaceInstUsesWith(PN, V);
9545 // If all PHI operands are the same operation, pull them through the PHI,
9546 // reducing code size.
9547 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9548 PN.getIncomingValue(0)->hasOneUse())
9549 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9552 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9553 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9554 // PHI)... break the cycle.
9555 if (PN.hasOneUse()) {
9556 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9557 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9558 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9559 PotentiallyDeadPHIs.insert(&PN);
9560 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9561 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9564 // If this phi has a single use, and if that use just computes a value for
9565 // the next iteration of a loop, delete the phi. This occurs with unused
9566 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9567 // common case here is good because the only other things that catch this
9568 // are induction variable analysis (sometimes) and ADCE, which is only run
9570 if (PHIUser->hasOneUse() &&
9571 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9572 PHIUser->use_back() == &PN) {
9573 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9577 // We sometimes end up with phi cycles that non-obviously end up being the
9578 // same value, for example:
9579 // z = some value; x = phi (y, z); y = phi (x, z)
9580 // where the phi nodes don't necessarily need to be in the same block. Do a
9581 // quick check to see if the PHI node only contains a single non-phi value, if
9582 // so, scan to see if the phi cycle is actually equal to that value.
9584 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9585 // Scan for the first non-phi operand.
9586 while (InValNo != NumOperandVals &&
9587 isa<PHINode>(PN.getIncomingValue(InValNo)))
9590 if (InValNo != NumOperandVals) {
9591 Value *NonPhiInVal = PN.getOperand(InValNo);
9593 // Scan the rest of the operands to see if there are any conflicts, if so
9594 // there is no need to recursively scan other phis.
9595 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9596 Value *OpVal = PN.getIncomingValue(InValNo);
9597 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9601 // If we scanned over all operands, then we have one unique value plus
9602 // phi values. Scan PHI nodes to see if they all merge in each other or
9604 if (InValNo == NumOperandVals) {
9605 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9606 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9607 return ReplaceInstUsesWith(PN, NonPhiInVal);
9614 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9615 Instruction *InsertPoint,
9617 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9618 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9619 // We must cast correctly to the pointer type. Ensure that we
9620 // sign extend the integer value if it is smaller as this is
9621 // used for address computation.
9622 Instruction::CastOps opcode =
9623 (VTySize < PtrSize ? Instruction::SExt :
9624 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9625 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9629 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9630 Value *PtrOp = GEP.getOperand(0);
9631 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
9632 // If so, eliminate the noop.
9633 if (GEP.getNumOperands() == 1)
9634 return ReplaceInstUsesWith(GEP, PtrOp);
9636 if (isa<UndefValue>(GEP.getOperand(0)))
9637 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9639 bool HasZeroPointerIndex = false;
9640 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9641 HasZeroPointerIndex = C->isNullValue();
9643 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9644 return ReplaceInstUsesWith(GEP, PtrOp);
9646 // Eliminate unneeded casts for indices.
9647 bool MadeChange = false;
9649 gep_type_iterator GTI = gep_type_begin(GEP);
9650 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
9651 i != e; ++i, ++GTI) {
9652 if (isa<SequentialType>(*GTI)) {
9653 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
9654 if (CI->getOpcode() == Instruction::ZExt ||
9655 CI->getOpcode() == Instruction::SExt) {
9656 const Type *SrcTy = CI->getOperand(0)->getType();
9657 // We can eliminate a cast from i32 to i64 iff the target
9658 // is a 32-bit pointer target.
9659 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9661 *i = CI->getOperand(0);
9665 // If we are using a wider index than needed for this platform, shrink it
9666 // to what we need. If the incoming value needs a cast instruction,
9667 // insert it. This explicit cast can make subsequent optimizations more
9670 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
9671 if (Constant *C = dyn_cast<Constant>(Op)) {
9672 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
9675 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9683 if (MadeChange) return &GEP;
9685 // If this GEP instruction doesn't move the pointer, and if the input operand
9686 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9687 // real input to the dest type.
9688 if (GEP.hasAllZeroIndices()) {
9689 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9690 // If the bitcast is of an allocation, and the allocation will be
9691 // converted to match the type of the cast, don't touch this.
9692 if (isa<AllocationInst>(BCI->getOperand(0))) {
9693 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
9694 if (Instruction *I = visitBitCast(*BCI)) {
9697 BCI->getParent()->getInstList().insert(BCI, I);
9698 ReplaceInstUsesWith(*BCI, I);
9703 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9707 // Combine Indices - If the source pointer to this getelementptr instruction
9708 // is a getelementptr instruction, combine the indices of the two
9709 // getelementptr instructions into a single instruction.
9711 SmallVector<Value*, 8> SrcGEPOperands;
9712 if (User *Src = dyn_castGetElementPtr(PtrOp))
9713 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9715 if (!SrcGEPOperands.empty()) {
9716 // Note that if our source is a gep chain itself that we wait for that
9717 // chain to be resolved before we perform this transformation. This
9718 // avoids us creating a TON of code in some cases.
9720 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9721 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9722 return 0; // Wait until our source is folded to completion.
9724 SmallVector<Value*, 8> Indices;
9726 // Find out whether the last index in the source GEP is a sequential idx.
9727 bool EndsWithSequential = false;
9728 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9729 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9730 EndsWithSequential = !isa<StructType>(*I);
9732 // Can we combine the two pointer arithmetics offsets?
9733 if (EndsWithSequential) {
9734 // Replace: gep (gep %P, long B), long A, ...
9735 // With: T = long A+B; gep %P, T, ...
9737 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9738 if (SO1 == Constant::getNullValue(SO1->getType())) {
9740 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9743 // If they aren't the same type, convert both to an integer of the
9744 // target's pointer size.
9745 if (SO1->getType() != GO1->getType()) {
9746 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9747 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9748 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9749 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9751 unsigned PS = TD->getPointerSizeInBits();
9752 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
9753 // Convert GO1 to SO1's type.
9754 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9756 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
9757 // Convert SO1 to GO1's type.
9758 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9760 const Type *PT = TD->getIntPtrType();
9761 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9762 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9766 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9767 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9769 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
9770 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9774 // Recycle the GEP we already have if possible.
9775 if (SrcGEPOperands.size() == 2) {
9776 GEP.setOperand(0, SrcGEPOperands[0]);
9777 GEP.setOperand(1, Sum);
9780 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9781 SrcGEPOperands.end()-1);
9782 Indices.push_back(Sum);
9783 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9785 } else if (isa<Constant>(*GEP.idx_begin()) &&
9786 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9787 SrcGEPOperands.size() != 1) {
9788 // Otherwise we can do the fold if the first index of the GEP is a zero
9789 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9790 SrcGEPOperands.end());
9791 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9794 if (!Indices.empty())
9795 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9796 Indices.end(), GEP.getName());
9798 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9799 // GEP of global variable. If all of the indices for this GEP are
9800 // constants, we can promote this to a constexpr instead of an instruction.
9802 // Scan for nonconstants...
9803 SmallVector<Constant*, 8> Indices;
9804 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9805 for (; I != E && isa<Constant>(*I); ++I)
9806 Indices.push_back(cast<Constant>(*I));
9808 if (I == E) { // If they are all constants...
9809 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9810 &Indices[0],Indices.size());
9812 // Replace all uses of the GEP with the new constexpr...
9813 return ReplaceInstUsesWith(GEP, CE);
9815 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
9816 if (!isa<PointerType>(X->getType())) {
9817 // Not interesting. Source pointer must be a cast from pointer.
9818 } else if (HasZeroPointerIndex) {
9819 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9820 // into : GEP [10 x i8]* X, i32 0, ...
9822 // This occurs when the program declares an array extern like "int X[];"
9824 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9825 const PointerType *XTy = cast<PointerType>(X->getType());
9826 if (const ArrayType *XATy =
9827 dyn_cast<ArrayType>(XTy->getElementType()))
9828 if (const ArrayType *CATy =
9829 dyn_cast<ArrayType>(CPTy->getElementType()))
9830 if (CATy->getElementType() == XATy->getElementType()) {
9831 // At this point, we know that the cast source type is a pointer
9832 // to an array of the same type as the destination pointer
9833 // array. Because the array type is never stepped over (there
9834 // is a leading zero) we can fold the cast into this GEP.
9835 GEP.setOperand(0, X);
9838 } else if (GEP.getNumOperands() == 2) {
9839 // Transform things like:
9840 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9841 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
9842 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9843 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9844 if (isa<ArrayType>(SrcElTy) &&
9845 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9846 TD->getABITypeSize(ResElTy)) {
9848 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9849 Idx[1] = GEP.getOperand(1);
9850 Value *V = InsertNewInstBefore(
9851 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
9852 // V and GEP are both pointer types --> BitCast
9853 return new BitCastInst(V, GEP.getType());
9856 // Transform things like:
9857 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
9858 // (where tmp = 8*tmp2) into:
9859 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
9861 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
9862 uint64_t ArrayEltSize =
9863 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
9865 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9866 // allow either a mul, shift, or constant here.
9868 ConstantInt *Scale = 0;
9869 if (ArrayEltSize == 1) {
9870 NewIdx = GEP.getOperand(1);
9871 Scale = ConstantInt::get(NewIdx->getType(), 1);
9872 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9873 NewIdx = ConstantInt::get(CI->getType(), 1);
9875 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9876 if (Inst->getOpcode() == Instruction::Shl &&
9877 isa<ConstantInt>(Inst->getOperand(1))) {
9878 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9879 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9880 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9881 NewIdx = Inst->getOperand(0);
9882 } else if (Inst->getOpcode() == Instruction::Mul &&
9883 isa<ConstantInt>(Inst->getOperand(1))) {
9884 Scale = cast<ConstantInt>(Inst->getOperand(1));
9885 NewIdx = Inst->getOperand(0);
9889 // If the index will be to exactly the right offset with the scale taken
9890 // out, perform the transformation. Note, we don't know whether Scale is
9891 // signed or not. We'll use unsigned version of division/modulo
9892 // operation after making sure Scale doesn't have the sign bit set.
9893 if (Scale && Scale->getSExtValue() >= 0LL &&
9894 Scale->getZExtValue() % ArrayEltSize == 0) {
9895 Scale = ConstantInt::get(Scale->getType(),
9896 Scale->getZExtValue() / ArrayEltSize);
9897 if (Scale->getZExtValue() != 1) {
9898 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
9900 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
9901 NewIdx = InsertNewInstBefore(Sc, GEP);
9904 // Insert the new GEP instruction.
9906 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9908 Instruction *NewGEP =
9909 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
9910 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9911 // The NewGEP must be pointer typed, so must the old one -> BitCast
9912 return new BitCastInst(NewGEP, GEP.getType());
9921 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9922 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9923 if (AI.isArrayAllocation()) { // Check C != 1
9924 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9926 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9927 AllocationInst *New = 0;
9929 // Create and insert the replacement instruction...
9930 if (isa<MallocInst>(AI))
9931 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9933 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9934 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9937 InsertNewInstBefore(New, AI);
9939 // Scan to the end of the allocation instructions, to skip over a block of
9940 // allocas if possible...
9942 BasicBlock::iterator It = New;
9943 while (isa<AllocationInst>(*It)) ++It;
9945 // Now that I is pointing to the first non-allocation-inst in the block,
9946 // insert our getelementptr instruction...
9948 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
9952 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
9953 New->getName()+".sub", It);
9955 // Now make everything use the getelementptr instead of the original
9957 return ReplaceInstUsesWith(AI, V);
9958 } else if (isa<UndefValue>(AI.getArraySize())) {
9959 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9963 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9964 // Note that we only do this for alloca's, because malloc should allocate and
9965 // return a unique pointer, even for a zero byte allocation.
9966 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
9967 TD->getABITypeSize(AI.getAllocatedType()) == 0)
9968 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9973 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9974 Value *Op = FI.getOperand(0);
9976 // free undef -> unreachable.
9977 if (isa<UndefValue>(Op)) {
9978 // Insert a new store to null because we cannot modify the CFG here.
9979 new StoreInst(ConstantInt::getTrue(),
9980 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
9981 return EraseInstFromFunction(FI);
9984 // If we have 'free null' delete the instruction. This can happen in stl code
9985 // when lots of inlining happens.
9986 if (isa<ConstantPointerNull>(Op))
9987 return EraseInstFromFunction(FI);
9989 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9990 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9991 FI.setOperand(0, CI->getOperand(0));
9995 // Change free (gep X, 0,0,0,0) into free(X)
9996 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9997 if (GEPI->hasAllZeroIndices()) {
9998 AddToWorkList(GEPI);
9999 FI.setOperand(0, GEPI->getOperand(0));
10004 // Change free(malloc) into nothing, if the malloc has a single use.
10005 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10006 if (MI->hasOneUse()) {
10007 EraseInstFromFunction(FI);
10008 return EraseInstFromFunction(*MI);
10015 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
10016 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
10017 const TargetData *TD) {
10018 User *CI = cast<User>(LI.getOperand(0));
10019 Value *CastOp = CI->getOperand(0);
10021 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10022 // Instead of loading constant c string, use corresponding integer value
10023 // directly if string length is small enough.
10025 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
10026 unsigned len = Str.length();
10027 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10028 unsigned numBits = Ty->getPrimitiveSizeInBits();
10029 // Replace LI with immediate integer store.
10030 if ((numBits >> 3) == len + 1) {
10031 APInt StrVal(numBits, 0);
10032 APInt SingleChar(numBits, 0);
10033 if (TD->isLittleEndian()) {
10034 for (signed i = len-1; i >= 0; i--) {
10035 SingleChar = (uint64_t) Str[i];
10036 StrVal = (StrVal << 8) | SingleChar;
10039 for (unsigned i = 0; i < len; i++) {
10040 SingleChar = (uint64_t) Str[i];
10041 StrVal = (StrVal << 8) | SingleChar;
10043 // Append NULL at the end.
10045 StrVal = (StrVal << 8) | SingleChar;
10047 Value *NL = ConstantInt::get(StrVal);
10048 return IC.ReplaceInstUsesWith(LI, NL);
10053 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10054 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10055 const Type *SrcPTy = SrcTy->getElementType();
10057 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
10058 isa<VectorType>(DestPTy)) {
10059 // If the source is an array, the code below will not succeed. Check to
10060 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10062 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10063 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10064 if (ASrcTy->getNumElements() != 0) {
10066 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10067 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10068 SrcTy = cast<PointerType>(CastOp->getType());
10069 SrcPTy = SrcTy->getElementType();
10072 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
10073 isa<VectorType>(SrcPTy)) &&
10074 // Do not allow turning this into a load of an integer, which is then
10075 // casted to a pointer, this pessimizes pointer analysis a lot.
10076 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10077 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10078 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10080 // Okay, we are casting from one integer or pointer type to another of
10081 // the same size. Instead of casting the pointer before the load, cast
10082 // the result of the loaded value.
10083 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10085 LI.isVolatile()),LI);
10086 // Now cast the result of the load.
10087 return new BitCastInst(NewLoad, LI.getType());
10094 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
10095 /// from this value cannot trap. If it is not obviously safe to load from the
10096 /// specified pointer, we do a quick local scan of the basic block containing
10097 /// ScanFrom, to determine if the address is already accessed.
10098 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
10099 // If it is an alloca it is always safe to load from.
10100 if (isa<AllocaInst>(V)) return true;
10102 // If it is a global variable it is mostly safe to load from.
10103 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
10104 // Don't try to evaluate aliases. External weak GV can be null.
10105 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
10107 // Otherwise, be a little bit agressive by scanning the local block where we
10108 // want to check to see if the pointer is already being loaded or stored
10109 // from/to. If so, the previous load or store would have already trapped,
10110 // so there is no harm doing an extra load (also, CSE will later eliminate
10111 // the load entirely).
10112 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10117 // If we see a free or a call (which might do a free) the pointer could be
10119 if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10122 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10123 if (LI->getOperand(0) == V) return true;
10124 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
10125 if (SI->getOperand(1) == V) return true;
10132 /// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10133 /// until we find the underlying object a pointer is referring to or something
10134 /// we don't understand. Note that the returned pointer may be offset from the
10135 /// input, because we ignore GEP indices.
10136 static Value *GetUnderlyingObject(Value *Ptr) {
10138 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10139 if (CE->getOpcode() == Instruction::BitCast ||
10140 CE->getOpcode() == Instruction::GetElementPtr)
10141 Ptr = CE->getOperand(0);
10144 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10145 Ptr = BCI->getOperand(0);
10146 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10147 Ptr = GEP->getOperand(0);
10154 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10155 Value *Op = LI.getOperand(0);
10157 // Attempt to improve the alignment.
10158 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10160 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10161 LI.getAlignment()))
10162 LI.setAlignment(KnownAlign);
10164 // load (cast X) --> cast (load X) iff safe
10165 if (isa<CastInst>(Op))
10166 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10169 // None of the following transforms are legal for volatile loads.
10170 if (LI.isVolatile()) return 0;
10172 if (&LI.getParent()->front() != &LI) {
10173 BasicBlock::iterator BBI = &LI; --BBI;
10174 // If the instruction immediately before this is a store to the same
10175 // address, do a simple form of store->load forwarding.
10176 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10177 if (SI->getOperand(1) == LI.getOperand(0))
10178 return ReplaceInstUsesWith(LI, SI->getOperand(0));
10179 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10180 if (LIB->getOperand(0) == LI.getOperand(0))
10181 return ReplaceInstUsesWith(LI, LIB);
10184 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10185 const Value *GEPI0 = GEPI->getOperand(0);
10186 // TODO: Consider a target hook for valid address spaces for this xform.
10187 if (isa<ConstantPointerNull>(GEPI0) &&
10188 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
10189 // Insert a new store to null instruction before the load to indicate
10190 // that this code is not reachable. We do this instead of inserting
10191 // an unreachable instruction directly because we cannot modify the
10193 new StoreInst(UndefValue::get(LI.getType()),
10194 Constant::getNullValue(Op->getType()), &LI);
10195 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10199 if (Constant *C = dyn_cast<Constant>(Op)) {
10200 // load null/undef -> undef
10201 // TODO: Consider a target hook for valid address spaces for this xform.
10202 if (isa<UndefValue>(C) || (C->isNullValue() &&
10203 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
10204 // Insert a new store to null instruction before the load to indicate that
10205 // this code is not reachable. We do this instead of inserting an
10206 // unreachable instruction directly because we cannot modify the CFG.
10207 new StoreInst(UndefValue::get(LI.getType()),
10208 Constant::getNullValue(Op->getType()), &LI);
10209 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10212 // Instcombine load (constant global) into the value loaded.
10213 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10214 if (GV->isConstant() && !GV->isDeclaration())
10215 return ReplaceInstUsesWith(LI, GV->getInitializer());
10217 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
10218 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
10219 if (CE->getOpcode() == Instruction::GetElementPtr) {
10220 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10221 if (GV->isConstant() && !GV->isDeclaration())
10223 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10224 return ReplaceInstUsesWith(LI, V);
10225 if (CE->getOperand(0)->isNullValue()) {
10226 // Insert a new store to null instruction before the load to indicate
10227 // that this code is not reachable. We do this instead of inserting
10228 // an unreachable instruction directly because we cannot modify the
10230 new StoreInst(UndefValue::get(LI.getType()),
10231 Constant::getNullValue(Op->getType()), &LI);
10232 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10235 } else if (CE->isCast()) {
10236 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
10242 // If this load comes from anywhere in a constant global, and if the global
10243 // is all undef or zero, we know what it loads.
10244 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10245 if (GV->isConstant() && GV->hasInitializer()) {
10246 if (GV->getInitializer()->isNullValue())
10247 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10248 else if (isa<UndefValue>(GV->getInitializer()))
10249 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10253 if (Op->hasOneUse()) {
10254 // Change select and PHI nodes to select values instead of addresses: this
10255 // helps alias analysis out a lot, allows many others simplifications, and
10256 // exposes redundancy in the code.
10258 // Note that we cannot do the transformation unless we know that the
10259 // introduced loads cannot trap! Something like this is valid as long as
10260 // the condition is always false: load (select bool %C, int* null, int* %G),
10261 // but it would not be valid if we transformed it to load from null
10262 // unconditionally.
10264 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10265 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
10266 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10267 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10268 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10269 SI->getOperand(1)->getName()+".val"), LI);
10270 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10271 SI->getOperand(2)->getName()+".val"), LI);
10272 return SelectInst::Create(SI->getCondition(), V1, V2);
10275 // load (select (cond, null, P)) -> load P
10276 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10277 if (C->isNullValue()) {
10278 LI.setOperand(0, SI->getOperand(2));
10282 // load (select (cond, P, null)) -> load P
10283 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10284 if (C->isNullValue()) {
10285 LI.setOperand(0, SI->getOperand(1));
10293 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10295 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10296 User *CI = cast<User>(SI.getOperand(1));
10297 Value *CastOp = CI->getOperand(0);
10299 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10300 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10301 const Type *SrcPTy = SrcTy->getElementType();
10303 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10304 // If the source is an array, the code below will not succeed. Check to
10305 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10307 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10308 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10309 if (ASrcTy->getNumElements() != 0) {
10311 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10312 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10313 SrcTy = cast<PointerType>(CastOp->getType());
10314 SrcPTy = SrcTy->getElementType();
10317 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10318 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10319 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10321 // Okay, we are casting from one integer or pointer type to another of
10322 // the same size. Instead of casting the pointer before
10323 // the store, cast the value to be stored.
10325 Value *SIOp0 = SI.getOperand(0);
10326 Instruction::CastOps opcode = Instruction::BitCast;
10327 const Type* CastSrcTy = SIOp0->getType();
10328 const Type* CastDstTy = SrcPTy;
10329 if (isa<PointerType>(CastDstTy)) {
10330 if (CastSrcTy->isInteger())
10331 opcode = Instruction::IntToPtr;
10332 } else if (isa<IntegerType>(CastDstTy)) {
10333 if (isa<PointerType>(SIOp0->getType()))
10334 opcode = Instruction::PtrToInt;
10336 if (Constant *C = dyn_cast<Constant>(SIOp0))
10337 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10339 NewCast = IC.InsertNewInstBefore(
10340 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
10342 return new StoreInst(NewCast, CastOp);
10349 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10350 Value *Val = SI.getOperand(0);
10351 Value *Ptr = SI.getOperand(1);
10353 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
10354 EraseInstFromFunction(SI);
10359 // If the RHS is an alloca with a single use, zapify the store, making the
10361 if (Ptr->hasOneUse() && !SI.isVolatile()) {
10362 if (isa<AllocaInst>(Ptr)) {
10363 EraseInstFromFunction(SI);
10368 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10369 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10370 GEP->getOperand(0)->hasOneUse()) {
10371 EraseInstFromFunction(SI);
10377 // Attempt to improve the alignment.
10378 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10380 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10381 SI.getAlignment()))
10382 SI.setAlignment(KnownAlign);
10384 // Do really simple DSE, to catch cases where there are several consequtive
10385 // stores to the same location, separated by a few arithmetic operations. This
10386 // situation often occurs with bitfield accesses.
10387 BasicBlock::iterator BBI = &SI;
10388 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10392 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10393 // Prev store isn't volatile, and stores to the same location?
10394 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10397 EraseInstFromFunction(*PrevSI);
10403 // If this is a load, we have to stop. However, if the loaded value is from
10404 // the pointer we're loading and is producing the pointer we're storing,
10405 // then *this* store is dead (X = load P; store X -> P).
10406 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10407 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
10408 EraseInstFromFunction(SI);
10412 // Otherwise, this is a load from some other location. Stores before it
10413 // may not be dead.
10417 // Don't skip over loads or things that can modify memory.
10418 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
10423 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
10425 // store X, null -> turns into 'unreachable' in SimplifyCFG
10426 if (isa<ConstantPointerNull>(Ptr)) {
10427 if (!isa<UndefValue>(Val)) {
10428 SI.setOperand(0, UndefValue::get(Val->getType()));
10429 if (Instruction *U = dyn_cast<Instruction>(Val))
10430 AddToWorkList(U); // Dropped a use.
10433 return 0; // Do not modify these!
10436 // store undef, Ptr -> noop
10437 if (isa<UndefValue>(Val)) {
10438 EraseInstFromFunction(SI);
10443 // If the pointer destination is a cast, see if we can fold the cast into the
10445 if (isa<CastInst>(Ptr))
10446 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10448 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10450 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10454 // If this store is the last instruction in the basic block, and if the block
10455 // ends with an unconditional branch, try to move it to the successor block.
10457 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10458 if (BI->isUnconditional())
10459 if (SimplifyStoreAtEndOfBlock(SI))
10460 return 0; // xform done!
10465 /// SimplifyStoreAtEndOfBlock - Turn things like:
10466 /// if () { *P = v1; } else { *P = v2 }
10467 /// into a phi node with a store in the successor.
10469 /// Simplify things like:
10470 /// *P = v1; if () { *P = v2; }
10471 /// into a phi node with a store in the successor.
10473 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10474 BasicBlock *StoreBB = SI.getParent();
10476 // Check to see if the successor block has exactly two incoming edges. If
10477 // so, see if the other predecessor contains a store to the same location.
10478 // if so, insert a PHI node (if needed) and move the stores down.
10479 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10481 // Determine whether Dest has exactly two predecessors and, if so, compute
10482 // the other predecessor.
10483 pred_iterator PI = pred_begin(DestBB);
10484 BasicBlock *OtherBB = 0;
10485 if (*PI != StoreBB)
10488 if (PI == pred_end(DestBB))
10491 if (*PI != StoreBB) {
10496 if (++PI != pred_end(DestBB))
10499 // Bail out if all the relevant blocks aren't distinct (this can happen,
10500 // for example, if SI is in an infinite loop)
10501 if (StoreBB == DestBB || OtherBB == DestBB)
10504 // Verify that the other block ends in a branch and is not otherwise empty.
10505 BasicBlock::iterator BBI = OtherBB->getTerminator();
10506 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10507 if (!OtherBr || BBI == OtherBB->begin())
10510 // If the other block ends in an unconditional branch, check for the 'if then
10511 // else' case. there is an instruction before the branch.
10512 StoreInst *OtherStore = 0;
10513 if (OtherBr->isUnconditional()) {
10514 // If this isn't a store, or isn't a store to the same location, bail out.
10516 OtherStore = dyn_cast<StoreInst>(BBI);
10517 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10520 // Otherwise, the other block ended with a conditional branch. If one of the
10521 // destinations is StoreBB, then we have the if/then case.
10522 if (OtherBr->getSuccessor(0) != StoreBB &&
10523 OtherBr->getSuccessor(1) != StoreBB)
10526 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10527 // if/then triangle. See if there is a store to the same ptr as SI that
10528 // lives in OtherBB.
10530 // Check to see if we find the matching store.
10531 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10532 if (OtherStore->getOperand(1) != SI.getOperand(1))
10536 // If we find something that may be using or overwriting the stored
10537 // value, or if we run out of instructions, we can't do the xform.
10538 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
10539 BBI == OtherBB->begin())
10543 // In order to eliminate the store in OtherBr, we have to
10544 // make sure nothing reads or overwrites the stored value in
10546 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10547 // FIXME: This should really be AA driven.
10548 if (I->mayReadFromMemory() || I->mayWriteToMemory())
10553 // Insert a PHI node now if we need it.
10554 Value *MergedVal = OtherStore->getOperand(0);
10555 if (MergedVal != SI.getOperand(0)) {
10556 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
10557 PN->reserveOperandSpace(2);
10558 PN->addIncoming(SI.getOperand(0), SI.getParent());
10559 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10560 MergedVal = InsertNewInstBefore(PN, DestBB->front());
10563 // Advance to a place where it is safe to insert the new store and
10565 BBI = DestBB->getFirstNonPHI();
10566 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10567 OtherStore->isVolatile()), *BBI);
10569 // Nuke the old stores.
10570 EraseInstFromFunction(SI);
10571 EraseInstFromFunction(*OtherStore);
10577 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10578 // Change br (not X), label True, label False to: br X, label False, True
10580 BasicBlock *TrueDest;
10581 BasicBlock *FalseDest;
10582 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10583 !isa<Constant>(X)) {
10584 // Swap Destinations and condition...
10585 BI.setCondition(X);
10586 BI.setSuccessor(0, FalseDest);
10587 BI.setSuccessor(1, TrueDest);
10591 // Cannonicalize fcmp_one -> fcmp_oeq
10592 FCmpInst::Predicate FPred; Value *Y;
10593 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10594 TrueDest, FalseDest)))
10595 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10596 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10597 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10598 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10599 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10600 NewSCC->takeName(I);
10601 // Swap Destinations and condition...
10602 BI.setCondition(NewSCC);
10603 BI.setSuccessor(0, FalseDest);
10604 BI.setSuccessor(1, TrueDest);
10605 RemoveFromWorkList(I);
10606 I->eraseFromParent();
10607 AddToWorkList(NewSCC);
10611 // Cannonicalize icmp_ne -> icmp_eq
10612 ICmpInst::Predicate IPred;
10613 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10614 TrueDest, FalseDest)))
10615 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10616 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10617 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10618 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10619 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10620 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10621 NewSCC->takeName(I);
10622 // Swap Destinations and condition...
10623 BI.setCondition(NewSCC);
10624 BI.setSuccessor(0, FalseDest);
10625 BI.setSuccessor(1, TrueDest);
10626 RemoveFromWorkList(I);
10627 I->eraseFromParent();;
10628 AddToWorkList(NewSCC);
10635 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10636 Value *Cond = SI.getCondition();
10637 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10638 if (I->getOpcode() == Instruction::Add)
10639 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10640 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10641 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10642 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10644 SI.setOperand(0, I->getOperand(0));
10652 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
10653 // See if we are trying to extract a known value. If so, use that instead.
10654 if (Value *Elt = FindInsertedValue(EV.getOperand(0), EV.idx_begin(),
10655 EV.idx_end(), &EV))
10656 return ReplaceInstUsesWith(EV, Elt);
10662 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10663 /// is to leave as a vector operation.
10664 static bool CheapToScalarize(Value *V, bool isConstant) {
10665 if (isa<ConstantAggregateZero>(V))
10667 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10668 if (isConstant) return true;
10669 // If all elts are the same, we can extract.
10670 Constant *Op0 = C->getOperand(0);
10671 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10672 if (C->getOperand(i) != Op0)
10676 Instruction *I = dyn_cast<Instruction>(V);
10677 if (!I) return false;
10679 // Insert element gets simplified to the inserted element or is deleted if
10680 // this is constant idx extract element and its a constant idx insertelt.
10681 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10682 isa<ConstantInt>(I->getOperand(2)))
10684 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10686 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10687 if (BO->hasOneUse() &&
10688 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10689 CheapToScalarize(BO->getOperand(1), isConstant)))
10691 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10692 if (CI->hasOneUse() &&
10693 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10694 CheapToScalarize(CI->getOperand(1), isConstant)))
10700 /// Read and decode a shufflevector mask.
10702 /// It turns undef elements into values that are larger than the number of
10703 /// elements in the input.
10704 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10705 unsigned NElts = SVI->getType()->getNumElements();
10706 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10707 return std::vector<unsigned>(NElts, 0);
10708 if (isa<UndefValue>(SVI->getOperand(2)))
10709 return std::vector<unsigned>(NElts, 2*NElts);
10711 std::vector<unsigned> Result;
10712 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10713 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
10714 if (isa<UndefValue>(*i))
10715 Result.push_back(NElts*2); // undef -> 8
10717 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
10721 /// FindScalarElement - Given a vector and an element number, see if the scalar
10722 /// value is already around as a register, for example if it were inserted then
10723 /// extracted from the vector.
10724 static Value *FindScalarElement(Value *V, unsigned EltNo) {
10725 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10726 const VectorType *PTy = cast<VectorType>(V->getType());
10727 unsigned Width = PTy->getNumElements();
10728 if (EltNo >= Width) // Out of range access.
10729 return UndefValue::get(PTy->getElementType());
10731 if (isa<UndefValue>(V))
10732 return UndefValue::get(PTy->getElementType());
10733 else if (isa<ConstantAggregateZero>(V))
10734 return Constant::getNullValue(PTy->getElementType());
10735 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10736 return CP->getOperand(EltNo);
10737 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10738 // If this is an insert to a variable element, we don't know what it is.
10739 if (!isa<ConstantInt>(III->getOperand(2)))
10741 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10743 // If this is an insert to the element we are looking for, return the
10745 if (EltNo == IIElt)
10746 return III->getOperand(1);
10748 // Otherwise, the insertelement doesn't modify the value, recurse on its
10750 return FindScalarElement(III->getOperand(0), EltNo);
10751 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10752 unsigned InEl = getShuffleMask(SVI)[EltNo];
10754 return FindScalarElement(SVI->getOperand(0), InEl);
10755 else if (InEl < Width*2)
10756 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10758 return UndefValue::get(PTy->getElementType());
10761 // Otherwise, we don't know.
10765 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10766 // If vector val is undef, replace extract with scalar undef.
10767 if (isa<UndefValue>(EI.getOperand(0)))
10768 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10770 // If vector val is constant 0, replace extract with scalar 0.
10771 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10772 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10774 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10775 // If vector val is constant with all elements the same, replace EI with
10776 // that element. When the elements are not identical, we cannot replace yet
10777 // (we do that below, but only when the index is constant).
10778 Constant *op0 = C->getOperand(0);
10779 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10780 if (C->getOperand(i) != op0) {
10785 return ReplaceInstUsesWith(EI, op0);
10788 // If extracting a specified index from the vector, see if we can recursively
10789 // find a previously computed scalar that was inserted into the vector.
10790 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10791 unsigned IndexVal = IdxC->getZExtValue();
10792 unsigned VectorWidth =
10793 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10795 // If this is extracting an invalid index, turn this into undef, to avoid
10796 // crashing the code below.
10797 if (IndexVal >= VectorWidth)
10798 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10800 // This instruction only demands the single element from the input vector.
10801 // If the input vector has a single use, simplify it based on this use
10803 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10804 uint64_t UndefElts;
10805 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10808 EI.setOperand(0, V);
10813 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10814 return ReplaceInstUsesWith(EI, Elt);
10816 // If the this extractelement is directly using a bitcast from a vector of
10817 // the same number of elements, see if we can find the source element from
10818 // it. In this case, we will end up needing to bitcast the scalars.
10819 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10820 if (const VectorType *VT =
10821 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10822 if (VT->getNumElements() == VectorWidth)
10823 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10824 return new BitCastInst(Elt, EI.getType());
10828 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10829 if (I->hasOneUse()) {
10830 // Push extractelement into predecessor operation if legal and
10831 // profitable to do so
10832 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10833 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10834 if (CheapToScalarize(BO, isConstantElt)) {
10835 ExtractElementInst *newEI0 =
10836 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10837 EI.getName()+".lhs");
10838 ExtractElementInst *newEI1 =
10839 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10840 EI.getName()+".rhs");
10841 InsertNewInstBefore(newEI0, EI);
10842 InsertNewInstBefore(newEI1, EI);
10843 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
10845 } else if (isa<LoadInst>(I)) {
10847 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
10848 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10849 PointerType::get(EI.getType(), AS),EI);
10850 GetElementPtrInst *GEP =
10851 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
10852 InsertNewInstBefore(GEP, EI);
10853 return new LoadInst(GEP);
10856 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10857 // Extracting the inserted element?
10858 if (IE->getOperand(2) == EI.getOperand(1))
10859 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10860 // If the inserted and extracted elements are constants, they must not
10861 // be the same value, extract from the pre-inserted value instead.
10862 if (isa<Constant>(IE->getOperand(2)) &&
10863 isa<Constant>(EI.getOperand(1))) {
10864 AddUsesToWorkList(EI);
10865 EI.setOperand(0, IE->getOperand(0));
10868 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10869 // If this is extracting an element from a shufflevector, figure out where
10870 // it came from and extract from the appropriate input element instead.
10871 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10872 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10874 if (SrcIdx < SVI->getType()->getNumElements())
10875 Src = SVI->getOperand(0);
10876 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10877 SrcIdx -= SVI->getType()->getNumElements();
10878 Src = SVI->getOperand(1);
10880 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10882 return new ExtractElementInst(Src, SrcIdx);
10889 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10890 /// elements from either LHS or RHS, return the shuffle mask and true.
10891 /// Otherwise, return false.
10892 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10893 std::vector<Constant*> &Mask) {
10894 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10895 "Invalid CollectSingleShuffleElements");
10896 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10898 if (isa<UndefValue>(V)) {
10899 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10901 } else if (V == LHS) {
10902 for (unsigned i = 0; i != NumElts; ++i)
10903 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10905 } else if (V == RHS) {
10906 for (unsigned i = 0; i != NumElts; ++i)
10907 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10909 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10910 // If this is an insert of an extract from some other vector, include it.
10911 Value *VecOp = IEI->getOperand(0);
10912 Value *ScalarOp = IEI->getOperand(1);
10913 Value *IdxOp = IEI->getOperand(2);
10915 if (!isa<ConstantInt>(IdxOp))
10917 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10919 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10920 // Okay, we can handle this if the vector we are insertinting into is
10921 // transitively ok.
10922 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10923 // If so, update the mask to reflect the inserted undef.
10924 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10927 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10928 if (isa<ConstantInt>(EI->getOperand(1)) &&
10929 EI->getOperand(0)->getType() == V->getType()) {
10930 unsigned ExtractedIdx =
10931 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10933 // This must be extracting from either LHS or RHS.
10934 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10935 // Okay, we can handle this if the vector we are insertinting into is
10936 // transitively ok.
10937 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10938 // If so, update the mask to reflect the inserted value.
10939 if (EI->getOperand(0) == LHS) {
10940 Mask[InsertedIdx & (NumElts-1)] =
10941 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10943 assert(EI->getOperand(0) == RHS);
10944 Mask[InsertedIdx & (NumElts-1)] =
10945 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10954 // TODO: Handle shufflevector here!
10959 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10960 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10961 /// that computes V and the LHS value of the shuffle.
10962 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10964 assert(isa<VectorType>(V->getType()) &&
10965 (RHS == 0 || V->getType() == RHS->getType()) &&
10966 "Invalid shuffle!");
10967 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10969 if (isa<UndefValue>(V)) {
10970 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10972 } else if (isa<ConstantAggregateZero>(V)) {
10973 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10975 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10976 // If this is an insert of an extract from some other vector, include it.
10977 Value *VecOp = IEI->getOperand(0);
10978 Value *ScalarOp = IEI->getOperand(1);
10979 Value *IdxOp = IEI->getOperand(2);
10981 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10982 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10983 EI->getOperand(0)->getType() == V->getType()) {
10984 unsigned ExtractedIdx =
10985 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10986 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10988 // Either the extracted from or inserted into vector must be RHSVec,
10989 // otherwise we'd end up with a shuffle of three inputs.
10990 if (EI->getOperand(0) == RHS || RHS == 0) {
10991 RHS = EI->getOperand(0);
10992 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10993 Mask[InsertedIdx & (NumElts-1)] =
10994 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10998 if (VecOp == RHS) {
10999 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11000 // Everything but the extracted element is replaced with the RHS.
11001 for (unsigned i = 0; i != NumElts; ++i) {
11002 if (i != InsertedIdx)
11003 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11008 // If this insertelement is a chain that comes from exactly these two
11009 // vectors, return the vector and the effective shuffle.
11010 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11011 return EI->getOperand(0);
11016 // TODO: Handle shufflevector here!
11018 // Otherwise, can't do anything fancy. Return an identity vector.
11019 for (unsigned i = 0; i != NumElts; ++i)
11020 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11024 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11025 Value *VecOp = IE.getOperand(0);
11026 Value *ScalarOp = IE.getOperand(1);
11027 Value *IdxOp = IE.getOperand(2);
11029 // Inserting an undef or into an undefined place, remove this.
11030 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11031 ReplaceInstUsesWith(IE, VecOp);
11033 // If the inserted element was extracted from some other vector, and if the
11034 // indexes are constant, try to turn this into a shufflevector operation.
11035 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11036 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11037 EI->getOperand(0)->getType() == IE.getType()) {
11038 unsigned NumVectorElts = IE.getType()->getNumElements();
11039 unsigned ExtractedIdx =
11040 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11041 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11043 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11044 return ReplaceInstUsesWith(IE, VecOp);
11046 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11047 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11049 // If we are extracting a value from a vector, then inserting it right
11050 // back into the same place, just use the input vector.
11051 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11052 return ReplaceInstUsesWith(IE, VecOp);
11054 // We could theoretically do this for ANY input. However, doing so could
11055 // turn chains of insertelement instructions into a chain of shufflevector
11056 // instructions, and right now we do not merge shufflevectors. As such,
11057 // only do this in a situation where it is clear that there is benefit.
11058 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11059 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11060 // the values of VecOp, except then one read from EIOp0.
11061 // Build a new shuffle mask.
11062 std::vector<Constant*> Mask;
11063 if (isa<UndefValue>(VecOp))
11064 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11066 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11067 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11070 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11071 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11072 ConstantVector::get(Mask));
11075 // If this insertelement isn't used by some other insertelement, turn it
11076 // (and any insertelements it points to), into one big shuffle.
11077 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11078 std::vector<Constant*> Mask;
11080 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11081 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11082 // We now have a shuffle of LHS, RHS, Mask.
11083 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11092 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11093 Value *LHS = SVI.getOperand(0);
11094 Value *RHS = SVI.getOperand(1);
11095 std::vector<unsigned> Mask = getShuffleMask(&SVI);
11097 bool MadeChange = false;
11099 // Undefined shuffle mask -> undefined value.
11100 if (isa<UndefValue>(SVI.getOperand(2)))
11101 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11103 // If we have shuffle(x, undef, mask) and any elements of mask refer to
11104 // the undef, change them to undefs.
11105 if (isa<UndefValue>(SVI.getOperand(1))) {
11106 // Scan to see if there are any references to the RHS. If so, replace them
11107 // with undef element refs and set MadeChange to true.
11108 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11109 if (Mask[i] >= e && Mask[i] != 2*e) {
11116 // Remap any references to RHS to use LHS.
11117 std::vector<Constant*> Elts;
11118 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11119 if (Mask[i] == 2*e)
11120 Elts.push_back(UndefValue::get(Type::Int32Ty));
11122 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11124 SVI.setOperand(2, ConstantVector::get(Elts));
11128 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11129 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11130 if (LHS == RHS || isa<UndefValue>(LHS)) {
11131 if (isa<UndefValue>(LHS) && LHS == RHS) {
11132 // shuffle(undef,undef,mask) -> undef.
11133 return ReplaceInstUsesWith(SVI, LHS);
11136 // Remap any references to RHS to use LHS.
11137 std::vector<Constant*> Elts;
11138 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11139 if (Mask[i] >= 2*e)
11140 Elts.push_back(UndefValue::get(Type::Int32Ty));
11142 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11143 (Mask[i] < e && isa<UndefValue>(LHS)))
11144 Mask[i] = 2*e; // Turn into undef.
11146 Mask[i] &= (e-1); // Force to LHS.
11147 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11150 SVI.setOperand(0, SVI.getOperand(1));
11151 SVI.setOperand(1, UndefValue::get(RHS->getType()));
11152 SVI.setOperand(2, ConstantVector::get(Elts));
11153 LHS = SVI.getOperand(0);
11154 RHS = SVI.getOperand(1);
11158 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11159 bool isLHSID = true, isRHSID = true;
11161 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11162 if (Mask[i] >= e*2) continue; // Ignore undef values.
11163 // Is this an identity shuffle of the LHS value?
11164 isLHSID &= (Mask[i] == i);
11166 // Is this an identity shuffle of the RHS value?
11167 isRHSID &= (Mask[i]-e == i);
11170 // Eliminate identity shuffles.
11171 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11172 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11174 // If the LHS is a shufflevector itself, see if we can combine it with this
11175 // one without producing an unusual shuffle. Here we are really conservative:
11176 // we are absolutely afraid of producing a shuffle mask not in the input
11177 // program, because the code gen may not be smart enough to turn a merged
11178 // shuffle into two specific shuffles: it may produce worse code. As such,
11179 // we only merge two shuffles if the result is one of the two input shuffle
11180 // masks. In this case, merging the shuffles just removes one instruction,
11181 // which we know is safe. This is good for things like turning:
11182 // (splat(splat)) -> splat.
11183 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11184 if (isa<UndefValue>(RHS)) {
11185 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11187 std::vector<unsigned> NewMask;
11188 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11189 if (Mask[i] >= 2*e)
11190 NewMask.push_back(2*e);
11192 NewMask.push_back(LHSMask[Mask[i]]);
11194 // If the result mask is equal to the src shuffle or this shuffle mask, do
11195 // the replacement.
11196 if (NewMask == LHSMask || NewMask == Mask) {
11197 std::vector<Constant*> Elts;
11198 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11199 if (NewMask[i] >= e*2) {
11200 Elts.push_back(UndefValue::get(Type::Int32Ty));
11202 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11205 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11206 LHSSVI->getOperand(1),
11207 ConstantVector::get(Elts));
11212 return MadeChange ? &SVI : 0;
11218 /// TryToSinkInstruction - Try to move the specified instruction from its
11219 /// current block into the beginning of DestBlock, which can only happen if it's
11220 /// safe to move the instruction past all of the instructions between it and the
11221 /// end of its block.
11222 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11223 assert(I->hasOneUse() && "Invariants didn't hold!");
11225 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
11226 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11229 // Do not sink alloca instructions out of the entry block.
11230 if (isa<AllocaInst>(I) && I->getParent() ==
11231 &DestBlock->getParent()->getEntryBlock())
11234 // We can only sink load instructions if there is nothing between the load and
11235 // the end of block that could change the value.
11236 if (I->mayReadFromMemory()) {
11237 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
11239 if (Scan->mayWriteToMemory())
11243 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
11245 I->moveBefore(InsertPos);
11251 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11252 /// all reachable code to the worklist.
11254 /// This has a couple of tricks to make the code faster and more powerful. In
11255 /// particular, we constant fold and DCE instructions as we go, to avoid adding
11256 /// them to the worklist (this significantly speeds up instcombine on code where
11257 /// many instructions are dead or constant). Additionally, if we find a branch
11258 /// whose condition is a known constant, we only visit the reachable successors.
11260 static void AddReachableCodeToWorklist(BasicBlock *BB,
11261 SmallPtrSet<BasicBlock*, 64> &Visited,
11263 const TargetData *TD) {
11264 std::vector<BasicBlock*> Worklist;
11265 Worklist.push_back(BB);
11267 while (!Worklist.empty()) {
11268 BB = Worklist.back();
11269 Worklist.pop_back();
11271 // We have now visited this block! If we've already been here, ignore it.
11272 if (!Visited.insert(BB)) continue;
11274 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11275 Instruction *Inst = BBI++;
11277 // DCE instruction if trivially dead.
11278 if (isInstructionTriviallyDead(Inst)) {
11280 DOUT << "IC: DCE: " << *Inst;
11281 Inst->eraseFromParent();
11285 // ConstantProp instruction if trivially constant.
11286 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11287 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11288 Inst->replaceAllUsesWith(C);
11290 Inst->eraseFromParent();
11294 IC.AddToWorkList(Inst);
11297 // Recursively visit successors. If this is a branch or switch on a
11298 // constant, only visit the reachable successor.
11299 TerminatorInst *TI = BB->getTerminator();
11300 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11301 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11302 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
11303 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
11304 Worklist.push_back(ReachableBB);
11307 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11308 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11309 // See if this is an explicit destination.
11310 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11311 if (SI->getCaseValue(i) == Cond) {
11312 BasicBlock *ReachableBB = SI->getSuccessor(i);
11313 Worklist.push_back(ReachableBB);
11317 // Otherwise it is the default destination.
11318 Worklist.push_back(SI->getSuccessor(0));
11323 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11324 Worklist.push_back(TI->getSuccessor(i));
11328 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11329 bool Changed = false;
11330 TD = &getAnalysis<TargetData>();
11332 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11333 << F.getNameStr() << "\n");
11336 // Do a depth-first traversal of the function, populate the worklist with
11337 // the reachable instructions. Ignore blocks that are not reachable. Keep
11338 // track of which blocks we visit.
11339 SmallPtrSet<BasicBlock*, 64> Visited;
11340 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11342 // Do a quick scan over the function. If we find any blocks that are
11343 // unreachable, remove any instructions inside of them. This prevents
11344 // the instcombine code from having to deal with some bad special cases.
11345 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11346 if (!Visited.count(BB)) {
11347 Instruction *Term = BB->getTerminator();
11348 while (Term != BB->begin()) { // Remove instrs bottom-up
11349 BasicBlock::iterator I = Term; --I;
11351 DOUT << "IC: DCE: " << *I;
11354 if (!I->use_empty())
11355 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11356 I->eraseFromParent();
11361 while (!Worklist.empty()) {
11362 Instruction *I = RemoveOneFromWorkList();
11363 if (I == 0) continue; // skip null values.
11365 // Check to see if we can DCE the instruction.
11366 if (isInstructionTriviallyDead(I)) {
11367 // Add operands to the worklist.
11368 if (I->getNumOperands() < 4)
11369 AddUsesToWorkList(*I);
11372 DOUT << "IC: DCE: " << *I;
11374 I->eraseFromParent();
11375 RemoveFromWorkList(I);
11379 // Instruction isn't dead, see if we can constant propagate it.
11380 if (Constant *C = ConstantFoldInstruction(I, TD)) {
11381 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11383 // Add operands to the worklist.
11384 AddUsesToWorkList(*I);
11385 ReplaceInstUsesWith(*I, C);
11388 I->eraseFromParent();
11389 RemoveFromWorkList(I);
11393 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
11394 // See if we can constant fold its operands.
11395 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
11396 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
11397 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
11403 // See if we can trivially sink this instruction to a successor basic block.
11404 // FIXME: Remove GetResultInst test when first class support for aggregates
11406 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
11407 BasicBlock *BB = I->getParent();
11408 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11409 if (UserParent != BB) {
11410 bool UserIsSuccessor = false;
11411 // See if the user is one of our successors.
11412 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11413 if (*SI == UserParent) {
11414 UserIsSuccessor = true;
11418 // If the user is one of our immediate successors, and if that successor
11419 // only has us as a predecessors (we'd have to split the critical edge
11420 // otherwise), we can keep going.
11421 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11422 next(pred_begin(UserParent)) == pred_end(UserParent))
11423 // Okay, the CFG is simple enough, try to sink this instruction.
11424 Changed |= TryToSinkInstruction(I, UserParent);
11428 // Now that we have an instruction, try combining it to simplify it...
11432 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11433 if (Instruction *Result = visit(*I)) {
11435 // Should we replace the old instruction with a new one?
11437 DOUT << "IC: Old = " << *I
11438 << " New = " << *Result;
11440 // Everything uses the new instruction now.
11441 I->replaceAllUsesWith(Result);
11443 // Push the new instruction and any users onto the worklist.
11444 AddToWorkList(Result);
11445 AddUsersToWorkList(*Result);
11447 // Move the name to the new instruction first.
11448 Result->takeName(I);
11450 // Insert the new instruction into the basic block...
11451 BasicBlock *InstParent = I->getParent();
11452 BasicBlock::iterator InsertPos = I;
11454 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11455 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11458 InstParent->getInstList().insert(InsertPos, Result);
11460 // Make sure that we reprocess all operands now that we reduced their
11462 AddUsesToWorkList(*I);
11464 // Instructions can end up on the worklist more than once. Make sure
11465 // we do not process an instruction that has been deleted.
11466 RemoveFromWorkList(I);
11468 // Erase the old instruction.
11469 InstParent->getInstList().erase(I);
11472 DOUT << "IC: Mod = " << OrigI
11473 << " New = " << *I;
11476 // If the instruction was modified, it's possible that it is now dead.
11477 // if so, remove it.
11478 if (isInstructionTriviallyDead(I)) {
11479 // Make sure we process all operands now that we are reducing their
11481 AddUsesToWorkList(*I);
11483 // Instructions may end up in the worklist more than once. Erase all
11484 // occurrences of this instruction.
11485 RemoveFromWorkList(I);
11486 I->eraseFromParent();
11489 AddUsersToWorkList(*I);
11496 assert(WorklistMap.empty() && "Worklist empty, but map not?");
11498 // Do an explicit clear, this shrinks the map if needed.
11499 WorklistMap.clear();
11504 bool InstCombiner::runOnFunction(Function &F) {
11505 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11507 bool EverMadeChange = false;
11509 // Iterate while there is work to do.
11510 unsigned Iteration = 0;
11511 while (DoOneIteration(F, Iteration++))
11512 EverMadeChange = true;
11513 return EverMadeChange;
11516 FunctionPass *llvm::createInstructionCombiningPass() {
11517 return new InstCombiner();