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/LLVMContext.h"
40 #include "llvm/Pass.h"
41 #include "llvm/DerivedTypes.h"
42 #include "llvm/GlobalVariable.h"
43 #include "llvm/Operator.h"
44 #include "llvm/Analysis/ConstantFolding.h"
45 #include "llvm/Analysis/ValueTracking.h"
46 #include "llvm/Target/TargetData.h"
47 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
48 #include "llvm/Transforms/Utils/Local.h"
49 #include "llvm/Support/CallSite.h"
50 #include "llvm/Support/ConstantRange.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/GetElementPtrTypeIterator.h"
54 #include "llvm/Support/InstVisitor.h"
55 #include "llvm/Support/MathExtras.h"
56 #include "llvm/Support/PatternMatch.h"
57 #include "llvm/Support/Compiler.h"
58 #include "llvm/Support/raw_ostream.h"
59 #include "llvm/ADT/DenseMap.h"
60 #include "llvm/ADT/SmallVector.h"
61 #include "llvm/ADT/SmallPtrSet.h"
62 #include "llvm/ADT/Statistic.h"
63 #include "llvm/ADT/STLExtras.h"
68 using namespace llvm::PatternMatch;
70 STATISTIC(NumCombined , "Number of insts combined");
71 STATISTIC(NumConstProp, "Number of constant folds");
72 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
73 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
74 STATISTIC(NumSunkInst , "Number of instructions sunk");
77 class VISIBILITY_HIDDEN InstCombiner
78 : public FunctionPass,
79 public InstVisitor<InstCombiner, Instruction*> {
80 // Worklist of all of the instructions that need to be simplified.
81 SmallVector<Instruction*, 256> Worklist;
82 DenseMap<Instruction*, unsigned> WorklistMap;
84 bool MustPreserveLCSSA;
86 static char ID; // Pass identification, replacement for typeid
87 InstCombiner() : FunctionPass(&ID) {}
90 LLVMContext *getContext() const { return Context; }
92 /// AddToWorkList - Add the specified instruction to the worklist if it
93 /// isn't already in it.
94 void AddToWorkList(Instruction *I) {
95 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
96 Worklist.push_back(I);
99 // RemoveFromWorkList - remove I from the worklist if it exists.
100 void RemoveFromWorkList(Instruction *I) {
101 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
102 if (It == WorklistMap.end()) return; // Not in worklist.
104 // Don't bother moving everything down, just null out the slot.
105 Worklist[It->second] = 0;
107 WorklistMap.erase(It);
110 Instruction *RemoveOneFromWorkList() {
111 Instruction *I = Worklist.back();
113 WorklistMap.erase(I);
118 /// AddUsersToWorkList - When an instruction is simplified, add all users of
119 /// the instruction to the work lists because they might get more simplified
122 void AddUsersToWorkList(Value &I) {
123 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
125 AddToWorkList(cast<Instruction>(*UI));
128 /// AddUsesToWorkList - When an instruction is simplified, add operands to
129 /// the work lists because they might get more simplified now.
131 void AddUsesToWorkList(Instruction &I) {
132 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
133 if (Instruction *Op = dyn_cast<Instruction>(*i))
137 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
138 /// dead. Add all of its operands to the worklist, turning them into
139 /// undef's to reduce the number of uses of those instructions.
141 /// Return the specified operand before it is turned into an undef.
143 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
144 Value *R = I.getOperand(op);
146 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
147 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
149 // Set the operand to undef to drop the use.
150 *i = UndefValue::get(Op->getType());
157 virtual bool runOnFunction(Function &F);
159 bool DoOneIteration(Function &F, unsigned ItNum);
161 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
162 AU.addPreservedID(LCSSAID);
163 AU.setPreservesCFG();
166 TargetData *getTargetData() const { return TD; }
168 // Visitation implementation - Implement instruction combining for different
169 // instruction types. The semantics are as follows:
171 // null - No change was made
172 // I - Change was made, I is still valid, I may be dead though
173 // otherwise - Change was made, replace I with returned instruction
175 Instruction *visitAdd(BinaryOperator &I);
176 Instruction *visitFAdd(BinaryOperator &I);
177 Instruction *visitSub(BinaryOperator &I);
178 Instruction *visitFSub(BinaryOperator &I);
179 Instruction *visitMul(BinaryOperator &I);
180 Instruction *visitFMul(BinaryOperator &I);
181 Instruction *visitURem(BinaryOperator &I);
182 Instruction *visitSRem(BinaryOperator &I);
183 Instruction *visitFRem(BinaryOperator &I);
184 bool SimplifyDivRemOfSelect(BinaryOperator &I);
185 Instruction *commonRemTransforms(BinaryOperator &I);
186 Instruction *commonIRemTransforms(BinaryOperator &I);
187 Instruction *commonDivTransforms(BinaryOperator &I);
188 Instruction *commonIDivTransforms(BinaryOperator &I);
189 Instruction *visitUDiv(BinaryOperator &I);
190 Instruction *visitSDiv(BinaryOperator &I);
191 Instruction *visitFDiv(BinaryOperator &I);
192 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
193 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
194 Instruction *visitAnd(BinaryOperator &I);
195 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
196 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
197 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
198 Value *A, Value *B, Value *C);
199 Instruction *visitOr (BinaryOperator &I);
200 Instruction *visitXor(BinaryOperator &I);
201 Instruction *visitShl(BinaryOperator &I);
202 Instruction *visitAShr(BinaryOperator &I);
203 Instruction *visitLShr(BinaryOperator &I);
204 Instruction *commonShiftTransforms(BinaryOperator &I);
205 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
207 Instruction *visitFCmpInst(FCmpInst &I);
208 Instruction *visitICmpInst(ICmpInst &I);
209 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
210 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
213 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
214 ConstantInt *DivRHS);
216 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
217 ICmpInst::Predicate Cond, Instruction &I);
218 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
220 Instruction *commonCastTransforms(CastInst &CI);
221 Instruction *commonIntCastTransforms(CastInst &CI);
222 Instruction *commonPointerCastTransforms(CastInst &CI);
223 Instruction *visitTrunc(TruncInst &CI);
224 Instruction *visitZExt(ZExtInst &CI);
225 Instruction *visitSExt(SExtInst &CI);
226 Instruction *visitFPTrunc(FPTruncInst &CI);
227 Instruction *visitFPExt(CastInst &CI);
228 Instruction *visitFPToUI(FPToUIInst &FI);
229 Instruction *visitFPToSI(FPToSIInst &FI);
230 Instruction *visitUIToFP(CastInst &CI);
231 Instruction *visitSIToFP(CastInst &CI);
232 Instruction *visitPtrToInt(PtrToIntInst &CI);
233 Instruction *visitIntToPtr(IntToPtrInst &CI);
234 Instruction *visitBitCast(BitCastInst &CI);
235 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
237 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
238 Instruction *visitSelectInst(SelectInst &SI);
239 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
240 Instruction *visitCallInst(CallInst &CI);
241 Instruction *visitInvokeInst(InvokeInst &II);
242 Instruction *visitPHINode(PHINode &PN);
243 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
244 Instruction *visitAllocationInst(AllocationInst &AI);
245 Instruction *visitFreeInst(FreeInst &FI);
246 Instruction *visitLoadInst(LoadInst &LI);
247 Instruction *visitStoreInst(StoreInst &SI);
248 Instruction *visitBranchInst(BranchInst &BI);
249 Instruction *visitSwitchInst(SwitchInst &SI);
250 Instruction *visitInsertElementInst(InsertElementInst &IE);
251 Instruction *visitExtractElementInst(ExtractElementInst &EI);
252 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
253 Instruction *visitExtractValueInst(ExtractValueInst &EV);
255 // visitInstruction - Specify what to return for unhandled instructions...
256 Instruction *visitInstruction(Instruction &I) { return 0; }
259 Instruction *visitCallSite(CallSite CS);
260 bool transformConstExprCastCall(CallSite CS);
261 Instruction *transformCallThroughTrampoline(CallSite CS);
262 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
263 bool DoXform = true);
264 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
265 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
269 // InsertNewInstBefore - insert an instruction New before instruction Old
270 // in the program. Add the new instruction to the worklist.
272 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
273 assert(New && New->getParent() == 0 &&
274 "New instruction already inserted into a basic block!");
275 BasicBlock *BB = Old.getParent();
276 BB->getInstList().insert(&Old, New); // Insert inst
281 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
282 /// This also adds the cast to the worklist. Finally, this returns the
284 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
286 if (V->getType() == Ty) return V;
288 if (Constant *CV = dyn_cast<Constant>(V))
289 return ConstantExpr::getCast(opc, CV, Ty);
291 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
296 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
297 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
301 // ReplaceInstUsesWith - This method is to be used when an instruction is
302 // found to be dead, replacable with another preexisting expression. Here
303 // we add all uses of I to the worklist, replace all uses of I with the new
304 // value, then return I, so that the inst combiner will know that I was
307 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
308 AddUsersToWorkList(I); // Add all modified instrs to worklist
310 I.replaceAllUsesWith(V);
313 // If we are replacing the instruction with itself, this must be in a
314 // segment of unreachable code, so just clobber the instruction.
315 I.replaceAllUsesWith(UndefValue::get(I.getType()));
320 // EraseInstFromFunction - When dealing with an instruction that has side
321 // effects or produces a void value, we can't rely on DCE to delete the
322 // instruction. Instead, visit methods should return the value returned by
324 Instruction *EraseInstFromFunction(Instruction &I) {
325 assert(I.use_empty() && "Cannot erase instruction that is used!");
326 AddUsesToWorkList(I);
327 RemoveFromWorkList(&I);
329 return 0; // Don't do anything with FI
332 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
333 APInt &KnownOne, unsigned Depth = 0) const {
334 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
337 bool MaskedValueIsZero(Value *V, const APInt &Mask,
338 unsigned Depth = 0) const {
339 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
341 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
342 return llvm::ComputeNumSignBits(Op, TD, Depth);
347 /// SimplifyCommutative - This performs a few simplifications for
348 /// commutative operators.
349 bool SimplifyCommutative(BinaryOperator &I);
351 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
352 /// most-complex to least-complex order.
353 bool SimplifyCompare(CmpInst &I);
355 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
356 /// based on the demanded bits.
357 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
358 APInt& KnownZero, APInt& KnownOne,
360 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
361 APInt& KnownZero, APInt& KnownOne,
364 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
365 /// SimplifyDemandedBits knows about. See if the instruction has any
366 /// properties that allow us to simplify its operands.
367 bool SimplifyDemandedInstructionBits(Instruction &Inst);
369 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
370 APInt& UndefElts, unsigned Depth = 0);
372 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
373 // PHI node as operand #0, see if we can fold the instruction into the PHI
374 // (which is only possible if all operands to the PHI are constants).
375 Instruction *FoldOpIntoPhi(Instruction &I);
377 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
378 // operator and they all are only used by the PHI, PHI together their
379 // inputs, and do the operation once, to the result of the PHI.
380 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
381 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
382 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
385 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
386 ConstantInt *AndRHS, BinaryOperator &TheAnd);
388 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
389 bool isSub, Instruction &I);
390 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
391 bool isSigned, bool Inside, Instruction &IB);
392 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
393 Instruction *MatchBSwap(BinaryOperator &I);
394 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
395 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
396 Instruction *SimplifyMemSet(MemSetInst *MI);
399 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
401 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
402 unsigned CastOpc, int &NumCastsRemoved);
403 unsigned GetOrEnforceKnownAlignment(Value *V,
404 unsigned PrefAlign = 0);
409 char InstCombiner::ID = 0;
410 static RegisterPass<InstCombiner>
411 X("instcombine", "Combine redundant instructions");
413 // getComplexity: Assign a complexity or rank value to LLVM Values...
414 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
415 static unsigned getComplexity(LLVMContext *Context, Value *V) {
416 if (isa<Instruction>(V)) {
417 if (BinaryOperator::isNeg(V) ||
418 BinaryOperator::isFNeg(V) ||
419 BinaryOperator::isNot(V))
423 if (isa<Argument>(V)) return 3;
424 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
427 // isOnlyUse - Return true if this instruction will be deleted if we stop using
429 static bool isOnlyUse(Value *V) {
430 return V->hasOneUse() || isa<Constant>(V);
433 // getPromotedType - Return the specified type promoted as it would be to pass
434 // though a va_arg area...
435 static const Type *getPromotedType(const Type *Ty) {
436 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
437 if (ITy->getBitWidth() < 32)
438 return Type::getInt32Ty(Ty->getContext());
443 /// getBitCastOperand - If the specified operand is a CastInst, a constant
444 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
445 /// operand value, otherwise return null.
446 static Value *getBitCastOperand(Value *V) {
447 if (Operator *O = dyn_cast<Operator>(V)) {
448 if (O->getOpcode() == Instruction::BitCast)
449 return O->getOperand(0);
450 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
451 if (GEP->hasAllZeroIndices())
452 return GEP->getPointerOperand();
457 /// This function is a wrapper around CastInst::isEliminableCastPair. It
458 /// simply extracts arguments and returns what that function returns.
459 static Instruction::CastOps
460 isEliminableCastPair(
461 const CastInst *CI, ///< The first cast instruction
462 unsigned opcode, ///< The opcode of the second cast instruction
463 const Type *DstTy, ///< The target type for the second cast instruction
464 TargetData *TD ///< The target data for pointer size
467 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
468 const Type *MidTy = CI->getType(); // B from above
470 // Get the opcodes of the two Cast instructions
471 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
472 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
474 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
476 TD ? TD->getIntPtrType(CI->getContext()) : 0);
478 // We don't want to form an inttoptr or ptrtoint that converts to an integer
479 // type that differs from the pointer size.
480 if ((Res == Instruction::IntToPtr &&
481 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
482 (Res == Instruction::PtrToInt &&
483 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
486 return Instruction::CastOps(Res);
489 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
490 /// in any code being generated. It does not require codegen if V is simple
491 /// enough or if the cast can be folded into other casts.
492 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
493 const Type *Ty, TargetData *TD) {
494 if (V->getType() == Ty || isa<Constant>(V)) return false;
496 // If this is another cast that can be eliminated, it isn't codegen either.
497 if (const CastInst *CI = dyn_cast<CastInst>(V))
498 if (isEliminableCastPair(CI, opcode, Ty, TD))
503 // SimplifyCommutative - This performs a few simplifications for commutative
506 // 1. Order operands such that they are listed from right (least complex) to
507 // left (most complex). This puts constants before unary operators before
510 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
511 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
513 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
514 bool Changed = false;
515 if (getComplexity(Context, I.getOperand(0)) <
516 getComplexity(Context, I.getOperand(1)))
517 Changed = !I.swapOperands();
519 if (!I.isAssociative()) return Changed;
520 Instruction::BinaryOps Opcode = I.getOpcode();
521 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
522 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
523 if (isa<Constant>(I.getOperand(1))) {
524 Constant *Folded = ConstantExpr::get(I.getOpcode(),
525 cast<Constant>(I.getOperand(1)),
526 cast<Constant>(Op->getOperand(1)));
527 I.setOperand(0, Op->getOperand(0));
528 I.setOperand(1, Folded);
530 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
531 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
532 isOnlyUse(Op) && isOnlyUse(Op1)) {
533 Constant *C1 = cast<Constant>(Op->getOperand(1));
534 Constant *C2 = cast<Constant>(Op1->getOperand(1));
536 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
537 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
538 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
542 I.setOperand(0, New);
543 I.setOperand(1, Folded);
550 /// SimplifyCompare - For a CmpInst this function just orders the operands
551 /// so that theyare listed from right (least complex) to left (most complex).
552 /// This puts constants before unary operators before binary operators.
553 bool InstCombiner::SimplifyCompare(CmpInst &I) {
554 if (getComplexity(Context, I.getOperand(0)) >=
555 getComplexity(Context, I.getOperand(1)))
558 // Compare instructions are not associative so there's nothing else we can do.
562 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
563 // if the LHS is a constant zero (which is the 'negate' form).
565 static inline Value *dyn_castNegVal(Value *V) {
566 if (BinaryOperator::isNeg(V))
567 return BinaryOperator::getNegArgument(V);
569 // Constants can be considered to be negated values if they can be folded.
570 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
571 return ConstantExpr::getNeg(C);
573 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
574 if (C->getType()->getElementType()->isInteger())
575 return ConstantExpr::getNeg(C);
580 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
581 // instruction if the LHS is a constant negative zero (which is the 'negate'
584 static inline Value *dyn_castFNegVal(Value *V) {
585 if (BinaryOperator::isFNeg(V))
586 return BinaryOperator::getFNegArgument(V);
588 // Constants can be considered to be negated values if they can be folded.
589 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
590 return ConstantExpr::getFNeg(C);
592 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
593 if (C->getType()->getElementType()->isFloatingPoint())
594 return ConstantExpr::getFNeg(C);
599 static inline Value *dyn_castNotVal(Value *V) {
600 if (BinaryOperator::isNot(V))
601 return BinaryOperator::getNotArgument(V);
603 // Constants can be considered to be not'ed values...
604 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
605 return ConstantInt::get(C->getType(), ~C->getValue());
609 // dyn_castFoldableMul - If this value is a multiply that can be folded into
610 // other computations (because it has a constant operand), return the
611 // non-constant operand of the multiply, and set CST to point to the multiplier.
612 // Otherwise, return null.
614 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
615 if (V->hasOneUse() && V->getType()->isInteger())
616 if (Instruction *I = dyn_cast<Instruction>(V)) {
617 if (I->getOpcode() == Instruction::Mul)
618 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
619 return I->getOperand(0);
620 if (I->getOpcode() == Instruction::Shl)
621 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
622 // The multiplier is really 1 << CST.
623 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
624 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
625 CST = ConstantInt::get(V->getType()->getContext(),
626 APInt(BitWidth, 1).shl(CSTVal));
627 return I->getOperand(0);
633 /// AddOne - Add one to a ConstantInt
634 static Constant *AddOne(Constant *C) {
635 return ConstantExpr::getAdd(C,
636 ConstantInt::get(C->getType(), 1));
638 /// SubOne - Subtract one from a ConstantInt
639 static Constant *SubOne(ConstantInt *C) {
640 return ConstantExpr::getSub(C,
641 ConstantInt::get(C->getType(), 1));
643 /// MultiplyOverflows - True if the multiply can not be expressed in an int
645 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
646 uint32_t W = C1->getBitWidth();
647 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
656 APInt MulExt = LHSExt * RHSExt;
659 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
660 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
661 return MulExt.slt(Min) || MulExt.sgt(Max);
663 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
667 /// ShrinkDemandedConstant - Check to see if the specified operand of the
668 /// specified instruction is a constant integer. If so, check to see if there
669 /// are any bits set in the constant that are not demanded. If so, shrink the
670 /// constant and return true.
671 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
673 assert(I && "No instruction?");
674 assert(OpNo < I->getNumOperands() && "Operand index too large");
676 // If the operand is not a constant integer, nothing to do.
677 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
678 if (!OpC) return false;
680 // If there are no bits set that aren't demanded, nothing to do.
681 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
682 if ((~Demanded & OpC->getValue()) == 0)
685 // This instruction is producing bits that are not demanded. Shrink the RHS.
686 Demanded &= OpC->getValue();
687 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
691 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
692 // set of known zero and one bits, compute the maximum and minimum values that
693 // could have the specified known zero and known one bits, returning them in
695 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
696 const APInt& KnownOne,
697 APInt& Min, APInt& Max) {
698 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
699 KnownZero.getBitWidth() == Min.getBitWidth() &&
700 KnownZero.getBitWidth() == Max.getBitWidth() &&
701 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
702 APInt UnknownBits = ~(KnownZero|KnownOne);
704 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
705 // bit if it is unknown.
707 Max = KnownOne|UnknownBits;
709 if (UnknownBits.isNegative()) { // Sign bit is unknown
710 Min.set(Min.getBitWidth()-1);
711 Max.clear(Max.getBitWidth()-1);
715 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
716 // a set of known zero and one bits, compute the maximum and minimum values that
717 // could have the specified known zero and known one bits, returning them in
719 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
720 const APInt &KnownOne,
721 APInt &Min, APInt &Max) {
722 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
723 KnownZero.getBitWidth() == Min.getBitWidth() &&
724 KnownZero.getBitWidth() == Max.getBitWidth() &&
725 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
726 APInt UnknownBits = ~(KnownZero|KnownOne);
728 // The minimum value is when the unknown bits are all zeros.
730 // The maximum value is when the unknown bits are all ones.
731 Max = KnownOne|UnknownBits;
734 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
735 /// SimplifyDemandedBits knows about. See if the instruction has any
736 /// properties that allow us to simplify its operands.
737 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
738 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
739 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
740 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
742 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
743 KnownZero, KnownOne, 0);
744 if (V == 0) return false;
745 if (V == &Inst) return true;
746 ReplaceInstUsesWith(Inst, V);
750 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
751 /// specified instruction operand if possible, updating it in place. It returns
752 /// true if it made any change and false otherwise.
753 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
754 APInt &KnownZero, APInt &KnownOne,
756 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
757 KnownZero, KnownOne, Depth);
758 if (NewVal == 0) return false;
764 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
765 /// value based on the demanded bits. When this function is called, it is known
766 /// that only the bits set in DemandedMask of the result of V are ever used
767 /// downstream. Consequently, depending on the mask and V, it may be possible
768 /// to replace V with a constant or one of its operands. In such cases, this
769 /// function does the replacement and returns true. In all other cases, it
770 /// returns false after analyzing the expression and setting KnownOne and known
771 /// to be one in the expression. KnownZero contains all the bits that are known
772 /// to be zero in the expression. These are provided to potentially allow the
773 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
774 /// the expression. KnownOne and KnownZero always follow the invariant that
775 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
776 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
777 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
778 /// and KnownOne must all be the same.
780 /// This returns null if it did not change anything and it permits no
781 /// simplification. This returns V itself if it did some simplification of V's
782 /// operands based on the information about what bits are demanded. This returns
783 /// some other non-null value if it found out that V is equal to another value
784 /// in the context where the specified bits are demanded, but not for all users.
785 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
786 APInt &KnownZero, APInt &KnownOne,
788 assert(V != 0 && "Null pointer of Value???");
789 assert(Depth <= 6 && "Limit Search Depth");
790 uint32_t BitWidth = DemandedMask.getBitWidth();
791 const Type *VTy = V->getType();
792 assert((TD || !isa<PointerType>(VTy)) &&
793 "SimplifyDemandedBits needs to know bit widths!");
794 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
795 (!VTy->isIntOrIntVector() ||
796 VTy->getScalarSizeInBits() == BitWidth) &&
797 KnownZero.getBitWidth() == BitWidth &&
798 KnownOne.getBitWidth() == BitWidth &&
799 "Value *V, DemandedMask, KnownZero and KnownOne "
800 "must have same BitWidth");
801 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
802 // We know all of the bits for a constant!
803 KnownOne = CI->getValue() & DemandedMask;
804 KnownZero = ~KnownOne & DemandedMask;
807 if (isa<ConstantPointerNull>(V)) {
808 // We know all of the bits for a constant!
810 KnownZero = DemandedMask;
816 if (DemandedMask == 0) { // Not demanding any bits from V.
817 if (isa<UndefValue>(V))
819 return UndefValue::get(VTy);
822 if (Depth == 6) // Limit search depth.
825 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
826 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
828 Instruction *I = dyn_cast<Instruction>(V);
830 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
831 return 0; // Only analyze instructions.
834 // If there are multiple uses of this value and we aren't at the root, then
835 // we can't do any simplifications of the operands, because DemandedMask
836 // only reflects the bits demanded by *one* of the users.
837 if (Depth != 0 && !I->hasOneUse()) {
838 // Despite the fact that we can't simplify this instruction in all User's
839 // context, we can at least compute the knownzero/knownone bits, and we can
840 // do simplifications that apply to *just* the one user if we know that
841 // this instruction has a simpler value in that context.
842 if (I->getOpcode() == Instruction::And) {
843 // If either the LHS or the RHS are Zero, the result is zero.
844 ComputeMaskedBits(I->getOperand(1), DemandedMask,
845 RHSKnownZero, RHSKnownOne, Depth+1);
846 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
847 LHSKnownZero, LHSKnownOne, Depth+1);
849 // If all of the demanded bits are known 1 on one side, return the other.
850 // These bits cannot contribute to the result of the 'and' in this
852 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
853 (DemandedMask & ~LHSKnownZero))
854 return I->getOperand(0);
855 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
856 (DemandedMask & ~RHSKnownZero))
857 return I->getOperand(1);
859 // If all of the demanded bits in the inputs are known zeros, return zero.
860 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
861 return Constant::getNullValue(VTy);
863 } else if (I->getOpcode() == Instruction::Or) {
864 // We can simplify (X|Y) -> X or Y in the user's context if we know that
865 // only bits from X or Y are demanded.
867 // If either the LHS or the RHS are One, the result is One.
868 ComputeMaskedBits(I->getOperand(1), DemandedMask,
869 RHSKnownZero, RHSKnownOne, Depth+1);
870 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
871 LHSKnownZero, LHSKnownOne, Depth+1);
873 // If all of the demanded bits are known zero on one side, return the
874 // other. These bits cannot contribute to the result of the 'or' in this
876 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
877 (DemandedMask & ~LHSKnownOne))
878 return I->getOperand(0);
879 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
880 (DemandedMask & ~RHSKnownOne))
881 return I->getOperand(1);
883 // If all of the potentially set bits on one side are known to be set on
884 // the other side, just use the 'other' side.
885 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
886 (DemandedMask & (~RHSKnownZero)))
887 return I->getOperand(0);
888 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
889 (DemandedMask & (~LHSKnownZero)))
890 return I->getOperand(1);
893 // Compute the KnownZero/KnownOne bits to simplify things downstream.
894 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
898 // If this is the root being simplified, allow it to have multiple uses,
899 // just set the DemandedMask to all bits so that we can try to simplify the
900 // operands. This allows visitTruncInst (for example) to simplify the
901 // operand of a trunc without duplicating all the logic below.
902 if (Depth == 0 && !V->hasOneUse())
903 DemandedMask = APInt::getAllOnesValue(BitWidth);
905 switch (I->getOpcode()) {
907 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
909 case Instruction::And:
910 // If either the LHS or the RHS are Zero, the result is zero.
911 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
912 RHSKnownZero, RHSKnownOne, Depth+1) ||
913 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
914 LHSKnownZero, LHSKnownOne, Depth+1))
916 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
917 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
919 // If all of the demanded bits are known 1 on one side, return the other.
920 // These bits cannot contribute to the result of the 'and'.
921 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
922 (DemandedMask & ~LHSKnownZero))
923 return I->getOperand(0);
924 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
925 (DemandedMask & ~RHSKnownZero))
926 return I->getOperand(1);
928 // If all of the demanded bits in the inputs are known zeros, return zero.
929 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
930 return Constant::getNullValue(VTy);
932 // If the RHS is a constant, see if we can simplify it.
933 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
936 // Output known-1 bits are only known if set in both the LHS & RHS.
937 RHSKnownOne &= LHSKnownOne;
938 // Output known-0 are known to be clear if zero in either the LHS | RHS.
939 RHSKnownZero |= LHSKnownZero;
941 case Instruction::Or:
942 // If either the LHS or the RHS are One, the result is One.
943 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
944 RHSKnownZero, RHSKnownOne, Depth+1) ||
945 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
946 LHSKnownZero, LHSKnownOne, Depth+1))
948 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
949 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
951 // If all of the demanded bits are known zero on one side, return the other.
952 // These bits cannot contribute to the result of the 'or'.
953 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
954 (DemandedMask & ~LHSKnownOne))
955 return I->getOperand(0);
956 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
957 (DemandedMask & ~RHSKnownOne))
958 return I->getOperand(1);
960 // If all of the potentially set bits on one side are known to be set on
961 // the other side, just use the 'other' side.
962 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
963 (DemandedMask & (~RHSKnownZero)))
964 return I->getOperand(0);
965 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
966 (DemandedMask & (~LHSKnownZero)))
967 return I->getOperand(1);
969 // If the RHS is a constant, see if we can simplify it.
970 if (ShrinkDemandedConstant(I, 1, DemandedMask))
973 // Output known-0 bits are only known if clear in both the LHS & RHS.
974 RHSKnownZero &= LHSKnownZero;
975 // Output known-1 are known to be set if set in either the LHS | RHS.
976 RHSKnownOne |= LHSKnownOne;
978 case Instruction::Xor: {
979 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
980 RHSKnownZero, RHSKnownOne, Depth+1) ||
981 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
982 LHSKnownZero, LHSKnownOne, Depth+1))
984 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
985 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
987 // If all of the demanded bits are known zero on one side, return the other.
988 // These bits cannot contribute to the result of the 'xor'.
989 if ((DemandedMask & RHSKnownZero) == DemandedMask)
990 return I->getOperand(0);
991 if ((DemandedMask & LHSKnownZero) == DemandedMask)
992 return I->getOperand(1);
994 // Output known-0 bits are known if clear or set in both the LHS & RHS.
995 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
996 (RHSKnownOne & LHSKnownOne);
997 // Output known-1 are known to be set if set in only one of the LHS, RHS.
998 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
999 (RHSKnownOne & LHSKnownZero);
1001 // If all of the demanded bits are known to be zero on one side or the
1002 // other, turn this into an *inclusive* or.
1003 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1004 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1006 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1008 return InsertNewInstBefore(Or, *I);
1011 // If all of the demanded bits on one side are known, and all of the set
1012 // bits on that side are also known to be set on the other side, turn this
1013 // into an AND, as we know the bits will be cleared.
1014 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1015 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1017 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1018 Constant *AndC = Constant::getIntegerValue(VTy,
1019 ~RHSKnownOne & DemandedMask);
1021 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1022 return InsertNewInstBefore(And, *I);
1026 // If the RHS is a constant, see if we can simplify it.
1027 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1028 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1031 RHSKnownZero = KnownZeroOut;
1032 RHSKnownOne = KnownOneOut;
1035 case Instruction::Select:
1036 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1037 RHSKnownZero, RHSKnownOne, Depth+1) ||
1038 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1039 LHSKnownZero, LHSKnownOne, Depth+1))
1041 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1042 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
1044 // If the operands are constants, see if we can simplify them.
1045 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1046 ShrinkDemandedConstant(I, 2, DemandedMask))
1049 // Only known if known in both the LHS and RHS.
1050 RHSKnownOne &= LHSKnownOne;
1051 RHSKnownZero &= LHSKnownZero;
1053 case Instruction::Trunc: {
1054 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1055 DemandedMask.zext(truncBf);
1056 RHSKnownZero.zext(truncBf);
1057 RHSKnownOne.zext(truncBf);
1058 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1059 RHSKnownZero, RHSKnownOne, Depth+1))
1061 DemandedMask.trunc(BitWidth);
1062 RHSKnownZero.trunc(BitWidth);
1063 RHSKnownOne.trunc(BitWidth);
1064 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1067 case Instruction::BitCast:
1068 if (!I->getOperand(0)->getType()->isIntOrIntVector())
1069 return false; // vector->int or fp->int?
1071 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1072 if (const VectorType *SrcVTy =
1073 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1074 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1075 // Don't touch a bitcast between vectors of different element counts.
1078 // Don't touch a scalar-to-vector bitcast.
1080 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1081 // Don't touch a vector-to-scalar bitcast.
1084 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1085 RHSKnownZero, RHSKnownOne, Depth+1))
1087 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1089 case Instruction::ZExt: {
1090 // Compute the bits in the result that are not present in the input.
1091 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1093 DemandedMask.trunc(SrcBitWidth);
1094 RHSKnownZero.trunc(SrcBitWidth);
1095 RHSKnownOne.trunc(SrcBitWidth);
1096 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1097 RHSKnownZero, RHSKnownOne, Depth+1))
1099 DemandedMask.zext(BitWidth);
1100 RHSKnownZero.zext(BitWidth);
1101 RHSKnownOne.zext(BitWidth);
1102 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1103 // The top bits are known to be zero.
1104 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1107 case Instruction::SExt: {
1108 // Compute the bits in the result that are not present in the input.
1109 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1111 APInt InputDemandedBits = DemandedMask &
1112 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1114 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1115 // If any of the sign extended bits are demanded, we know that the sign
1117 if ((NewBits & DemandedMask) != 0)
1118 InputDemandedBits.set(SrcBitWidth-1);
1120 InputDemandedBits.trunc(SrcBitWidth);
1121 RHSKnownZero.trunc(SrcBitWidth);
1122 RHSKnownOne.trunc(SrcBitWidth);
1123 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1124 RHSKnownZero, RHSKnownOne, Depth+1))
1126 InputDemandedBits.zext(BitWidth);
1127 RHSKnownZero.zext(BitWidth);
1128 RHSKnownOne.zext(BitWidth);
1129 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1131 // If the sign bit of the input is known set or clear, then we know the
1132 // top bits of the result.
1134 // If the input sign bit is known zero, or if the NewBits are not demanded
1135 // convert this into a zero extension.
1136 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1137 // Convert to ZExt cast
1138 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1139 return InsertNewInstBefore(NewCast, *I);
1140 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1141 RHSKnownOne |= NewBits;
1145 case Instruction::Add: {
1146 // Figure out what the input bits are. If the top bits of the and result
1147 // are not demanded, then the add doesn't demand them from its input
1149 unsigned NLZ = DemandedMask.countLeadingZeros();
1151 // If there is a constant on the RHS, there are a variety of xformations
1153 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1154 // If null, this should be simplified elsewhere. Some of the xforms here
1155 // won't work if the RHS is zero.
1159 // If the top bit of the output is demanded, demand everything from the
1160 // input. Otherwise, we demand all the input bits except NLZ top bits.
1161 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1163 // Find information about known zero/one bits in the input.
1164 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
1165 LHSKnownZero, LHSKnownOne, Depth+1))
1168 // If the RHS of the add has bits set that can't affect the input, reduce
1170 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1173 // Avoid excess work.
1174 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1177 // Turn it into OR if input bits are zero.
1178 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1180 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1182 return InsertNewInstBefore(Or, *I);
1185 // We can say something about the output known-zero and known-one bits,
1186 // depending on potential carries from the input constant and the
1187 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1188 // bits set and the RHS constant is 0x01001, then we know we have a known
1189 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1191 // To compute this, we first compute the potential carry bits. These are
1192 // the bits which may be modified. I'm not aware of a better way to do
1194 const APInt &RHSVal = RHS->getValue();
1195 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1197 // Now that we know which bits have carries, compute the known-1/0 sets.
1199 // Bits are known one if they are known zero in one operand and one in the
1200 // other, and there is no input carry.
1201 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1202 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1204 // Bits are known zero if they are known zero in both operands and there
1205 // is no input carry.
1206 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1208 // If the high-bits of this ADD are not demanded, then it does not demand
1209 // the high bits of its LHS or RHS.
1210 if (DemandedMask[BitWidth-1] == 0) {
1211 // Right fill the mask of bits for this ADD to demand the most
1212 // significant bit and all those below it.
1213 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1214 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1215 LHSKnownZero, LHSKnownOne, Depth+1) ||
1216 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1217 LHSKnownZero, LHSKnownOne, Depth+1))
1223 case Instruction::Sub:
1224 // If the high-bits of this SUB are not demanded, then it does not demand
1225 // the high bits of its LHS or RHS.
1226 if (DemandedMask[BitWidth-1] == 0) {
1227 // Right fill the mask of bits for this SUB to demand the most
1228 // significant bit and all those below it.
1229 uint32_t NLZ = DemandedMask.countLeadingZeros();
1230 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1231 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1232 LHSKnownZero, LHSKnownOne, Depth+1) ||
1233 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1234 LHSKnownZero, LHSKnownOne, Depth+1))
1237 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1238 // the known zeros and ones.
1239 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1241 case Instruction::Shl:
1242 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1243 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1244 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1245 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1246 RHSKnownZero, RHSKnownOne, Depth+1))
1248 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1249 RHSKnownZero <<= ShiftAmt;
1250 RHSKnownOne <<= ShiftAmt;
1251 // low bits known zero.
1253 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1256 case Instruction::LShr:
1257 // For a logical shift right
1258 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1259 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1261 // Unsigned shift right.
1262 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1263 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1264 RHSKnownZero, RHSKnownOne, Depth+1))
1266 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1267 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1268 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1270 // Compute the new bits that are at the top now.
1271 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1272 RHSKnownZero |= HighBits; // high bits known zero.
1276 case Instruction::AShr:
1277 // If this is an arithmetic shift right and only the low-bit is set, we can
1278 // always convert this into a logical shr, even if the shift amount is
1279 // variable. The low bit of the shift cannot be an input sign bit unless
1280 // the shift amount is >= the size of the datatype, which is undefined.
1281 if (DemandedMask == 1) {
1282 // Perform the logical shift right.
1283 Instruction *NewVal = BinaryOperator::CreateLShr(
1284 I->getOperand(0), I->getOperand(1), I->getName());
1285 return InsertNewInstBefore(NewVal, *I);
1288 // If the sign bit is the only bit demanded by this ashr, then there is no
1289 // need to do it, the shift doesn't change the high bit.
1290 if (DemandedMask.isSignBit())
1291 return I->getOperand(0);
1293 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1294 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1296 // Signed shift right.
1297 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1298 // If any of the "high bits" are demanded, we should set the sign bit as
1300 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1301 DemandedMaskIn.set(BitWidth-1);
1302 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1303 RHSKnownZero, RHSKnownOne, Depth+1))
1305 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1306 // Compute the new bits that are at the top now.
1307 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1308 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1309 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1311 // Handle the sign bits.
1312 APInt SignBit(APInt::getSignBit(BitWidth));
1313 // Adjust to where it is now in the mask.
1314 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1316 // If the input sign bit is known to be zero, or if none of the top bits
1317 // are demanded, turn this into an unsigned shift right.
1318 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
1319 (HighBits & ~DemandedMask) == HighBits) {
1320 // Perform the logical shift right.
1321 Instruction *NewVal = BinaryOperator::CreateLShr(
1322 I->getOperand(0), SA, I->getName());
1323 return InsertNewInstBefore(NewVal, *I);
1324 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1325 RHSKnownOne |= HighBits;
1329 case Instruction::SRem:
1330 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1331 APInt RA = Rem->getValue().abs();
1332 if (RA.isPowerOf2()) {
1333 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
1334 return I->getOperand(0);
1336 APInt LowBits = RA - 1;
1337 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1338 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1339 LHSKnownZero, LHSKnownOne, Depth+1))
1342 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1343 LHSKnownZero |= ~LowBits;
1345 KnownZero |= LHSKnownZero & DemandedMask;
1347 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
1351 case Instruction::URem: {
1352 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1353 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1354 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1355 KnownZero2, KnownOne2, Depth+1) ||
1356 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1357 KnownZero2, KnownOne2, Depth+1))
1360 unsigned Leaders = KnownZero2.countLeadingOnes();
1361 Leaders = std::max(Leaders,
1362 KnownZero2.countLeadingOnes());
1363 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1366 case Instruction::Call:
1367 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1368 switch (II->getIntrinsicID()) {
1370 case Intrinsic::bswap: {
1371 // If the only bits demanded come from one byte of the bswap result,
1372 // just shift the input byte into position to eliminate the bswap.
1373 unsigned NLZ = DemandedMask.countLeadingZeros();
1374 unsigned NTZ = DemandedMask.countTrailingZeros();
1376 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1377 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1378 // have 14 leading zeros, round to 8.
1381 // If we need exactly one byte, we can do this transformation.
1382 if (BitWidth-NLZ-NTZ == 8) {
1383 unsigned ResultBit = NTZ;
1384 unsigned InputBit = BitWidth-NTZ-8;
1386 // Replace this with either a left or right shift to get the byte into
1388 Instruction *NewVal;
1389 if (InputBit > ResultBit)
1390 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1391 ConstantInt::get(I->getType(), InputBit-ResultBit));
1393 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1394 ConstantInt::get(I->getType(), ResultBit-InputBit));
1395 NewVal->takeName(I);
1396 return InsertNewInstBefore(NewVal, *I);
1399 // TODO: Could compute known zero/one bits based on the input.
1404 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1408 // If the client is only demanding bits that we know, return the known
1410 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1411 return Constant::getIntegerValue(VTy, RHSKnownOne);
1416 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1417 /// any number of elements. DemandedElts contains the set of elements that are
1418 /// actually used by the caller. This method analyzes which elements of the
1419 /// operand are undef and returns that information in UndefElts.
1421 /// If the information about demanded elements can be used to simplify the
1422 /// operation, the operation is simplified, then the resultant value is
1423 /// returned. This returns null if no change was made.
1424 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1427 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1428 APInt EltMask(APInt::getAllOnesValue(VWidth));
1429 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1431 if (isa<UndefValue>(V)) {
1432 // If the entire vector is undefined, just return this info.
1433 UndefElts = EltMask;
1435 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1436 UndefElts = EltMask;
1437 return UndefValue::get(V->getType());
1441 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1442 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1443 Constant *Undef = UndefValue::get(EltTy);
1445 std::vector<Constant*> Elts;
1446 for (unsigned i = 0; i != VWidth; ++i)
1447 if (!DemandedElts[i]) { // If not demanded, set to undef.
1448 Elts.push_back(Undef);
1450 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1451 Elts.push_back(Undef);
1453 } else { // Otherwise, defined.
1454 Elts.push_back(CP->getOperand(i));
1457 // If we changed the constant, return it.
1458 Constant *NewCP = ConstantVector::get(Elts);
1459 return NewCP != CP ? NewCP : 0;
1460 } else if (isa<ConstantAggregateZero>(V)) {
1461 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1464 // Check if this is identity. If so, return 0 since we are not simplifying
1466 if (DemandedElts == ((1ULL << VWidth) -1))
1469 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1470 Constant *Zero = Constant::getNullValue(EltTy);
1471 Constant *Undef = UndefValue::get(EltTy);
1472 std::vector<Constant*> Elts;
1473 for (unsigned i = 0; i != VWidth; ++i) {
1474 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1475 Elts.push_back(Elt);
1477 UndefElts = DemandedElts ^ EltMask;
1478 return ConstantVector::get(Elts);
1481 // Limit search depth.
1485 // If multiple users are using the root value, procede with
1486 // simplification conservatively assuming that all elements
1488 if (!V->hasOneUse()) {
1489 // Quit if we find multiple users of a non-root value though.
1490 // They'll be handled when it's their turn to be visited by
1491 // the main instcombine process.
1493 // TODO: Just compute the UndefElts information recursively.
1496 // Conservatively assume that all elements are needed.
1497 DemandedElts = EltMask;
1500 Instruction *I = dyn_cast<Instruction>(V);
1501 if (!I) return 0; // Only analyze instructions.
1503 bool MadeChange = false;
1504 APInt UndefElts2(VWidth, 0);
1506 switch (I->getOpcode()) {
1509 case Instruction::InsertElement: {
1510 // If this is a variable index, we don't know which element it overwrites.
1511 // demand exactly the same input as we produce.
1512 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1514 // Note that we can't propagate undef elt info, because we don't know
1515 // which elt is getting updated.
1516 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1517 UndefElts2, Depth+1);
1518 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1522 // If this is inserting an element that isn't demanded, remove this
1524 unsigned IdxNo = Idx->getZExtValue();
1525 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1526 return AddSoonDeadInstToWorklist(*I, 0);
1528 // Otherwise, the element inserted overwrites whatever was there, so the
1529 // input demanded set is simpler than the output set.
1530 APInt DemandedElts2 = DemandedElts;
1531 DemandedElts2.clear(IdxNo);
1532 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1533 UndefElts, Depth+1);
1534 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1536 // The inserted element is defined.
1537 UndefElts.clear(IdxNo);
1540 case Instruction::ShuffleVector: {
1541 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1542 uint64_t LHSVWidth =
1543 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1544 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1545 for (unsigned i = 0; i < VWidth; i++) {
1546 if (DemandedElts[i]) {
1547 unsigned MaskVal = Shuffle->getMaskValue(i);
1548 if (MaskVal != -1u) {
1549 assert(MaskVal < LHSVWidth * 2 &&
1550 "shufflevector mask index out of range!");
1551 if (MaskVal < LHSVWidth)
1552 LeftDemanded.set(MaskVal);
1554 RightDemanded.set(MaskVal - LHSVWidth);
1559 APInt UndefElts4(LHSVWidth, 0);
1560 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1561 UndefElts4, Depth+1);
1562 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1564 APInt UndefElts3(LHSVWidth, 0);
1565 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1566 UndefElts3, Depth+1);
1567 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1569 bool NewUndefElts = false;
1570 for (unsigned i = 0; i < VWidth; i++) {
1571 unsigned MaskVal = Shuffle->getMaskValue(i);
1572 if (MaskVal == -1u) {
1574 } else if (MaskVal < LHSVWidth) {
1575 if (UndefElts4[MaskVal]) {
1576 NewUndefElts = true;
1580 if (UndefElts3[MaskVal - LHSVWidth]) {
1581 NewUndefElts = true;
1588 // Add additional discovered undefs.
1589 std::vector<Constant*> Elts;
1590 for (unsigned i = 0; i < VWidth; ++i) {
1592 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1594 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1595 Shuffle->getMaskValue(i)));
1597 I->setOperand(2, ConstantVector::get(Elts));
1602 case Instruction::BitCast: {
1603 // Vector->vector casts only.
1604 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1606 unsigned InVWidth = VTy->getNumElements();
1607 APInt InputDemandedElts(InVWidth, 0);
1610 if (VWidth == InVWidth) {
1611 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1612 // elements as are demanded of us.
1614 InputDemandedElts = DemandedElts;
1615 } else if (VWidth > InVWidth) {
1619 // If there are more elements in the result than there are in the source,
1620 // then an input element is live if any of the corresponding output
1621 // elements are live.
1622 Ratio = VWidth/InVWidth;
1623 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1624 if (DemandedElts[OutIdx])
1625 InputDemandedElts.set(OutIdx/Ratio);
1631 // If there are more elements in the source than there are in the result,
1632 // then an input element is live if the corresponding output element is
1634 Ratio = InVWidth/VWidth;
1635 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1636 if (DemandedElts[InIdx/Ratio])
1637 InputDemandedElts.set(InIdx);
1640 // div/rem demand all inputs, because they don't want divide by zero.
1641 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1642 UndefElts2, Depth+1);
1644 I->setOperand(0, TmpV);
1648 UndefElts = UndefElts2;
1649 if (VWidth > InVWidth) {
1650 llvm_unreachable("Unimp");
1651 // If there are more elements in the result than there are in the source,
1652 // then an output element is undef if the corresponding input element is
1654 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1655 if (UndefElts2[OutIdx/Ratio])
1656 UndefElts.set(OutIdx);
1657 } else if (VWidth < InVWidth) {
1658 llvm_unreachable("Unimp");
1659 // If there are more elements in the source than there are in the result,
1660 // then a result element is undef if all of the corresponding input
1661 // elements are undef.
1662 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1663 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1664 if (!UndefElts2[InIdx]) // Not undef?
1665 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
1669 case Instruction::And:
1670 case Instruction::Or:
1671 case Instruction::Xor:
1672 case Instruction::Add:
1673 case Instruction::Sub:
1674 case Instruction::Mul:
1675 // div/rem demand all inputs, because they don't want divide by zero.
1676 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1677 UndefElts, Depth+1);
1678 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1679 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1680 UndefElts2, Depth+1);
1681 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1683 // Output elements are undefined if both are undefined. Consider things
1684 // like undef&0. The result is known zero, not undef.
1685 UndefElts &= UndefElts2;
1688 case Instruction::Call: {
1689 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1691 switch (II->getIntrinsicID()) {
1694 // Binary vector operations that work column-wise. A dest element is a
1695 // function of the corresponding input elements from the two inputs.
1696 case Intrinsic::x86_sse_sub_ss:
1697 case Intrinsic::x86_sse_mul_ss:
1698 case Intrinsic::x86_sse_min_ss:
1699 case Intrinsic::x86_sse_max_ss:
1700 case Intrinsic::x86_sse2_sub_sd:
1701 case Intrinsic::x86_sse2_mul_sd:
1702 case Intrinsic::x86_sse2_min_sd:
1703 case Intrinsic::x86_sse2_max_sd:
1704 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1705 UndefElts, Depth+1);
1706 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1707 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1708 UndefElts2, Depth+1);
1709 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1711 // If only the low elt is demanded and this is a scalarizable intrinsic,
1712 // scalarize it now.
1713 if (DemandedElts == 1) {
1714 switch (II->getIntrinsicID()) {
1716 case Intrinsic::x86_sse_sub_ss:
1717 case Intrinsic::x86_sse_mul_ss:
1718 case Intrinsic::x86_sse2_sub_sd:
1719 case Intrinsic::x86_sse2_mul_sd:
1720 // TODO: Lower MIN/MAX/ABS/etc
1721 Value *LHS = II->getOperand(1);
1722 Value *RHS = II->getOperand(2);
1723 // Extract the element as scalars.
1724 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
1725 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1726 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1727 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1729 switch (II->getIntrinsicID()) {
1730 default: llvm_unreachable("Case stmts out of sync!");
1731 case Intrinsic::x86_sse_sub_ss:
1732 case Intrinsic::x86_sse2_sub_sd:
1733 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1734 II->getName()), *II);
1736 case Intrinsic::x86_sse_mul_ss:
1737 case Intrinsic::x86_sse2_mul_sd:
1738 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1739 II->getName()), *II);
1744 InsertElementInst::Create(
1745 UndefValue::get(II->getType()), TmpV,
1746 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1747 InsertNewInstBefore(New, *II);
1748 AddSoonDeadInstToWorklist(*II, 0);
1753 // Output elements are undefined if both are undefined. Consider things
1754 // like undef&0. The result is known zero, not undef.
1755 UndefElts &= UndefElts2;
1761 return MadeChange ? I : 0;
1765 /// AssociativeOpt - Perform an optimization on an associative operator. This
1766 /// function is designed to check a chain of associative operators for a
1767 /// potential to apply a certain optimization. Since the optimization may be
1768 /// applicable if the expression was reassociated, this checks the chain, then
1769 /// reassociates the expression as necessary to expose the optimization
1770 /// opportunity. This makes use of a special Functor, which must define
1771 /// 'shouldApply' and 'apply' methods.
1773 template<typename Functor>
1774 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1775 unsigned Opcode = Root.getOpcode();
1776 Value *LHS = Root.getOperand(0);
1778 // Quick check, see if the immediate LHS matches...
1779 if (F.shouldApply(LHS))
1780 return F.apply(Root);
1782 // Otherwise, if the LHS is not of the same opcode as the root, return.
1783 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1784 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1785 // Should we apply this transform to the RHS?
1786 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1788 // If not to the RHS, check to see if we should apply to the LHS...
1789 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1790 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1794 // If the functor wants to apply the optimization to the RHS of LHSI,
1795 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1797 // Now all of the instructions are in the current basic block, go ahead
1798 // and perform the reassociation.
1799 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1801 // First move the selected RHS to the LHS of the root...
1802 Root.setOperand(0, LHSI->getOperand(1));
1804 // Make what used to be the LHS of the root be the user of the root...
1805 Value *ExtraOperand = TmpLHSI->getOperand(1);
1806 if (&Root == TmpLHSI) {
1807 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1810 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1811 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1812 BasicBlock::iterator ARI = &Root; ++ARI;
1813 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
1816 // Now propagate the ExtraOperand down the chain of instructions until we
1818 while (TmpLHSI != LHSI) {
1819 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1820 // Move the instruction to immediately before the chain we are
1821 // constructing to avoid breaking dominance properties.
1822 NextLHSI->moveBefore(ARI);
1825 Value *NextOp = NextLHSI->getOperand(1);
1826 NextLHSI->setOperand(1, ExtraOperand);
1828 ExtraOperand = NextOp;
1831 // Now that the instructions are reassociated, have the functor perform
1832 // the transformation...
1833 return F.apply(Root);
1836 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1843 // AddRHS - Implements: X + X --> X << 1
1846 explicit AddRHS(Value *rhs) : RHS(rhs) {}
1847 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1848 Instruction *apply(BinaryOperator &Add) const {
1849 return BinaryOperator::CreateShl(Add.getOperand(0),
1850 ConstantInt::get(Add.getType(), 1));
1854 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1856 struct AddMaskingAnd {
1858 explicit AddMaskingAnd(Constant *c) : C2(c) {}
1859 bool shouldApply(Value *LHS) const {
1861 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1862 ConstantExpr::getAnd(C1, C2)->isNullValue();
1864 Instruction *apply(BinaryOperator &Add) const {
1865 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1871 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1873 LLVMContext *Context = IC->getContext();
1875 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1876 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1879 // Figure out if the constant is the left or the right argument.
1880 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1881 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1883 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1885 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1886 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1889 Value *Op0 = SO, *Op1 = ConstOperand;
1891 std::swap(Op0, Op1);
1893 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1894 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1895 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1896 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1897 Op0, Op1, SO->getName()+".cmp");
1899 llvm_unreachable("Unknown binary instruction type!");
1901 return IC->InsertNewInstBefore(New, I);
1904 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1905 // constant as the other operand, try to fold the binary operator into the
1906 // select arguments. This also works for Cast instructions, which obviously do
1907 // not have a second operand.
1908 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1910 // Don't modify shared select instructions
1911 if (!SI->hasOneUse()) return 0;
1912 Value *TV = SI->getOperand(1);
1913 Value *FV = SI->getOperand(2);
1915 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1916 // Bool selects with constant operands can be folded to logical ops.
1917 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
1919 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1920 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1922 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1929 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1930 /// node as operand #0, see if we can fold the instruction into the PHI (which
1931 /// is only possible if all operands to the PHI are constants).
1932 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1933 PHINode *PN = cast<PHINode>(I.getOperand(0));
1934 unsigned NumPHIValues = PN->getNumIncomingValues();
1935 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1937 // Check to see if all of the operands of the PHI are constants. If there is
1938 // one non-constant value, remember the BB it is. If there is more than one
1939 // or if *it* is a PHI, bail out.
1940 BasicBlock *NonConstBB = 0;
1941 for (unsigned i = 0; i != NumPHIValues; ++i)
1942 if (!isa<Constant>(PN->getIncomingValue(i))) {
1943 if (NonConstBB) return 0; // More than one non-const value.
1944 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1945 NonConstBB = PN->getIncomingBlock(i);
1947 // If the incoming non-constant value is in I's block, we have an infinite
1949 if (NonConstBB == I.getParent())
1953 // If there is exactly one non-constant value, we can insert a copy of the
1954 // operation in that block. However, if this is a critical edge, we would be
1955 // inserting the computation one some other paths (e.g. inside a loop). Only
1956 // do this if the pred block is unconditionally branching into the phi block.
1958 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1959 if (!BI || !BI->isUnconditional()) return 0;
1962 // Okay, we can do the transformation: create the new PHI node.
1963 PHINode *NewPN = PHINode::Create(I.getType(), "");
1964 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1965 InsertNewInstBefore(NewPN, *PN);
1966 NewPN->takeName(PN);
1968 // Next, add all of the operands to the PHI.
1969 if (I.getNumOperands() == 2) {
1970 Constant *C = cast<Constant>(I.getOperand(1));
1971 for (unsigned i = 0; i != NumPHIValues; ++i) {
1973 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1974 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1975 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1977 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1979 assert(PN->getIncomingBlock(i) == NonConstBB);
1980 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1981 InV = BinaryOperator::Create(BO->getOpcode(),
1982 PN->getIncomingValue(i), C, "phitmp",
1983 NonConstBB->getTerminator());
1984 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1985 InV = CmpInst::Create(*Context, CI->getOpcode(),
1987 PN->getIncomingValue(i), C, "phitmp",
1988 NonConstBB->getTerminator());
1990 llvm_unreachable("Unknown binop!");
1992 AddToWorkList(cast<Instruction>(InV));
1994 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1997 CastInst *CI = cast<CastInst>(&I);
1998 const Type *RetTy = CI->getType();
1999 for (unsigned i = 0; i != NumPHIValues; ++i) {
2001 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2002 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2004 assert(PN->getIncomingBlock(i) == NonConstBB);
2005 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
2006 I.getType(), "phitmp",
2007 NonConstBB->getTerminator());
2008 AddToWorkList(cast<Instruction>(InV));
2010 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2013 return ReplaceInstUsesWith(I, NewPN);
2017 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2018 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2019 /// This basically requires proving that the add in the original type would not
2020 /// overflow to change the sign bit or have a carry out.
2021 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2022 // There are different heuristics we can use for this. Here are some simple
2025 // Add has the property that adding any two 2's complement numbers can only
2026 // have one carry bit which can change a sign. As such, if LHS and RHS each
2027 // have at least two sign bits, we know that the addition of the two values will
2028 // sign extend fine.
2029 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2033 // If one of the operands only has one non-zero bit, and if the other operand
2034 // has a known-zero bit in a more significant place than it (not including the
2035 // sign bit) the ripple may go up to and fill the zero, but won't change the
2036 // sign. For example, (X & ~4) + 1.
2044 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2045 bool Changed = SimplifyCommutative(I);
2046 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2048 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2049 // X + undef -> undef
2050 if (isa<UndefValue>(RHS))
2051 return ReplaceInstUsesWith(I, RHS);
2054 if (RHSC->isNullValue())
2055 return ReplaceInstUsesWith(I, LHS);
2057 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2058 // X + (signbit) --> X ^ signbit
2059 const APInt& Val = CI->getValue();
2060 uint32_t BitWidth = Val.getBitWidth();
2061 if (Val == APInt::getSignBit(BitWidth))
2062 return BinaryOperator::CreateXor(LHS, RHS);
2064 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2065 // (X & 254)+1 -> (X&254)|1
2066 if (SimplifyDemandedInstructionBits(I))
2069 // zext(bool) + C -> bool ? C + 1 : C
2070 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2071 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2072 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2075 if (isa<PHINode>(LHS))
2076 if (Instruction *NV = FoldOpIntoPhi(I))
2079 ConstantInt *XorRHS = 0;
2081 if (isa<ConstantInt>(RHSC) &&
2082 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2083 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2084 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2086 uint32_t Size = TySizeBits / 2;
2087 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2088 APInt CFF80Val(-C0080Val);
2090 if (TySizeBits > Size) {
2091 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2092 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2093 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2094 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2095 // This is a sign extend if the top bits are known zero.
2096 if (!MaskedValueIsZero(XorLHS,
2097 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2098 Size = 0; // Not a sign ext, but can't be any others either.
2103 C0080Val = APIntOps::lshr(C0080Val, Size);
2104 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2105 } while (Size >= 1);
2107 // FIXME: This shouldn't be necessary. When the backends can handle types
2108 // with funny bit widths then this switch statement should be removed. It
2109 // is just here to get the size of the "middle" type back up to something
2110 // that the back ends can handle.
2111 const Type *MiddleType = 0;
2114 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2115 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2116 case 8: MiddleType = Type::getInt8Ty(*Context); break;
2119 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2120 InsertNewInstBefore(NewTrunc, I);
2121 return new SExtInst(NewTrunc, I.getType(), I.getName());
2126 if (I.getType() == Type::getInt1Ty(*Context))
2127 return BinaryOperator::CreateXor(LHS, RHS);
2130 if (I.getType()->isInteger()) {
2131 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2134 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2135 if (RHSI->getOpcode() == Instruction::Sub)
2136 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2137 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2139 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2140 if (LHSI->getOpcode() == Instruction::Sub)
2141 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2142 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2147 // -A + -B --> -(A + B)
2148 if (Value *LHSV = dyn_castNegVal(LHS)) {
2149 if (LHS->getType()->isIntOrIntVector()) {
2150 if (Value *RHSV = dyn_castNegVal(RHS)) {
2151 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2152 InsertNewInstBefore(NewAdd, I);
2153 return BinaryOperator::CreateNeg(NewAdd);
2157 return BinaryOperator::CreateSub(RHS, LHSV);
2161 if (!isa<Constant>(RHS))
2162 if (Value *V = dyn_castNegVal(RHS))
2163 return BinaryOperator::CreateSub(LHS, V);
2167 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2168 if (X == RHS) // X*C + X --> X * (C+1)
2169 return BinaryOperator::CreateMul(RHS, AddOne(C2));
2171 // X*C1 + X*C2 --> X * (C1+C2)
2173 if (X == dyn_castFoldableMul(RHS, C1))
2174 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2177 // X + X*C --> X * (C+1)
2178 if (dyn_castFoldableMul(RHS, C2) == LHS)
2179 return BinaryOperator::CreateMul(LHS, AddOne(C2));
2181 // X + ~X --> -1 since ~X = -X-1
2182 if (dyn_castNotVal(LHS) == RHS ||
2183 dyn_castNotVal(RHS) == LHS)
2184 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2187 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2188 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2189 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2192 // A+B --> A|B iff A and B have no bits set in common.
2193 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2194 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2195 APInt LHSKnownOne(IT->getBitWidth(), 0);
2196 APInt LHSKnownZero(IT->getBitWidth(), 0);
2197 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2198 if (LHSKnownZero != 0) {
2199 APInt RHSKnownOne(IT->getBitWidth(), 0);
2200 APInt RHSKnownZero(IT->getBitWidth(), 0);
2201 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2203 // No bits in common -> bitwise or.
2204 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2205 return BinaryOperator::CreateOr(LHS, RHS);
2209 // W*X + Y*Z --> W * (X+Z) iff W == Y
2210 if (I.getType()->isIntOrIntVector()) {
2211 Value *W, *X, *Y, *Z;
2212 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2213 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2217 } else if (Y == X) {
2219 } else if (X == Z) {
2226 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2227 LHS->getName()), I);
2228 return BinaryOperator::CreateMul(W, NewAdd);
2233 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2235 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2236 return BinaryOperator::CreateSub(SubOne(CRHS), X);
2238 // (X & FF00) + xx00 -> (X+xx00) & FF00
2239 if (LHS->hasOneUse() &&
2240 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2241 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2242 if (Anded == CRHS) {
2243 // See if all bits from the first bit set in the Add RHS up are included
2244 // in the mask. First, get the rightmost bit.
2245 const APInt& AddRHSV = CRHS->getValue();
2247 // Form a mask of all bits from the lowest bit added through the top.
2248 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2250 // See if the and mask includes all of these bits.
2251 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2253 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2254 // Okay, the xform is safe. Insert the new add pronto.
2255 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2256 LHS->getName()), I);
2257 return BinaryOperator::CreateAnd(NewAdd, C2);
2262 // Try to fold constant add into select arguments.
2263 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2264 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2268 // add (select X 0 (sub n A)) A --> select X A n
2270 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2273 SI = dyn_cast<SelectInst>(RHS);
2276 if (SI && SI->hasOneUse()) {
2277 Value *TV = SI->getTrueValue();
2278 Value *FV = SI->getFalseValue();
2281 // Can we fold the add into the argument of the select?
2282 // We check both true and false select arguments for a matching subtract.
2283 if (match(FV, m_Zero()) &&
2284 match(TV, m_Sub(m_Value(N), m_Specific(A))))
2285 // Fold the add into the true select value.
2286 return SelectInst::Create(SI->getCondition(), N, A);
2287 if (match(TV, m_Zero()) &&
2288 match(FV, m_Sub(m_Value(N), m_Specific(A))))
2289 // Fold the add into the false select value.
2290 return SelectInst::Create(SI->getCondition(), A, N);
2294 // Check for (add (sext x), y), see if we can merge this into an
2295 // integer add followed by a sext.
2296 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2297 // (add (sext x), cst) --> (sext (add x, cst'))
2298 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2300 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2301 if (LHSConv->hasOneUse() &&
2302 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2303 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2304 // Insert the new, smaller add.
2305 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2307 InsertNewInstBefore(NewAdd, I);
2308 return new SExtInst(NewAdd, I.getType());
2312 // (add (sext x), (sext y)) --> (sext (add int x, y))
2313 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2314 // Only do this if x/y have the same type, if at last one of them has a
2315 // single use (so we don't increase the number of sexts), and if the
2316 // integer add will not overflow.
2317 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2318 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2319 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2320 RHSConv->getOperand(0))) {
2321 // Insert the new integer add.
2322 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2323 RHSConv->getOperand(0),
2325 InsertNewInstBefore(NewAdd, I);
2326 return new SExtInst(NewAdd, I.getType());
2331 return Changed ? &I : 0;
2334 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2335 bool Changed = SimplifyCommutative(I);
2336 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2338 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2340 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2341 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2342 (I.getType())->getValueAPF()))
2343 return ReplaceInstUsesWith(I, LHS);
2346 if (isa<PHINode>(LHS))
2347 if (Instruction *NV = FoldOpIntoPhi(I))
2352 // -A + -B --> -(A + B)
2353 if (Value *LHSV = dyn_castFNegVal(LHS))
2354 return BinaryOperator::CreateFSub(RHS, LHSV);
2357 if (!isa<Constant>(RHS))
2358 if (Value *V = dyn_castFNegVal(RHS))
2359 return BinaryOperator::CreateFSub(LHS, V);
2361 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2362 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2363 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2364 return ReplaceInstUsesWith(I, LHS);
2366 // Check for (add double (sitofp x), y), see if we can merge this into an
2367 // integer add followed by a promotion.
2368 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2369 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2370 // ... if the constant fits in the integer value. This is useful for things
2371 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2372 // requires a constant pool load, and generally allows the add to be better
2374 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2376 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2377 if (LHSConv->hasOneUse() &&
2378 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2379 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2380 // Insert the new integer add.
2381 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2383 InsertNewInstBefore(NewAdd, I);
2384 return new SIToFPInst(NewAdd, I.getType());
2388 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2389 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2390 // Only do this if x/y have the same type, if at last one of them has a
2391 // single use (so we don't increase the number of int->fp conversions),
2392 // and if the integer add will not overflow.
2393 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2394 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2395 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2396 RHSConv->getOperand(0))) {
2397 // Insert the new integer add.
2398 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2399 RHSConv->getOperand(0),
2401 InsertNewInstBefore(NewAdd, I);
2402 return new SIToFPInst(NewAdd, I.getType());
2407 return Changed ? &I : 0;
2410 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2411 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2413 if (Op0 == Op1) // sub X, X -> 0
2414 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2416 // If this is a 'B = x-(-A)', change to B = x+A...
2417 if (Value *V = dyn_castNegVal(Op1))
2418 return BinaryOperator::CreateAdd(Op0, V);
2420 if (isa<UndefValue>(Op0))
2421 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2422 if (isa<UndefValue>(Op1))
2423 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2425 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2426 // Replace (-1 - A) with (~A)...
2427 if (C->isAllOnesValue())
2428 return BinaryOperator::CreateNot(Op1);
2430 // C - ~X == X + (1+C)
2432 if (match(Op1, m_Not(m_Value(X))))
2433 return BinaryOperator::CreateAdd(X, AddOne(C));
2435 // -(X >>u 31) -> (X >>s 31)
2436 // -(X >>s 31) -> (X >>u 31)
2438 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2439 if (SI->getOpcode() == Instruction::LShr) {
2440 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2441 // Check to see if we are shifting out everything but the sign bit.
2442 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2443 SI->getType()->getPrimitiveSizeInBits()-1) {
2444 // Ok, the transformation is safe. Insert AShr.
2445 return BinaryOperator::Create(Instruction::AShr,
2446 SI->getOperand(0), CU, SI->getName());
2450 else if (SI->getOpcode() == Instruction::AShr) {
2451 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2452 // Check to see if we are shifting out everything but the sign bit.
2453 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2454 SI->getType()->getPrimitiveSizeInBits()-1) {
2455 // Ok, the transformation is safe. Insert LShr.
2456 return BinaryOperator::CreateLShr(
2457 SI->getOperand(0), CU, SI->getName());
2464 // Try to fold constant sub into select arguments.
2465 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2466 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2469 // C - zext(bool) -> bool ? C - 1 : C
2470 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2471 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2472 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2475 if (I.getType() == Type::getInt1Ty(*Context))
2476 return BinaryOperator::CreateXor(Op0, Op1);
2478 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2479 if (Op1I->getOpcode() == Instruction::Add) {
2480 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2481 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2483 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2484 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2486 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2487 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2488 // C1-(X+C2) --> (C1-C2)-X
2489 return BinaryOperator::CreateSub(
2490 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2494 if (Op1I->hasOneUse()) {
2495 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2496 // is not used by anyone else...
2498 if (Op1I->getOpcode() == Instruction::Sub) {
2499 // Swap the two operands of the subexpr...
2500 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2501 Op1I->setOperand(0, IIOp1);
2502 Op1I->setOperand(1, IIOp0);
2504 // Create the new top level add instruction...
2505 return BinaryOperator::CreateAdd(Op0, Op1);
2508 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2510 if (Op1I->getOpcode() == Instruction::And &&
2511 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2512 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2515 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2516 return BinaryOperator::CreateAnd(Op0, NewNot);
2519 // 0 - (X sdiv C) -> (X sdiv -C)
2520 if (Op1I->getOpcode() == Instruction::SDiv)
2521 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2523 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2524 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2525 ConstantExpr::getNeg(DivRHS));
2527 // X - X*C --> X * (1-C)
2528 ConstantInt *C2 = 0;
2529 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2531 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2533 return BinaryOperator::CreateMul(Op0, CP1);
2538 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2539 if (Op0I->getOpcode() == Instruction::Add) {
2540 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2541 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2542 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2543 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2544 } else if (Op0I->getOpcode() == Instruction::Sub) {
2545 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2546 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2552 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2553 if (X == Op1) // X*C - X --> X * (C-1)
2554 return BinaryOperator::CreateMul(Op1, SubOne(C1));
2556 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2557 if (X == dyn_castFoldableMul(Op1, C2))
2558 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2563 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2564 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2566 // If this is a 'B = x-(-A)', change to B = x+A...
2567 if (Value *V = dyn_castFNegVal(Op1))
2568 return BinaryOperator::CreateFAdd(Op0, V);
2570 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2571 if (Op1I->getOpcode() == Instruction::FAdd) {
2572 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2573 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2575 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2576 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2584 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2585 /// comparison only checks the sign bit. If it only checks the sign bit, set
2586 /// TrueIfSigned if the result of the comparison is true when the input value is
2588 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2589 bool &TrueIfSigned) {
2591 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2592 TrueIfSigned = true;
2593 return RHS->isZero();
2594 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2595 TrueIfSigned = true;
2596 return RHS->isAllOnesValue();
2597 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2598 TrueIfSigned = false;
2599 return RHS->isAllOnesValue();
2600 case ICmpInst::ICMP_UGT:
2601 // True if LHS u> RHS and RHS == high-bit-mask - 1
2602 TrueIfSigned = true;
2603 return RHS->getValue() ==
2604 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2605 case ICmpInst::ICMP_UGE:
2606 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2607 TrueIfSigned = true;
2608 return RHS->getValue().isSignBit();
2614 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2615 bool Changed = SimplifyCommutative(I);
2616 Value *Op0 = I.getOperand(0);
2618 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2619 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2621 // Simplify mul instructions with a constant RHS...
2622 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2623 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2625 // ((X << C1)*C2) == (X * (C2 << C1))
2626 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2627 if (SI->getOpcode() == Instruction::Shl)
2628 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2629 return BinaryOperator::CreateMul(SI->getOperand(0),
2630 ConstantExpr::getShl(CI, ShOp));
2633 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2634 if (CI->equalsInt(1)) // X * 1 == X
2635 return ReplaceInstUsesWith(I, Op0);
2636 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2637 return BinaryOperator::CreateNeg(Op0, I.getName());
2639 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2640 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2641 return BinaryOperator::CreateShl(Op0,
2642 ConstantInt::get(Op0->getType(), Val.logBase2()));
2644 } else if (isa<VectorType>(Op1->getType())) {
2645 if (Op1->isNullValue())
2646 return ReplaceInstUsesWith(I, Op1);
2648 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2649 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2650 return BinaryOperator::CreateNeg(Op0, I.getName());
2652 // As above, vector X*splat(1.0) -> X in all defined cases.
2653 if (Constant *Splat = Op1V->getSplatValue()) {
2654 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2655 if (CI->equalsInt(1))
2656 return ReplaceInstUsesWith(I, Op0);
2661 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2662 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2663 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2664 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2665 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2667 InsertNewInstBefore(Add, I);
2668 Value *C1C2 = ConstantExpr::getMul(Op1,
2669 cast<Constant>(Op0I->getOperand(1)));
2670 return BinaryOperator::CreateAdd(Add, C1C2);
2674 // Try to fold constant mul into select arguments.
2675 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2676 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2679 if (isa<PHINode>(Op0))
2680 if (Instruction *NV = FoldOpIntoPhi(I))
2684 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2685 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2686 return BinaryOperator::CreateMul(Op0v, Op1v);
2688 // (X / Y) * Y = X - (X % Y)
2689 // (X / Y) * -Y = (X % Y) - X
2691 Value *Op1 = I.getOperand(1);
2692 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2694 (BO->getOpcode() != Instruction::UDiv &&
2695 BO->getOpcode() != Instruction::SDiv)) {
2697 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2699 Value *Neg = dyn_castNegVal(Op1);
2700 if (BO && BO->hasOneUse() &&
2701 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2702 (BO->getOpcode() == Instruction::UDiv ||
2703 BO->getOpcode() == Instruction::SDiv)) {
2704 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2706 // If the division is exact, X % Y is zero.
2707 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2708 if (SDiv->isExact()) {
2710 return ReplaceInstUsesWith(I, Op0BO);
2712 return BinaryOperator::CreateNeg(Op0BO);
2716 if (BO->getOpcode() == Instruction::UDiv)
2717 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2719 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2721 InsertNewInstBefore(Rem, I);
2725 return BinaryOperator::CreateSub(Op0BO, Rem);
2727 return BinaryOperator::CreateSub(Rem, Op0BO);
2731 if (I.getType() == Type::getInt1Ty(*Context))
2732 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2734 // If one of the operands of the multiply is a cast from a boolean value, then
2735 // we know the bool is either zero or one, so this is a 'masking' multiply.
2736 // See if we can simplify things based on how the boolean was originally
2738 CastInst *BoolCast = 0;
2739 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2740 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2743 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2744 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2747 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2748 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2749 const Type *SCOpTy = SCIOp0->getType();
2752 // If the icmp is true iff the sign bit of X is set, then convert this
2753 // multiply into a shift/and combination.
2754 if (isa<ConstantInt>(SCIOp1) &&
2755 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2757 // Shift the X value right to turn it into "all signbits".
2758 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2759 SCOpTy->getPrimitiveSizeInBits()-1);
2761 InsertNewInstBefore(
2762 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2763 BoolCast->getOperand(0)->getName()+
2766 // If the multiply type is not the same as the source type, sign extend
2767 // or truncate to the multiply type.
2768 if (I.getType() != V->getType()) {
2769 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2770 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2771 Instruction::CastOps opcode =
2772 (SrcBits == DstBits ? Instruction::BitCast :
2773 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2774 V = InsertCastBefore(opcode, V, I.getType(), I);
2777 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2778 return BinaryOperator::CreateAnd(V, OtherOp);
2783 return Changed ? &I : 0;
2786 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2787 bool Changed = SimplifyCommutative(I);
2788 Value *Op0 = I.getOperand(0);
2790 // Simplify mul instructions with a constant RHS...
2791 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2792 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2793 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2794 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2795 if (Op1F->isExactlyValue(1.0))
2796 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2797 } else if (isa<VectorType>(Op1->getType())) {
2798 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2799 // As above, vector X*splat(1.0) -> X in all defined cases.
2800 if (Constant *Splat = Op1V->getSplatValue()) {
2801 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2802 if (F->isExactlyValue(1.0))
2803 return ReplaceInstUsesWith(I, Op0);
2808 // Try to fold constant mul into select arguments.
2809 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2810 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2813 if (isa<PHINode>(Op0))
2814 if (Instruction *NV = FoldOpIntoPhi(I))
2818 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2819 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2820 return BinaryOperator::CreateFMul(Op0v, Op1v);
2822 return Changed ? &I : 0;
2825 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2827 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2828 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2830 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2831 int NonNullOperand = -1;
2832 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2833 if (ST->isNullValue())
2835 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2836 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2837 if (ST->isNullValue())
2840 if (NonNullOperand == -1)
2843 Value *SelectCond = SI->getOperand(0);
2845 // Change the div/rem to use 'Y' instead of the select.
2846 I.setOperand(1, SI->getOperand(NonNullOperand));
2848 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2849 // problem. However, the select, or the condition of the select may have
2850 // multiple uses. Based on our knowledge that the operand must be non-zero,
2851 // propagate the known value for the select into other uses of it, and
2852 // propagate a known value of the condition into its other users.
2854 // If the select and condition only have a single use, don't bother with this,
2856 if (SI->use_empty() && SelectCond->hasOneUse())
2859 // Scan the current block backward, looking for other uses of SI.
2860 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2862 while (BBI != BBFront) {
2864 // If we found a call to a function, we can't assume it will return, so
2865 // information from below it cannot be propagated above it.
2866 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2869 // Replace uses of the select or its condition with the known values.
2870 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2873 *I = SI->getOperand(NonNullOperand);
2875 } else if (*I == SelectCond) {
2876 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2877 ConstantInt::getFalse(*Context);
2882 // If we past the instruction, quit looking for it.
2885 if (&*BBI == SelectCond)
2888 // If we ran out of things to eliminate, break out of the loop.
2889 if (SelectCond == 0 && SI == 0)
2897 /// This function implements the transforms on div instructions that work
2898 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2899 /// used by the visitors to those instructions.
2900 /// @brief Transforms common to all three div instructions
2901 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2902 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2904 // undef / X -> 0 for integer.
2905 // undef / X -> undef for FP (the undef could be a snan).
2906 if (isa<UndefValue>(Op0)) {
2907 if (Op0->getType()->isFPOrFPVector())
2908 return ReplaceInstUsesWith(I, Op0);
2909 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2912 // X / undef -> undef
2913 if (isa<UndefValue>(Op1))
2914 return ReplaceInstUsesWith(I, Op1);
2919 /// This function implements the transforms common to both integer division
2920 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2921 /// division instructions.
2922 /// @brief Common integer divide transforms
2923 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2924 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2926 // (sdiv X, X) --> 1 (udiv X, X) --> 1
2928 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2929 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2930 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2931 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2934 Constant *CI = ConstantInt::get(I.getType(), 1);
2935 return ReplaceInstUsesWith(I, CI);
2938 if (Instruction *Common = commonDivTransforms(I))
2941 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2942 // This does not apply for fdiv.
2943 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2946 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2948 if (RHS->equalsInt(1))
2949 return ReplaceInstUsesWith(I, Op0);
2951 // (X / C1) / C2 -> X / (C1*C2)
2952 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2953 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2954 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2955 if (MultiplyOverflows(RHS, LHSRHS,
2956 I.getOpcode()==Instruction::SDiv))
2957 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2959 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2960 ConstantExpr::getMul(RHS, LHSRHS));
2963 if (!RHS->isZero()) { // avoid X udiv 0
2964 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2965 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2967 if (isa<PHINode>(Op0))
2968 if (Instruction *NV = FoldOpIntoPhi(I))
2973 // 0 / X == 0, we don't need to preserve faults!
2974 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2975 if (LHS->equalsInt(0))
2976 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2978 // It can't be division by zero, hence it must be division by one.
2979 if (I.getType() == Type::getInt1Ty(*Context))
2980 return ReplaceInstUsesWith(I, Op0);
2982 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2983 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2986 return ReplaceInstUsesWith(I, Op0);
2992 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2993 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2995 // Handle the integer div common cases
2996 if (Instruction *Common = commonIDivTransforms(I))
2999 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3000 // X udiv C^2 -> X >> C
3001 // Check to see if this is an unsigned division with an exact power of 2,
3002 // if so, convert to a right shift.
3003 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
3004 return BinaryOperator::CreateLShr(Op0,
3005 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3007 // X udiv C, where C >= signbit
3008 if (C->getValue().isNegative()) {
3009 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3010 ICmpInst::ICMP_ULT, Op0, C),
3012 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3013 ConstantInt::get(I.getType(), 1));
3017 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3018 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3019 if (RHSI->getOpcode() == Instruction::Shl &&
3020 isa<ConstantInt>(RHSI->getOperand(0))) {
3021 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3022 if (C1.isPowerOf2()) {
3023 Value *N = RHSI->getOperand(1);
3024 const Type *NTy = N->getType();
3025 if (uint32_t C2 = C1.logBase2()) {
3026 Constant *C2V = ConstantInt::get(NTy, C2);
3027 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3029 return BinaryOperator::CreateLShr(Op0, N);
3034 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3035 // where C1&C2 are powers of two.
3036 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3037 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3038 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3039 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3040 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3041 // Compute the shift amounts
3042 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3043 // Construct the "on true" case of the select
3044 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3045 Instruction *TSI = BinaryOperator::CreateLShr(
3046 Op0, TC, SI->getName()+".t");
3047 TSI = InsertNewInstBefore(TSI, I);
3049 // Construct the "on false" case of the select
3050 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
3051 Instruction *FSI = BinaryOperator::CreateLShr(
3052 Op0, FC, SI->getName()+".f");
3053 FSI = InsertNewInstBefore(FSI, I);
3055 // construct the select instruction and return it.
3056 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3062 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3063 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3065 // Handle the integer div common cases
3066 if (Instruction *Common = commonIDivTransforms(I))
3069 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3071 if (RHS->isAllOnesValue())
3072 return BinaryOperator::CreateNeg(Op0);
3074 // sdiv X, C --> ashr X, log2(C)
3075 if (cast<SDivOperator>(&I)->isExact() &&
3076 RHS->getValue().isNonNegative() &&
3077 RHS->getValue().isPowerOf2()) {
3078 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3079 RHS->getValue().exactLogBase2());
3080 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3083 // -X/C --> X/-C provided the negation doesn't overflow.
3084 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3085 if (isa<Constant>(Sub->getOperand(0)) &&
3086 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3087 Sub->hasNoSignedOverflow())
3088 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3089 ConstantExpr::getNeg(RHS));
3092 // If the sign bits of both operands are zero (i.e. we can prove they are
3093 // unsigned inputs), turn this into a udiv.
3094 if (I.getType()->isInteger()) {
3095 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3096 if (MaskedValueIsZero(Op0, Mask)) {
3097 if (MaskedValueIsZero(Op1, Mask)) {
3098 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3099 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3101 ConstantInt *ShiftedInt;
3102 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3103 ShiftedInt->getValue().isPowerOf2()) {
3104 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3105 // Safe because the only negative value (1 << Y) can take on is
3106 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3107 // the sign bit set.
3108 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3116 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3117 return commonDivTransforms(I);
3120 /// This function implements the transforms on rem instructions that work
3121 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3122 /// is used by the visitors to those instructions.
3123 /// @brief Transforms common to all three rem instructions
3124 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3125 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3127 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3128 if (I.getType()->isFPOrFPVector())
3129 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
3130 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3132 if (isa<UndefValue>(Op1))
3133 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3135 // Handle cases involving: rem X, (select Cond, Y, Z)
3136 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3142 /// This function implements the transforms common to both integer remainder
3143 /// instructions (urem and srem). It is called by the visitors to those integer
3144 /// remainder instructions.
3145 /// @brief Common integer remainder transforms
3146 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3147 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3149 if (Instruction *common = commonRemTransforms(I))
3152 // 0 % X == 0 for integer, we don't need to preserve faults!
3153 if (Constant *LHS = dyn_cast<Constant>(Op0))
3154 if (LHS->isNullValue())
3155 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3157 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3158 // X % 0 == undef, we don't need to preserve faults!
3159 if (RHS->equalsInt(0))
3160 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3162 if (RHS->equalsInt(1)) // X % 1 == 0
3163 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3165 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3166 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3167 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3169 } else if (isa<PHINode>(Op0I)) {
3170 if (Instruction *NV = FoldOpIntoPhi(I))
3174 // See if we can fold away this rem instruction.
3175 if (SimplifyDemandedInstructionBits(I))
3183 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3184 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3186 if (Instruction *common = commonIRemTransforms(I))
3189 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3190 // X urem C^2 -> X and C
3191 // Check to see if this is an unsigned remainder with an exact power of 2,
3192 // if so, convert to a bitwise and.
3193 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3194 if (C->getValue().isPowerOf2())
3195 return BinaryOperator::CreateAnd(Op0, SubOne(C));
3198 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3199 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3200 if (RHSI->getOpcode() == Instruction::Shl &&
3201 isa<ConstantInt>(RHSI->getOperand(0))) {
3202 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3203 Constant *N1 = Constant::getAllOnesValue(I.getType());
3204 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3206 return BinaryOperator::CreateAnd(Op0, Add);
3211 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3212 // where C1&C2 are powers of two.
3213 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3214 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3215 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3216 // STO == 0 and SFO == 0 handled above.
3217 if ((STO->getValue().isPowerOf2()) &&
3218 (SFO->getValue().isPowerOf2())) {
3219 Value *TrueAnd = InsertNewInstBefore(
3220 BinaryOperator::CreateAnd(Op0, SubOne(STO),
3221 SI->getName()+".t"), I);
3222 Value *FalseAnd = InsertNewInstBefore(
3223 BinaryOperator::CreateAnd(Op0, SubOne(SFO),
3224 SI->getName()+".f"), I);
3225 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3233 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3234 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3236 // Handle the integer rem common cases
3237 if (Instruction *common = commonIRemTransforms(I))
3240 if (Value *RHSNeg = dyn_castNegVal(Op1))
3241 if (!isa<Constant>(RHSNeg) ||
3242 (isa<ConstantInt>(RHSNeg) &&
3243 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3245 AddUsesToWorkList(I);
3246 I.setOperand(1, RHSNeg);
3250 // If the sign bits of both operands are zero (i.e. we can prove they are
3251 // unsigned inputs), turn this into a urem.
3252 if (I.getType()->isInteger()) {
3253 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3254 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3255 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3256 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3260 // If it's a constant vector, flip any negative values positive.
3261 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3262 unsigned VWidth = RHSV->getNumOperands();
3264 bool hasNegative = false;
3265 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3266 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3267 if (RHS->getValue().isNegative())
3271 std::vector<Constant *> Elts(VWidth);
3272 for (unsigned i = 0; i != VWidth; ++i) {
3273 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3274 if (RHS->getValue().isNegative())
3275 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3281 Constant *NewRHSV = ConstantVector::get(Elts);
3282 if (NewRHSV != RHSV) {
3283 AddUsesToWorkList(I);
3284 I.setOperand(1, NewRHSV);
3293 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3294 return commonRemTransforms(I);
3297 // isOneBitSet - Return true if there is exactly one bit set in the specified
3299 static bool isOneBitSet(const ConstantInt *CI) {
3300 return CI->getValue().isPowerOf2();
3303 // isHighOnes - Return true if the constant is of the form 1+0+.
3304 // This is the same as lowones(~X).
3305 static bool isHighOnes(const ConstantInt *CI) {
3306 return (~CI->getValue() + 1).isPowerOf2();
3309 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3310 /// are carefully arranged to allow folding of expressions such as:
3312 /// (A < B) | (A > B) --> (A != B)
3314 /// Note that this is only valid if the first and second predicates have the
3315 /// same sign. Is illegal to do: (A u< B) | (A s> B)
3317 /// Three bits are used to represent the condition, as follows:
3322 /// <=> Value Definition
3323 /// 000 0 Always false
3330 /// 111 7 Always true
3332 static unsigned getICmpCode(const ICmpInst *ICI) {
3333 switch (ICI->getPredicate()) {
3335 case ICmpInst::ICMP_UGT: return 1; // 001
3336 case ICmpInst::ICMP_SGT: return 1; // 001
3337 case ICmpInst::ICMP_EQ: return 2; // 010
3338 case ICmpInst::ICMP_UGE: return 3; // 011
3339 case ICmpInst::ICMP_SGE: return 3; // 011
3340 case ICmpInst::ICMP_ULT: return 4; // 100
3341 case ICmpInst::ICMP_SLT: return 4; // 100
3342 case ICmpInst::ICMP_NE: return 5; // 101
3343 case ICmpInst::ICMP_ULE: return 6; // 110
3344 case ICmpInst::ICMP_SLE: return 6; // 110
3347 llvm_unreachable("Invalid ICmp predicate!");
3352 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3353 /// predicate into a three bit mask. It also returns whether it is an ordered
3354 /// predicate by reference.
3355 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3358 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3359 case FCmpInst::FCMP_UNO: return 0; // 000
3360 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3361 case FCmpInst::FCMP_UGT: return 1; // 001
3362 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3363 case FCmpInst::FCMP_UEQ: return 2; // 010
3364 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3365 case FCmpInst::FCMP_UGE: return 3; // 011
3366 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3367 case FCmpInst::FCMP_ULT: return 4; // 100
3368 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3369 case FCmpInst::FCMP_UNE: return 5; // 101
3370 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3371 case FCmpInst::FCMP_ULE: return 6; // 110
3374 // Not expecting FCMP_FALSE and FCMP_TRUE;
3375 llvm_unreachable("Unexpected FCmp predicate!");
3380 /// getICmpValue - This is the complement of getICmpCode, which turns an
3381 /// opcode and two operands into either a constant true or false, or a brand
3382 /// new ICmp instruction. The sign is passed in to determine which kind
3383 /// of predicate to use in the new icmp instruction.
3384 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3385 LLVMContext *Context) {
3387 default: llvm_unreachable("Illegal ICmp code!");
3388 case 0: return ConstantInt::getFalse(*Context);
3391 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
3393 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3394 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
3397 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
3399 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
3402 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
3404 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3405 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
3408 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
3410 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
3411 case 7: return ConstantInt::getTrue(*Context);
3415 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3416 /// opcode and two operands into either a FCmp instruction. isordered is passed
3417 /// in to determine which kind of predicate to use in the new fcmp instruction.
3418 static Value *getFCmpValue(bool isordered, unsigned code,
3419 Value *LHS, Value *RHS, LLVMContext *Context) {
3421 default: llvm_unreachable("Illegal FCmp code!");
3424 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
3426 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
3429 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
3431 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
3434 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
3436 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
3439 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
3441 return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
3444 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
3446 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
3449 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
3451 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
3454 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
3456 return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
3457 case 7: return ConstantInt::getTrue(*Context);
3461 /// PredicatesFoldable - Return true if both predicates match sign or if at
3462 /// least one of them is an equality comparison (which is signless).
3463 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3464 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3465 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3466 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3470 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3471 struct FoldICmpLogical {
3474 ICmpInst::Predicate pred;
3475 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3476 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3477 pred(ICI->getPredicate()) {}
3478 bool shouldApply(Value *V) const {
3479 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3480 if (PredicatesFoldable(pred, ICI->getPredicate()))
3481 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3482 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3485 Instruction *apply(Instruction &Log) const {
3486 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3487 if (ICI->getOperand(0) != LHS) {
3488 assert(ICI->getOperand(1) == LHS);
3489 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3492 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3493 unsigned LHSCode = getICmpCode(ICI);
3494 unsigned RHSCode = getICmpCode(RHSICI);
3496 switch (Log.getOpcode()) {
3497 case Instruction::And: Code = LHSCode & RHSCode; break;
3498 case Instruction::Or: Code = LHSCode | RHSCode; break;
3499 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3500 default: llvm_unreachable("Illegal logical opcode!"); return 0;
3503 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3504 ICmpInst::isSignedPredicate(ICI->getPredicate());
3506 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3507 if (Instruction *I = dyn_cast<Instruction>(RV))
3509 // Otherwise, it's a constant boolean value...
3510 return IC.ReplaceInstUsesWith(Log, RV);
3513 } // end anonymous namespace
3515 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3516 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3517 // guaranteed to be a binary operator.
3518 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3520 ConstantInt *AndRHS,
3521 BinaryOperator &TheAnd) {
3522 Value *X = Op->getOperand(0);
3523 Constant *Together = 0;
3525 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3527 switch (Op->getOpcode()) {
3528 case Instruction::Xor:
3529 if (Op->hasOneUse()) {
3530 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3531 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3532 InsertNewInstBefore(And, TheAnd);
3534 return BinaryOperator::CreateXor(And, Together);
3537 case Instruction::Or:
3538 if (Together == AndRHS) // (X | C) & C --> C
3539 return ReplaceInstUsesWith(TheAnd, AndRHS);
3541 if (Op->hasOneUse() && Together != OpRHS) {
3542 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3543 Instruction *Or = BinaryOperator::CreateOr(X, Together);
3544 InsertNewInstBefore(Or, TheAnd);
3546 return BinaryOperator::CreateAnd(Or, AndRHS);
3549 case Instruction::Add:
3550 if (Op->hasOneUse()) {
3551 // Adding a one to a single bit bit-field should be turned into an XOR
3552 // of the bit. First thing to check is to see if this AND is with a
3553 // single bit constant.
3554 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3556 // If there is only one bit set...
3557 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3558 // Ok, at this point, we know that we are masking the result of the
3559 // ADD down to exactly one bit. If the constant we are adding has
3560 // no bits set below this bit, then we can eliminate the ADD.
3561 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3563 // Check to see if any bits below the one bit set in AndRHSV are set.
3564 if ((AddRHS & (AndRHSV-1)) == 0) {
3565 // If not, the only thing that can effect the output of the AND is
3566 // the bit specified by AndRHSV. If that bit is set, the effect of
3567 // the XOR is to toggle the bit. If it is clear, then the ADD has
3569 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3570 TheAnd.setOperand(0, X);
3573 // Pull the XOR out of the AND.
3574 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3575 InsertNewInstBefore(NewAnd, TheAnd);
3576 NewAnd->takeName(Op);
3577 return BinaryOperator::CreateXor(NewAnd, AndRHS);
3584 case Instruction::Shl: {
3585 // We know that the AND will not produce any of the bits shifted in, so if
3586 // the anded constant includes them, clear them now!
3588 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3589 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3590 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3591 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3593 if (CI->getValue() == ShlMask) {
3594 // Masking out bits that the shift already masks
3595 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3596 } else if (CI != AndRHS) { // Reducing bits set in and.
3597 TheAnd.setOperand(1, CI);
3602 case Instruction::LShr:
3604 // We know that the AND will not produce any of the bits shifted in, so if
3605 // the anded constant includes them, clear them now! This only applies to
3606 // unsigned shifts, because a signed shr may bring in set bits!
3608 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3609 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3610 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3611 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3613 if (CI->getValue() == ShrMask) {
3614 // Masking out bits that the shift already masks.
3615 return ReplaceInstUsesWith(TheAnd, Op);
3616 } else if (CI != AndRHS) {
3617 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3622 case Instruction::AShr:
3624 // See if this is shifting in some sign extension, then masking it out
3626 if (Op->hasOneUse()) {
3627 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3628 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3629 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3630 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3631 if (C == AndRHS) { // Masking out bits shifted in.
3632 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3633 // Make the argument unsigned.
3634 Value *ShVal = Op->getOperand(0);
3635 ShVal = InsertNewInstBefore(
3636 BinaryOperator::CreateLShr(ShVal, OpRHS,
3637 Op->getName()), TheAnd);
3638 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3647 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3648 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3649 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3650 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3651 /// insert new instructions.
3652 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3653 bool isSigned, bool Inside,
3655 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3656 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3657 "Lo is not <= Hi in range emission code!");
3660 if (Lo == Hi) // Trivially false.
3661 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
3663 // V >= Min && V < Hi --> V < Hi
3664 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3665 ICmpInst::Predicate pred = (isSigned ?
3666 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3667 return new ICmpInst(*Context, pred, V, Hi);
3670 // Emit V-Lo <u Hi-Lo
3671 Constant *NegLo = ConstantExpr::getNeg(Lo);
3672 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3673 InsertNewInstBefore(Add, IB);
3674 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3675 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
3678 if (Lo == Hi) // Trivially true.
3679 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
3681 // V < Min || V >= Hi -> V > Hi-1
3682 Hi = SubOne(cast<ConstantInt>(Hi));
3683 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3684 ICmpInst::Predicate pred = (isSigned ?
3685 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3686 return new ICmpInst(*Context, pred, V, Hi);
3689 // Emit V-Lo >u Hi-1-Lo
3690 // Note that Hi has already had one subtracted from it, above.
3691 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3692 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3693 InsertNewInstBefore(Add, IB);
3694 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3695 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
3698 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3699 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3700 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3701 // not, since all 1s are not contiguous.
3702 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3703 const APInt& V = Val->getValue();
3704 uint32_t BitWidth = Val->getType()->getBitWidth();
3705 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3707 // look for the first zero bit after the run of ones
3708 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3709 // look for the first non-zero bit
3710 ME = V.getActiveBits();
3714 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3715 /// where isSub determines whether the operator is a sub. If we can fold one of
3716 /// the following xforms:
3718 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3719 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3720 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3722 /// return (A +/- B).
3724 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3725 ConstantInt *Mask, bool isSub,
3727 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3728 if (!LHSI || LHSI->getNumOperands() != 2 ||
3729 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3731 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3733 switch (LHSI->getOpcode()) {
3735 case Instruction::And:
3736 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3737 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3738 if ((Mask->getValue().countLeadingZeros() +
3739 Mask->getValue().countPopulation()) ==
3740 Mask->getValue().getBitWidth())
3743 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3744 // part, we don't need any explicit masks to take them out of A. If that
3745 // is all N is, ignore it.
3746 uint32_t MB = 0, ME = 0;
3747 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3748 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3749 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3750 if (MaskedValueIsZero(RHS, Mask))
3755 case Instruction::Or:
3756 case Instruction::Xor:
3757 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3758 if ((Mask->getValue().countLeadingZeros() +
3759 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3760 && ConstantExpr::getAnd(N, Mask)->isNullValue())
3767 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3769 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3770 return InsertNewInstBefore(New, I);
3773 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3774 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3775 ICmpInst *LHS, ICmpInst *RHS) {
3777 ConstantInt *LHSCst, *RHSCst;
3778 ICmpInst::Predicate LHSCC, RHSCC;
3780 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3781 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3782 m_ConstantInt(LHSCst))) ||
3783 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3784 m_ConstantInt(RHSCst))))
3787 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3788 // where C is a power of 2
3789 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3790 LHSCst->getValue().isPowerOf2()) {
3791 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3792 InsertNewInstBefore(NewOr, I);
3793 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
3796 // From here on, we only handle:
3797 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3798 if (Val != Val2) return 0;
3800 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3801 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3802 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3803 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3804 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3807 // We can't fold (ugt x, C) & (sgt x, C2).
3808 if (!PredicatesFoldable(LHSCC, RHSCC))
3811 // Ensure that the larger constant is on the RHS.
3813 if (ICmpInst::isSignedPredicate(LHSCC) ||
3814 (ICmpInst::isEquality(LHSCC) &&
3815 ICmpInst::isSignedPredicate(RHSCC)))
3816 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3818 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3821 std::swap(LHS, RHS);
3822 std::swap(LHSCst, RHSCst);
3823 std::swap(LHSCC, RHSCC);
3826 // At this point, we know we have have two icmp instructions
3827 // comparing a value against two constants and and'ing the result
3828 // together. Because of the above check, we know that we only have
3829 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3830 // (from the FoldICmpLogical check above), that the two constants
3831 // are not equal and that the larger constant is on the RHS
3832 assert(LHSCst != RHSCst && "Compares not folded above?");
3835 default: llvm_unreachable("Unknown integer condition code!");
3836 case ICmpInst::ICMP_EQ:
3838 default: llvm_unreachable("Unknown integer condition code!");
3839 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3840 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3841 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3842 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3843 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3844 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3845 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3846 return ReplaceInstUsesWith(I, LHS);
3848 case ICmpInst::ICMP_NE:
3850 default: llvm_unreachable("Unknown integer condition code!");
3851 case ICmpInst::ICMP_ULT:
3852 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3853 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
3854 break; // (X != 13 & X u< 15) -> no change
3855 case ICmpInst::ICMP_SLT:
3856 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3857 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
3858 break; // (X != 13 & X s< 15) -> no change
3859 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3860 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3861 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3862 return ReplaceInstUsesWith(I, RHS);
3863 case ICmpInst::ICMP_NE:
3864 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3865 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3866 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3867 Val->getName()+".off");
3868 InsertNewInstBefore(Add, I);
3869 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
3870 ConstantInt::get(Add->getType(), 1));
3872 break; // (X != 13 & X != 15) -> no change
3875 case ICmpInst::ICMP_ULT:
3877 default: llvm_unreachable("Unknown integer condition code!");
3878 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3879 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3880 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3881 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3883 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3884 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3885 return ReplaceInstUsesWith(I, LHS);
3886 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3890 case ICmpInst::ICMP_SLT:
3892 default: llvm_unreachable("Unknown integer condition code!");
3893 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3894 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3895 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3896 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3898 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3899 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3900 return ReplaceInstUsesWith(I, LHS);
3901 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3905 case ICmpInst::ICMP_UGT:
3907 default: llvm_unreachable("Unknown integer condition code!");
3908 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3909 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3910 return ReplaceInstUsesWith(I, RHS);
3911 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3913 case ICmpInst::ICMP_NE:
3914 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3915 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3916 break; // (X u> 13 & X != 15) -> no change
3917 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
3918 return InsertRangeTest(Val, AddOne(LHSCst),
3919 RHSCst, false, true, I);
3920 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3924 case ICmpInst::ICMP_SGT:
3926 default: llvm_unreachable("Unknown integer condition code!");
3927 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3928 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3929 return ReplaceInstUsesWith(I, RHS);
3930 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3932 case ICmpInst::ICMP_NE:
3933 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3934 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3935 break; // (X s> 13 & X != 15) -> no change
3936 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
3937 return InsertRangeTest(Val, AddOne(LHSCst),
3938 RHSCst, true, true, I);
3939 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3948 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3951 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3952 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3953 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3954 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3955 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3956 // If either of the constants are nans, then the whole thing returns
3958 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3959 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3960 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
3961 LHS->getOperand(0), RHS->getOperand(0));
3964 // Handle vector zeros. This occurs because the canonical form of
3965 // "fcmp ord x,x" is "fcmp ord x, 0".
3966 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3967 isa<ConstantAggregateZero>(RHS->getOperand(1)))
3968 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
3969 LHS->getOperand(0), RHS->getOperand(0));
3973 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3974 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3975 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3978 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3979 // Swap RHS operands to match LHS.
3980 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3981 std::swap(Op1LHS, Op1RHS);
3984 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3985 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3987 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3989 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
3990 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3991 if (Op0CC == FCmpInst::FCMP_TRUE)
3992 return ReplaceInstUsesWith(I, RHS);
3993 if (Op1CC == FCmpInst::FCMP_TRUE)
3994 return ReplaceInstUsesWith(I, LHS);
3998 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3999 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4001 std::swap(LHS, RHS);
4002 std::swap(Op0Pred, Op1Pred);
4003 std::swap(Op0Ordered, Op1Ordered);
4006 // uno && ueq -> uno && (uno || eq) -> ueq
4007 // ord && olt -> ord && (ord && lt) -> olt
4008 if (Op0Ordered == Op1Ordered)
4009 return ReplaceInstUsesWith(I, RHS);
4011 // uno && oeq -> uno && (ord && eq) -> false
4012 // uno && ord -> false
4014 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4015 // ord && ueq -> ord && (uno || eq) -> oeq
4016 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4017 Op0LHS, Op0RHS, Context));
4025 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4026 bool Changed = SimplifyCommutative(I);
4027 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4029 if (isa<UndefValue>(Op1)) // X & undef -> 0
4030 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4034 return ReplaceInstUsesWith(I, Op1);
4036 // See if we can simplify any instructions used by the instruction whose sole
4037 // purpose is to compute bits we don't care about.
4038 if (SimplifyDemandedInstructionBits(I))
4040 if (isa<VectorType>(I.getType())) {
4041 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4042 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
4043 return ReplaceInstUsesWith(I, I.getOperand(0));
4044 } else if (isa<ConstantAggregateZero>(Op1)) {
4045 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
4049 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4050 const APInt& AndRHSMask = AndRHS->getValue();
4051 APInt NotAndRHS(~AndRHSMask);
4053 // Optimize a variety of ((val OP C1) & C2) combinations...
4054 if (isa<BinaryOperator>(Op0)) {
4055 Instruction *Op0I = cast<Instruction>(Op0);
4056 Value *Op0LHS = Op0I->getOperand(0);
4057 Value *Op0RHS = Op0I->getOperand(1);
4058 switch (Op0I->getOpcode()) {
4059 case Instruction::Xor:
4060 case Instruction::Or:
4061 // If the mask is only needed on one incoming arm, push it up.
4062 if (Op0I->hasOneUse()) {
4063 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4064 // Not masking anything out for the LHS, move to RHS.
4065 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
4066 Op0RHS->getName()+".masked");
4067 InsertNewInstBefore(NewRHS, I);
4068 return BinaryOperator::Create(
4069 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4071 if (!isa<Constant>(Op0RHS) &&
4072 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4073 // Not masking anything out for the RHS, move to LHS.
4074 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4075 Op0LHS->getName()+".masked");
4076 InsertNewInstBefore(NewLHS, I);
4077 return BinaryOperator::Create(
4078 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4083 case Instruction::Add:
4084 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4085 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4086 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4087 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4088 return BinaryOperator::CreateAnd(V, AndRHS);
4089 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4090 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
4093 case Instruction::Sub:
4094 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4095 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4096 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4097 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4098 return BinaryOperator::CreateAnd(V, AndRHS);
4100 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4101 // has 1's for all bits that the subtraction with A might affect.
4102 if (Op0I->hasOneUse()) {
4103 uint32_t BitWidth = AndRHSMask.getBitWidth();
4104 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4105 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4107 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4108 if (!(A && A->isZero()) && // avoid infinite recursion.
4109 MaskedValueIsZero(Op0LHS, Mask)) {
4110 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
4111 InsertNewInstBefore(NewNeg, I);
4112 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4117 case Instruction::Shl:
4118 case Instruction::LShr:
4119 // (1 << x) & 1 --> zext(x == 0)
4120 // (1 >> x) & 1 --> zext(x == 0)
4121 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4122 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4123 Op0RHS, Constant::getNullValue(I.getType()));
4124 InsertNewInstBefore(NewICmp, I);
4125 return new ZExtInst(NewICmp, I.getType());
4130 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4131 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4133 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4134 // If this is an integer truncation or change from signed-to-unsigned, and
4135 // if the source is an and/or with immediate, transform it. This
4136 // frequently occurs for bitfield accesses.
4137 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4138 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4139 CastOp->getNumOperands() == 2)
4140 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4141 if (CastOp->getOpcode() == Instruction::And) {
4142 // Change: and (cast (and X, C1) to T), C2
4143 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4144 // This will fold the two constants together, which may allow
4145 // other simplifications.
4146 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4147 CastOp->getOperand(0), I.getType(),
4148 CastOp->getName()+".shrunk");
4149 NewCast = InsertNewInstBefore(NewCast, I);
4150 // trunc_or_bitcast(C1)&C2
4152 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4153 C3 = ConstantExpr::getAnd(C3, AndRHS);
4154 return BinaryOperator::CreateAnd(NewCast, C3);
4155 } else if (CastOp->getOpcode() == Instruction::Or) {
4156 // Change: and (cast (or X, C1) to T), C2
4157 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4159 ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4160 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4162 return ReplaceInstUsesWith(I, AndRHS);
4168 // Try to fold constant and into select arguments.
4169 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4170 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4172 if (isa<PHINode>(Op0))
4173 if (Instruction *NV = FoldOpIntoPhi(I))
4177 Value *Op0NotVal = dyn_castNotVal(Op0);
4178 Value *Op1NotVal = dyn_castNotVal(Op1);
4180 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4181 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4183 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4184 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4185 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4186 I.getName()+".demorgan");
4187 InsertNewInstBefore(Or, I);
4188 return BinaryOperator::CreateNot(Or);
4192 Value *A = 0, *B = 0, *C = 0, *D = 0;
4193 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4194 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4195 return ReplaceInstUsesWith(I, Op1);
4197 // (A|B) & ~(A&B) -> A^B
4198 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4199 if ((A == C && B == D) || (A == D && B == C))
4200 return BinaryOperator::CreateXor(A, B);
4204 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4205 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4206 return ReplaceInstUsesWith(I, Op0);
4208 // ~(A&B) & (A|B) -> A^B
4209 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4210 if ((A == C && B == D) || (A == D && B == C))
4211 return BinaryOperator::CreateXor(A, B);
4215 if (Op0->hasOneUse() &&
4216 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4217 if (A == Op1) { // (A^B)&A -> A&(A^B)
4218 I.swapOperands(); // Simplify below
4219 std::swap(Op0, Op1);
4220 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4221 cast<BinaryOperator>(Op0)->swapOperands();
4222 I.swapOperands(); // Simplify below
4223 std::swap(Op0, Op1);
4227 if (Op1->hasOneUse() &&
4228 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4229 if (B == Op0) { // B&(A^B) -> B&(B^A)
4230 cast<BinaryOperator>(Op1)->swapOperands();
4233 if (A == Op0) { // A&(A^B) -> A & ~B
4234 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4235 InsertNewInstBefore(NotB, I);
4236 return BinaryOperator::CreateAnd(A, NotB);
4240 // (A&((~A)|B)) -> A&B
4241 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4242 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4243 return BinaryOperator::CreateAnd(A, Op1);
4244 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4245 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4246 return BinaryOperator::CreateAnd(A, Op0);
4249 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4250 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4251 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4254 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4255 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4259 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4260 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4261 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4262 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4263 const Type *SrcTy = Op0C->getOperand(0)->getType();
4264 if (SrcTy == Op1C->getOperand(0)->getType() &&
4265 SrcTy->isIntOrIntVector() &&
4266 // Only do this if the casts both really cause code to be generated.
4267 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4269 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4271 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4272 Op1C->getOperand(0),
4274 InsertNewInstBefore(NewOp, I);
4275 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4279 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4280 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4281 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4282 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4283 SI0->getOperand(1) == SI1->getOperand(1) &&
4284 (SI0->hasOneUse() || SI1->hasOneUse())) {
4285 Instruction *NewOp =
4286 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4288 SI0->getName()), I);
4289 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4290 SI1->getOperand(1));
4294 // If and'ing two fcmp, try combine them into one.
4295 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4296 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4297 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4301 return Changed ? &I : 0;
4304 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4305 /// capable of providing pieces of a bswap. The subexpression provides pieces
4306 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4307 /// the expression came from the corresponding "byte swapped" byte in some other
4308 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4309 /// we know that the expression deposits the low byte of %X into the high byte
4310 /// of the bswap result and that all other bytes are zero. This expression is
4311 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4314 /// This function returns true if the match was unsuccessful and false if so.
4315 /// On entry to the function the "OverallLeftShift" is a signed integer value
4316 /// indicating the number of bytes that the subexpression is later shifted. For
4317 /// example, if the expression is later right shifted by 16 bits, the
4318 /// OverallLeftShift value would be -2 on entry. This is used to specify which
4319 /// byte of ByteValues is actually being set.
4321 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4322 /// byte is masked to zero by a user. For example, in (X & 255), X will be
4323 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4324 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
4325 /// always in the local (OverallLeftShift) coordinate space.
4327 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4328 SmallVector<Value*, 8> &ByteValues) {
4329 if (Instruction *I = dyn_cast<Instruction>(V)) {
4330 // If this is an or instruction, it may be an inner node of the bswap.
4331 if (I->getOpcode() == Instruction::Or) {
4332 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4334 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4338 // If this is a logical shift by a constant multiple of 8, recurse with
4339 // OverallLeftShift and ByteMask adjusted.
4340 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4342 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4343 // Ensure the shift amount is defined and of a byte value.
4344 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4347 unsigned ByteShift = ShAmt >> 3;
4348 if (I->getOpcode() == Instruction::Shl) {
4349 // X << 2 -> collect(X, +2)
4350 OverallLeftShift += ByteShift;
4351 ByteMask >>= ByteShift;
4353 // X >>u 2 -> collect(X, -2)
4354 OverallLeftShift -= ByteShift;
4355 ByteMask <<= ByteShift;
4356 ByteMask &= (~0U >> (32-ByteValues.size()));
4359 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4360 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4362 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4366 // If this is a logical 'and' with a mask that clears bytes, clear the
4367 // corresponding bytes in ByteMask.
4368 if (I->getOpcode() == Instruction::And &&
4369 isa<ConstantInt>(I->getOperand(1))) {
4370 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4371 unsigned NumBytes = ByteValues.size();
4372 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4373 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4375 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4376 // If this byte is masked out by a later operation, we don't care what
4378 if ((ByteMask & (1 << i)) == 0)
4381 // If the AndMask is all zeros for this byte, clear the bit.
4382 APInt MaskB = AndMask & Byte;
4384 ByteMask &= ~(1U << i);
4388 // If the AndMask is not all ones for this byte, it's not a bytezap.
4392 // Otherwise, this byte is kept.
4395 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4400 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4401 // the input value to the bswap. Some observations: 1) if more than one byte
4402 // is demanded from this input, then it could not be successfully assembled
4403 // into a byteswap. At least one of the two bytes would not be aligned with
4404 // their ultimate destination.
4405 if (!isPowerOf2_32(ByteMask)) return true;
4406 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4408 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4409 // is demanded, it needs to go into byte 0 of the result. This means that the
4410 // byte needs to be shifted until it lands in the right byte bucket. The
4411 // shift amount depends on the position: if the byte is coming from the high
4412 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4413 // low part, it must be shifted left.
4414 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4415 if (InputByteNo < ByteValues.size()/2) {
4416 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4419 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4423 // If the destination byte value is already defined, the values are or'd
4424 // together, which isn't a bswap (unless it's an or of the same bits).
4425 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4427 ByteValues[DestByteNo] = V;
4431 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4432 /// If so, insert the new bswap intrinsic and return it.
4433 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4434 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4435 if (!ITy || ITy->getBitWidth() % 16 ||
4436 // ByteMask only allows up to 32-byte values.
4437 ITy->getBitWidth() > 32*8)
4438 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4440 /// ByteValues - For each byte of the result, we keep track of which value
4441 /// defines each byte.
4442 SmallVector<Value*, 8> ByteValues;
4443 ByteValues.resize(ITy->getBitWidth()/8);
4445 // Try to find all the pieces corresponding to the bswap.
4446 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4447 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4450 // Check to see if all of the bytes come from the same value.
4451 Value *V = ByteValues[0];
4452 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4454 // Check to make sure that all of the bytes come from the same value.
4455 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4456 if (ByteValues[i] != V)
4458 const Type *Tys[] = { ITy };
4459 Module *M = I.getParent()->getParent()->getParent();
4460 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4461 return CallInst::Create(F, V);
4464 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4465 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4466 /// we can simplify this expression to "cond ? C : D or B".
4467 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4469 LLVMContext *Context) {
4470 // If A is not a select of -1/0, this cannot match.
4472 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4475 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4476 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4477 return SelectInst::Create(Cond, C, B);
4478 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4479 return SelectInst::Create(Cond, C, B);
4480 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4481 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4482 return SelectInst::Create(Cond, C, D);
4483 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4484 return SelectInst::Create(Cond, C, D);
4488 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4489 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4490 ICmpInst *LHS, ICmpInst *RHS) {
4492 ConstantInt *LHSCst, *RHSCst;
4493 ICmpInst::Predicate LHSCC, RHSCC;
4495 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4496 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4497 m_ConstantInt(LHSCst))) ||
4498 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4499 m_ConstantInt(RHSCst))))
4502 // From here on, we only handle:
4503 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4504 if (Val != Val2) return 0;
4506 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4507 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4508 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4509 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4510 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4513 // We can't fold (ugt x, C) | (sgt x, C2).
4514 if (!PredicatesFoldable(LHSCC, RHSCC))
4517 // Ensure that the larger constant is on the RHS.
4519 if (ICmpInst::isSignedPredicate(LHSCC) ||
4520 (ICmpInst::isEquality(LHSCC) &&
4521 ICmpInst::isSignedPredicate(RHSCC)))
4522 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4524 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4527 std::swap(LHS, RHS);
4528 std::swap(LHSCst, RHSCst);
4529 std::swap(LHSCC, RHSCC);
4532 // At this point, we know we have have two icmp instructions
4533 // comparing a value against two constants and or'ing the result
4534 // together. Because of the above check, we know that we only have
4535 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4536 // FoldICmpLogical check above), that the two constants are not
4538 assert(LHSCst != RHSCst && "Compares not folded above?");
4541 default: llvm_unreachable("Unknown integer condition code!");
4542 case ICmpInst::ICMP_EQ:
4544 default: llvm_unreachable("Unknown integer condition code!");
4545 case ICmpInst::ICMP_EQ:
4546 if (LHSCst == SubOne(RHSCst)) {
4547 // (X == 13 | X == 14) -> X-13 <u 2
4548 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4549 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4550 Val->getName()+".off");
4551 InsertNewInstBefore(Add, I);
4552 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4553 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
4555 break; // (X == 13 | X == 15) -> no change
4556 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4557 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4559 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4560 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4561 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4562 return ReplaceInstUsesWith(I, RHS);
4565 case ICmpInst::ICMP_NE:
4567 default: llvm_unreachable("Unknown integer condition code!");
4568 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4569 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4570 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4571 return ReplaceInstUsesWith(I, LHS);
4572 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4573 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4574 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4575 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4578 case ICmpInst::ICMP_ULT:
4580 default: llvm_unreachable("Unknown integer condition code!");
4581 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4583 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4584 // If RHSCst is [us]MAXINT, it is always false. Not handling
4585 // this can cause overflow.
4586 if (RHSCst->isMaxValue(false))
4587 return ReplaceInstUsesWith(I, LHS);
4588 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4590 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4592 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4593 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4594 return ReplaceInstUsesWith(I, RHS);
4595 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4599 case ICmpInst::ICMP_SLT:
4601 default: llvm_unreachable("Unknown integer condition code!");
4602 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4604 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4605 // If RHSCst is [us]MAXINT, it is always false. Not handling
4606 // this can cause overflow.
4607 if (RHSCst->isMaxValue(true))
4608 return ReplaceInstUsesWith(I, LHS);
4609 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4611 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4613 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4614 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4615 return ReplaceInstUsesWith(I, RHS);
4616 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4620 case ICmpInst::ICMP_UGT:
4622 default: llvm_unreachable("Unknown integer condition code!");
4623 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4624 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4625 return ReplaceInstUsesWith(I, LHS);
4626 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4628 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4629 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4630 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4631 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4635 case ICmpInst::ICMP_SGT:
4637 default: llvm_unreachable("Unknown integer condition code!");
4638 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4639 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4640 return ReplaceInstUsesWith(I, LHS);
4641 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4643 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4644 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4645 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4646 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4654 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4656 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4657 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4658 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4659 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4660 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4661 // If either of the constants are nans, then the whole thing returns
4663 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4664 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4666 // Otherwise, no need to compare the two constants, compare the
4668 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4669 LHS->getOperand(0), RHS->getOperand(0));
4672 // Handle vector zeros. This occurs because the canonical form of
4673 // "fcmp uno x,x" is "fcmp uno x, 0".
4674 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4675 isa<ConstantAggregateZero>(RHS->getOperand(1)))
4676 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4677 LHS->getOperand(0), RHS->getOperand(0));
4682 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4683 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4684 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4686 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4687 // Swap RHS operands to match LHS.
4688 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4689 std::swap(Op1LHS, Op1RHS);
4691 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4692 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4694 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4696 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4697 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4698 if (Op0CC == FCmpInst::FCMP_FALSE)
4699 return ReplaceInstUsesWith(I, RHS);
4700 if (Op1CC == FCmpInst::FCMP_FALSE)
4701 return ReplaceInstUsesWith(I, LHS);
4704 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4705 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4706 if (Op0Ordered == Op1Ordered) {
4707 // If both are ordered or unordered, return a new fcmp with
4708 // or'ed predicates.
4709 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4710 Op0LHS, Op0RHS, Context);
4711 if (Instruction *I = dyn_cast<Instruction>(RV))
4713 // Otherwise, it's a constant boolean value...
4714 return ReplaceInstUsesWith(I, RV);
4720 /// FoldOrWithConstants - This helper function folds:
4722 /// ((A | B) & C1) | (B & C2)
4728 /// when the XOR of the two constants is "all ones" (-1).
4729 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4730 Value *A, Value *B, Value *C) {
4731 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4735 ConstantInt *CI2 = 0;
4736 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4738 APInt Xor = CI1->getValue() ^ CI2->getValue();
4739 if (!Xor.isAllOnesValue()) return 0;
4741 if (V1 == A || V1 == B) {
4742 Instruction *NewOp =
4743 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4744 return BinaryOperator::CreateOr(NewOp, V1);
4750 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4751 bool Changed = SimplifyCommutative(I);
4752 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4754 if (isa<UndefValue>(Op1)) // X | undef -> -1
4755 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4759 return ReplaceInstUsesWith(I, Op0);
4761 // See if we can simplify any instructions used by the instruction whose sole
4762 // purpose is to compute bits we don't care about.
4763 if (SimplifyDemandedInstructionBits(I))
4765 if (isa<VectorType>(I.getType())) {
4766 if (isa<ConstantAggregateZero>(Op1)) {
4767 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4768 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4769 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4770 return ReplaceInstUsesWith(I, I.getOperand(1));
4775 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4776 ConstantInt *C1 = 0; Value *X = 0;
4777 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4778 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
4780 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4781 InsertNewInstBefore(Or, I);
4783 return BinaryOperator::CreateAnd(Or,
4784 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4787 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4788 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
4790 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4791 InsertNewInstBefore(Or, I);
4793 return BinaryOperator::CreateXor(Or,
4794 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4797 // Try to fold constant and into select arguments.
4798 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4799 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4801 if (isa<PHINode>(Op0))
4802 if (Instruction *NV = FoldOpIntoPhi(I))
4806 Value *A = 0, *B = 0;
4807 ConstantInt *C1 = 0, *C2 = 0;
4809 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4810 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4811 return ReplaceInstUsesWith(I, Op1);
4812 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4813 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4814 return ReplaceInstUsesWith(I, Op0);
4816 // (A | B) | C and A | (B | C) -> bswap if possible.
4817 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4818 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4819 match(Op1, m_Or(m_Value(), m_Value())) ||
4820 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4821 match(Op1, m_Shift(m_Value(), m_Value())))) {
4822 if (Instruction *BSwap = MatchBSwap(I))
4826 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4827 if (Op0->hasOneUse() &&
4828 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4829 MaskedValueIsZero(Op1, C1->getValue())) {
4830 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4831 InsertNewInstBefore(NOr, I);
4833 return BinaryOperator::CreateXor(NOr, C1);
4836 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4837 if (Op1->hasOneUse() &&
4838 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4839 MaskedValueIsZero(Op0, C1->getValue())) {
4840 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4841 InsertNewInstBefore(NOr, I);
4843 return BinaryOperator::CreateXor(NOr, C1);
4847 Value *C = 0, *D = 0;
4848 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4849 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4850 Value *V1 = 0, *V2 = 0, *V3 = 0;
4851 C1 = dyn_cast<ConstantInt>(C);
4852 C2 = dyn_cast<ConstantInt>(D);
4853 if (C1 && C2) { // (A & C1)|(B & C2)
4854 // If we have: ((V + N) & C1) | (V & C2)
4855 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4856 // replace with V+N.
4857 if (C1->getValue() == ~C2->getValue()) {
4858 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4859 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4860 // Add commutes, try both ways.
4861 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4862 return ReplaceInstUsesWith(I, A);
4863 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4864 return ReplaceInstUsesWith(I, A);
4866 // Or commutes, try both ways.
4867 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4868 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4869 // Add commutes, try both ways.
4870 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4871 return ReplaceInstUsesWith(I, B);
4872 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4873 return ReplaceInstUsesWith(I, B);
4876 V1 = 0; V2 = 0; V3 = 0;
4879 // Check to see if we have any common things being and'ed. If so, find the
4880 // terms for V1 & (V2|V3).
4881 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4882 if (A == B) // (A & C)|(A & D) == A & (C|D)
4883 V1 = A, V2 = C, V3 = D;
4884 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4885 V1 = A, V2 = B, V3 = C;
4886 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4887 V1 = C, V2 = A, V3 = D;
4888 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4889 V1 = C, V2 = A, V3 = B;
4893 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4894 return BinaryOperator::CreateAnd(V1, Or);
4898 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
4899 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4901 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4903 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4905 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4908 // ((A&~B)|(~A&B)) -> A^B
4909 if ((match(C, m_Not(m_Specific(D))) &&
4910 match(B, m_Not(m_Specific(A)))))
4911 return BinaryOperator::CreateXor(A, D);
4912 // ((~B&A)|(~A&B)) -> A^B
4913 if ((match(A, m_Not(m_Specific(D))) &&
4914 match(B, m_Not(m_Specific(C)))))
4915 return BinaryOperator::CreateXor(C, D);
4916 // ((A&~B)|(B&~A)) -> A^B
4917 if ((match(C, m_Not(m_Specific(B))) &&
4918 match(D, m_Not(m_Specific(A)))))
4919 return BinaryOperator::CreateXor(A, B);
4920 // ((~B&A)|(B&~A)) -> A^B
4921 if ((match(A, m_Not(m_Specific(B))) &&
4922 match(D, m_Not(m_Specific(C)))))
4923 return BinaryOperator::CreateXor(C, B);
4926 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4927 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4928 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4929 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4930 SI0->getOperand(1) == SI1->getOperand(1) &&
4931 (SI0->hasOneUse() || SI1->hasOneUse())) {
4932 Instruction *NewOp =
4933 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4935 SI0->getName()), I);
4936 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4937 SI1->getOperand(1));
4941 // ((A|B)&1)|(B&-2) -> (A&1) | B
4942 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4943 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4944 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4945 if (Ret) return Ret;
4947 // (B&-2)|((A|B)&1) -> (A&1) | B
4948 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4949 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4950 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4951 if (Ret) return Ret;
4954 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4955 if (A == Op1) // ~A | A == -1
4956 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4960 // Note, A is still live here!
4961 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4963 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4965 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4966 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4967 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4968 I.getName()+".demorgan"), I);
4969 return BinaryOperator::CreateNot(And);
4973 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4974 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4975 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4978 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4979 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4983 // fold (or (cast A), (cast B)) -> (cast (or A, B))
4984 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4985 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4986 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4987 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4988 !isa<ICmpInst>(Op1C->getOperand(0))) {
4989 const Type *SrcTy = Op0C->getOperand(0)->getType();
4990 if (SrcTy == Op1C->getOperand(0)->getType() &&
4991 SrcTy->isIntOrIntVector() &&
4992 // Only do this if the casts both really cause code to be
4994 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4996 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4998 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4999 Op1C->getOperand(0),
5001 InsertNewInstBefore(NewOp, I);
5002 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5009 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5010 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
5011 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5012 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5016 return Changed ? &I : 0;
5021 // XorSelf - Implements: X ^ X --> 0
5024 XorSelf(Value *rhs) : RHS(rhs) {}
5025 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5026 Instruction *apply(BinaryOperator &Xor) const {
5033 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5034 bool Changed = SimplifyCommutative(I);
5035 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5037 if (isa<UndefValue>(Op1)) {
5038 if (isa<UndefValue>(Op0))
5039 // Handle undef ^ undef -> 0 special case. This is a common
5041 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5042 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
5045 // xor X, X = 0, even if X is nested in a sequence of Xor's.
5046 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5047 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5048 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5051 // See if we can simplify any instructions used by the instruction whose sole
5052 // purpose is to compute bits we don't care about.
5053 if (SimplifyDemandedInstructionBits(I))
5055 if (isa<VectorType>(I.getType()))
5056 if (isa<ConstantAggregateZero>(Op1))
5057 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
5059 // Is this a ~ operation?
5060 if (Value *NotOp = dyn_castNotVal(&I)) {
5061 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5062 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5063 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5064 if (Op0I->getOpcode() == Instruction::And ||
5065 Op0I->getOpcode() == Instruction::Or) {
5066 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5067 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5069 BinaryOperator::CreateNot(Op0I->getOperand(1),
5070 Op0I->getOperand(1)->getName()+".not");
5071 InsertNewInstBefore(NotY, I);
5072 if (Op0I->getOpcode() == Instruction::And)
5073 return BinaryOperator::CreateOr(Op0NotVal, NotY);
5075 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5082 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5083 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
5084 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5085 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5086 return new ICmpInst(*Context, ICI->getInversePredicate(),
5087 ICI->getOperand(0), ICI->getOperand(1));
5089 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5090 return new FCmpInst(*Context, FCI->getInversePredicate(),
5091 FCI->getOperand(0), FCI->getOperand(1));
5094 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5095 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5096 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5097 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5098 Instruction::CastOps Opcode = Op0C->getOpcode();
5099 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5100 if (RHS == ConstantExpr::getCast(Opcode,
5101 ConstantInt::getTrue(*Context),
5102 Op0C->getDestTy())) {
5103 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5105 CI->getOpcode(), CI->getInversePredicate(),
5106 CI->getOperand(0), CI->getOperand(1)), I);
5107 NewCI->takeName(CI);
5108 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5115 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5116 // ~(c-X) == X-c-1 == X+(-c-1)
5117 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5118 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5119 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5120 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5121 ConstantInt::get(I.getType(), 1));
5122 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5125 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5126 if (Op0I->getOpcode() == Instruction::Add) {
5127 // ~(X-c) --> (-c-1)-X
5128 if (RHS->isAllOnesValue()) {
5129 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5130 return BinaryOperator::CreateSub(
5131 ConstantExpr::getSub(NegOp0CI,
5132 ConstantInt::get(I.getType(), 1)),
5133 Op0I->getOperand(0));
5134 } else if (RHS->getValue().isSignBit()) {
5135 // (X + C) ^ signbit -> (X + C + signbit)
5136 Constant *C = ConstantInt::get(*Context,
5137 RHS->getValue() + Op0CI->getValue());
5138 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5141 } else if (Op0I->getOpcode() == Instruction::Or) {
5142 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5143 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5144 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5145 // Anything in both C1 and C2 is known to be zero, remove it from
5147 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5148 NewRHS = ConstantExpr::getAnd(NewRHS,
5149 ConstantExpr::getNot(CommonBits));
5150 AddToWorkList(Op0I);
5151 I.setOperand(0, Op0I->getOperand(0));
5152 I.setOperand(1, NewRHS);
5159 // Try to fold constant and into select arguments.
5160 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5161 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5163 if (isa<PHINode>(Op0))
5164 if (Instruction *NV = FoldOpIntoPhi(I))
5168 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
5170 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5172 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
5174 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5177 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5180 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5181 if (A == Op0) { // B^(B|A) == (A|B)^B
5182 Op1I->swapOperands();
5184 std::swap(Op0, Op1);
5185 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5186 I.swapOperands(); // Simplified below.
5187 std::swap(Op0, Op1);
5189 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5190 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5191 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5192 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
5193 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
5195 if (A == Op0) { // A^(A&B) -> A^(B&A)
5196 Op1I->swapOperands();
5199 if (B == Op0) { // A^(B&A) -> (B&A)^A
5200 I.swapOperands(); // Simplified below.
5201 std::swap(Op0, Op1);
5206 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5209 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5210 Op0I->hasOneUse()) {
5211 if (A == Op1) // (B|A)^B == (A|B)^B
5213 if (B == Op1) { // (A|B)^B == A & ~B
5215 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5216 return BinaryOperator::CreateAnd(A, NotB);
5218 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5219 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5220 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5221 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
5222 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5224 if (A == Op1) // (A&B)^A -> (B&A)^A
5226 if (B == Op1 && // (B&A)^A == ~B & A
5227 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5229 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5230 return BinaryOperator::CreateAnd(N, Op1);
5235 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5236 if (Op0I && Op1I && Op0I->isShift() &&
5237 Op0I->getOpcode() == Op1I->getOpcode() &&
5238 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5239 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5240 Instruction *NewOp =
5241 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5242 Op1I->getOperand(0),
5243 Op0I->getName()), I);
5244 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
5245 Op1I->getOperand(1));
5249 Value *A, *B, *C, *D;
5250 // (A & B)^(A | B) -> A ^ B
5251 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5252 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5253 if ((A == C && B == D) || (A == D && B == C))
5254 return BinaryOperator::CreateXor(A, B);
5256 // (A | B)^(A & B) -> A ^ B
5257 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5258 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5259 if ((A == C && B == D) || (A == D && B == C))
5260 return BinaryOperator::CreateXor(A, B);
5264 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5265 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5266 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5267 // (X & Y)^(X & Y) -> (Y^Z) & X
5268 Value *X = 0, *Y = 0, *Z = 0;
5270 X = A, Y = B, Z = D;
5272 X = A, Y = B, Z = C;
5274 X = B, Y = A, Z = D;
5276 X = B, Y = A, Z = C;
5279 Instruction *NewOp =
5280 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5281 return BinaryOperator::CreateAnd(NewOp, X);
5286 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5287 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5288 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5291 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5292 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5293 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5294 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5295 const Type *SrcTy = Op0C->getOperand(0)->getType();
5296 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5297 // Only do this if the casts both really cause code to be generated.
5298 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5300 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5302 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5303 Op1C->getOperand(0),
5305 InsertNewInstBefore(NewOp, I);
5306 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5311 return Changed ? &I : 0;
5314 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5315 LLVMContext *Context) {
5316 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5319 static bool HasAddOverflow(ConstantInt *Result,
5320 ConstantInt *In1, ConstantInt *In2,
5323 if (In2->getValue().isNegative())
5324 return Result->getValue().sgt(In1->getValue());
5326 return Result->getValue().slt(In1->getValue());
5328 return Result->getValue().ult(In1->getValue());
5331 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5332 /// overflowed for this type.
5333 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5334 Constant *In2, LLVMContext *Context,
5335 bool IsSigned = false) {
5336 Result = ConstantExpr::getAdd(In1, In2);
5338 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5339 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5340 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5341 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5342 ExtractElement(In1, Idx, Context),
5343 ExtractElement(In2, Idx, Context),
5350 return HasAddOverflow(cast<ConstantInt>(Result),
5351 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5355 static bool HasSubOverflow(ConstantInt *Result,
5356 ConstantInt *In1, ConstantInt *In2,
5359 if (In2->getValue().isNegative())
5360 return Result->getValue().slt(In1->getValue());
5362 return Result->getValue().sgt(In1->getValue());
5364 return Result->getValue().ugt(In1->getValue());
5367 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5368 /// overflowed for this type.
5369 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5370 Constant *In2, LLVMContext *Context,
5371 bool IsSigned = false) {
5372 Result = ConstantExpr::getSub(In1, In2);
5374 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5375 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5376 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5377 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5378 ExtractElement(In1, Idx, Context),
5379 ExtractElement(In2, Idx, Context),
5386 return HasSubOverflow(cast<ConstantInt>(Result),
5387 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5391 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5392 /// code necessary to compute the offset from the base pointer (without adding
5393 /// in the base pointer). Return the result as a signed integer of intptr size.
5394 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5395 TargetData &TD = *IC.getTargetData();
5396 gep_type_iterator GTI = gep_type_begin(GEP);
5397 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
5398 LLVMContext *Context = IC.getContext();
5399 Value *Result = Constant::getNullValue(IntPtrTy);
5401 // Build a mask for high order bits.
5402 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5403 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5405 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5408 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5409 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5410 if (OpC->isZero()) continue;
5412 // Handle a struct index, which adds its field offset to the pointer.
5413 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5414 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5416 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5418 ConstantInt::get(*Context,
5419 RC->getValue() + APInt(IntPtrWidth, Size));
5421 Result = IC.InsertNewInstBefore(
5422 BinaryOperator::CreateAdd(Result,
5423 ConstantInt::get(IntPtrTy, Size),
5424 GEP->getName()+".offs"), I);
5428 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5430 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5431 Scale = ConstantExpr::getMul(OC, Scale);
5432 if (Constant *RC = dyn_cast<Constant>(Result))
5433 Result = ConstantExpr::getAdd(RC, Scale);
5435 // Emit an add instruction.
5436 Result = IC.InsertNewInstBefore(
5437 BinaryOperator::CreateAdd(Result, Scale,
5438 GEP->getName()+".offs"), I);
5442 // Convert to correct type.
5443 if (Op->getType() != IntPtrTy) {
5444 if (Constant *OpC = dyn_cast<Constant>(Op))
5445 Op = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true);
5447 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5449 Op->getName()+".c"), I);
5452 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5453 if (Constant *OpC = dyn_cast<Constant>(Op))
5454 Op = ConstantExpr::getMul(OpC, Scale);
5455 else // We'll let instcombine(mul) convert this to a shl if possible.
5456 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5457 GEP->getName()+".idx"), I);
5460 // Emit an add instruction.
5461 if (isa<Constant>(Op) && isa<Constant>(Result))
5462 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5463 cast<Constant>(Result));
5465 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5466 GEP->getName()+".offs"), I);
5472 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5473 /// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5474 /// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5475 /// be complex, and scales are involved. The above expression would also be
5476 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5477 /// This later form is less amenable to optimization though, and we are allowed
5478 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5480 /// If we can't emit an optimized form for this expression, this returns null.
5482 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5484 TargetData &TD = *IC.getTargetData();
5485 gep_type_iterator GTI = gep_type_begin(GEP);
5487 // Check to see if this gep only has a single variable index. If so, and if
5488 // any constant indices are a multiple of its scale, then we can compute this
5489 // in terms of the scale of the variable index. For example, if the GEP
5490 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5491 // because the expression will cross zero at the same point.
5492 unsigned i, e = GEP->getNumOperands();
5494 for (i = 1; i != e; ++i, ++GTI) {
5495 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5496 // Compute the aggregate offset of constant indices.
5497 if (CI->isZero()) continue;
5499 // Handle a struct index, which adds its field offset to the pointer.
5500 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5501 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5503 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5504 Offset += Size*CI->getSExtValue();
5507 // Found our variable index.
5512 // If there are no variable indices, we must have a constant offset, just
5513 // evaluate it the general way.
5514 if (i == e) return 0;
5516 Value *VariableIdx = GEP->getOperand(i);
5517 // Determine the scale factor of the variable element. For example, this is
5518 // 4 if the variable index is into an array of i32.
5519 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5521 // Verify that there are no other variable indices. If so, emit the hard way.
5522 for (++i, ++GTI; i != e; ++i, ++GTI) {
5523 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5526 // Compute the aggregate offset of constant indices.
5527 if (CI->isZero()) continue;
5529 // Handle a struct index, which adds its field offset to the pointer.
5530 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5531 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5533 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5534 Offset += Size*CI->getSExtValue();
5538 // Okay, we know we have a single variable index, which must be a
5539 // pointer/array/vector index. If there is no offset, life is simple, return
5541 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5543 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5544 // we don't need to bother extending: the extension won't affect where the
5545 // computation crosses zero.
5546 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5547 VariableIdx = new TruncInst(VariableIdx,
5548 TD.getIntPtrType(VariableIdx->getContext()),
5549 VariableIdx->getName(), &I);
5553 // Otherwise, there is an index. The computation we will do will be modulo
5554 // the pointer size, so get it.
5555 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5557 Offset &= PtrSizeMask;
5558 VariableScale &= PtrSizeMask;
5560 // To do this transformation, any constant index must be a multiple of the
5561 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5562 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5563 // multiple of the variable scale.
5564 int64_t NewOffs = Offset / (int64_t)VariableScale;
5565 if (Offset != NewOffs*(int64_t)VariableScale)
5568 // Okay, we can do this evaluation. Start by converting the index to intptr.
5569 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
5570 if (VariableIdx->getType() != IntPtrTy)
5571 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5573 VariableIdx->getName(), &I);
5574 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5575 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5579 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5580 /// else. At this point we know that the GEP is on the LHS of the comparison.
5581 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5582 ICmpInst::Predicate Cond,
5584 // Look through bitcasts.
5585 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5586 RHS = BCI->getOperand(0);
5588 Value *PtrBase = GEPLHS->getOperand(0);
5589 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5590 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
5591 // This transformation (ignoring the base and scales) is valid because we
5592 // know pointers can't overflow since the gep is inbounds. See if we can
5593 // output an optimized form.
5594 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5596 // If not, synthesize the offset the hard way.
5598 Offset = EmitGEPOffset(GEPLHS, I, *this);
5599 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
5600 Constant::getNullValue(Offset->getType()));
5601 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5602 // If the base pointers are different, but the indices are the same, just
5603 // compare the base pointer.
5604 if (PtrBase != GEPRHS->getOperand(0)) {
5605 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5606 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5607 GEPRHS->getOperand(0)->getType();
5609 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5610 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5611 IndicesTheSame = false;
5615 // If all indices are the same, just compare the base pointers.
5617 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
5618 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5620 // Otherwise, the base pointers are different and the indices are
5621 // different, bail out.
5625 // If one of the GEPs has all zero indices, recurse.
5626 bool AllZeros = true;
5627 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5628 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5629 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5634 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5635 ICmpInst::getSwappedPredicate(Cond), I);
5637 // If the other GEP has all zero indices, recurse.
5639 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5640 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5641 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5646 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5648 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5649 // If the GEPs only differ by one index, compare it.
5650 unsigned NumDifferences = 0; // Keep track of # differences.
5651 unsigned DiffOperand = 0; // The operand that differs.
5652 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5653 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5654 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5655 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5656 // Irreconcilable differences.
5660 if (NumDifferences++) break;
5665 if (NumDifferences == 0) // SAME GEP?
5666 return ReplaceInstUsesWith(I, // No comparison is needed here.
5667 ConstantInt::get(Type::getInt1Ty(*Context),
5668 ICmpInst::isTrueWhenEqual(Cond)));
5670 else if (NumDifferences == 1) {
5671 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5672 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5673 // Make sure we do a signed comparison here.
5674 return new ICmpInst(*Context,
5675 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5679 // Only lower this if the icmp is the only user of the GEP or if we expect
5680 // the result to fold to a constant!
5682 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5683 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5684 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5685 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5686 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5687 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
5693 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5695 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5698 if (!isa<ConstantFP>(RHSC)) return 0;
5699 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5701 // Get the width of the mantissa. We don't want to hack on conversions that
5702 // might lose information from the integer, e.g. "i64 -> float"
5703 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5704 if (MantissaWidth == -1) return 0; // Unknown.
5706 // Check to see that the input is converted from an integer type that is small
5707 // enough that preserves all bits. TODO: check here for "known" sign bits.
5708 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5709 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5711 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5712 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5716 // If the conversion would lose info, don't hack on this.
5717 if ((int)InputSize > MantissaWidth)
5720 // Otherwise, we can potentially simplify the comparison. We know that it
5721 // will always come through as an integer value and we know the constant is
5722 // not a NAN (it would have been previously simplified).
5723 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5725 ICmpInst::Predicate Pred;
5726 switch (I.getPredicate()) {
5727 default: llvm_unreachable("Unexpected predicate!");
5728 case FCmpInst::FCMP_UEQ:
5729 case FCmpInst::FCMP_OEQ:
5730 Pred = ICmpInst::ICMP_EQ;
5732 case FCmpInst::FCMP_UGT:
5733 case FCmpInst::FCMP_OGT:
5734 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5736 case FCmpInst::FCMP_UGE:
5737 case FCmpInst::FCMP_OGE:
5738 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5740 case FCmpInst::FCMP_ULT:
5741 case FCmpInst::FCMP_OLT:
5742 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5744 case FCmpInst::FCMP_ULE:
5745 case FCmpInst::FCMP_OLE:
5746 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5748 case FCmpInst::FCMP_UNE:
5749 case FCmpInst::FCMP_ONE:
5750 Pred = ICmpInst::ICMP_NE;
5752 case FCmpInst::FCMP_ORD:
5753 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5754 case FCmpInst::FCMP_UNO:
5755 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5758 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5760 // Now we know that the APFloat is a normal number, zero or inf.
5762 // See if the FP constant is too large for the integer. For example,
5763 // comparing an i8 to 300.0.
5764 unsigned IntWidth = IntTy->getScalarSizeInBits();
5767 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5768 // and large values.
5769 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5770 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5771 APFloat::rmNearestTiesToEven);
5772 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5773 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5774 Pred == ICmpInst::ICMP_SLE)
5775 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5776 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5779 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5780 // +INF and large values.
5781 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5782 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5783 APFloat::rmNearestTiesToEven);
5784 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5785 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5786 Pred == ICmpInst::ICMP_ULE)
5787 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5788 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5793 // See if the RHS value is < SignedMin.
5794 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5795 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5796 APFloat::rmNearestTiesToEven);
5797 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5798 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5799 Pred == ICmpInst::ICMP_SGE)
5800 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5801 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5805 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5806 // [0, UMAX], but it may still be fractional. See if it is fractional by
5807 // casting the FP value to the integer value and back, checking for equality.
5808 // Don't do this for zero, because -0.0 is not fractional.
5809 Constant *RHSInt = LHSUnsigned
5810 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5811 : ConstantExpr::getFPToSI(RHSC, IntTy);
5812 if (!RHS.isZero()) {
5813 bool Equal = LHSUnsigned
5814 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5815 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5817 // If we had a comparison against a fractional value, we have to adjust
5818 // the compare predicate and sometimes the value. RHSC is rounded towards
5819 // zero at this point.
5821 default: llvm_unreachable("Unexpected integer comparison!");
5822 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5823 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5824 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5825 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5826 case ICmpInst::ICMP_ULE:
5827 // (float)int <= 4.4 --> int <= 4
5828 // (float)int <= -4.4 --> false
5829 if (RHS.isNegative())
5830 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5832 case ICmpInst::ICMP_SLE:
5833 // (float)int <= 4.4 --> int <= 4
5834 // (float)int <= -4.4 --> int < -4
5835 if (RHS.isNegative())
5836 Pred = ICmpInst::ICMP_SLT;
5838 case ICmpInst::ICMP_ULT:
5839 // (float)int < -4.4 --> false
5840 // (float)int < 4.4 --> int <= 4
5841 if (RHS.isNegative())
5842 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5843 Pred = ICmpInst::ICMP_ULE;
5845 case ICmpInst::ICMP_SLT:
5846 // (float)int < -4.4 --> int < -4
5847 // (float)int < 4.4 --> int <= 4
5848 if (!RHS.isNegative())
5849 Pred = ICmpInst::ICMP_SLE;
5851 case ICmpInst::ICMP_UGT:
5852 // (float)int > 4.4 --> int > 4
5853 // (float)int > -4.4 --> true
5854 if (RHS.isNegative())
5855 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5857 case ICmpInst::ICMP_SGT:
5858 // (float)int > 4.4 --> int > 4
5859 // (float)int > -4.4 --> int >= -4
5860 if (RHS.isNegative())
5861 Pred = ICmpInst::ICMP_SGE;
5863 case ICmpInst::ICMP_UGE:
5864 // (float)int >= -4.4 --> true
5865 // (float)int >= 4.4 --> int > 4
5866 if (!RHS.isNegative())
5867 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5868 Pred = ICmpInst::ICMP_UGT;
5870 case ICmpInst::ICMP_SGE:
5871 // (float)int >= -4.4 --> int >= -4
5872 // (float)int >= 4.4 --> int > 4
5873 if (!RHS.isNegative())
5874 Pred = ICmpInst::ICMP_SGT;
5880 // Lower this FP comparison into an appropriate integer version of the
5882 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
5885 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5886 bool Changed = SimplifyCompare(I);
5887 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5889 // Fold trivial predicates.
5890 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5891 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5892 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5893 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5895 // Simplify 'fcmp pred X, X'
5897 switch (I.getPredicate()) {
5898 default: llvm_unreachable("Unknown predicate!");
5899 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5900 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5901 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5902 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5903 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5904 case FCmpInst::FCMP_OLT: // True if ordered and less than
5905 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5906 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5908 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5909 case FCmpInst::FCMP_ULT: // True if unordered or less than
5910 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5911 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5912 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5913 I.setPredicate(FCmpInst::FCMP_UNO);
5914 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5917 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5918 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5919 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5920 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5921 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5922 I.setPredicate(FCmpInst::FCMP_ORD);
5923 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5928 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5929 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
5931 // Handle fcmp with constant RHS
5932 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5933 // If the constant is a nan, see if we can fold the comparison based on it.
5934 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5935 if (CFP->getValueAPF().isNaN()) {
5936 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5937 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5938 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5939 "Comparison must be either ordered or unordered!");
5940 // True if unordered.
5941 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5945 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5946 switch (LHSI->getOpcode()) {
5947 case Instruction::PHI:
5948 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5949 // block. If in the same block, we're encouraging jump threading. If
5950 // not, we are just pessimizing the code by making an i1 phi.
5951 if (LHSI->getParent() == I.getParent())
5952 if (Instruction *NV = FoldOpIntoPhi(I))
5955 case Instruction::SIToFP:
5956 case Instruction::UIToFP:
5957 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5960 case Instruction::Select:
5961 // If either operand of the select is a constant, we can fold the
5962 // comparison into the select arms, which will cause one to be
5963 // constant folded and the select turned into a bitwise or.
5964 Value *Op1 = 0, *Op2 = 0;
5965 if (LHSI->hasOneUse()) {
5966 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5967 // Fold the known value into the constant operand.
5968 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5969 // Insert a new FCmp of the other select operand.
5970 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5971 LHSI->getOperand(2), RHSC,
5973 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5974 // Fold the known value into the constant operand.
5975 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5976 // Insert a new FCmp of the other select operand.
5977 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5978 LHSI->getOperand(1), RHSC,
5984 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5989 return Changed ? &I : 0;
5992 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5993 bool Changed = SimplifyCompare(I);
5994 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5995 const Type *Ty = Op0->getType();
5999 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
6000 I.isTrueWhenEqual()));
6002 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
6003 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
6005 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
6006 // addresses never equal each other! We already know that Op0 != Op1.
6007 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
6008 isa<ConstantPointerNull>(Op0)) &&
6009 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
6010 isa<ConstantPointerNull>(Op1)))
6011 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
6012 !I.isTrueWhenEqual()));
6014 // icmp's with boolean values can always be turned into bitwise operations
6015 if (Ty == Type::getInt1Ty(*Context)) {
6016 switch (I.getPredicate()) {
6017 default: llvm_unreachable("Invalid icmp instruction!");
6018 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
6019 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
6020 InsertNewInstBefore(Xor, I);
6021 return BinaryOperator::CreateNot(Xor);
6023 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
6024 return BinaryOperator::CreateXor(Op0, Op1);
6026 case ICmpInst::ICMP_UGT:
6027 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
6029 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
6030 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
6031 InsertNewInstBefore(Not, I);
6032 return BinaryOperator::CreateAnd(Not, Op1);
6034 case ICmpInst::ICMP_SGT:
6035 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
6037 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
6038 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6039 InsertNewInstBefore(Not, I);
6040 return BinaryOperator::CreateAnd(Not, Op0);
6042 case ICmpInst::ICMP_UGE:
6043 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6045 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
6046 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
6047 InsertNewInstBefore(Not, I);
6048 return BinaryOperator::CreateOr(Not, Op1);
6050 case ICmpInst::ICMP_SGE:
6051 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6053 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
6054 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6055 InsertNewInstBefore(Not, I);
6056 return BinaryOperator::CreateOr(Not, Op0);
6061 unsigned BitWidth = 0;
6063 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6064 else if (Ty->isIntOrIntVector())
6065 BitWidth = Ty->getScalarSizeInBits();
6067 bool isSignBit = false;
6069 // See if we are doing a comparison with a constant.
6070 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6071 Value *A = 0, *B = 0;
6073 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6074 if (I.isEquality() && CI->isNullValue() &&
6075 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6076 // (icmp cond A B) if cond is equality
6077 return new ICmpInst(*Context, I.getPredicate(), A, B);
6080 // If we have an icmp le or icmp ge instruction, turn it into the
6081 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6082 // them being folded in the code below.
6083 switch (I.getPredicate()) {
6085 case ICmpInst::ICMP_ULE:
6086 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
6087 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6088 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6090 case ICmpInst::ICMP_SLE:
6091 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
6092 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6093 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6095 case ICmpInst::ICMP_UGE:
6096 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
6097 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6098 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6100 case ICmpInst::ICMP_SGE:
6101 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
6102 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6103 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6107 // If this comparison is a normal comparison, it demands all
6108 // bits, if it is a sign bit comparison, it only demands the sign bit.
6110 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6113 // See if we can fold the comparison based on range information we can get
6114 // by checking whether bits are known to be zero or one in the input.
6115 if (BitWidth != 0) {
6116 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6117 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6119 if (SimplifyDemandedBits(I.getOperandUse(0),
6120 isSignBit ? APInt::getSignBit(BitWidth)
6121 : APInt::getAllOnesValue(BitWidth),
6122 Op0KnownZero, Op0KnownOne, 0))
6124 if (SimplifyDemandedBits(I.getOperandUse(1),
6125 APInt::getAllOnesValue(BitWidth),
6126 Op1KnownZero, Op1KnownOne, 0))
6129 // Given the known and unknown bits, compute a range that the LHS could be
6130 // in. Compute the Min, Max and RHS values based on the known bits. For the
6131 // EQ and NE we use unsigned values.
6132 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6133 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6134 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6135 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6137 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6140 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6142 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6146 // If Min and Max are known to be the same, then SimplifyDemandedBits
6147 // figured out that the LHS is a constant. Just constant fold this now so
6148 // that code below can assume that Min != Max.
6149 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6150 return new ICmpInst(*Context, I.getPredicate(),
6151 ConstantInt::get(*Context, Op0Min), Op1);
6152 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6153 return new ICmpInst(*Context, I.getPredicate(), Op0,
6154 ConstantInt::get(*Context, Op1Min));
6156 // Based on the range information we know about the LHS, see if we can
6157 // simplify this comparison. For example, (x&4) < 8 is always true.
6158 switch (I.getPredicate()) {
6159 default: llvm_unreachable("Unknown icmp opcode!");
6160 case ICmpInst::ICMP_EQ:
6161 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6162 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6164 case ICmpInst::ICMP_NE:
6165 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6166 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6168 case ICmpInst::ICMP_ULT:
6169 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
6170 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6171 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
6172 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6173 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
6174 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6175 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6176 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
6177 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6180 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6181 if (CI->isMinValue(true))
6182 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6183 Constant::getAllOnesValue(Op0->getType()));
6186 case ICmpInst::ICMP_UGT:
6187 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
6188 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6189 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
6190 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6192 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
6193 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6194 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6195 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
6196 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6199 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6200 if (CI->isMaxValue(true))
6201 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6202 Constant::getNullValue(Op0->getType()));
6205 case ICmpInst::ICMP_SLT:
6206 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
6207 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6208 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
6209 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6210 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
6211 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6212 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6213 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
6214 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6218 case ICmpInst::ICMP_SGT:
6219 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
6220 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6221 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
6222 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6224 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
6225 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6226 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6227 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
6228 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6232 case ICmpInst::ICMP_SGE:
6233 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6234 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
6235 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6236 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
6237 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6239 case ICmpInst::ICMP_SLE:
6240 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6241 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
6242 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6243 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
6244 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6246 case ICmpInst::ICMP_UGE:
6247 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6248 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
6249 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6250 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
6251 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6253 case ICmpInst::ICMP_ULE:
6254 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6255 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
6256 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6257 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
6258 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6262 // Turn a signed comparison into an unsigned one if both operands
6263 // are known to have the same sign.
6264 if (I.isSignedPredicate() &&
6265 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6266 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6267 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
6270 // Test if the ICmpInst instruction is used exclusively by a select as
6271 // part of a minimum or maximum operation. If so, refrain from doing
6272 // any other folding. This helps out other analyses which understand
6273 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6274 // and CodeGen. And in this case, at least one of the comparison
6275 // operands has at least one user besides the compare (the select),
6276 // which would often largely negate the benefit of folding anyway.
6278 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6279 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6280 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6283 // See if we are doing a comparison between a constant and an instruction that
6284 // can be folded into the comparison.
6285 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6286 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6287 // instruction, see if that instruction also has constants so that the
6288 // instruction can be folded into the icmp
6289 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6290 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6294 // Handle icmp with constant (but not simple integer constant) RHS
6295 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6296 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6297 switch (LHSI->getOpcode()) {
6298 case Instruction::GetElementPtr:
6299 if (RHSC->isNullValue()) {
6300 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6301 bool isAllZeros = true;
6302 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6303 if (!isa<Constant>(LHSI->getOperand(i)) ||
6304 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6309 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
6310 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6314 case Instruction::PHI:
6315 // Only fold icmp into the PHI if the phi and fcmp are in the same
6316 // block. If in the same block, we're encouraging jump threading. If
6317 // not, we are just pessimizing the code by making an i1 phi.
6318 if (LHSI->getParent() == I.getParent())
6319 if (Instruction *NV = FoldOpIntoPhi(I))
6322 case Instruction::Select: {
6323 // If either operand of the select is a constant, we can fold the
6324 // comparison into the select arms, which will cause one to be
6325 // constant folded and the select turned into a bitwise or.
6326 Value *Op1 = 0, *Op2 = 0;
6327 if (LHSI->hasOneUse()) {
6328 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6329 // Fold the known value into the constant operand.
6330 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6331 // Insert a new ICmp of the other select operand.
6332 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6333 LHSI->getOperand(2), RHSC,
6335 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6336 // Fold the known value into the constant operand.
6337 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6338 // Insert a new ICmp of the other select operand.
6339 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6340 LHSI->getOperand(1), RHSC,
6346 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6349 case Instruction::Malloc:
6350 // If we have (malloc != null), and if the malloc has a single use, we
6351 // can assume it is successful and remove the malloc.
6352 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6353 AddToWorkList(LHSI);
6354 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
6355 !I.isTrueWhenEqual()));
6361 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6362 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6363 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6365 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6366 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6367 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6370 // Test to see if the operands of the icmp are casted versions of other
6371 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6373 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6374 if (isa<PointerType>(Op0->getType()) &&
6375 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6376 // We keep moving the cast from the left operand over to the right
6377 // operand, where it can often be eliminated completely.
6378 Op0 = CI->getOperand(0);
6380 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6381 // so eliminate it as well.
6382 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6383 Op1 = CI2->getOperand(0);
6385 // If Op1 is a constant, we can fold the cast into the constant.
6386 if (Op0->getType() != Op1->getType()) {
6387 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6388 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6390 // Otherwise, cast the RHS right before the icmp
6391 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6394 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
6398 if (isa<CastInst>(Op0)) {
6399 // Handle the special case of: icmp (cast bool to X), <cst>
6400 // This comes up when you have code like
6403 // For generality, we handle any zero-extension of any operand comparison
6404 // with a constant or another cast from the same type.
6405 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6406 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6410 // See if it's the same type of instruction on the left and right.
6411 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6412 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6413 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6414 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6415 switch (Op0I->getOpcode()) {
6417 case Instruction::Add:
6418 case Instruction::Sub:
6419 case Instruction::Xor:
6420 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
6421 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
6422 Op1I->getOperand(0));
6423 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6424 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6425 if (CI->getValue().isSignBit()) {
6426 ICmpInst::Predicate Pred = I.isSignedPredicate()
6427 ? I.getUnsignedPredicate()
6428 : I.getSignedPredicate();
6429 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6430 Op1I->getOperand(0));
6433 if (CI->getValue().isMaxSignedValue()) {
6434 ICmpInst::Predicate Pred = I.isSignedPredicate()
6435 ? I.getUnsignedPredicate()
6436 : I.getSignedPredicate();
6437 Pred = I.getSwappedPredicate(Pred);
6438 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6439 Op1I->getOperand(0));
6443 case Instruction::Mul:
6444 if (!I.isEquality())
6447 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6448 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6449 // Mask = -1 >> count-trailing-zeros(Cst).
6450 if (!CI->isZero() && !CI->isOne()) {
6451 const APInt &AP = CI->getValue();
6452 ConstantInt *Mask = ConstantInt::get(*Context,
6453 APInt::getLowBitsSet(AP.getBitWidth(),
6455 AP.countTrailingZeros()));
6456 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6458 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6460 InsertNewInstBefore(And1, I);
6461 InsertNewInstBefore(And2, I);
6462 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
6471 // ~x < ~y --> y < x
6473 if (match(Op0, m_Not(m_Value(A))) &&
6474 match(Op1, m_Not(m_Value(B))))
6475 return new ICmpInst(*Context, I.getPredicate(), B, A);
6478 if (I.isEquality()) {
6479 Value *A, *B, *C, *D;
6481 // -x == -y --> x == y
6482 if (match(Op0, m_Neg(m_Value(A))) &&
6483 match(Op1, m_Neg(m_Value(B))))
6484 return new ICmpInst(*Context, I.getPredicate(), A, B);
6486 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6487 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6488 Value *OtherVal = A == Op1 ? B : A;
6489 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6490 Constant::getNullValue(A->getType()));
6493 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6494 // A^c1 == C^c2 --> A == C^(c1^c2)
6495 ConstantInt *C1, *C2;
6496 if (match(B, m_ConstantInt(C1)) &&
6497 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6499 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6500 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6501 return new ICmpInst(*Context, I.getPredicate(), A,
6502 InsertNewInstBefore(Xor, I));
6505 // A^B == A^D -> B == D
6506 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6507 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6508 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6509 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
6513 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6514 (A == Op0 || B == Op0)) {
6515 // A == (A^B) -> B == 0
6516 Value *OtherVal = A == Op0 ? B : A;
6517 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6518 Constant::getNullValue(A->getType()));
6521 // (A-B) == A -> B == 0
6522 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6523 return new ICmpInst(*Context, I.getPredicate(), B,
6524 Constant::getNullValue(B->getType()));
6526 // A == (A-B) -> B == 0
6527 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6528 return new ICmpInst(*Context, I.getPredicate(), B,
6529 Constant::getNullValue(B->getType()));
6531 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6532 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6533 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6534 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6535 Value *X = 0, *Y = 0, *Z = 0;
6538 X = B; Y = D; Z = A;
6539 } else if (A == D) {
6540 X = B; Y = C; Z = A;
6541 } else if (B == C) {
6542 X = A; Y = D; Z = B;
6543 } else if (B == D) {
6544 X = A; Y = C; Z = B;
6547 if (X) { // Build (X^Y) & Z
6548 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6549 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6550 I.setOperand(0, Op1);
6551 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6556 return Changed ? &I : 0;
6560 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6561 /// and CmpRHS are both known to be integer constants.
6562 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6563 ConstantInt *DivRHS) {
6564 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6565 const APInt &CmpRHSV = CmpRHS->getValue();
6567 // FIXME: If the operand types don't match the type of the divide
6568 // then don't attempt this transform. The code below doesn't have the
6569 // logic to deal with a signed divide and an unsigned compare (and
6570 // vice versa). This is because (x /s C1) <s C2 produces different
6571 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6572 // (x /u C1) <u C2. Simply casting the operands and result won't
6573 // work. :( The if statement below tests that condition and bails
6575 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6576 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6578 if (DivRHS->isZero())
6579 return 0; // The ProdOV computation fails on divide by zero.
6580 if (DivIsSigned && DivRHS->isAllOnesValue())
6581 return 0; // The overflow computation also screws up here
6582 if (DivRHS->isOne())
6583 return 0; // Not worth bothering, and eliminates some funny cases
6586 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6587 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6588 // C2 (CI). By solving for X we can turn this into a range check
6589 // instead of computing a divide.
6590 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6592 // Determine if the product overflows by seeing if the product is
6593 // not equal to the divide. Make sure we do the same kind of divide
6594 // as in the LHS instruction that we're folding.
6595 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6596 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6598 // Get the ICmp opcode
6599 ICmpInst::Predicate Pred = ICI.getPredicate();
6601 // Figure out the interval that is being checked. For example, a comparison
6602 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6603 // Compute this interval based on the constants involved and the signedness of
6604 // the compare/divide. This computes a half-open interval, keeping track of
6605 // whether either value in the interval overflows. After analysis each
6606 // overflow variable is set to 0 if it's corresponding bound variable is valid
6607 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6608 int LoOverflow = 0, HiOverflow = 0;
6609 Constant *LoBound = 0, *HiBound = 0;
6611 if (!DivIsSigned) { // udiv
6612 // e.g. X/5 op 3 --> [15, 20)
6614 HiOverflow = LoOverflow = ProdOV;
6616 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6617 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6618 if (CmpRHSV == 0) { // (X / pos) op 0
6619 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
6620 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6622 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
6623 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6624 HiOverflow = LoOverflow = ProdOV;
6626 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6627 } else { // (X / pos) op neg
6628 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
6629 HiBound = AddOne(Prod);
6630 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6632 ConstantInt* DivNeg =
6633 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6634 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6638 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6639 if (CmpRHSV == 0) { // (X / neg) op 0
6640 // e.g. X/-5 op 0 --> [-4, 5)
6641 LoBound = AddOne(DivRHS);
6642 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6643 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6644 HiOverflow = 1; // [INTMIN+1, overflow)
6645 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6647 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
6648 // e.g. X/-5 op 3 --> [-19, -14)
6649 HiBound = AddOne(Prod);
6650 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6652 LoOverflow = AddWithOverflow(LoBound, HiBound,
6653 DivRHS, Context, true) ? -1 : 0;
6654 } else { // (X / neg) op neg
6655 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6656 LoOverflow = HiOverflow = ProdOV;
6658 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6661 // Dividing by a negative swaps the condition. LT <-> GT
6662 Pred = ICmpInst::getSwappedPredicate(Pred);
6665 Value *X = DivI->getOperand(0);
6667 default: llvm_unreachable("Unhandled icmp opcode!");
6668 case ICmpInst::ICMP_EQ:
6669 if (LoOverflow && HiOverflow)
6670 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6671 else if (HiOverflow)
6672 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
6673 ICmpInst::ICMP_UGE, X, LoBound);
6674 else if (LoOverflow)
6675 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
6676 ICmpInst::ICMP_ULT, X, HiBound);
6678 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6679 case ICmpInst::ICMP_NE:
6680 if (LoOverflow && HiOverflow)
6681 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6682 else if (HiOverflow)
6683 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
6684 ICmpInst::ICMP_ULT, X, LoBound);
6685 else if (LoOverflow)
6686 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
6687 ICmpInst::ICMP_UGE, X, HiBound);
6689 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6690 case ICmpInst::ICMP_ULT:
6691 case ICmpInst::ICMP_SLT:
6692 if (LoOverflow == +1) // Low bound is greater than input range.
6693 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6694 if (LoOverflow == -1) // Low bound is less than input range.
6695 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6696 return new ICmpInst(*Context, Pred, X, LoBound);
6697 case ICmpInst::ICMP_UGT:
6698 case ICmpInst::ICMP_SGT:
6699 if (HiOverflow == +1) // High bound greater than input range.
6700 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6701 else if (HiOverflow == -1) // High bound less than input range.
6702 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6703 if (Pred == ICmpInst::ICMP_UGT)
6704 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
6706 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
6711 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6713 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6716 const APInt &RHSV = RHS->getValue();
6718 switch (LHSI->getOpcode()) {
6719 case Instruction::Trunc:
6720 if (ICI.isEquality() && LHSI->hasOneUse()) {
6721 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6722 // of the high bits truncated out of x are known.
6723 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6724 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6725 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6726 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6727 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6729 // If all the high bits are known, we can do this xform.
6730 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6731 // Pull in the high bits from known-ones set.
6732 APInt NewRHS(RHS->getValue());
6733 NewRHS.zext(SrcBits);
6735 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6736 ConstantInt::get(*Context, NewRHS));
6741 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6742 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6743 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6745 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6746 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6747 Value *CompareVal = LHSI->getOperand(0);
6749 // If the sign bit of the XorCST is not set, there is no change to
6750 // the operation, just stop using the Xor.
6751 if (!XorCST->getValue().isNegative()) {
6752 ICI.setOperand(0, CompareVal);
6753 AddToWorkList(LHSI);
6757 // Was the old condition true if the operand is positive?
6758 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6760 // If so, the new one isn't.
6761 isTrueIfPositive ^= true;
6763 if (isTrueIfPositive)
6764 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
6767 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
6771 if (LHSI->hasOneUse()) {
6772 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6773 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6774 const APInt &SignBit = XorCST->getValue();
6775 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6776 ? ICI.getUnsignedPredicate()
6777 : ICI.getSignedPredicate();
6778 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6779 ConstantInt::get(*Context, RHSV ^ SignBit));
6782 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6783 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6784 const APInt &NotSignBit = XorCST->getValue();
6785 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6786 ? ICI.getUnsignedPredicate()
6787 : ICI.getSignedPredicate();
6788 Pred = ICI.getSwappedPredicate(Pred);
6789 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6790 ConstantInt::get(*Context, RHSV ^ NotSignBit));
6795 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6796 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6797 LHSI->getOperand(0)->hasOneUse()) {
6798 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6800 // If the LHS is an AND of a truncating cast, we can widen the
6801 // and/compare to be the input width without changing the value
6802 // produced, eliminating a cast.
6803 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6804 // We can do this transformation if either the AND constant does not
6805 // have its sign bit set or if it is an equality comparison.
6806 // Extending a relational comparison when we're checking the sign
6807 // bit would not work.
6808 if (Cast->hasOneUse() &&
6809 (ICI.isEquality() ||
6810 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6812 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6813 APInt NewCST = AndCST->getValue();
6814 NewCST.zext(BitWidth);
6816 NewCI.zext(BitWidth);
6817 Instruction *NewAnd =
6818 BinaryOperator::CreateAnd(Cast->getOperand(0),
6819 ConstantInt::get(*Context, NewCST), LHSI->getName());
6820 InsertNewInstBefore(NewAnd, ICI);
6821 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
6822 ConstantInt::get(*Context, NewCI));
6826 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6827 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6828 // happens a LOT in code produced by the C front-end, for bitfield
6830 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6831 if (Shift && !Shift->isShift())
6835 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6836 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6837 const Type *AndTy = AndCST->getType(); // Type of the and.
6839 // We can fold this as long as we can't shift unknown bits
6840 // into the mask. This can only happen with signed shift
6841 // rights, as they sign-extend.
6843 bool CanFold = Shift->isLogicalShift();
6845 // To test for the bad case of the signed shr, see if any
6846 // of the bits shifted in could be tested after the mask.
6847 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6848 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6850 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6851 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6852 AndCST->getValue()) == 0)
6858 if (Shift->getOpcode() == Instruction::Shl)
6859 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6861 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6863 // Check to see if we are shifting out any of the bits being
6865 if (ConstantExpr::get(Shift->getOpcode(),
6866 NewCst, ShAmt) != RHS) {
6867 // If we shifted bits out, the fold is not going to work out.
6868 // As a special case, check to see if this means that the
6869 // result is always true or false now.
6870 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6871 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6872 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6873 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6875 ICI.setOperand(1, NewCst);
6876 Constant *NewAndCST;
6877 if (Shift->getOpcode() == Instruction::Shl)
6878 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6880 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6881 LHSI->setOperand(1, NewAndCST);
6882 LHSI->setOperand(0, Shift->getOperand(0));
6883 AddToWorkList(Shift); // Shift is dead.
6884 AddUsesToWorkList(ICI);
6890 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6891 // preferable because it allows the C<<Y expression to be hoisted out
6892 // of a loop if Y is invariant and X is not.
6893 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6894 ICI.isEquality() && !Shift->isArithmeticShift() &&
6895 !isa<Constant>(Shift->getOperand(0))) {
6898 if (Shift->getOpcode() == Instruction::LShr) {
6899 NS = BinaryOperator::CreateShl(AndCST,
6900 Shift->getOperand(1), "tmp");
6902 // Insert a logical shift.
6903 NS = BinaryOperator::CreateLShr(AndCST,
6904 Shift->getOperand(1), "tmp");
6906 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6908 // Compute X & (C << Y).
6909 Instruction *NewAnd =
6910 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6911 InsertNewInstBefore(NewAnd, ICI);
6913 ICI.setOperand(0, NewAnd);
6919 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6920 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6923 uint32_t TypeBits = RHSV.getBitWidth();
6925 // Check that the shift amount is in range. If not, don't perform
6926 // undefined shifts. When the shift is visited it will be
6928 if (ShAmt->uge(TypeBits))
6931 if (ICI.isEquality()) {
6932 // If we are comparing against bits always shifted out, the
6933 // comparison cannot succeed.
6935 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6937 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6938 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6939 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6940 return ReplaceInstUsesWith(ICI, Cst);
6943 if (LHSI->hasOneUse()) {
6944 // Otherwise strength reduce the shift into an and.
6945 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6947 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
6948 TypeBits-ShAmtVal));
6951 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6952 Mask, LHSI->getName()+".mask");
6953 Value *And = InsertNewInstBefore(AndI, ICI);
6954 return new ICmpInst(*Context, ICI.getPredicate(), And,
6955 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6959 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6960 bool TrueIfSigned = false;
6961 if (LHSI->hasOneUse() &&
6962 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6963 // (X << 31) <s 0 --> (X&1) != 0
6964 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6965 (TypeBits-ShAmt->getZExtValue()-1));
6967 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6968 Mask, LHSI->getName()+".mask");
6969 Value *And = InsertNewInstBefore(AndI, ICI);
6971 return new ICmpInst(*Context,
6972 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6973 And, Constant::getNullValue(And->getType()));
6978 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6979 case Instruction::AShr: {
6980 // Only handle equality comparisons of shift-by-constant.
6981 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6982 if (!ShAmt || !ICI.isEquality()) break;
6984 // Check that the shift amount is in range. If not, don't perform
6985 // undefined shifts. When the shift is visited it will be
6987 uint32_t TypeBits = RHSV.getBitWidth();
6988 if (ShAmt->uge(TypeBits))
6991 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6993 // If we are comparing against bits always shifted out, the
6994 // comparison cannot succeed.
6995 APInt Comp = RHSV << ShAmtVal;
6996 if (LHSI->getOpcode() == Instruction::LShr)
6997 Comp = Comp.lshr(ShAmtVal);
6999 Comp = Comp.ashr(ShAmtVal);
7001 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7002 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7003 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
7004 return ReplaceInstUsesWith(ICI, Cst);
7007 // Otherwise, check to see if the bits shifted out are known to be zero.
7008 // If so, we can compare against the unshifted value:
7009 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
7010 if (LHSI->hasOneUse() &&
7011 MaskedValueIsZero(LHSI->getOperand(0),
7012 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7013 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
7014 ConstantExpr::getShl(RHS, ShAmt));
7017 if (LHSI->hasOneUse()) {
7018 // Otherwise strength reduce the shift into an and.
7019 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7020 Constant *Mask = ConstantInt::get(*Context, Val);
7023 BinaryOperator::CreateAnd(LHSI->getOperand(0),
7024 Mask, LHSI->getName()+".mask");
7025 Value *And = InsertNewInstBefore(AndI, ICI);
7026 return new ICmpInst(*Context, ICI.getPredicate(), And,
7027 ConstantExpr::getShl(RHS, ShAmt));
7032 case Instruction::SDiv:
7033 case Instruction::UDiv:
7034 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7035 // Fold this div into the comparison, producing a range check.
7036 // Determine, based on the divide type, what the range is being
7037 // checked. If there is an overflow on the low or high side, remember
7038 // it, otherwise compute the range [low, hi) bounding the new value.
7039 // See: InsertRangeTest above for the kinds of replacements possible.
7040 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7041 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7046 case Instruction::Add:
7047 // Fold: icmp pred (add, X, C1), C2
7049 if (!ICI.isEquality()) {
7050 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7052 const APInt &LHSV = LHSC->getValue();
7054 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7057 if (ICI.isSignedPredicate()) {
7058 if (CR.getLower().isSignBit()) {
7059 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7060 ConstantInt::get(*Context, CR.getUpper()));
7061 } else if (CR.getUpper().isSignBit()) {
7062 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7063 ConstantInt::get(*Context, CR.getLower()));
7066 if (CR.getLower().isMinValue()) {
7067 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7068 ConstantInt::get(*Context, CR.getUpper()));
7069 } else if (CR.getUpper().isMinValue()) {
7070 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7071 ConstantInt::get(*Context, CR.getLower()));
7078 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7079 if (ICI.isEquality()) {
7080 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7082 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7083 // the second operand is a constant, simplify a bit.
7084 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7085 switch (BO->getOpcode()) {
7086 case Instruction::SRem:
7087 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7088 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7089 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7090 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7091 Instruction *NewRem =
7092 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7094 InsertNewInstBefore(NewRem, ICI);
7095 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
7096 Constant::getNullValue(BO->getType()));
7100 case Instruction::Add:
7101 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7102 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7103 if (BO->hasOneUse())
7104 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7105 ConstantExpr::getSub(RHS, BOp1C));
7106 } else if (RHSV == 0) {
7107 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7108 // efficiently invertible, or if the add has just this one use.
7109 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7111 if (Value *NegVal = dyn_castNegVal(BOp1))
7112 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
7113 else if (Value *NegVal = dyn_castNegVal(BOp0))
7114 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
7115 else if (BO->hasOneUse()) {
7116 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
7117 InsertNewInstBefore(Neg, ICI);
7119 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
7123 case Instruction::Xor:
7124 // For the xor case, we can xor two constants together, eliminating
7125 // the explicit xor.
7126 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7127 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7128 ConstantExpr::getXor(RHS, BOC));
7131 case Instruction::Sub:
7132 // Replace (([sub|xor] A, B) != 0) with (A != B)
7134 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7138 case Instruction::Or:
7139 // If bits are being or'd in that are not present in the constant we
7140 // are comparing against, then the comparison could never succeed!
7141 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7142 Constant *NotCI = ConstantExpr::getNot(RHS);
7143 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7144 return ReplaceInstUsesWith(ICI,
7145 ConstantInt::get(Type::getInt1Ty(*Context),
7150 case Instruction::And:
7151 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7152 // If bits are being compared against that are and'd out, then the
7153 // comparison can never succeed!
7154 if ((RHSV & ~BOC->getValue()) != 0)
7155 return ReplaceInstUsesWith(ICI,
7156 ConstantInt::get(Type::getInt1Ty(*Context),
7159 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7160 if (RHS == BOC && RHSV.isPowerOf2())
7161 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
7162 ICmpInst::ICMP_NE, LHSI,
7163 Constant::getNullValue(RHS->getType()));
7165 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7166 if (BOC->getValue().isSignBit()) {
7167 Value *X = BO->getOperand(0);
7168 Constant *Zero = Constant::getNullValue(X->getType());
7169 ICmpInst::Predicate pred = isICMP_NE ?
7170 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7171 return new ICmpInst(*Context, pred, X, Zero);
7174 // ((X & ~7) == 0) --> X < 8
7175 if (RHSV == 0 && isHighOnes(BOC)) {
7176 Value *X = BO->getOperand(0);
7177 Constant *NegX = ConstantExpr::getNeg(BOC);
7178 ICmpInst::Predicate pred = isICMP_NE ?
7179 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7180 return new ICmpInst(*Context, pred, X, NegX);
7185 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7186 // Handle icmp {eq|ne} <intrinsic>, intcst.
7187 if (II->getIntrinsicID() == Intrinsic::bswap) {
7189 ICI.setOperand(0, II->getOperand(1));
7190 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7198 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7199 /// We only handle extending casts so far.
7201 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7202 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7203 Value *LHSCIOp = LHSCI->getOperand(0);
7204 const Type *SrcTy = LHSCIOp->getType();
7205 const Type *DestTy = LHSCI->getType();
7208 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7209 // integer type is the same size as the pointer type.
7210 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7211 TD->getPointerSizeInBits() ==
7212 cast<IntegerType>(DestTy)->getBitWidth()) {
7214 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7215 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7216 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7217 RHSOp = RHSC->getOperand(0);
7218 // If the pointer types don't match, insert a bitcast.
7219 if (LHSCIOp->getType() != RHSOp->getType())
7220 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7224 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
7227 // The code below only handles extension cast instructions, so far.
7229 if (LHSCI->getOpcode() != Instruction::ZExt &&
7230 LHSCI->getOpcode() != Instruction::SExt)
7233 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7234 bool isSignedCmp = ICI.isSignedPredicate();
7236 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7237 // Not an extension from the same type?
7238 RHSCIOp = CI->getOperand(0);
7239 if (RHSCIOp->getType() != LHSCIOp->getType())
7242 // If the signedness of the two casts doesn't agree (i.e. one is a sext
7243 // and the other is a zext), then we can't handle this.
7244 if (CI->getOpcode() != LHSCI->getOpcode())
7247 // Deal with equality cases early.
7248 if (ICI.isEquality())
7249 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7251 // A signed comparison of sign extended values simplifies into a
7252 // signed comparison.
7253 if (isSignedCmp && isSignedExt)
7254 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7256 // The other three cases all fold into an unsigned comparison.
7257 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7260 // If we aren't dealing with a constant on the RHS, exit early
7261 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7265 // Compute the constant that would happen if we truncated to SrcTy then
7266 // reextended to DestTy.
7267 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7268 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7271 // If the re-extended constant didn't change...
7273 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7274 // For example, we might have:
7275 // %A = sext i16 %X to i32
7276 // %B = icmp ugt i32 %A, 1330
7277 // It is incorrect to transform this into
7278 // %B = icmp ugt i16 %X, 1330
7279 // because %A may have negative value.
7281 // However, we allow this when the compare is EQ/NE, because they are
7283 if (isSignedExt == isSignedCmp || ICI.isEquality())
7284 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
7288 // The re-extended constant changed so the constant cannot be represented
7289 // in the shorter type. Consequently, we cannot emit a simple comparison.
7291 // First, handle some easy cases. We know the result cannot be equal at this
7292 // point so handle the ICI.isEquality() cases
7293 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7294 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7295 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7296 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7298 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7299 // should have been folded away previously and not enter in here.
7302 // We're performing a signed comparison.
7303 if (cast<ConstantInt>(CI)->getValue().isNegative())
7304 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
7306 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
7308 // We're performing an unsigned comparison.
7310 // We're performing an unsigned comp with a sign extended value.
7311 // This is true if the input is >= 0. [aka >s -1]
7312 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7313 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7314 LHSCIOp, NegOne, ICI.getName()), ICI);
7316 // Unsigned extend & unsigned compare -> always true.
7317 Result = ConstantInt::getTrue(*Context);
7321 // Finally, return the value computed.
7322 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7323 ICI.getPredicate() == ICmpInst::ICMP_SLT)
7324 return ReplaceInstUsesWith(ICI, Result);
7326 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7327 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7328 "ICmp should be folded!");
7329 if (Constant *CI = dyn_cast<Constant>(Result))
7330 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7331 return BinaryOperator::CreateNot(Result);
7334 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7335 return commonShiftTransforms(I);
7338 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7339 return commonShiftTransforms(I);
7342 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7343 if (Instruction *R = commonShiftTransforms(I))
7346 Value *Op0 = I.getOperand(0);
7348 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7349 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7350 if (CSI->isAllOnesValue())
7351 return ReplaceInstUsesWith(I, CSI);
7353 // See if we can turn a signed shr into an unsigned shr.
7354 if (MaskedValueIsZero(Op0,
7355 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7356 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7358 // Arithmetic shifting an all-sign-bit value is a no-op.
7359 unsigned NumSignBits = ComputeNumSignBits(Op0);
7360 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7361 return ReplaceInstUsesWith(I, Op0);
7366 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7367 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7368 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7370 // shl X, 0 == X and shr X, 0 == X
7371 // shl 0, X == 0 and shr 0, X == 0
7372 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7373 Op0 == Constant::getNullValue(Op0->getType()))
7374 return ReplaceInstUsesWith(I, Op0);
7376 if (isa<UndefValue>(Op0)) {
7377 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7378 return ReplaceInstUsesWith(I, Op0);
7379 else // undef << X -> 0, undef >>u X -> 0
7380 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7382 if (isa<UndefValue>(Op1)) {
7383 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7384 return ReplaceInstUsesWith(I, Op0);
7385 else // X << undef, X >>u undef -> 0
7386 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7389 // See if we can fold away this shift.
7390 if (SimplifyDemandedInstructionBits(I))
7393 // Try to fold constant and into select arguments.
7394 if (isa<Constant>(Op0))
7395 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7396 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7399 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7400 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7405 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7406 BinaryOperator &I) {
7407 bool isLeftShift = I.getOpcode() == Instruction::Shl;
7409 // See if we can simplify any instructions used by the instruction whose sole
7410 // purpose is to compute bits we don't care about.
7411 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7413 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7416 if (Op1->uge(TypeBits)) {
7417 if (I.getOpcode() != Instruction::AShr)
7418 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7420 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7425 // ((X*C1) << C2) == (X * (C1 << C2))
7426 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7427 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7428 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7429 return BinaryOperator::CreateMul(BO->getOperand(0),
7430 ConstantExpr::getShl(BOOp, Op1));
7432 // Try to fold constant and into select arguments.
7433 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7434 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7436 if (isa<PHINode>(Op0))
7437 if (Instruction *NV = FoldOpIntoPhi(I))
7440 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7441 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7442 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7443 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7444 // place. Don't try to do this transformation in this case. Also, we
7445 // require that the input operand is a shift-by-constant so that we have
7446 // confidence that the shifts will get folded together. We could do this
7447 // xform in more cases, but it is unlikely to be profitable.
7448 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7449 isa<ConstantInt>(TrOp->getOperand(1))) {
7450 // Okay, we'll do this xform. Make the shift of shift.
7451 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7452 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7454 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7456 // For logical shifts, the truncation has the effect of making the high
7457 // part of the register be zeros. Emulate this by inserting an AND to
7458 // clear the top bits as needed. This 'and' will usually be zapped by
7459 // other xforms later if dead.
7460 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7461 unsigned DstSize = TI->getType()->getScalarSizeInBits();
7462 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7464 // The mask we constructed says what the trunc would do if occurring
7465 // between the shifts. We want to know the effect *after* the second
7466 // shift. We know that it is a logical shift by a constant, so adjust the
7467 // mask as appropriate.
7468 if (I.getOpcode() == Instruction::Shl)
7469 MaskV <<= Op1->getZExtValue();
7471 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7472 MaskV = MaskV.lshr(Op1->getZExtValue());
7476 BinaryOperator::CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7478 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7480 // Return the value truncated to the interesting size.
7481 return new TruncInst(And, I.getType());
7485 if (Op0->hasOneUse()) {
7486 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7487 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7490 switch (Op0BO->getOpcode()) {
7492 case Instruction::Add:
7493 case Instruction::And:
7494 case Instruction::Or:
7495 case Instruction::Xor: {
7496 // These operators commute.
7497 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7498 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7499 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7501 Instruction *YS = BinaryOperator::CreateShl(
7502 Op0BO->getOperand(0), Op1,
7504 InsertNewInstBefore(YS, I); // (Y << C)
7506 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7507 Op0BO->getOperand(1)->getName());
7508 InsertNewInstBefore(X, I); // (X + (Y << C))
7509 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7510 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7511 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7514 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7515 Value *Op0BOOp1 = Op0BO->getOperand(1);
7516 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7518 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7519 m_ConstantInt(CC))) &&
7520 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7521 Instruction *YS = BinaryOperator::CreateShl(
7522 Op0BO->getOperand(0), Op1,
7524 InsertNewInstBefore(YS, I); // (Y << C)
7526 BinaryOperator::CreateAnd(V1,
7527 ConstantExpr::getShl(CC, Op1),
7528 V1->getName()+".mask");
7529 InsertNewInstBefore(XM, I); // X & (CC << C)
7531 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7536 case Instruction::Sub: {
7537 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7538 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7539 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7540 m_Specific(Op1)))) {
7541 Instruction *YS = BinaryOperator::CreateShl(
7542 Op0BO->getOperand(1), Op1,
7544 InsertNewInstBefore(YS, I); // (Y << C)
7546 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7547 Op0BO->getOperand(0)->getName());
7548 InsertNewInstBefore(X, I); // (X + (Y << C))
7549 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7550 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7551 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7554 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7555 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7556 match(Op0BO->getOperand(0),
7557 m_And(m_Shr(m_Value(V1), m_Value(V2)),
7558 m_ConstantInt(CC))) && V2 == Op1 &&
7559 cast<BinaryOperator>(Op0BO->getOperand(0))
7560 ->getOperand(0)->hasOneUse()) {
7561 Instruction *YS = BinaryOperator::CreateShl(
7562 Op0BO->getOperand(1), Op1,
7564 InsertNewInstBefore(YS, I); // (Y << C)
7566 BinaryOperator::CreateAnd(V1,
7567 ConstantExpr::getShl(CC, Op1),
7568 V1->getName()+".mask");
7569 InsertNewInstBefore(XM, I); // X & (CC << C)
7571 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7579 // If the operand is an bitwise operator with a constant RHS, and the
7580 // shift is the only use, we can pull it out of the shift.
7581 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7582 bool isValid = true; // Valid only for And, Or, Xor
7583 bool highBitSet = false; // Transform if high bit of constant set?
7585 switch (Op0BO->getOpcode()) {
7586 default: isValid = false; break; // Do not perform transform!
7587 case Instruction::Add:
7588 isValid = isLeftShift;
7590 case Instruction::Or:
7591 case Instruction::Xor:
7594 case Instruction::And:
7599 // If this is a signed shift right, and the high bit is modified
7600 // by the logical operation, do not perform the transformation.
7601 // The highBitSet boolean indicates the value of the high bit of
7602 // the constant which would cause it to be modified for this
7605 if (isValid && I.getOpcode() == Instruction::AShr)
7606 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7609 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7611 Instruction *NewShift =
7612 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7613 InsertNewInstBefore(NewShift, I);
7614 NewShift->takeName(Op0BO);
7616 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7623 // Find out if this is a shift of a shift by a constant.
7624 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7625 if (ShiftOp && !ShiftOp->isShift())
7628 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7629 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7630 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7631 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7632 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7633 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7634 Value *X = ShiftOp->getOperand(0);
7636 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
7638 const IntegerType *Ty = cast<IntegerType>(I.getType());
7640 // Check for (X << c1) << c2 and (X >> c1) >> c2
7641 if (I.getOpcode() == ShiftOp->getOpcode()) {
7642 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7644 if (AmtSum >= TypeBits) {
7645 if (I.getOpcode() != Instruction::AShr)
7646 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7647 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7650 return BinaryOperator::Create(I.getOpcode(), X,
7651 ConstantInt::get(Ty, AmtSum));
7652 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7653 I.getOpcode() == Instruction::AShr) {
7654 if (AmtSum >= TypeBits)
7655 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7657 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
7658 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7659 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7660 I.getOpcode() == Instruction::LShr) {
7661 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7662 if (AmtSum >= TypeBits)
7663 AmtSum = TypeBits-1;
7665 Instruction *Shift =
7666 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7667 InsertNewInstBefore(Shift, I);
7669 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7670 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7673 // Okay, if we get here, one shift must be left, and the other shift must be
7674 // right. See if the amounts are equal.
7675 if (ShiftAmt1 == ShiftAmt2) {
7676 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7677 if (I.getOpcode() == Instruction::Shl) {
7678 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7679 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7681 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7682 if (I.getOpcode() == Instruction::LShr) {
7683 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7684 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7686 // We can simplify ((X << C) >>s C) into a trunc + sext.
7687 // NOTE: we could do this for any C, but that would make 'unusual' integer
7688 // types. For now, just stick to ones well-supported by the code
7690 const Type *SExtType = 0;
7691 switch (Ty->getBitWidth() - ShiftAmt1) {
7698 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7703 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7704 InsertNewInstBefore(NewTrunc, I);
7705 return new SExtInst(NewTrunc, Ty);
7707 // Otherwise, we can't handle it yet.
7708 } else if (ShiftAmt1 < ShiftAmt2) {
7709 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7711 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7712 if (I.getOpcode() == Instruction::Shl) {
7713 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7714 ShiftOp->getOpcode() == Instruction::AShr);
7715 Instruction *Shift =
7716 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7717 InsertNewInstBefore(Shift, I);
7719 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7720 return BinaryOperator::CreateAnd(Shift,
7721 ConstantInt::get(*Context, Mask));
7724 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7725 if (I.getOpcode() == Instruction::LShr) {
7726 assert(ShiftOp->getOpcode() == Instruction::Shl);
7727 Instruction *Shift =
7728 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7729 InsertNewInstBefore(Shift, I);
7731 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7732 return BinaryOperator::CreateAnd(Shift,
7733 ConstantInt::get(*Context, Mask));
7736 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7738 assert(ShiftAmt2 < ShiftAmt1);
7739 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7741 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7742 if (I.getOpcode() == Instruction::Shl) {
7743 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7744 ShiftOp->getOpcode() == Instruction::AShr);
7745 Instruction *Shift =
7746 BinaryOperator::Create(ShiftOp->getOpcode(), X,
7747 ConstantInt::get(Ty, ShiftDiff));
7748 InsertNewInstBefore(Shift, I);
7750 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7751 return BinaryOperator::CreateAnd(Shift,
7752 ConstantInt::get(*Context, Mask));
7755 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7756 if (I.getOpcode() == Instruction::LShr) {
7757 assert(ShiftOp->getOpcode() == Instruction::Shl);
7758 Instruction *Shift =
7759 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7760 InsertNewInstBefore(Shift, I);
7762 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7763 return BinaryOperator::CreateAnd(Shift,
7764 ConstantInt::get(*Context, Mask));
7767 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7774 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7775 /// expression. If so, decompose it, returning some value X, such that Val is
7778 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7779 int &Offset, LLVMContext *Context) {
7780 assert(Val->getType() == Type::getInt32Ty(*Context) && "Unexpected allocation size type!");
7781 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7782 Offset = CI->getZExtValue();
7784 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7785 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7786 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7787 if (I->getOpcode() == Instruction::Shl) {
7788 // This is a value scaled by '1 << the shift amt'.
7789 Scale = 1U << RHS->getZExtValue();
7791 return I->getOperand(0);
7792 } else if (I->getOpcode() == Instruction::Mul) {
7793 // This value is scaled by 'RHS'.
7794 Scale = RHS->getZExtValue();
7796 return I->getOperand(0);
7797 } else if (I->getOpcode() == Instruction::Add) {
7798 // We have X+C. Check to see if we really have (X*C2)+C1,
7799 // where C1 is divisible by C2.
7802 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7804 Offset += RHS->getZExtValue();
7811 // Otherwise, we can't look past this.
7818 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7819 /// try to eliminate the cast by moving the type information into the alloc.
7820 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7821 AllocationInst &AI) {
7822 const PointerType *PTy = cast<PointerType>(CI.getType());
7824 // Remove any uses of AI that are dead.
7825 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7827 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7828 Instruction *User = cast<Instruction>(*UI++);
7829 if (isInstructionTriviallyDead(User)) {
7830 while (UI != E && *UI == User)
7831 ++UI; // If this instruction uses AI more than once, don't break UI.
7834 DOUT << "IC: DCE: " << *User << '\n';
7835 EraseInstFromFunction(*User);
7839 // This requires TargetData to get the alloca alignment and size information.
7842 // Get the type really allocated and the type casted to.
7843 const Type *AllocElTy = AI.getAllocatedType();
7844 const Type *CastElTy = PTy->getElementType();
7845 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7847 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7848 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7849 if (CastElTyAlign < AllocElTyAlign) return 0;
7851 // If the allocation has multiple uses, only promote it if we are strictly
7852 // increasing the alignment of the resultant allocation. If we keep it the
7853 // same, we open the door to infinite loops of various kinds. (A reference
7854 // from a dbg.declare doesn't count as a use for this purpose.)
7855 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7856 CastElTyAlign == AllocElTyAlign) return 0;
7858 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7859 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7860 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7862 // See if we can satisfy the modulus by pulling a scale out of the array
7864 unsigned ArraySizeScale;
7866 Value *NumElements = // See if the array size is a decomposable linear expr.
7867 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7868 ArrayOffset, Context);
7870 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7872 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7873 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7875 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7880 // If the allocation size is constant, form a constant mul expression
7881 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7882 if (isa<ConstantInt>(NumElements))
7883 Amt = ConstantExpr::getMul(cast<ConstantInt>(NumElements),
7884 cast<ConstantInt>(Amt));
7885 // otherwise multiply the amount and the number of elements
7887 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7888 Amt = InsertNewInstBefore(Tmp, AI);
7892 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7893 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7894 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7895 Amt = InsertNewInstBefore(Tmp, AI);
7898 AllocationInst *New;
7899 if (isa<MallocInst>(AI))
7900 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7902 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7903 InsertNewInstBefore(New, AI);
7906 // If the allocation has one real use plus a dbg.declare, just remove the
7908 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7909 EraseInstFromFunction(*DI);
7911 // If the allocation has multiple real uses, insert a cast and change all
7912 // things that used it to use the new cast. This will also hack on CI, but it
7914 else if (!AI.hasOneUse()) {
7915 AddUsesToWorkList(AI);
7916 // New is the allocation instruction, pointer typed. AI is the original
7917 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7918 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7919 InsertNewInstBefore(NewCast, AI);
7920 AI.replaceAllUsesWith(NewCast);
7922 return ReplaceInstUsesWith(CI, New);
7925 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7926 /// and return it as type Ty without inserting any new casts and without
7927 /// changing the computed value. This is used by code that tries to decide
7928 /// whether promoting or shrinking integer operations to wider or smaller types
7929 /// will allow us to eliminate a truncate or extend.
7931 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7932 /// extension operation if Ty is larger.
7934 /// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7935 /// should return true if trunc(V) can be computed by computing V in the smaller
7936 /// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7937 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7938 /// efficiently truncated.
7940 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7941 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7942 /// the final result.
7943 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7945 int &NumCastsRemoved){
7946 // We can always evaluate constants in another type.
7947 if (isa<Constant>(V))
7950 Instruction *I = dyn_cast<Instruction>(V);
7951 if (!I) return false;
7953 const Type *OrigTy = V->getType();
7955 // If this is an extension or truncate, we can often eliminate it.
7956 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7957 // If this is a cast from the destination type, we can trivially eliminate
7958 // it, and this will remove a cast overall.
7959 if (I->getOperand(0)->getType() == Ty) {
7960 // If the first operand is itself a cast, and is eliminable, do not count
7961 // this as an eliminable cast. We would prefer to eliminate those two
7963 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7969 // We can't extend or shrink something that has multiple uses: doing so would
7970 // require duplicating the instruction in general, which isn't profitable.
7971 if (!I->hasOneUse()) return false;
7973 unsigned Opc = I->getOpcode();
7975 case Instruction::Add:
7976 case Instruction::Sub:
7977 case Instruction::Mul:
7978 case Instruction::And:
7979 case Instruction::Or:
7980 case Instruction::Xor:
7981 // These operators can all arbitrarily be extended or truncated.
7982 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7984 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7987 case Instruction::UDiv:
7988 case Instruction::URem: {
7989 // UDiv and URem can be truncated if all the truncated bits are zero.
7990 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7991 uint32_t BitWidth = Ty->getScalarSizeInBits();
7992 if (BitWidth < OrigBitWidth) {
7993 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7994 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7995 MaskedValueIsZero(I->getOperand(1), Mask)) {
7996 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7998 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8004 case Instruction::Shl:
8005 // If we are truncating the result of this SHL, and if it's a shift of a
8006 // constant amount, we can always perform a SHL in a smaller type.
8007 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8008 uint32_t BitWidth = Ty->getScalarSizeInBits();
8009 if (BitWidth < OrigTy->getScalarSizeInBits() &&
8010 CI->getLimitedValue(BitWidth) < BitWidth)
8011 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8015 case Instruction::LShr:
8016 // If this is a truncate of a logical shr, we can truncate it to a smaller
8017 // lshr iff we know that the bits we would otherwise be shifting in are
8019 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
8020 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8021 uint32_t BitWidth = Ty->getScalarSizeInBits();
8022 if (BitWidth < OrigBitWidth &&
8023 MaskedValueIsZero(I->getOperand(0),
8024 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8025 CI->getLimitedValue(BitWidth) < BitWidth) {
8026 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8031 case Instruction::ZExt:
8032 case Instruction::SExt:
8033 case Instruction::Trunc:
8034 // If this is the same kind of case as our original (e.g. zext+zext), we
8035 // can safely replace it. Note that replacing it does not reduce the number
8036 // of casts in the input.
8040 // sext (zext ty1), ty2 -> zext ty2
8041 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
8044 case Instruction::Select: {
8045 SelectInst *SI = cast<SelectInst>(I);
8046 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8048 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8051 case Instruction::PHI: {
8052 // We can change a phi if we can change all operands.
8053 PHINode *PN = cast<PHINode>(I);
8054 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8055 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8061 // TODO: Can handle more cases here.
8068 /// EvaluateInDifferentType - Given an expression that
8069 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8070 /// evaluate the expression.
8071 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
8073 if (Constant *C = dyn_cast<Constant>(V))
8074 return ConstantExpr::getIntegerCast(C, Ty,
8075 isSigned /*Sext or ZExt*/);
8077 // Otherwise, it must be an instruction.
8078 Instruction *I = cast<Instruction>(V);
8079 Instruction *Res = 0;
8080 unsigned Opc = I->getOpcode();
8082 case Instruction::Add:
8083 case Instruction::Sub:
8084 case Instruction::Mul:
8085 case Instruction::And:
8086 case Instruction::Or:
8087 case Instruction::Xor:
8088 case Instruction::AShr:
8089 case Instruction::LShr:
8090 case Instruction::Shl:
8091 case Instruction::UDiv:
8092 case Instruction::URem: {
8093 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8094 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8095 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8098 case Instruction::Trunc:
8099 case Instruction::ZExt:
8100 case Instruction::SExt:
8101 // If the source type of the cast is the type we're trying for then we can
8102 // just return the source. There's no need to insert it because it is not
8104 if (I->getOperand(0)->getType() == Ty)
8105 return I->getOperand(0);
8107 // Otherwise, must be the same type of cast, so just reinsert a new one.
8108 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8111 case Instruction::Select: {
8112 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8113 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8114 Res = SelectInst::Create(I->getOperand(0), True, False);
8117 case Instruction::PHI: {
8118 PHINode *OPN = cast<PHINode>(I);
8119 PHINode *NPN = PHINode::Create(Ty);
8120 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8121 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8122 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8128 // TODO: Can handle more cases here.
8129 llvm_unreachable("Unreachable!");
8134 return InsertNewInstBefore(Res, *I);
8137 /// @brief Implement the transforms common to all CastInst visitors.
8138 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8139 Value *Src = CI.getOperand(0);
8141 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8142 // eliminate it now.
8143 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8144 if (Instruction::CastOps opc =
8145 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8146 // The first cast (CSrc) is eliminable so we need to fix up or replace
8147 // the second cast (CI). CSrc will then have a good chance of being dead.
8148 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8152 // If we are casting a select then fold the cast into the select
8153 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8154 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8157 // If we are casting a PHI then fold the cast into the PHI
8158 if (isa<PHINode>(Src))
8159 if (Instruction *NV = FoldOpIntoPhi(CI))
8165 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8166 /// or not there is a sequence of GEP indices into the type that will land us at
8167 /// the specified offset. If so, fill them into NewIndices and return the
8168 /// resultant element type, otherwise return null.
8169 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8170 SmallVectorImpl<Value*> &NewIndices,
8171 const TargetData *TD,
8172 LLVMContext *Context) {
8174 if (!Ty->isSized()) return 0;
8176 // Start with the index over the outer type. Note that the type size
8177 // might be zero (even if the offset isn't zero) if the indexed type
8178 // is something like [0 x {int, int}]
8179 const Type *IntPtrTy = TD->getIntPtrType(*Context);
8180 int64_t FirstIdx = 0;
8181 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8182 FirstIdx = Offset/TySize;
8183 Offset -= FirstIdx*TySize;
8185 // Handle hosts where % returns negative instead of values [0..TySize).
8189 assert(Offset >= 0);
8191 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8194 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8196 // Index into the types. If we fail, set OrigBase to null.
8198 // Indexing into tail padding between struct/array elements.
8199 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8202 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8203 const StructLayout *SL = TD->getStructLayout(STy);
8204 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8205 "Offset must stay within the indexed type");
8207 unsigned Elt = SL->getElementContainingOffset(Offset);
8208 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8210 Offset -= SL->getElementOffset(Elt);
8211 Ty = STy->getElementType(Elt);
8212 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8213 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8214 assert(EltSize && "Cannot index into a zero-sized array");
8215 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8217 Ty = AT->getElementType();
8219 // Otherwise, we can't index into the middle of this atomic type, bail.
8227 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8228 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8229 Value *Src = CI.getOperand(0);
8231 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8232 // If casting the result of a getelementptr instruction with no offset, turn
8233 // this into a cast of the original pointer!
8234 if (GEP->hasAllZeroIndices()) {
8235 // Changing the cast operand is usually not a good idea but it is safe
8236 // here because the pointer operand is being replaced with another
8237 // pointer operand so the opcode doesn't need to change.
8239 CI.setOperand(0, GEP->getOperand(0));
8243 // If the GEP has a single use, and the base pointer is a bitcast, and the
8244 // GEP computes a constant offset, see if we can convert these three
8245 // instructions into fewer. This typically happens with unions and other
8246 // non-type-safe code.
8247 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8248 if (GEP->hasAllConstantIndices()) {
8249 // We are guaranteed to get a constant from EmitGEPOffset.
8250 ConstantInt *OffsetV =
8251 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8252 int64_t Offset = OffsetV->getSExtValue();
8254 // Get the base pointer input of the bitcast, and the type it points to.
8255 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8256 const Type *GEPIdxTy =
8257 cast<PointerType>(OrigBase->getType())->getElementType();
8258 SmallVector<Value*, 8> NewIndices;
8259 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8260 // If we were able to index down into an element, create the GEP
8261 // and bitcast the result. This eliminates one bitcast, potentially
8263 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8265 NewIndices.end(), "");
8266 InsertNewInstBefore(NGEP, CI);
8267 NGEP->takeName(GEP);
8268 if (cast<GEPOperator>(GEP)->isInBounds())
8269 cast<GEPOperator>(NGEP)->setIsInBounds(true);
8271 if (isa<BitCastInst>(CI))
8272 return new BitCastInst(NGEP, CI.getType());
8273 assert(isa<PtrToIntInst>(CI));
8274 return new PtrToIntInst(NGEP, CI.getType());
8280 return commonCastTransforms(CI);
8283 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8284 /// type like i42. We don't want to introduce operations on random non-legal
8285 /// integer types where they don't already exist in the code. In the future,
8286 /// we should consider making this based off target-data, so that 32-bit targets
8287 /// won't get i64 operations etc.
8288 static bool isSafeIntegerType(const Type *Ty) {
8289 switch (Ty->getPrimitiveSizeInBits()) {
8300 /// commonIntCastTransforms - This function implements the common transforms
8301 /// for trunc, zext, and sext.
8302 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8303 if (Instruction *Result = commonCastTransforms(CI))
8306 Value *Src = CI.getOperand(0);
8307 const Type *SrcTy = Src->getType();
8308 const Type *DestTy = CI.getType();
8309 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8310 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8312 // See if we can simplify any instructions used by the LHS whose sole
8313 // purpose is to compute bits we don't care about.
8314 if (SimplifyDemandedInstructionBits(CI))
8317 // If the source isn't an instruction or has more than one use then we
8318 // can't do anything more.
8319 Instruction *SrcI = dyn_cast<Instruction>(Src);
8320 if (!SrcI || !Src->hasOneUse())
8323 // Attempt to propagate the cast into the instruction for int->int casts.
8324 int NumCastsRemoved = 0;
8325 // Only do this if the dest type is a simple type, don't convert the
8326 // expression tree to something weird like i93 unless the source is also
8328 if ((isSafeIntegerType(DestTy->getScalarType()) ||
8329 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8330 CanEvaluateInDifferentType(SrcI, DestTy,
8331 CI.getOpcode(), NumCastsRemoved)) {
8332 // If this cast is a truncate, evaluting in a different type always
8333 // eliminates the cast, so it is always a win. If this is a zero-extension,
8334 // we need to do an AND to maintain the clear top-part of the computation,
8335 // so we require that the input have eliminated at least one cast. If this
8336 // is a sign extension, we insert two new casts (to do the extension) so we
8337 // require that two casts have been eliminated.
8338 bool DoXForm = false;
8339 bool JustReplace = false;
8340 switch (CI.getOpcode()) {
8342 // All the others use floating point so we shouldn't actually
8343 // get here because of the check above.
8344 llvm_unreachable("Unknown cast type");
8345 case Instruction::Trunc:
8348 case Instruction::ZExt: {
8349 DoXForm = NumCastsRemoved >= 1;
8350 if (!DoXForm && 0) {
8351 // If it's unnecessary to issue an AND to clear the high bits, it's
8352 // always profitable to do this xform.
8353 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8354 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8355 if (MaskedValueIsZero(TryRes, Mask))
8356 return ReplaceInstUsesWith(CI, TryRes);
8358 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8359 if (TryI->use_empty())
8360 EraseInstFromFunction(*TryI);
8364 case Instruction::SExt: {
8365 DoXForm = NumCastsRemoved >= 2;
8366 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8367 // If we do not have to emit the truncate + sext pair, then it's always
8368 // profitable to do this xform.
8370 // It's not safe to eliminate the trunc + sext pair if one of the
8371 // eliminated cast is a truncate. e.g.
8372 // t2 = trunc i32 t1 to i16
8373 // t3 = sext i16 t2 to i32
8376 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8377 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8378 if (NumSignBits > (DestBitSize - SrcBitSize))
8379 return ReplaceInstUsesWith(CI, TryRes);
8381 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8382 if (TryI->use_empty())
8383 EraseInstFromFunction(*TryI);
8390 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8392 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8393 CI.getOpcode() == Instruction::SExt);
8395 // Just replace this cast with the result.
8396 return ReplaceInstUsesWith(CI, Res);
8398 assert(Res->getType() == DestTy);
8399 switch (CI.getOpcode()) {
8400 default: llvm_unreachable("Unknown cast type!");
8401 case Instruction::Trunc:
8402 // Just replace this cast with the result.
8403 return ReplaceInstUsesWith(CI, Res);
8404 case Instruction::ZExt: {
8405 assert(SrcBitSize < DestBitSize && "Not a zext?");
8407 // If the high bits are already zero, just replace this cast with the
8409 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8410 if (MaskedValueIsZero(Res, Mask))
8411 return ReplaceInstUsesWith(CI, Res);
8413 // We need to emit an AND to clear the high bits.
8414 Constant *C = ConstantInt::get(*Context,
8415 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8416 return BinaryOperator::CreateAnd(Res, C);
8418 case Instruction::SExt: {
8419 // If the high bits are already filled with sign bit, just replace this
8420 // cast with the result.
8421 unsigned NumSignBits = ComputeNumSignBits(Res);
8422 if (NumSignBits > (DestBitSize - SrcBitSize))
8423 return ReplaceInstUsesWith(CI, Res);
8425 // We need to emit a cast to truncate, then a cast to sext.
8426 return CastInst::Create(Instruction::SExt,
8427 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8434 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8435 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8437 switch (SrcI->getOpcode()) {
8438 case Instruction::Add:
8439 case Instruction::Mul:
8440 case Instruction::And:
8441 case Instruction::Or:
8442 case Instruction::Xor:
8443 // If we are discarding information, rewrite.
8444 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8445 // Don't insert two casts unless at least one can be eliminated.
8446 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8447 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8448 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8449 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8450 return BinaryOperator::Create(
8451 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8455 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8456 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8457 SrcI->getOpcode() == Instruction::Xor &&
8458 Op1 == ConstantInt::getTrue(*Context) &&
8459 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8460 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8461 return BinaryOperator::CreateXor(New,
8462 ConstantInt::get(CI.getType(), 1));
8466 case Instruction::Shl: {
8467 // Canonicalize trunc inside shl, if we can.
8468 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8469 if (CI && DestBitSize < SrcBitSize &&
8470 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8471 Value *Op0c = InsertCastBefore(Instruction::Trunc, Op0, DestTy, *SrcI);
8472 Value *Op1c = InsertCastBefore(Instruction::Trunc, Op1, DestTy, *SrcI);
8473 return BinaryOperator::CreateShl(Op0c, Op1c);
8481 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8482 if (Instruction *Result = commonIntCastTransforms(CI))
8485 Value *Src = CI.getOperand(0);
8486 const Type *Ty = CI.getType();
8487 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8488 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8490 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8491 if (DestBitWidth == 1) {
8492 Constant *One = ConstantInt::get(Src->getType(), 1);
8493 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8494 Value *Zero = Constant::getNullValue(Src->getType());
8495 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
8498 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8499 ConstantInt *ShAmtV = 0;
8501 if (Src->hasOneUse() &&
8502 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8503 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8505 // Get a mask for the bits shifting in.
8506 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8507 if (MaskedValueIsZero(ShiftOp, Mask)) {
8508 if (ShAmt >= DestBitWidth) // All zeros.
8509 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8511 // Okay, we can shrink this. Truncate the input, then return a new
8513 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8514 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8515 return BinaryOperator::CreateLShr(V1, V2);
8522 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8523 /// in order to eliminate the icmp.
8524 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8526 // If we are just checking for a icmp eq of a single bit and zext'ing it
8527 // to an integer, then shift the bit to the appropriate place and then
8528 // cast to integer to avoid the comparison.
8529 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8530 const APInt &Op1CV = Op1C->getValue();
8532 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8533 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8534 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8535 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8536 if (!DoXform) return ICI;
8538 Value *In = ICI->getOperand(0);
8539 Value *Sh = ConstantInt::get(In->getType(),
8540 In->getType()->getScalarSizeInBits()-1);
8541 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8542 In->getName()+".lobit"),
8544 if (In->getType() != CI.getType())
8545 In = CastInst::CreateIntegerCast(In, CI.getType(),
8546 false/*ZExt*/, "tmp", &CI);
8548 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8549 Constant *One = ConstantInt::get(In->getType(), 1);
8550 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8551 In->getName()+".not"),
8555 return ReplaceInstUsesWith(CI, In);
8560 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8561 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8562 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8563 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8564 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8565 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8566 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8567 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8568 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8569 // This only works for EQ and NE
8570 ICI->isEquality()) {
8571 // If Op1C some other power of two, convert:
8572 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8573 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8574 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8575 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8577 APInt KnownZeroMask(~KnownZero);
8578 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8579 if (!DoXform) return ICI;
8581 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8582 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8583 // (X&4) == 2 --> false
8584 // (X&4) != 2 --> true
8585 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8586 Res = ConstantExpr::getZExt(Res, CI.getType());
8587 return ReplaceInstUsesWith(CI, Res);
8590 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8591 Value *In = ICI->getOperand(0);
8593 // Perform a logical shr by shiftamt.
8594 // Insert the shift to put the result in the low bit.
8595 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8596 ConstantInt::get(In->getType(), ShiftAmt),
8597 In->getName()+".lobit"), CI);
8600 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8601 Constant *One = ConstantInt::get(In->getType(), 1);
8602 In = BinaryOperator::CreateXor(In, One, "tmp");
8603 InsertNewInstBefore(cast<Instruction>(In), CI);
8606 if (CI.getType() == In->getType())
8607 return ReplaceInstUsesWith(CI, In);
8609 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8617 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8618 // If one of the common conversion will work ..
8619 if (Instruction *Result = commonIntCastTransforms(CI))
8622 Value *Src = CI.getOperand(0);
8624 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8625 // types and if the sizes are just right we can convert this into a logical
8626 // 'and' which will be much cheaper than the pair of casts.
8627 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8628 // Get the sizes of the types involved. We know that the intermediate type
8629 // will be smaller than A or C, but don't know the relation between A and C.
8630 Value *A = CSrc->getOperand(0);
8631 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8632 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8633 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8634 // If we're actually extending zero bits, then if
8635 // SrcSize < DstSize: zext(a & mask)
8636 // SrcSize == DstSize: a & mask
8637 // SrcSize > DstSize: trunc(a) & mask
8638 if (SrcSize < DstSize) {
8639 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8640 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8642 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8643 InsertNewInstBefore(And, CI);
8644 return new ZExtInst(And, CI.getType());
8645 } else if (SrcSize == DstSize) {
8646 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8647 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8649 } else if (SrcSize > DstSize) {
8650 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8651 InsertNewInstBefore(Trunc, CI);
8652 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8653 return BinaryOperator::CreateAnd(Trunc,
8654 ConstantInt::get(Trunc->getType(),
8659 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8660 return transformZExtICmp(ICI, CI);
8662 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8663 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8664 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8665 // of the (zext icmp) will be transformed.
8666 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8667 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8668 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8669 (transformZExtICmp(LHS, CI, false) ||
8670 transformZExtICmp(RHS, CI, false))) {
8671 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8672 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8673 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8677 // zext(trunc(t) & C) -> (t & zext(C)).
8678 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8679 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8680 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8681 Value *TI0 = TI->getOperand(0);
8682 if (TI0->getType() == CI.getType())
8684 BinaryOperator::CreateAnd(TI0,
8685 ConstantExpr::getZExt(C, CI.getType()));
8688 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8689 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8690 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8691 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8692 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8693 And->getOperand(1) == C)
8694 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8695 Value *TI0 = TI->getOperand(0);
8696 if (TI0->getType() == CI.getType()) {
8697 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8698 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8699 InsertNewInstBefore(NewAnd, *And);
8700 return BinaryOperator::CreateXor(NewAnd, ZC);
8707 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8708 if (Instruction *I = commonIntCastTransforms(CI))
8711 Value *Src = CI.getOperand(0);
8713 // Canonicalize sign-extend from i1 to a select.
8714 if (Src->getType() == Type::getInt1Ty(*Context))
8715 return SelectInst::Create(Src,
8716 Constant::getAllOnesValue(CI.getType()),
8717 Constant::getNullValue(CI.getType()));
8719 // See if the value being truncated is already sign extended. If so, just
8720 // eliminate the trunc/sext pair.
8721 if (Operator::getOpcode(Src) == Instruction::Trunc) {
8722 Value *Op = cast<User>(Src)->getOperand(0);
8723 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8724 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8725 unsigned DestBits = CI.getType()->getScalarSizeInBits();
8726 unsigned NumSignBits = ComputeNumSignBits(Op);
8728 if (OpBits == DestBits) {
8729 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8730 // bits, it is already ready.
8731 if (NumSignBits > DestBits-MidBits)
8732 return ReplaceInstUsesWith(CI, Op);
8733 } else if (OpBits < DestBits) {
8734 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8735 // bits, just sext from i32.
8736 if (NumSignBits > OpBits-MidBits)
8737 return new SExtInst(Op, CI.getType(), "tmp");
8739 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8740 // bits, just truncate to i32.
8741 if (NumSignBits > OpBits-MidBits)
8742 return new TruncInst(Op, CI.getType(), "tmp");
8746 // If the input is a shl/ashr pair of a same constant, then this is a sign
8747 // extension from a smaller value. If we could trust arbitrary bitwidth
8748 // integers, we could turn this into a truncate to the smaller bit and then
8749 // use a sext for the whole extension. Since we don't, look deeper and check
8750 // for a truncate. If the source and dest are the same type, eliminate the
8751 // trunc and extend and just do shifts. For example, turn:
8752 // %a = trunc i32 %i to i8
8753 // %b = shl i8 %a, 6
8754 // %c = ashr i8 %b, 6
8755 // %d = sext i8 %c to i32
8757 // %a = shl i32 %i, 30
8758 // %d = ashr i32 %a, 30
8760 ConstantInt *BA = 0, *CA = 0;
8761 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8762 m_ConstantInt(CA))) &&
8763 BA == CA && isa<TruncInst>(A)) {
8764 Value *I = cast<TruncInst>(A)->getOperand(0);
8765 if (I->getType() == CI.getType()) {
8766 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8767 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8768 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8769 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8770 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8772 return BinaryOperator::CreateAShr(I, ShAmtV);
8779 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8780 /// in the specified FP type without changing its value.
8781 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8782 LLVMContext *Context) {
8784 APFloat F = CFP->getValueAPF();
8785 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8787 return ConstantFP::get(*Context, F);
8791 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8792 /// through it until we get the source value.
8793 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8794 if (Instruction *I = dyn_cast<Instruction>(V))
8795 if (I->getOpcode() == Instruction::FPExt)
8796 return LookThroughFPExtensions(I->getOperand(0), Context);
8798 // If this value is a constant, return the constant in the smallest FP type
8799 // that can accurately represent it. This allows us to turn
8800 // (float)((double)X+2.0) into x+2.0f.
8801 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8802 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8803 return V; // No constant folding of this.
8804 // See if the value can be truncated to float and then reextended.
8805 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8807 if (CFP->getType() == Type::getDoubleTy(*Context))
8808 return V; // Won't shrink.
8809 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8811 // Don't try to shrink to various long double types.
8817 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8818 if (Instruction *I = commonCastTransforms(CI))
8821 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8822 // smaller than the destination type, we can eliminate the truncate by doing
8823 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
8824 // many builtins (sqrt, etc).
8825 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8826 if (OpI && OpI->hasOneUse()) {
8827 switch (OpI->getOpcode()) {
8829 case Instruction::FAdd:
8830 case Instruction::FSub:
8831 case Instruction::FMul:
8832 case Instruction::FDiv:
8833 case Instruction::FRem:
8834 const Type *SrcTy = OpI->getType();
8835 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8836 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8837 if (LHSTrunc->getType() != SrcTy &&
8838 RHSTrunc->getType() != SrcTy) {
8839 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8840 // If the source types were both smaller than the destination type of
8841 // the cast, do this xform.
8842 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8843 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8844 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8846 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8848 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8857 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8858 return commonCastTransforms(CI);
8861 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8862 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8864 return commonCastTransforms(FI);
8866 // fptoui(uitofp(X)) --> X
8867 // fptoui(sitofp(X)) --> X
8868 // This is safe if the intermediate type has enough bits in its mantissa to
8869 // accurately represent all values of X. For example, do not do this with
8870 // i64->float->i64. This is also safe for sitofp case, because any negative
8871 // 'X' value would cause an undefined result for the fptoui.
8872 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8873 OpI->getOperand(0)->getType() == FI.getType() &&
8874 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8875 OpI->getType()->getFPMantissaWidth())
8876 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8878 return commonCastTransforms(FI);
8881 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8882 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8884 return commonCastTransforms(FI);
8886 // fptosi(sitofp(X)) --> X
8887 // fptosi(uitofp(X)) --> X
8888 // This is safe if the intermediate type has enough bits in its mantissa to
8889 // accurately represent all values of X. For example, do not do this with
8890 // i64->float->i64. This is also safe for sitofp case, because any negative
8891 // 'X' value would cause an undefined result for the fptoui.
8892 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8893 OpI->getOperand(0)->getType() == FI.getType() &&
8894 (int)FI.getType()->getScalarSizeInBits() <=
8895 OpI->getType()->getFPMantissaWidth())
8896 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8898 return commonCastTransforms(FI);
8901 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8902 return commonCastTransforms(CI);
8905 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8906 return commonCastTransforms(CI);
8909 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8910 // If the destination integer type is smaller than the intptr_t type for
8911 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8912 // trunc to be exposed to other transforms. Don't do this for extending
8913 // ptrtoint's, because we don't know if the target sign or zero extends its
8916 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8917 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8918 TD->getIntPtrType(CI.getContext()),
8920 return new TruncInst(P, CI.getType());
8923 return commonPointerCastTransforms(CI);
8926 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8927 // If the source integer type is larger than the intptr_t type for
8928 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8929 // allows the trunc to be exposed to other transforms. Don't do this for
8930 // extending inttoptr's, because we don't know if the target sign or zero
8931 // extends to pointers.
8933 CI.getOperand(0)->getType()->getScalarSizeInBits() >
8934 TD->getPointerSizeInBits()) {
8935 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8936 TD->getIntPtrType(CI.getContext()),
8938 return new IntToPtrInst(P, CI.getType());
8941 if (Instruction *I = commonCastTransforms(CI))
8947 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8948 // If the operands are integer typed then apply the integer transforms,
8949 // otherwise just apply the common ones.
8950 Value *Src = CI.getOperand(0);
8951 const Type *SrcTy = Src->getType();
8952 const Type *DestTy = CI.getType();
8954 if (isa<PointerType>(SrcTy)) {
8955 if (Instruction *I = commonPointerCastTransforms(CI))
8958 if (Instruction *Result = commonCastTransforms(CI))
8963 // Get rid of casts from one type to the same type. These are useless and can
8964 // be replaced by the operand.
8965 if (DestTy == Src->getType())
8966 return ReplaceInstUsesWith(CI, Src);
8968 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8969 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8970 const Type *DstElTy = DstPTy->getElementType();
8971 const Type *SrcElTy = SrcPTy->getElementType();
8973 // If the address spaces don't match, don't eliminate the bitcast, which is
8974 // required for changing types.
8975 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8978 // If we are casting a malloc or alloca to a pointer to a type of the same
8979 // size, rewrite the allocation instruction to allocate the "right" type.
8980 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8981 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8984 // If the source and destination are pointers, and this cast is equivalent
8985 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8986 // This can enhance SROA and other transforms that want type-safe pointers.
8987 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8988 unsigned NumZeros = 0;
8989 while (SrcElTy != DstElTy &&
8990 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8991 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8992 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8996 // If we found a path from the src to dest, create the getelementptr now.
8997 if (SrcElTy == DstElTy) {
8998 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8999 Instruction *GEP = GetElementPtrInst::Create(Src,
9000 Idxs.begin(), Idxs.end(), "",
9001 ((Instruction*) NULL));
9002 cast<GEPOperator>(GEP)->setIsInBounds(true);
9007 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9008 if (DestVTy->getNumElements() == 1) {
9009 if (!isa<VectorType>(SrcTy)) {
9010 Value *Elem = InsertCastBefore(Instruction::BitCast, Src,
9011 DestVTy->getElementType(), CI);
9012 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
9013 Constant::getNullValue(Type::getInt32Ty(*Context)));
9015 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9019 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9020 if (SrcVTy->getNumElements() == 1) {
9021 if (!isa<VectorType>(DestTy)) {
9023 ExtractElementInst::Create(Src, Constant::getNullValue(Type::getInt32Ty(*Context)));
9024 InsertNewInstBefore(Elem, CI);
9025 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9030 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9031 if (SVI->hasOneUse()) {
9032 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9033 // a bitconvert to a vector with the same # elts.
9034 if (isa<VectorType>(DestTy) &&
9035 cast<VectorType>(DestTy)->getNumElements() ==
9036 SVI->getType()->getNumElements() &&
9037 SVI->getType()->getNumElements() ==
9038 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9040 // If either of the operands is a cast from CI.getType(), then
9041 // evaluating the shuffle in the casted destination's type will allow
9042 // us to eliminate at least one cast.
9043 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9044 Tmp->getOperand(0)->getType() == DestTy) ||
9045 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9046 Tmp->getOperand(0)->getType() == DestTy)) {
9047 Value *LHS = InsertCastBefore(Instruction::BitCast,
9048 SVI->getOperand(0), DestTy, CI);
9049 Value *RHS = InsertCastBefore(Instruction::BitCast,
9050 SVI->getOperand(1), DestTy, CI);
9051 // Return a new shuffle vector. Use the same element ID's, as we
9052 // know the vector types match #elts.
9053 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9061 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9063 /// %D = select %cond, %C, %A
9065 /// %C = select %cond, %B, 0
9068 /// Assuming that the specified instruction is an operand to the select, return
9069 /// a bitmask indicating which operands of this instruction are foldable if they
9070 /// equal the other incoming value of the select.
9072 static unsigned GetSelectFoldableOperands(Instruction *I) {
9073 switch (I->getOpcode()) {
9074 case Instruction::Add:
9075 case Instruction::Mul:
9076 case Instruction::And:
9077 case Instruction::Or:
9078 case Instruction::Xor:
9079 return 3; // Can fold through either operand.
9080 case Instruction::Sub: // Can only fold on the amount subtracted.
9081 case Instruction::Shl: // Can only fold on the shift amount.
9082 case Instruction::LShr:
9083 case Instruction::AShr:
9086 return 0; // Cannot fold
9090 /// GetSelectFoldableConstant - For the same transformation as the previous
9091 /// function, return the identity constant that goes into the select.
9092 static Constant *GetSelectFoldableConstant(Instruction *I,
9093 LLVMContext *Context) {
9094 switch (I->getOpcode()) {
9095 default: llvm_unreachable("This cannot happen!");
9096 case Instruction::Add:
9097 case Instruction::Sub:
9098 case Instruction::Or:
9099 case Instruction::Xor:
9100 case Instruction::Shl:
9101 case Instruction::LShr:
9102 case Instruction::AShr:
9103 return Constant::getNullValue(I->getType());
9104 case Instruction::And:
9105 return Constant::getAllOnesValue(I->getType());
9106 case Instruction::Mul:
9107 return ConstantInt::get(I->getType(), 1);
9111 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9112 /// have the same opcode and only one use each. Try to simplify this.
9113 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9115 if (TI->getNumOperands() == 1) {
9116 // If this is a non-volatile load or a cast from the same type,
9119 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9122 return 0; // unknown unary op.
9125 // Fold this by inserting a select from the input values.
9126 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9127 FI->getOperand(0), SI.getName()+".v");
9128 InsertNewInstBefore(NewSI, SI);
9129 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
9133 // Only handle binary operators here.
9134 if (!isa<BinaryOperator>(TI))
9137 // Figure out if the operations have any operands in common.
9138 Value *MatchOp, *OtherOpT, *OtherOpF;
9140 if (TI->getOperand(0) == FI->getOperand(0)) {
9141 MatchOp = TI->getOperand(0);
9142 OtherOpT = TI->getOperand(1);
9143 OtherOpF = FI->getOperand(1);
9144 MatchIsOpZero = true;
9145 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9146 MatchOp = TI->getOperand(1);
9147 OtherOpT = TI->getOperand(0);
9148 OtherOpF = FI->getOperand(0);
9149 MatchIsOpZero = false;
9150 } else if (!TI->isCommutative()) {
9152 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9153 MatchOp = TI->getOperand(0);
9154 OtherOpT = TI->getOperand(1);
9155 OtherOpF = FI->getOperand(0);
9156 MatchIsOpZero = true;
9157 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9158 MatchOp = TI->getOperand(1);
9159 OtherOpT = TI->getOperand(0);
9160 OtherOpF = FI->getOperand(1);
9161 MatchIsOpZero = true;
9166 // If we reach here, they do have operations in common.
9167 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9168 OtherOpF, SI.getName()+".v");
9169 InsertNewInstBefore(NewSI, SI);
9171 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9173 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9175 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9177 llvm_unreachable("Shouldn't get here");
9181 static bool isSelect01(Constant *C1, Constant *C2) {
9182 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9185 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9188 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9191 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9192 /// facilitate further optimization.
9193 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9195 // See the comment above GetSelectFoldableOperands for a description of the
9196 // transformation we are doing here.
9197 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9198 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9199 !isa<Constant>(FalseVal)) {
9200 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9201 unsigned OpToFold = 0;
9202 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9204 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9209 Constant *C = GetSelectFoldableConstant(TVI, Context);
9210 Value *OOp = TVI->getOperand(2-OpToFold);
9211 // Avoid creating select between 2 constants unless it's selecting
9213 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9214 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9215 InsertNewInstBefore(NewSel, SI);
9216 NewSel->takeName(TVI);
9217 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9218 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9219 llvm_unreachable("Unknown instruction!!");
9226 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9227 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9228 !isa<Constant>(TrueVal)) {
9229 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9230 unsigned OpToFold = 0;
9231 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9233 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9238 Constant *C = GetSelectFoldableConstant(FVI, Context);
9239 Value *OOp = FVI->getOperand(2-OpToFold);
9240 // Avoid creating select between 2 constants unless it's selecting
9242 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9243 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9244 InsertNewInstBefore(NewSel, SI);
9245 NewSel->takeName(FVI);
9246 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9247 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9248 llvm_unreachable("Unknown instruction!!");
9258 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9259 /// ICmpInst as its first operand.
9261 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9263 bool Changed = false;
9264 ICmpInst::Predicate Pred = ICI->getPredicate();
9265 Value *CmpLHS = ICI->getOperand(0);
9266 Value *CmpRHS = ICI->getOperand(1);
9267 Value *TrueVal = SI.getTrueValue();
9268 Value *FalseVal = SI.getFalseValue();
9270 // Check cases where the comparison is with a constant that
9271 // can be adjusted to fit the min/max idiom. We may edit ICI in
9272 // place here, so make sure the select is the only user.
9273 if (ICI->hasOneUse())
9274 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9277 case ICmpInst::ICMP_ULT:
9278 case ICmpInst::ICMP_SLT: {
9279 // X < MIN ? T : F --> F
9280 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9281 return ReplaceInstUsesWith(SI, FalseVal);
9282 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
9283 Constant *AdjustedRHS = SubOne(CI);
9284 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9285 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9286 Pred = ICmpInst::getSwappedPredicate(Pred);
9287 CmpRHS = AdjustedRHS;
9288 std::swap(FalseVal, TrueVal);
9289 ICI->setPredicate(Pred);
9290 ICI->setOperand(1, CmpRHS);
9291 SI.setOperand(1, TrueVal);
9292 SI.setOperand(2, FalseVal);
9297 case ICmpInst::ICMP_UGT:
9298 case ICmpInst::ICMP_SGT: {
9299 // X > MAX ? T : F --> F
9300 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9301 return ReplaceInstUsesWith(SI, FalseVal);
9302 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
9303 Constant *AdjustedRHS = AddOne(CI);
9304 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9305 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9306 Pred = ICmpInst::getSwappedPredicate(Pred);
9307 CmpRHS = AdjustedRHS;
9308 std::swap(FalseVal, TrueVal);
9309 ICI->setPredicate(Pred);
9310 ICI->setOperand(1, CmpRHS);
9311 SI.setOperand(1, TrueVal);
9312 SI.setOperand(2, FalseVal);
9319 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9320 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
9321 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9322 if (match(TrueVal, m_ConstantInt<-1>()) &&
9323 match(FalseVal, m_ConstantInt<0>()))
9324 Pred = ICI->getPredicate();
9325 else if (match(TrueVal, m_ConstantInt<0>()) &&
9326 match(FalseVal, m_ConstantInt<-1>()))
9327 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9329 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9330 // If we are just checking for a icmp eq of a single bit and zext'ing it
9331 // to an integer, then shift the bit to the appropriate place and then
9332 // cast to integer to avoid the comparison.
9333 const APInt &Op1CV = CI->getValue();
9335 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9336 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9337 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9338 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9339 Value *In = ICI->getOperand(0);
9340 Value *Sh = ConstantInt::get(In->getType(),
9341 In->getType()->getScalarSizeInBits()-1);
9342 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9343 In->getName()+".lobit"),
9345 if (In->getType() != SI.getType())
9346 In = CastInst::CreateIntegerCast(In, SI.getType(),
9347 true/*SExt*/, "tmp", ICI);
9349 if (Pred == ICmpInst::ICMP_SGT)
9350 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9351 In->getName()+".not"), *ICI);
9353 return ReplaceInstUsesWith(SI, In);
9358 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9359 // Transform (X == Y) ? X : Y -> Y
9360 if (Pred == ICmpInst::ICMP_EQ)
9361 return ReplaceInstUsesWith(SI, FalseVal);
9362 // Transform (X != Y) ? X : Y -> X
9363 if (Pred == ICmpInst::ICMP_NE)
9364 return ReplaceInstUsesWith(SI, TrueVal);
9365 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9367 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9368 // Transform (X == Y) ? Y : X -> X
9369 if (Pred == ICmpInst::ICMP_EQ)
9370 return ReplaceInstUsesWith(SI, FalseVal);
9371 // Transform (X != Y) ? Y : X -> Y
9372 if (Pred == ICmpInst::ICMP_NE)
9373 return ReplaceInstUsesWith(SI, TrueVal);
9374 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9377 /// NOTE: if we wanted to, this is where to detect integer ABS
9379 return Changed ? &SI : 0;
9382 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9383 Value *CondVal = SI.getCondition();
9384 Value *TrueVal = SI.getTrueValue();
9385 Value *FalseVal = SI.getFalseValue();
9387 // select true, X, Y -> X
9388 // select false, X, Y -> Y
9389 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9390 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9392 // select C, X, X -> X
9393 if (TrueVal == FalseVal)
9394 return ReplaceInstUsesWith(SI, TrueVal);
9396 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9397 return ReplaceInstUsesWith(SI, FalseVal);
9398 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9399 return ReplaceInstUsesWith(SI, TrueVal);
9400 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9401 if (isa<Constant>(TrueVal))
9402 return ReplaceInstUsesWith(SI, TrueVal);
9404 return ReplaceInstUsesWith(SI, FalseVal);
9407 if (SI.getType() == Type::getInt1Ty(*Context)) {
9408 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9409 if (C->getZExtValue()) {
9410 // Change: A = select B, true, C --> A = or B, C
9411 return BinaryOperator::CreateOr(CondVal, FalseVal);
9413 // Change: A = select B, false, C --> A = and !B, C
9415 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9416 "not."+CondVal->getName()), SI);
9417 return BinaryOperator::CreateAnd(NotCond, FalseVal);
9419 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9420 if (C->getZExtValue() == false) {
9421 // Change: A = select B, C, false --> A = and B, C
9422 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9424 // Change: A = select B, C, true --> A = or !B, C
9426 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9427 "not."+CondVal->getName()), SI);
9428 return BinaryOperator::CreateOr(NotCond, TrueVal);
9432 // select a, b, a -> a&b
9433 // select a, a, b -> a|b
9434 if (CondVal == TrueVal)
9435 return BinaryOperator::CreateOr(CondVal, FalseVal);
9436 else if (CondVal == FalseVal)
9437 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9440 // Selecting between two integer constants?
9441 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9442 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9443 // select C, 1, 0 -> zext C to int
9444 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9445 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9446 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9447 // select C, 0, 1 -> zext !C to int
9449 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9450 "not."+CondVal->getName()), SI);
9451 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9454 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9455 // If one of the constants is zero (we know they can't both be) and we
9456 // have an icmp instruction with zero, and we have an 'and' with the
9457 // non-constant value, eliminate this whole mess. This corresponds to
9458 // cases like this: ((X & 27) ? 27 : 0)
9459 if (TrueValC->isZero() || FalseValC->isZero())
9460 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9461 cast<Constant>(IC->getOperand(1))->isNullValue())
9462 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9463 if (ICA->getOpcode() == Instruction::And &&
9464 isa<ConstantInt>(ICA->getOperand(1)) &&
9465 (ICA->getOperand(1) == TrueValC ||
9466 ICA->getOperand(1) == FalseValC) &&
9467 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9468 // Okay, now we know that everything is set up, we just don't
9469 // know whether we have a icmp_ne or icmp_eq and whether the
9470 // true or false val is the zero.
9471 bool ShouldNotVal = !TrueValC->isZero();
9472 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9475 V = InsertNewInstBefore(BinaryOperator::Create(
9476 Instruction::Xor, V, ICA->getOperand(1)), SI);
9477 return ReplaceInstUsesWith(SI, V);
9482 // See if we are selecting two values based on a comparison of the two values.
9483 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9484 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9485 // Transform (X == Y) ? X : Y -> Y
9486 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9487 // This is not safe in general for floating point:
9488 // consider X== -0, Y== +0.
9489 // It becomes safe if either operand is a nonzero constant.
9490 ConstantFP *CFPt, *CFPf;
9491 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9492 !CFPt->getValueAPF().isZero()) ||
9493 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9494 !CFPf->getValueAPF().isZero()))
9495 return ReplaceInstUsesWith(SI, FalseVal);
9497 // Transform (X != Y) ? X : Y -> X
9498 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9499 return ReplaceInstUsesWith(SI, TrueVal);
9500 // NOTE: if we wanted to, this is where to detect MIN/MAX
9502 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9503 // Transform (X == Y) ? Y : X -> X
9504 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9505 // This is not safe in general for floating point:
9506 // consider X== -0, Y== +0.
9507 // It becomes safe if either operand is a nonzero constant.
9508 ConstantFP *CFPt, *CFPf;
9509 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9510 !CFPt->getValueAPF().isZero()) ||
9511 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9512 !CFPf->getValueAPF().isZero()))
9513 return ReplaceInstUsesWith(SI, FalseVal);
9515 // Transform (X != Y) ? Y : X -> Y
9516 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9517 return ReplaceInstUsesWith(SI, TrueVal);
9518 // NOTE: if we wanted to, this is where to detect MIN/MAX
9520 // NOTE: if we wanted to, this is where to detect ABS
9523 // See if we are selecting two values based on a comparison of the two values.
9524 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9525 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9528 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9529 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9530 if (TI->hasOneUse() && FI->hasOneUse()) {
9531 Instruction *AddOp = 0, *SubOp = 0;
9533 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9534 if (TI->getOpcode() == FI->getOpcode())
9535 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9538 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9539 // even legal for FP.
9540 if ((TI->getOpcode() == Instruction::Sub &&
9541 FI->getOpcode() == Instruction::Add) ||
9542 (TI->getOpcode() == Instruction::FSub &&
9543 FI->getOpcode() == Instruction::FAdd)) {
9544 AddOp = FI; SubOp = TI;
9545 } else if ((FI->getOpcode() == Instruction::Sub &&
9546 TI->getOpcode() == Instruction::Add) ||
9547 (FI->getOpcode() == Instruction::FSub &&
9548 TI->getOpcode() == Instruction::FAdd)) {
9549 AddOp = TI; SubOp = FI;
9553 Value *OtherAddOp = 0;
9554 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9555 OtherAddOp = AddOp->getOperand(1);
9556 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9557 OtherAddOp = AddOp->getOperand(0);
9561 // So at this point we know we have (Y -> OtherAddOp):
9562 // select C, (add X, Y), (sub X, Z)
9563 Value *NegVal; // Compute -Z
9564 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9565 NegVal = ConstantExpr::getNeg(C);
9567 NegVal = InsertNewInstBefore(
9568 BinaryOperator::CreateNeg(SubOp->getOperand(1),
9572 Value *NewTrueOp = OtherAddOp;
9573 Value *NewFalseOp = NegVal;
9575 std::swap(NewTrueOp, NewFalseOp);
9576 Instruction *NewSel =
9577 SelectInst::Create(CondVal, NewTrueOp,
9578 NewFalseOp, SI.getName() + ".p");
9580 NewSel = InsertNewInstBefore(NewSel, SI);
9581 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9586 // See if we can fold the select into one of our operands.
9587 if (SI.getType()->isInteger()) {
9588 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9593 if (BinaryOperator::isNot(CondVal)) {
9594 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9595 SI.setOperand(1, FalseVal);
9596 SI.setOperand(2, TrueVal);
9603 /// EnforceKnownAlignment - If the specified pointer points to an object that
9604 /// we control, modify the object's alignment to PrefAlign. This isn't
9605 /// often possible though. If alignment is important, a more reliable approach
9606 /// is to simply align all global variables and allocation instructions to
9607 /// their preferred alignment from the beginning.
9609 static unsigned EnforceKnownAlignment(Value *V,
9610 unsigned Align, unsigned PrefAlign) {
9612 User *U = dyn_cast<User>(V);
9613 if (!U) return Align;
9615 switch (Operator::getOpcode(U)) {
9617 case Instruction::BitCast:
9618 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9619 case Instruction::GetElementPtr: {
9620 // If all indexes are zero, it is just the alignment of the base pointer.
9621 bool AllZeroOperands = true;
9622 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9623 if (!isa<Constant>(*i) ||
9624 !cast<Constant>(*i)->isNullValue()) {
9625 AllZeroOperands = false;
9629 if (AllZeroOperands) {
9630 // Treat this like a bitcast.
9631 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9637 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9638 // If there is a large requested alignment and we can, bump up the alignment
9640 if (!GV->isDeclaration()) {
9641 if (GV->getAlignment() >= PrefAlign)
9642 Align = GV->getAlignment();
9644 GV->setAlignment(PrefAlign);
9648 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9649 // If there is a requested alignment and if this is an alloca, round up. We
9650 // don't do this for malloc, because some systems can't respect the request.
9651 if (isa<AllocaInst>(AI)) {
9652 if (AI->getAlignment() >= PrefAlign)
9653 Align = AI->getAlignment();
9655 AI->setAlignment(PrefAlign);
9664 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9665 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9666 /// and it is more than the alignment of the ultimate object, see if we can
9667 /// increase the alignment of the ultimate object, making this check succeed.
9668 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9669 unsigned PrefAlign) {
9670 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9671 sizeof(PrefAlign) * CHAR_BIT;
9672 APInt Mask = APInt::getAllOnesValue(BitWidth);
9673 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9674 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9675 unsigned TrailZ = KnownZero.countTrailingOnes();
9676 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9678 if (PrefAlign > Align)
9679 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9681 // We don't need to make any adjustment.
9685 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9686 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9687 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9688 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9689 unsigned CopyAlign = MI->getAlignment();
9691 if (CopyAlign < MinAlign) {
9692 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9697 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9699 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9700 if (MemOpLength == 0) return 0;
9702 // Source and destination pointer types are always "i8*" for intrinsic. See
9703 // if the size is something we can handle with a single primitive load/store.
9704 // A single load+store correctly handles overlapping memory in the memmove
9706 unsigned Size = MemOpLength->getZExtValue();
9707 if (Size == 0) return MI; // Delete this mem transfer.
9709 if (Size > 8 || (Size&(Size-1)))
9710 return 0; // If not 1/2/4/8 bytes, exit.
9712 // Use an integer load+store unless we can find something better.
9714 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9716 // Memcpy forces the use of i8* for the source and destination. That means
9717 // that if you're using memcpy to move one double around, you'll get a cast
9718 // from double* to i8*. We'd much rather use a double load+store rather than
9719 // an i64 load+store, here because this improves the odds that the source or
9720 // dest address will be promotable. See if we can find a better type than the
9721 // integer datatype.
9722 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9723 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9724 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9725 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9726 // down through these levels if so.
9727 while (!SrcETy->isSingleValueType()) {
9728 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9729 if (STy->getNumElements() == 1)
9730 SrcETy = STy->getElementType(0);
9733 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9734 if (ATy->getNumElements() == 1)
9735 SrcETy = ATy->getElementType();
9742 if (SrcETy->isSingleValueType())
9743 NewPtrTy = PointerType::getUnqual(SrcETy);
9748 // If the memcpy/memmove provides better alignment info than we can
9750 SrcAlign = std::max(SrcAlign, CopyAlign);
9751 DstAlign = std::max(DstAlign, CopyAlign);
9753 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9754 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9755 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9756 InsertNewInstBefore(L, *MI);
9757 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9759 // Set the size of the copy to 0, it will be deleted on the next iteration.
9760 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9764 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9765 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9766 if (MI->getAlignment() < Alignment) {
9767 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9772 // Extract the length and alignment and fill if they are constant.
9773 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9774 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9775 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9777 uint64_t Len = LenC->getZExtValue();
9778 Alignment = MI->getAlignment();
9780 // If the length is zero, this is a no-op
9781 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9783 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9784 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9785 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
9787 Value *Dest = MI->getDest();
9788 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9790 // Alignment 0 is identity for alignment 1 for memset, but not store.
9791 if (Alignment == 0) Alignment = 1;
9793 // Extract the fill value and store.
9794 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9795 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9796 Dest, false, Alignment), *MI);
9798 // Set the size of the copy to 0, it will be deleted on the next iteration.
9799 MI->setLength(Constant::getNullValue(LenC->getType()));
9807 /// visitCallInst - CallInst simplification. This mostly only handles folding
9808 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9809 /// the heavy lifting.
9811 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9812 // If the caller function is nounwind, mark the call as nounwind, even if the
9814 if (CI.getParent()->getParent()->doesNotThrow() &&
9815 !CI.doesNotThrow()) {
9816 CI.setDoesNotThrow();
9822 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9823 if (!II) return visitCallSite(&CI);
9825 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9827 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9828 bool Changed = false;
9830 // memmove/cpy/set of zero bytes is a noop.
9831 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9832 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9834 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9835 if (CI->getZExtValue() == 1) {
9836 // Replace the instruction with just byte operations. We would
9837 // transform other cases to loads/stores, but we don't know if
9838 // alignment is sufficient.
9842 // If we have a memmove and the source operation is a constant global,
9843 // then the source and dest pointers can't alias, so we can change this
9844 // into a call to memcpy.
9845 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9846 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9847 if (GVSrc->isConstant()) {
9848 Module *M = CI.getParent()->getParent()->getParent();
9849 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9851 Tys[0] = CI.getOperand(3)->getType();
9853 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9857 // memmove(x,x,size) -> noop.
9858 if (MMI->getSource() == MMI->getDest())
9859 return EraseInstFromFunction(CI);
9862 // If we can determine a pointer alignment that is bigger than currently
9863 // set, update the alignment.
9864 if (isa<MemTransferInst>(MI)) {
9865 if (Instruction *I = SimplifyMemTransfer(MI))
9867 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9868 if (Instruction *I = SimplifyMemSet(MSI))
9872 if (Changed) return II;
9875 switch (II->getIntrinsicID()) {
9877 case Intrinsic::bswap:
9878 // bswap(bswap(x)) -> x
9879 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9880 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9881 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9883 case Intrinsic::ppc_altivec_lvx:
9884 case Intrinsic::ppc_altivec_lvxl:
9885 case Intrinsic::x86_sse_loadu_ps:
9886 case Intrinsic::x86_sse2_loadu_pd:
9887 case Intrinsic::x86_sse2_loadu_dq:
9888 // Turn PPC lvx -> load if the pointer is known aligned.
9889 // Turn X86 loadups -> load if the pointer is known aligned.
9890 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9891 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9892 PointerType::getUnqual(II->getType()),
9894 return new LoadInst(Ptr);
9897 case Intrinsic::ppc_altivec_stvx:
9898 case Intrinsic::ppc_altivec_stvxl:
9899 // Turn stvx -> store if the pointer is known aligned.
9900 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9901 const Type *OpPtrTy =
9902 PointerType::getUnqual(II->getOperand(1)->getType());
9903 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9904 return new StoreInst(II->getOperand(1), Ptr);
9907 case Intrinsic::x86_sse_storeu_ps:
9908 case Intrinsic::x86_sse2_storeu_pd:
9909 case Intrinsic::x86_sse2_storeu_dq:
9910 // Turn X86 storeu -> store if the pointer is known aligned.
9911 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9912 const Type *OpPtrTy =
9913 PointerType::getUnqual(II->getOperand(2)->getType());
9914 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9915 return new StoreInst(II->getOperand(2), Ptr);
9919 case Intrinsic::x86_sse_cvttss2si: {
9920 // These intrinsics only demands the 0th element of its input vector. If
9921 // we can simplify the input based on that, do so now.
9923 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9924 APInt DemandedElts(VWidth, 1);
9925 APInt UndefElts(VWidth, 0);
9926 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9928 II->setOperand(1, V);
9934 case Intrinsic::ppc_altivec_vperm:
9935 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9936 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9937 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9939 // Check that all of the elements are integer constants or undefs.
9940 bool AllEltsOk = true;
9941 for (unsigned i = 0; i != 16; ++i) {
9942 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9943 !isa<UndefValue>(Mask->getOperand(i))) {
9950 // Cast the input vectors to byte vectors.
9951 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9952 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9953 Value *Result = UndefValue::get(Op0->getType());
9955 // Only extract each element once.
9956 Value *ExtractedElts[32];
9957 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9959 for (unsigned i = 0; i != 16; ++i) {
9960 if (isa<UndefValue>(Mask->getOperand(i)))
9962 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9963 Idx &= 31; // Match the hardware behavior.
9965 if (ExtractedElts[Idx] == 0) {
9967 ExtractElementInst::Create(Idx < 16 ? Op0 : Op1,
9968 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false), "tmp");
9969 InsertNewInstBefore(Elt, CI);
9970 ExtractedElts[Idx] = Elt;
9973 // Insert this value into the result vector.
9974 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9975 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9977 InsertNewInstBefore(cast<Instruction>(Result), CI);
9979 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9984 case Intrinsic::stackrestore: {
9985 // If the save is right next to the restore, remove the restore. This can
9986 // happen when variable allocas are DCE'd.
9987 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9988 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9989 BasicBlock::iterator BI = SS;
9991 return EraseInstFromFunction(CI);
9995 // Scan down this block to see if there is another stack restore in the
9996 // same block without an intervening call/alloca.
9997 BasicBlock::iterator BI = II;
9998 TerminatorInst *TI = II->getParent()->getTerminator();
9999 bool CannotRemove = false;
10000 for (++BI; &*BI != TI; ++BI) {
10001 if (isa<AllocaInst>(BI)) {
10002 CannotRemove = true;
10005 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10006 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10007 // If there is a stackrestore below this one, remove this one.
10008 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10009 return EraseInstFromFunction(CI);
10010 // Otherwise, ignore the intrinsic.
10012 // If we found a non-intrinsic call, we can't remove the stack
10014 CannotRemove = true;
10020 // If the stack restore is in a return/unwind block and if there are no
10021 // allocas or calls between the restore and the return, nuke the restore.
10022 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10023 return EraseInstFromFunction(CI);
10028 return visitCallSite(II);
10031 // InvokeInst simplification
10033 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10034 return visitCallSite(&II);
10037 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
10038 /// passed through the varargs area, we can eliminate the use of the cast.
10039 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10040 const CastInst * const CI,
10041 const TargetData * const TD,
10043 if (!CI->isLosslessCast())
10046 // The size of ByVal arguments is derived from the type, so we
10047 // can't change to a type with a different size. If the size were
10048 // passed explicitly we could avoid this check.
10049 if (!CS.paramHasAttr(ix, Attribute::ByVal))
10052 const Type* SrcTy =
10053 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10054 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10055 if (!SrcTy->isSized() || !DstTy->isSized())
10057 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10062 // visitCallSite - Improvements for call and invoke instructions.
10064 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10065 bool Changed = false;
10067 // If the callee is a constexpr cast of a function, attempt to move the cast
10068 // to the arguments of the call/invoke.
10069 if (transformConstExprCastCall(CS)) return 0;
10071 Value *Callee = CS.getCalledValue();
10073 if (Function *CalleeF = dyn_cast<Function>(Callee))
10074 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10075 Instruction *OldCall = CS.getInstruction();
10076 // If the call and callee calling conventions don't match, this call must
10077 // be unreachable, as the call is undefined.
10078 new StoreInst(ConstantInt::getTrue(*Context),
10079 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
10081 if (!OldCall->use_empty())
10082 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10083 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10084 return EraseInstFromFunction(*OldCall);
10088 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10089 // This instruction is not reachable, just remove it. We insert a store to
10090 // undef so that we know that this code is not reachable, despite the fact
10091 // that we can't modify the CFG here.
10092 new StoreInst(ConstantInt::getTrue(*Context),
10093 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
10094 CS.getInstruction());
10096 if (!CS.getInstruction()->use_empty())
10097 CS.getInstruction()->
10098 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10100 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10101 // Don't break the CFG, insert a dummy cond branch.
10102 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10103 ConstantInt::getTrue(*Context), II);
10105 return EraseInstFromFunction(*CS.getInstruction());
10108 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10109 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10110 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10111 return transformCallThroughTrampoline(CS);
10113 const PointerType *PTy = cast<PointerType>(Callee->getType());
10114 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10115 if (FTy->isVarArg()) {
10116 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10117 // See if we can optimize any arguments passed through the varargs area of
10119 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10120 E = CS.arg_end(); I != E; ++I, ++ix) {
10121 CastInst *CI = dyn_cast<CastInst>(*I);
10122 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10123 *I = CI->getOperand(0);
10129 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10130 // Inline asm calls cannot throw - mark them 'nounwind'.
10131 CS.setDoesNotThrow();
10135 return Changed ? CS.getInstruction() : 0;
10138 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10139 // attempt to move the cast to the arguments of the call/invoke.
10141 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10142 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10143 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10144 if (CE->getOpcode() != Instruction::BitCast ||
10145 !isa<Function>(CE->getOperand(0)))
10147 Function *Callee = cast<Function>(CE->getOperand(0));
10148 Instruction *Caller = CS.getInstruction();
10149 const AttrListPtr &CallerPAL = CS.getAttributes();
10151 // Okay, this is a cast from a function to a different type. Unless doing so
10152 // would cause a type conversion of one of our arguments, change this call to
10153 // be a direct call with arguments casted to the appropriate types.
10155 const FunctionType *FT = Callee->getFunctionType();
10156 const Type *OldRetTy = Caller->getType();
10157 const Type *NewRetTy = FT->getReturnType();
10159 if (isa<StructType>(NewRetTy))
10160 return false; // TODO: Handle multiple return values.
10162 // Check to see if we are changing the return type...
10163 if (OldRetTy != NewRetTy) {
10164 if (Callee->isDeclaration() &&
10165 // Conversion is ok if changing from one pointer type to another or from
10166 // a pointer to an integer of the same size.
10167 !((isa<PointerType>(OldRetTy) || !TD ||
10168 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10169 (isa<PointerType>(NewRetTy) || !TD ||
10170 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10171 return false; // Cannot transform this return value.
10173 if (!Caller->use_empty() &&
10174 // void -> non-void is handled specially
10175 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
10176 return false; // Cannot transform this return value.
10178 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10179 Attributes RAttrs = CallerPAL.getRetAttributes();
10180 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10181 return false; // Attribute not compatible with transformed value.
10184 // If the callsite is an invoke instruction, and the return value is used by
10185 // a PHI node in a successor, we cannot change the return type of the call
10186 // because there is no place to put the cast instruction (without breaking
10187 // the critical edge). Bail out in this case.
10188 if (!Caller->use_empty())
10189 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10190 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10192 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10193 if (PN->getParent() == II->getNormalDest() ||
10194 PN->getParent() == II->getUnwindDest())
10198 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10199 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10201 CallSite::arg_iterator AI = CS.arg_begin();
10202 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10203 const Type *ParamTy = FT->getParamType(i);
10204 const Type *ActTy = (*AI)->getType();
10206 if (!CastInst::isCastable(ActTy, ParamTy))
10207 return false; // Cannot transform this parameter value.
10209 if (CallerPAL.getParamAttributes(i + 1)
10210 & Attribute::typeIncompatible(ParamTy))
10211 return false; // Attribute not compatible with transformed value.
10213 // Converting from one pointer type to another or between a pointer and an
10214 // integer of the same size is safe even if we do not have a body.
10215 bool isConvertible = ActTy == ParamTy ||
10216 (TD && ((isa<PointerType>(ParamTy) ||
10217 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10218 (isa<PointerType>(ActTy) ||
10219 ActTy == TD->getIntPtrType(Caller->getContext()))));
10220 if (Callee->isDeclaration() && !isConvertible) return false;
10223 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10224 Callee->isDeclaration())
10225 return false; // Do not delete arguments unless we have a function body.
10227 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10228 !CallerPAL.isEmpty())
10229 // In this case we have more arguments than the new function type, but we
10230 // won't be dropping them. Check that these extra arguments have attributes
10231 // that are compatible with being a vararg call argument.
10232 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10233 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10235 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10236 if (PAttrs & Attribute::VarArgsIncompatible)
10240 // Okay, we decided that this is a safe thing to do: go ahead and start
10241 // inserting cast instructions as necessary...
10242 std::vector<Value*> Args;
10243 Args.reserve(NumActualArgs);
10244 SmallVector<AttributeWithIndex, 8> attrVec;
10245 attrVec.reserve(NumCommonArgs);
10247 // Get any return attributes.
10248 Attributes RAttrs = CallerPAL.getRetAttributes();
10250 // If the return value is not being used, the type may not be compatible
10251 // with the existing attributes. Wipe out any problematic attributes.
10252 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10254 // Add the new return attributes.
10256 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10258 AI = CS.arg_begin();
10259 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10260 const Type *ParamTy = FT->getParamType(i);
10261 if ((*AI)->getType() == ParamTy) {
10262 Args.push_back(*AI);
10264 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10265 false, ParamTy, false);
10266 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10267 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10270 // Add any parameter attributes.
10271 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10272 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10275 // If the function takes more arguments than the call was taking, add them
10277 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10278 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10280 // If we are removing arguments to the function, emit an obnoxious warning...
10281 if (FT->getNumParams() < NumActualArgs) {
10282 if (!FT->isVarArg()) {
10283 errs() << "WARNING: While resolving call to function '"
10284 << Callee->getName() << "' arguments were dropped!\n";
10286 // Add all of the arguments in their promoted form to the arg list...
10287 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10288 const Type *PTy = getPromotedType((*AI)->getType());
10289 if (PTy != (*AI)->getType()) {
10290 // Must promote to pass through va_arg area!
10291 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10293 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10294 InsertNewInstBefore(Cast, *Caller);
10295 Args.push_back(Cast);
10297 Args.push_back(*AI);
10300 // Add any parameter attributes.
10301 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10302 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10307 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10308 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10310 if (NewRetTy == Type::getVoidTy(*Context))
10311 Caller->setName(""); // Void type should not have a name.
10313 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10317 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10318 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10319 Args.begin(), Args.end(),
10320 Caller->getName(), Caller);
10321 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10322 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10324 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10325 Caller->getName(), Caller);
10326 CallInst *CI = cast<CallInst>(Caller);
10327 if (CI->isTailCall())
10328 cast<CallInst>(NC)->setTailCall();
10329 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10330 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10333 // Insert a cast of the return type as necessary.
10335 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10336 if (NV->getType() != Type::getVoidTy(*Context)) {
10337 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
10339 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10341 // If this is an invoke instruction, we should insert it after the first
10342 // non-phi, instruction in the normal successor block.
10343 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10344 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10345 InsertNewInstBefore(NC, *I);
10347 // Otherwise, it's a call, just insert cast right after the call instr
10348 InsertNewInstBefore(NC, *Caller);
10350 AddUsersToWorkList(*Caller);
10352 NV = UndefValue::get(Caller->getType());
10356 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10357 Caller->replaceAllUsesWith(NV);
10358 Caller->eraseFromParent();
10359 RemoveFromWorkList(Caller);
10363 // transformCallThroughTrampoline - Turn a call to a function created by the
10364 // init_trampoline intrinsic into a direct call to the underlying function.
10366 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10367 Value *Callee = CS.getCalledValue();
10368 const PointerType *PTy = cast<PointerType>(Callee->getType());
10369 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10370 const AttrListPtr &Attrs = CS.getAttributes();
10372 // If the call already has the 'nest' attribute somewhere then give up -
10373 // otherwise 'nest' would occur twice after splicing in the chain.
10374 if (Attrs.hasAttrSomewhere(Attribute::Nest))
10377 IntrinsicInst *Tramp =
10378 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10380 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10381 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10382 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10384 const AttrListPtr &NestAttrs = NestF->getAttributes();
10385 if (!NestAttrs.isEmpty()) {
10386 unsigned NestIdx = 1;
10387 const Type *NestTy = 0;
10388 Attributes NestAttr = Attribute::None;
10390 // Look for a parameter marked with the 'nest' attribute.
10391 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10392 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10393 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10394 // Record the parameter type and any other attributes.
10396 NestAttr = NestAttrs.getParamAttributes(NestIdx);
10401 Instruction *Caller = CS.getInstruction();
10402 std::vector<Value*> NewArgs;
10403 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10405 SmallVector<AttributeWithIndex, 8> NewAttrs;
10406 NewAttrs.reserve(Attrs.getNumSlots() + 1);
10408 // Insert the nest argument into the call argument list, which may
10409 // mean appending it. Likewise for attributes.
10411 // Add any result attributes.
10412 if (Attributes Attr = Attrs.getRetAttributes())
10413 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10417 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10419 if (Idx == NestIdx) {
10420 // Add the chain argument and attributes.
10421 Value *NestVal = Tramp->getOperand(3);
10422 if (NestVal->getType() != NestTy)
10423 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10424 NewArgs.push_back(NestVal);
10425 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10431 // Add the original argument and attributes.
10432 NewArgs.push_back(*I);
10433 if (Attributes Attr = Attrs.getParamAttributes(Idx))
10435 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10441 // Add any function attributes.
10442 if (Attributes Attr = Attrs.getFnAttributes())
10443 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10445 // The trampoline may have been bitcast to a bogus type (FTy).
10446 // Handle this by synthesizing a new function type, equal to FTy
10447 // with the chain parameter inserted.
10449 std::vector<const Type*> NewTypes;
10450 NewTypes.reserve(FTy->getNumParams()+1);
10452 // Insert the chain's type into the list of parameter types, which may
10453 // mean appending it.
10456 FunctionType::param_iterator I = FTy->param_begin(),
10457 E = FTy->param_end();
10460 if (Idx == NestIdx)
10461 // Add the chain's type.
10462 NewTypes.push_back(NestTy);
10467 // Add the original type.
10468 NewTypes.push_back(*I);
10474 // Replace the trampoline call with a direct call. Let the generic
10475 // code sort out any function type mismatches.
10476 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
10478 Constant *NewCallee =
10479 NestF->getType() == PointerType::getUnqual(NewFTy) ?
10480 NestF : ConstantExpr::getBitCast(NestF,
10481 PointerType::getUnqual(NewFTy));
10482 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10485 Instruction *NewCaller;
10486 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10487 NewCaller = InvokeInst::Create(NewCallee,
10488 II->getNormalDest(), II->getUnwindDest(),
10489 NewArgs.begin(), NewArgs.end(),
10490 Caller->getName(), Caller);
10491 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10492 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10494 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10495 Caller->getName(), Caller);
10496 if (cast<CallInst>(Caller)->isTailCall())
10497 cast<CallInst>(NewCaller)->setTailCall();
10498 cast<CallInst>(NewCaller)->
10499 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10500 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10502 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10503 Caller->replaceAllUsesWith(NewCaller);
10504 Caller->eraseFromParent();
10505 RemoveFromWorkList(Caller);
10510 // Replace the trampoline call with a direct call. Since there is no 'nest'
10511 // parameter, there is no need to adjust the argument list. Let the generic
10512 // code sort out any function type mismatches.
10513 Constant *NewCallee =
10514 NestF->getType() == PTy ? NestF :
10515 ConstantExpr::getBitCast(NestF, PTy);
10516 CS.setCalledFunction(NewCallee);
10517 return CS.getInstruction();
10520 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10521 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10522 /// and a single binop.
10523 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10524 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10525 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10526 unsigned Opc = FirstInst->getOpcode();
10527 Value *LHSVal = FirstInst->getOperand(0);
10528 Value *RHSVal = FirstInst->getOperand(1);
10530 const Type *LHSType = LHSVal->getType();
10531 const Type *RHSType = RHSVal->getType();
10533 // Scan to see if all operands are the same opcode, all have one use, and all
10534 // kill their operands (i.e. the operands have one use).
10535 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10536 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10537 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10538 // Verify type of the LHS matches so we don't fold cmp's of different
10539 // types or GEP's with different index types.
10540 I->getOperand(0)->getType() != LHSType ||
10541 I->getOperand(1)->getType() != RHSType)
10544 // If they are CmpInst instructions, check their predicates
10545 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10546 if (cast<CmpInst>(I)->getPredicate() !=
10547 cast<CmpInst>(FirstInst)->getPredicate())
10550 // Keep track of which operand needs a phi node.
10551 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10552 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10555 // Otherwise, this is safe to transform!
10557 Value *InLHS = FirstInst->getOperand(0);
10558 Value *InRHS = FirstInst->getOperand(1);
10559 PHINode *NewLHS = 0, *NewRHS = 0;
10561 NewLHS = PHINode::Create(LHSType,
10562 FirstInst->getOperand(0)->getName() + ".pn");
10563 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10564 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10565 InsertNewInstBefore(NewLHS, PN);
10570 NewRHS = PHINode::Create(RHSType,
10571 FirstInst->getOperand(1)->getName() + ".pn");
10572 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10573 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10574 InsertNewInstBefore(NewRHS, PN);
10578 // Add all operands to the new PHIs.
10579 if (NewLHS || NewRHS) {
10580 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10581 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10583 Value *NewInLHS = InInst->getOperand(0);
10584 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10587 Value *NewInRHS = InInst->getOperand(1);
10588 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10593 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10594 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10595 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10596 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10600 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10601 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10603 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10604 FirstInst->op_end());
10605 // This is true if all GEP bases are allocas and if all indices into them are
10607 bool AllBasePointersAreAllocas = true;
10609 // Scan to see if all operands are the same opcode, all have one use, and all
10610 // kill their operands (i.e. the operands have one use).
10611 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10612 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10613 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10614 GEP->getNumOperands() != FirstInst->getNumOperands())
10617 // Keep track of whether or not all GEPs are of alloca pointers.
10618 if (AllBasePointersAreAllocas &&
10619 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10620 !GEP->hasAllConstantIndices()))
10621 AllBasePointersAreAllocas = false;
10623 // Compare the operand lists.
10624 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10625 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10628 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10629 // if one of the PHIs has a constant for the index. The index may be
10630 // substantially cheaper to compute for the constants, so making it a
10631 // variable index could pessimize the path. This also handles the case
10632 // for struct indices, which must always be constant.
10633 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10634 isa<ConstantInt>(GEP->getOperand(op)))
10637 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10639 FixedOperands[op] = 0; // Needs a PHI.
10643 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10644 // bother doing this transformation. At best, this will just save a bit of
10645 // offset calculation, but all the predecessors will have to materialize the
10646 // stack address into a register anyway. We'd actually rather *clone* the
10647 // load up into the predecessors so that we have a load of a gep of an alloca,
10648 // which can usually all be folded into the load.
10649 if (AllBasePointersAreAllocas)
10652 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10653 // that is variable.
10654 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10656 bool HasAnyPHIs = false;
10657 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10658 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10659 Value *FirstOp = FirstInst->getOperand(i);
10660 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10661 FirstOp->getName()+".pn");
10662 InsertNewInstBefore(NewPN, PN);
10664 NewPN->reserveOperandSpace(e);
10665 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10666 OperandPhis[i] = NewPN;
10667 FixedOperands[i] = NewPN;
10672 // Add all operands to the new PHIs.
10674 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10675 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10676 BasicBlock *InBB = PN.getIncomingBlock(i);
10678 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10679 if (PHINode *OpPhi = OperandPhis[op])
10680 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10684 Value *Base = FixedOperands[0];
10685 GetElementPtrInst *GEP =
10686 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10687 FixedOperands.end());
10688 if (cast<GEPOperator>(FirstInst)->isInBounds())
10689 cast<GEPOperator>(GEP)->setIsInBounds(true);
10694 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10695 /// sink the load out of the block that defines it. This means that it must be
10696 /// obvious the value of the load is not changed from the point of the load to
10697 /// the end of the block it is in.
10699 /// Finally, it is safe, but not profitable, to sink a load targetting a
10700 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
10702 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10703 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10705 for (++BBI; BBI != E; ++BBI)
10706 if (BBI->mayWriteToMemory())
10709 // Check for non-address taken alloca. If not address-taken already, it isn't
10710 // profitable to do this xform.
10711 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10712 bool isAddressTaken = false;
10713 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10715 if (isa<LoadInst>(UI)) continue;
10716 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10717 // If storing TO the alloca, then the address isn't taken.
10718 if (SI->getOperand(1) == AI) continue;
10720 isAddressTaken = true;
10724 if (!isAddressTaken && AI->isStaticAlloca())
10728 // If this load is a load from a GEP with a constant offset from an alloca,
10729 // then we don't want to sink it. In its present form, it will be
10730 // load [constant stack offset]. Sinking it will cause us to have to
10731 // materialize the stack addresses in each predecessor in a register only to
10732 // do a shared load from register in the successor.
10733 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10734 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10735 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10742 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10743 // operator and they all are only used by the PHI, PHI together their
10744 // inputs, and do the operation once, to the result of the PHI.
10745 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10746 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10748 // Scan the instruction, looking for input operations that can be folded away.
10749 // If all input operands to the phi are the same instruction (e.g. a cast from
10750 // the same type or "+42") we can pull the operation through the PHI, reducing
10751 // code size and simplifying code.
10752 Constant *ConstantOp = 0;
10753 const Type *CastSrcTy = 0;
10754 bool isVolatile = false;
10755 if (isa<CastInst>(FirstInst)) {
10756 CastSrcTy = FirstInst->getOperand(0)->getType();
10757 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10758 // Can fold binop, compare or shift here if the RHS is a constant,
10759 // otherwise call FoldPHIArgBinOpIntoPHI.
10760 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10761 if (ConstantOp == 0)
10762 return FoldPHIArgBinOpIntoPHI(PN);
10763 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10764 isVolatile = LI->isVolatile();
10765 // We can't sink the load if the loaded value could be modified between the
10766 // load and the PHI.
10767 if (LI->getParent() != PN.getIncomingBlock(0) ||
10768 !isSafeAndProfitableToSinkLoad(LI))
10771 // If the PHI is of volatile loads and the load block has multiple
10772 // successors, sinking it would remove a load of the volatile value from
10773 // the path through the other successor.
10775 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10778 } else if (isa<GetElementPtrInst>(FirstInst)) {
10779 return FoldPHIArgGEPIntoPHI(PN);
10781 return 0; // Cannot fold this operation.
10784 // Check to see if all arguments are the same operation.
10785 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10786 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10787 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10788 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10791 if (I->getOperand(0)->getType() != CastSrcTy)
10792 return 0; // Cast operation must match.
10793 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10794 // We can't sink the load if the loaded value could be modified between
10795 // the load and the PHI.
10796 if (LI->isVolatile() != isVolatile ||
10797 LI->getParent() != PN.getIncomingBlock(i) ||
10798 !isSafeAndProfitableToSinkLoad(LI))
10801 // If the PHI is of volatile loads and the load block has multiple
10802 // successors, sinking it would remove a load of the volatile value from
10803 // the path through the other successor.
10805 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10808 } else if (I->getOperand(1) != ConstantOp) {
10813 // Okay, they are all the same operation. Create a new PHI node of the
10814 // correct type, and PHI together all of the LHS's of the instructions.
10815 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10816 PN.getName()+".in");
10817 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10819 Value *InVal = FirstInst->getOperand(0);
10820 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10822 // Add all operands to the new PHI.
10823 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10824 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10825 if (NewInVal != InVal)
10827 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10832 // The new PHI unions all of the same values together. This is really
10833 // common, so we handle it intelligently here for compile-time speed.
10837 InsertNewInstBefore(NewPN, PN);
10841 // Insert and return the new operation.
10842 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10843 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10844 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10845 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10846 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10847 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10848 PhiVal, ConstantOp);
10849 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10851 // If this was a volatile load that we are merging, make sure to loop through
10852 // and mark all the input loads as non-volatile. If we don't do this, we will
10853 // insert a new volatile load and the old ones will not be deletable.
10855 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10856 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10858 return new LoadInst(PhiVal, "", isVolatile);
10861 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10863 static bool DeadPHICycle(PHINode *PN,
10864 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10865 if (PN->use_empty()) return true;
10866 if (!PN->hasOneUse()) return false;
10868 // Remember this node, and if we find the cycle, return.
10869 if (!PotentiallyDeadPHIs.insert(PN))
10872 // Don't scan crazily complex things.
10873 if (PotentiallyDeadPHIs.size() == 16)
10876 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10877 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10882 /// PHIsEqualValue - Return true if this phi node is always equal to
10883 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10884 /// z = some value; x = phi (y, z); y = phi (x, z)
10885 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10886 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10887 // See if we already saw this PHI node.
10888 if (!ValueEqualPHIs.insert(PN))
10891 // Don't scan crazily complex things.
10892 if (ValueEqualPHIs.size() == 16)
10895 // Scan the operands to see if they are either phi nodes or are equal to
10897 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10898 Value *Op = PN->getIncomingValue(i);
10899 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10900 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10902 } else if (Op != NonPhiInVal)
10910 // PHINode simplification
10912 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10913 // If LCSSA is around, don't mess with Phi nodes
10914 if (MustPreserveLCSSA) return 0;
10916 if (Value *V = PN.hasConstantValue())
10917 return ReplaceInstUsesWith(PN, V);
10919 // If all PHI operands are the same operation, pull them through the PHI,
10920 // reducing code size.
10921 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10922 isa<Instruction>(PN.getIncomingValue(1)) &&
10923 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10924 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10925 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10926 // than themselves more than once.
10927 PN.getIncomingValue(0)->hasOneUse())
10928 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10931 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10932 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10933 // PHI)... break the cycle.
10934 if (PN.hasOneUse()) {
10935 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10936 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10937 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10938 PotentiallyDeadPHIs.insert(&PN);
10939 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10940 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10943 // If this phi has a single use, and if that use just computes a value for
10944 // the next iteration of a loop, delete the phi. This occurs with unused
10945 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10946 // common case here is good because the only other things that catch this
10947 // are induction variable analysis (sometimes) and ADCE, which is only run
10949 if (PHIUser->hasOneUse() &&
10950 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10951 PHIUser->use_back() == &PN) {
10952 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10956 // We sometimes end up with phi cycles that non-obviously end up being the
10957 // same value, for example:
10958 // z = some value; x = phi (y, z); y = phi (x, z)
10959 // where the phi nodes don't necessarily need to be in the same block. Do a
10960 // quick check to see if the PHI node only contains a single non-phi value, if
10961 // so, scan to see if the phi cycle is actually equal to that value.
10963 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10964 // Scan for the first non-phi operand.
10965 while (InValNo != NumOperandVals &&
10966 isa<PHINode>(PN.getIncomingValue(InValNo)))
10969 if (InValNo != NumOperandVals) {
10970 Value *NonPhiInVal = PN.getOperand(InValNo);
10972 // Scan the rest of the operands to see if there are any conflicts, if so
10973 // there is no need to recursively scan other phis.
10974 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10975 Value *OpVal = PN.getIncomingValue(InValNo);
10976 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10980 // If we scanned over all operands, then we have one unique value plus
10981 // phi values. Scan PHI nodes to see if they all merge in each other or
10983 if (InValNo == NumOperandVals) {
10984 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10985 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10986 return ReplaceInstUsesWith(PN, NonPhiInVal);
10993 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10994 Instruction *InsertPoint,
10995 InstCombiner *IC) {
10996 unsigned PtrSize = DTy->getScalarSizeInBits();
10997 unsigned VTySize = V->getType()->getScalarSizeInBits();
10998 // We must cast correctly to the pointer type. Ensure that we
10999 // sign extend the integer value if it is smaller as this is
11000 // used for address computation.
11001 Instruction::CastOps opcode =
11002 (VTySize < PtrSize ? Instruction::SExt :
11003 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
11004 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
11008 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11009 Value *PtrOp = GEP.getOperand(0);
11010 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
11011 // If so, eliminate the noop.
11012 if (GEP.getNumOperands() == 1)
11013 return ReplaceInstUsesWith(GEP, PtrOp);
11015 if (isa<UndefValue>(GEP.getOperand(0)))
11016 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
11018 bool HasZeroPointerIndex = false;
11019 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11020 HasZeroPointerIndex = C->isNullValue();
11022 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11023 return ReplaceInstUsesWith(GEP, PtrOp);
11025 // Eliminate unneeded casts for indices.
11026 bool MadeChange = false;
11028 gep_type_iterator GTI = gep_type_begin(GEP);
11029 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11030 i != e; ++i, ++GTI) {
11031 if (TD && isa<SequentialType>(*GTI)) {
11032 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
11033 if (CI->getOpcode() == Instruction::ZExt ||
11034 CI->getOpcode() == Instruction::SExt) {
11035 const Type *SrcTy = CI->getOperand(0)->getType();
11036 // We can eliminate a cast from i32 to i64 iff the target
11037 // is a 32-bit pointer target.
11038 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
11040 *i = CI->getOperand(0);
11044 // If we are using a wider index than needed for this platform, shrink it
11045 // to what we need. If narrower, sign-extend it to what we need.
11046 // If the incoming value needs a cast instruction,
11047 // insert it. This explicit cast can make subsequent optimizations more
11050 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
11051 if (Constant *C = dyn_cast<Constant>(Op)) {
11052 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType(GEP.getContext()));
11055 Op = InsertCastBefore(Instruction::Trunc, Op,
11056 TD->getIntPtrType(GEP.getContext()),
11061 } else if (TD->getTypeSizeInBits(Op->getType())
11062 < TD->getPointerSizeInBits()) {
11063 if (Constant *C = dyn_cast<Constant>(Op)) {
11064 *i = ConstantExpr::getSExt(C, TD->getIntPtrType(GEP.getContext()));
11067 Op = InsertCastBefore(Instruction::SExt, Op,
11068 TD->getIntPtrType(GEP.getContext()), GEP);
11075 if (MadeChange) return &GEP;
11077 // Combine Indices - If the source pointer to this getelementptr instruction
11078 // is a getelementptr instruction, combine the indices of the two
11079 // getelementptr instructions into a single instruction.
11081 SmallVector<Value*, 8> SrcGEPOperands;
11082 bool BothInBounds = cast<GEPOperator>(&GEP)->isInBounds();
11083 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
11084 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11085 if (!Src->isInBounds())
11086 BothInBounds = false;
11089 if (!SrcGEPOperands.empty()) {
11090 // Note that if our source is a gep chain itself that we wait for that
11091 // chain to be resolved before we perform this transformation. This
11092 // avoids us creating a TON of code in some cases.
11094 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11095 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11096 return 0; // Wait until our source is folded to completion.
11098 SmallVector<Value*, 8> Indices;
11100 // Find out whether the last index in the source GEP is a sequential idx.
11101 bool EndsWithSequential = false;
11102 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11103 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11104 EndsWithSequential = !isa<StructType>(*I);
11106 // Can we combine the two pointer arithmetics offsets?
11107 if (EndsWithSequential) {
11108 // Replace: gep (gep %P, long B), long A, ...
11109 // With: T = long A+B; gep %P, T, ...
11111 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11112 if (SO1 == Constant::getNullValue(SO1->getType())) {
11114 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11117 // If they aren't the same type, convert both to an integer of the
11118 // target's pointer size.
11119 if (SO1->getType() != GO1->getType()) {
11120 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11122 ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
11123 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11125 ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
11127 unsigned PS = TD->getPointerSizeInBits();
11128 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11129 // Convert GO1 to SO1's type.
11130 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11132 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11133 // Convert SO1 to GO1's type.
11134 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11136 const Type *PT = TD->getIntPtrType(GEP.getContext());
11137 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11138 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11142 if (isa<Constant>(SO1) && isa<Constant>(GO1))
11143 Sum = ConstantExpr::getAdd(cast<Constant>(SO1),
11144 cast<Constant>(GO1));
11146 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11147 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11151 // Recycle the GEP we already have if possible.
11152 if (SrcGEPOperands.size() == 2) {
11153 GEP.setOperand(0, SrcGEPOperands[0]);
11154 GEP.setOperand(1, Sum);
11157 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11158 SrcGEPOperands.end()-1);
11159 Indices.push_back(Sum);
11160 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11162 } else if (isa<Constant>(*GEP.idx_begin()) &&
11163 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11164 SrcGEPOperands.size() != 1) {
11165 // Otherwise we can do the fold if the first index of the GEP is a zero
11166 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11167 SrcGEPOperands.end());
11168 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11171 if (!Indices.empty()) {
11172 GetElementPtrInst *NewGEP = GetElementPtrInst::Create(SrcGEPOperands[0],
11177 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11181 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11182 // GEP of global variable. If all of the indices for this GEP are
11183 // constants, we can promote this to a constexpr instead of an instruction.
11185 // Scan for nonconstants...
11186 SmallVector<Constant*, 8> Indices;
11187 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11188 for (; I != E && isa<Constant>(*I); ++I)
11189 Indices.push_back(cast<Constant>(*I));
11191 if (I == E) { // If they are all constants...
11192 Constant *CE = ConstantExpr::getGetElementPtr(GV,
11193 &Indices[0],Indices.size());
11195 // Replace all uses of the GEP with the new constexpr...
11196 return ReplaceInstUsesWith(GEP, CE);
11198 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
11199 if (!isa<PointerType>(X->getType())) {
11200 // Not interesting. Source pointer must be a cast from pointer.
11201 } else if (HasZeroPointerIndex) {
11202 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11203 // into : GEP [10 x i8]* X, i32 0, ...
11205 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11206 // into : GEP i8* X, ...
11208 // This occurs when the program declares an array extern like "int X[];"
11209 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11210 const PointerType *XTy = cast<PointerType>(X->getType());
11211 if (const ArrayType *CATy =
11212 dyn_cast<ArrayType>(CPTy->getElementType())) {
11213 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11214 if (CATy->getElementType() == XTy->getElementType()) {
11215 // -> GEP i8* X, ...
11216 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11217 GetElementPtrInst *NewGEP =
11218 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11220 if (cast<GEPOperator>(&GEP)->isInBounds())
11221 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11223 } else if (const ArrayType *XATy =
11224 dyn_cast<ArrayType>(XTy->getElementType())) {
11225 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11226 if (CATy->getElementType() == XATy->getElementType()) {
11227 // -> GEP [10 x i8]* X, i32 0, ...
11228 // At this point, we know that the cast source type is a pointer
11229 // to an array of the same type as the destination pointer
11230 // array. Because the array type is never stepped over (there
11231 // is a leading zero) we can fold the cast into this GEP.
11232 GEP.setOperand(0, X);
11237 } else if (GEP.getNumOperands() == 2) {
11238 // Transform things like:
11239 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11240 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11241 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11242 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11243 if (TD && isa<ArrayType>(SrcElTy) &&
11244 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11245 TD->getTypeAllocSize(ResElTy)) {
11247 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11248 Idx[1] = GEP.getOperand(1);
11249 GetElementPtrInst *NewGEP =
11250 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11251 if (cast<GEPOperator>(&GEP)->isInBounds())
11252 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11253 Value *V = InsertNewInstBefore(NewGEP, GEP);
11254 // V and GEP are both pointer types --> BitCast
11255 return new BitCastInst(V, GEP.getType());
11258 // Transform things like:
11259 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11260 // (where tmp = 8*tmp2) into:
11261 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11263 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
11264 uint64_t ArrayEltSize =
11265 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11267 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11268 // allow either a mul, shift, or constant here.
11270 ConstantInt *Scale = 0;
11271 if (ArrayEltSize == 1) {
11272 NewIdx = GEP.getOperand(1);
11274 ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11275 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11276 NewIdx = ConstantInt::get(CI->getType(), 1);
11278 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11279 if (Inst->getOpcode() == Instruction::Shl &&
11280 isa<ConstantInt>(Inst->getOperand(1))) {
11281 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11282 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11283 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11285 NewIdx = Inst->getOperand(0);
11286 } else if (Inst->getOpcode() == Instruction::Mul &&
11287 isa<ConstantInt>(Inst->getOperand(1))) {
11288 Scale = cast<ConstantInt>(Inst->getOperand(1));
11289 NewIdx = Inst->getOperand(0);
11293 // If the index will be to exactly the right offset with the scale taken
11294 // out, perform the transformation. Note, we don't know whether Scale is
11295 // signed or not. We'll use unsigned version of division/modulo
11296 // operation after making sure Scale doesn't have the sign bit set.
11297 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11298 Scale->getZExtValue() % ArrayEltSize == 0) {
11299 Scale = ConstantInt::get(Scale->getType(),
11300 Scale->getZExtValue() / ArrayEltSize);
11301 if (Scale->getZExtValue() != 1) {
11303 ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11305 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11306 NewIdx = InsertNewInstBefore(Sc, GEP);
11309 // Insert the new GEP instruction.
11311 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11313 Instruction *NewGEP =
11314 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11315 if (cast<GEPOperator>(&GEP)->isInBounds())
11316 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11317 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11318 // The NewGEP must be pointer typed, so must the old one -> BitCast
11319 return new BitCastInst(NewGEP, GEP.getType());
11325 /// See if we can simplify:
11326 /// X = bitcast A to B*
11327 /// Y = gep X, <...constant indices...>
11328 /// into a gep of the original struct. This is important for SROA and alias
11329 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
11330 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11332 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11333 // Determine how much the GEP moves the pointer. We are guaranteed to get
11334 // a constant back from EmitGEPOffset.
11335 ConstantInt *OffsetV =
11336 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11337 int64_t Offset = OffsetV->getSExtValue();
11339 // If this GEP instruction doesn't move the pointer, just replace the GEP
11340 // with a bitcast of the real input to the dest type.
11342 // If the bitcast is of an allocation, and the allocation will be
11343 // converted to match the type of the cast, don't touch this.
11344 if (isa<AllocationInst>(BCI->getOperand(0))) {
11345 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11346 if (Instruction *I = visitBitCast(*BCI)) {
11349 BCI->getParent()->getInstList().insert(BCI, I);
11350 ReplaceInstUsesWith(*BCI, I);
11355 return new BitCastInst(BCI->getOperand(0), GEP.getType());
11358 // Otherwise, if the offset is non-zero, we need to find out if there is a
11359 // field at Offset in 'A's type. If so, we can pull the cast through the
11361 SmallVector<Value*, 8> NewIndices;
11363 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11364 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11365 Instruction *NGEP =
11366 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11368 if (NGEP->getType() == GEP.getType()) return NGEP;
11369 if (cast<GEPOperator>(&GEP)->isInBounds())
11370 cast<GEPOperator>(NGEP)->setIsInBounds(true);
11371 InsertNewInstBefore(NGEP, GEP);
11372 NGEP->takeName(&GEP);
11373 return new BitCastInst(NGEP, GEP.getType());
11381 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11382 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11383 if (AI.isArrayAllocation()) { // Check C != 1
11384 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11385 const Type *NewTy =
11386 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11387 AllocationInst *New = 0;
11389 // Create and insert the replacement instruction...
11390 if (isa<MallocInst>(AI))
11391 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11393 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11394 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11397 InsertNewInstBefore(New, AI);
11399 // Scan to the end of the allocation instructions, to skip over a block of
11400 // allocas if possible...also skip interleaved debug info
11402 BasicBlock::iterator It = New;
11403 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11405 // Now that I is pointing to the first non-allocation-inst in the block,
11406 // insert our getelementptr instruction...
11408 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11412 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11413 New->getName()+".sub", It);
11414 cast<GEPOperator>(V)->setIsInBounds(true);
11416 // Now make everything use the getelementptr instead of the original
11418 return ReplaceInstUsesWith(AI, V);
11419 } else if (isa<UndefValue>(AI.getArraySize())) {
11420 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11424 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11425 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11426 // Note that we only do this for alloca's, because malloc should allocate
11427 // and return a unique pointer, even for a zero byte allocation.
11428 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11429 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11431 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11432 if (AI.getAlignment() == 0)
11433 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11439 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11440 Value *Op = FI.getOperand(0);
11442 // free undef -> unreachable.
11443 if (isa<UndefValue>(Op)) {
11444 // Insert a new store to null because we cannot modify the CFG here.
11445 new StoreInst(ConstantInt::getTrue(*Context),
11446 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
11447 return EraseInstFromFunction(FI);
11450 // If we have 'free null' delete the instruction. This can happen in stl code
11451 // when lots of inlining happens.
11452 if (isa<ConstantPointerNull>(Op))
11453 return EraseInstFromFunction(FI);
11455 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11456 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11457 FI.setOperand(0, CI->getOperand(0));
11461 // Change free (gep X, 0,0,0,0) into free(X)
11462 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11463 if (GEPI->hasAllZeroIndices()) {
11464 AddToWorkList(GEPI);
11465 FI.setOperand(0, GEPI->getOperand(0));
11470 // Change free(malloc) into nothing, if the malloc has a single use.
11471 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11472 if (MI->hasOneUse()) {
11473 EraseInstFromFunction(FI);
11474 return EraseInstFromFunction(*MI);
11481 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11482 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11483 const TargetData *TD) {
11484 User *CI = cast<User>(LI.getOperand(0));
11485 Value *CastOp = CI->getOperand(0);
11486 LLVMContext *Context = IC.getContext();
11489 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11490 // Instead of loading constant c string, use corresponding integer value
11491 // directly if string length is small enough.
11493 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11494 unsigned len = Str.length();
11495 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11496 unsigned numBits = Ty->getPrimitiveSizeInBits();
11497 // Replace LI with immediate integer store.
11498 if ((numBits >> 3) == len + 1) {
11499 APInt StrVal(numBits, 0);
11500 APInt SingleChar(numBits, 0);
11501 if (TD->isLittleEndian()) {
11502 for (signed i = len-1; i >= 0; i--) {
11503 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11504 StrVal = (StrVal << 8) | SingleChar;
11507 for (unsigned i = 0; i < len; i++) {
11508 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11509 StrVal = (StrVal << 8) | SingleChar;
11511 // Append NULL at the end.
11513 StrVal = (StrVal << 8) | SingleChar;
11515 Value *NL = ConstantInt::get(*Context, StrVal);
11516 return IC.ReplaceInstUsesWith(LI, NL);
11522 const PointerType *DestTy = cast<PointerType>(CI->getType());
11523 const Type *DestPTy = DestTy->getElementType();
11524 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11526 // If the address spaces don't match, don't eliminate the cast.
11527 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11530 const Type *SrcPTy = SrcTy->getElementType();
11532 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11533 isa<VectorType>(DestPTy)) {
11534 // If the source is an array, the code below will not succeed. Check to
11535 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11537 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11538 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11539 if (ASrcTy->getNumElements() != 0) {
11541 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
11542 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11543 SrcTy = cast<PointerType>(CastOp->getType());
11544 SrcPTy = SrcTy->getElementType();
11547 if (IC.getTargetData() &&
11548 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
11549 isa<VectorType>(SrcPTy)) &&
11550 // Do not allow turning this into a load of an integer, which is then
11551 // casted to a pointer, this pessimizes pointer analysis a lot.
11552 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11553 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11554 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11556 // Okay, we are casting from one integer or pointer type to another of
11557 // the same size. Instead of casting the pointer before the load, cast
11558 // the result of the loaded value.
11559 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11561 LI.isVolatile()),LI);
11562 // Now cast the result of the load.
11563 return new BitCastInst(NewLoad, LI.getType());
11570 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11571 Value *Op = LI.getOperand(0);
11573 // Attempt to improve the alignment.
11575 unsigned KnownAlign =
11576 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11578 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11579 LI.getAlignment()))
11580 LI.setAlignment(KnownAlign);
11583 // load (cast X) --> cast (load X) iff safe
11584 if (isa<CastInst>(Op))
11585 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11588 // None of the following transforms are legal for volatile loads.
11589 if (LI.isVolatile()) return 0;
11591 // Do really simple store-to-load forwarding and load CSE, to catch cases
11592 // where there are several consequtive memory accesses to the same location,
11593 // separated by a few arithmetic operations.
11594 BasicBlock::iterator BBI = &LI;
11595 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11596 return ReplaceInstUsesWith(LI, AvailableVal);
11598 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11599 const Value *GEPI0 = GEPI->getOperand(0);
11600 // TODO: Consider a target hook for valid address spaces for this xform.
11601 if (isa<ConstantPointerNull>(GEPI0) &&
11602 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11603 // Insert a new store to null instruction before the load to indicate
11604 // that this code is not reachable. We do this instead of inserting
11605 // an unreachable instruction directly because we cannot modify the
11607 new StoreInst(UndefValue::get(LI.getType()),
11608 Constant::getNullValue(Op->getType()), &LI);
11609 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11613 if (Constant *C = dyn_cast<Constant>(Op)) {
11614 // load null/undef -> undef
11615 // TODO: Consider a target hook for valid address spaces for this xform.
11616 if (isa<UndefValue>(C) || (C->isNullValue() &&
11617 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11618 // Insert a new store to null instruction before the load to indicate that
11619 // this code is not reachable. We do this instead of inserting an
11620 // unreachable instruction directly because we cannot modify the CFG.
11621 new StoreInst(UndefValue::get(LI.getType()),
11622 Constant::getNullValue(Op->getType()), &LI);
11623 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11626 // Instcombine load (constant global) into the value loaded.
11627 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11628 if (GV->isConstant() && GV->hasDefinitiveInitializer())
11629 return ReplaceInstUsesWith(LI, GV->getInitializer());
11631 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11632 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11633 if (CE->getOpcode() == Instruction::GetElementPtr) {
11634 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11635 if (GV->isConstant() && GV->hasDefinitiveInitializer())
11637 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
11639 return ReplaceInstUsesWith(LI, V);
11640 if (CE->getOperand(0)->isNullValue()) {
11641 // Insert a new store to null instruction before the load to indicate
11642 // that this code is not reachable. We do this instead of inserting
11643 // an unreachable instruction directly because we cannot modify the
11645 new StoreInst(UndefValue::get(LI.getType()),
11646 Constant::getNullValue(Op->getType()), &LI);
11647 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11650 } else if (CE->isCast()) {
11651 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11657 // If this load comes from anywhere in a constant global, and if the global
11658 // is all undef or zero, we know what it loads.
11659 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11660 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11661 if (GV->getInitializer()->isNullValue())
11662 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11663 else if (isa<UndefValue>(GV->getInitializer()))
11664 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11668 if (Op->hasOneUse()) {
11669 // Change select and PHI nodes to select values instead of addresses: this
11670 // helps alias analysis out a lot, allows many others simplifications, and
11671 // exposes redundancy in the code.
11673 // Note that we cannot do the transformation unless we know that the
11674 // introduced loads cannot trap! Something like this is valid as long as
11675 // the condition is always false: load (select bool %C, int* null, int* %G),
11676 // but it would not be valid if we transformed it to load from null
11677 // unconditionally.
11679 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11680 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11681 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11682 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11683 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11684 SI->getOperand(1)->getName()+".val"), LI);
11685 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11686 SI->getOperand(2)->getName()+".val"), LI);
11687 return SelectInst::Create(SI->getCondition(), V1, V2);
11690 // load (select (cond, null, P)) -> load P
11691 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11692 if (C->isNullValue()) {
11693 LI.setOperand(0, SI->getOperand(2));
11697 // load (select (cond, P, null)) -> load P
11698 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11699 if (C->isNullValue()) {
11700 LI.setOperand(0, SI->getOperand(1));
11708 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11709 /// when possible. This makes it generally easy to do alias analysis and/or
11710 /// SROA/mem2reg of the memory object.
11711 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11712 User *CI = cast<User>(SI.getOperand(1));
11713 Value *CastOp = CI->getOperand(0);
11715 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11716 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11717 if (SrcTy == 0) return 0;
11719 const Type *SrcPTy = SrcTy->getElementType();
11721 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11724 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11725 /// to its first element. This allows us to handle things like:
11726 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11727 /// on 32-bit hosts.
11728 SmallVector<Value*, 4> NewGEPIndices;
11730 // If the source is an array, the code below will not succeed. Check to
11731 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11733 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11734 // Index through pointer.
11735 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11736 NewGEPIndices.push_back(Zero);
11739 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11740 if (!STy->getNumElements()) /* Struct can be empty {} */
11742 NewGEPIndices.push_back(Zero);
11743 SrcPTy = STy->getElementType(0);
11744 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11745 NewGEPIndices.push_back(Zero);
11746 SrcPTy = ATy->getElementType();
11752 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11755 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11758 // If the pointers point into different address spaces or if they point to
11759 // values with different sizes, we can't do the transformation.
11760 if (!IC.getTargetData() ||
11761 SrcTy->getAddressSpace() !=
11762 cast<PointerType>(CI->getType())->getAddressSpace() ||
11763 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11764 IC.getTargetData()->getTypeSizeInBits(DestPTy))
11767 // Okay, we are casting from one integer or pointer type to another of
11768 // the same size. Instead of casting the pointer before
11769 // the store, cast the value to be stored.
11771 Value *SIOp0 = SI.getOperand(0);
11772 Instruction::CastOps opcode = Instruction::BitCast;
11773 const Type* CastSrcTy = SIOp0->getType();
11774 const Type* CastDstTy = SrcPTy;
11775 if (isa<PointerType>(CastDstTy)) {
11776 if (CastSrcTy->isInteger())
11777 opcode = Instruction::IntToPtr;
11778 } else if (isa<IntegerType>(CastDstTy)) {
11779 if (isa<PointerType>(SIOp0->getType()))
11780 opcode = Instruction::PtrToInt;
11783 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11784 // emit a GEP to index into its first field.
11785 if (!NewGEPIndices.empty()) {
11786 if (Constant *C = dyn_cast<Constant>(CastOp))
11787 CastOp = ConstantExpr::getGetElementPtr(C, &NewGEPIndices[0],
11788 NewGEPIndices.size());
11790 CastOp = IC.InsertNewInstBefore(
11791 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11792 NewGEPIndices.end()), SI);
11793 cast<GEPOperator>(CastOp)->setIsInBounds(true);
11796 if (Constant *C = dyn_cast<Constant>(SIOp0))
11797 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11799 NewCast = IC.InsertNewInstBefore(
11800 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11802 return new StoreInst(NewCast, CastOp);
11805 /// equivalentAddressValues - Test if A and B will obviously have the same
11806 /// value. This includes recognizing that %t0 and %t1 will have the same
11807 /// value in code like this:
11808 /// %t0 = getelementptr \@a, 0, 3
11809 /// store i32 0, i32* %t0
11810 /// %t1 = getelementptr \@a, 0, 3
11811 /// %t2 = load i32* %t1
11813 static bool equivalentAddressValues(Value *A, Value *B) {
11814 // Test if the values are trivially equivalent.
11815 if (A == B) return true;
11817 // Test if the values come form identical arithmetic instructions.
11818 if (isa<BinaryOperator>(A) ||
11819 isa<CastInst>(A) ||
11821 isa<GetElementPtrInst>(A))
11822 if (Instruction *BI = dyn_cast<Instruction>(B))
11823 if (cast<Instruction>(A)->isIdenticalTo(BI))
11826 // Otherwise they may not be equivalent.
11830 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11831 // return the llvm.dbg.declare.
11832 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11833 if (!V->hasNUses(2))
11835 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11837 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11839 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11840 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11847 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11848 Value *Val = SI.getOperand(0);
11849 Value *Ptr = SI.getOperand(1);
11851 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11852 EraseInstFromFunction(SI);
11857 // If the RHS is an alloca with a single use, zapify the store, making the
11859 // If the RHS is an alloca with a two uses, the other one being a
11860 // llvm.dbg.declare, zapify the store and the declare, making the
11861 // alloca dead. We must do this to prevent declare's from affecting
11863 if (!SI.isVolatile()) {
11864 if (Ptr->hasOneUse()) {
11865 if (isa<AllocaInst>(Ptr)) {
11866 EraseInstFromFunction(SI);
11870 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11871 if (isa<AllocaInst>(GEP->getOperand(0))) {
11872 if (GEP->getOperand(0)->hasOneUse()) {
11873 EraseInstFromFunction(SI);
11877 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11878 EraseInstFromFunction(*DI);
11879 EraseInstFromFunction(SI);
11886 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11887 EraseInstFromFunction(*DI);
11888 EraseInstFromFunction(SI);
11894 // Attempt to improve the alignment.
11896 unsigned KnownAlign =
11897 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11899 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11900 SI.getAlignment()))
11901 SI.setAlignment(KnownAlign);
11904 // Do really simple DSE, to catch cases where there are several consecutive
11905 // stores to the same location, separated by a few arithmetic operations. This
11906 // situation often occurs with bitfield accesses.
11907 BasicBlock::iterator BBI = &SI;
11908 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11911 // Don't count debug info directives, lest they affect codegen,
11912 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11913 // It is necessary for correctness to skip those that feed into a
11914 // llvm.dbg.declare, as these are not present when debugging is off.
11915 if (isa<DbgInfoIntrinsic>(BBI) ||
11916 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11921 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11922 // Prev store isn't volatile, and stores to the same location?
11923 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11924 SI.getOperand(1))) {
11927 EraseInstFromFunction(*PrevSI);
11933 // If this is a load, we have to stop. However, if the loaded value is from
11934 // the pointer we're loading and is producing the pointer we're storing,
11935 // then *this* store is dead (X = load P; store X -> P).
11936 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11937 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11938 !SI.isVolatile()) {
11939 EraseInstFromFunction(SI);
11943 // Otherwise, this is a load from some other location. Stores before it
11944 // may not be dead.
11948 // Don't skip over loads or things that can modify memory.
11949 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11954 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11956 // store X, null -> turns into 'unreachable' in SimplifyCFG
11957 if (isa<ConstantPointerNull>(Ptr) &&
11958 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11959 if (!isa<UndefValue>(Val)) {
11960 SI.setOperand(0, UndefValue::get(Val->getType()));
11961 if (Instruction *U = dyn_cast<Instruction>(Val))
11962 AddToWorkList(U); // Dropped a use.
11965 return 0; // Do not modify these!
11968 // store undef, Ptr -> noop
11969 if (isa<UndefValue>(Val)) {
11970 EraseInstFromFunction(SI);
11975 // If the pointer destination is a cast, see if we can fold the cast into the
11977 if (isa<CastInst>(Ptr))
11978 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11980 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11982 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11986 // If this store is the last instruction in the basic block (possibly
11987 // excepting debug info instructions and the pointer bitcasts that feed
11988 // into them), and if the block ends with an unconditional branch, try
11989 // to move it to the successor block.
11993 } while (isa<DbgInfoIntrinsic>(BBI) ||
11994 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11995 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11996 if (BI->isUnconditional())
11997 if (SimplifyStoreAtEndOfBlock(SI))
11998 return 0; // xform done!
12003 /// SimplifyStoreAtEndOfBlock - Turn things like:
12004 /// if () { *P = v1; } else { *P = v2 }
12005 /// into a phi node with a store in the successor.
12007 /// Simplify things like:
12008 /// *P = v1; if () { *P = v2; }
12009 /// into a phi node with a store in the successor.
12011 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12012 BasicBlock *StoreBB = SI.getParent();
12014 // Check to see if the successor block has exactly two incoming edges. If
12015 // so, see if the other predecessor contains a store to the same location.
12016 // if so, insert a PHI node (if needed) and move the stores down.
12017 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
12019 // Determine whether Dest has exactly two predecessors and, if so, compute
12020 // the other predecessor.
12021 pred_iterator PI = pred_begin(DestBB);
12022 BasicBlock *OtherBB = 0;
12023 if (*PI != StoreBB)
12026 if (PI == pred_end(DestBB))
12029 if (*PI != StoreBB) {
12034 if (++PI != pred_end(DestBB))
12037 // Bail out if all the relevant blocks aren't distinct (this can happen,
12038 // for example, if SI is in an infinite loop)
12039 if (StoreBB == DestBB || OtherBB == DestBB)
12042 // Verify that the other block ends in a branch and is not otherwise empty.
12043 BasicBlock::iterator BBI = OtherBB->getTerminator();
12044 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12045 if (!OtherBr || BBI == OtherBB->begin())
12048 // If the other block ends in an unconditional branch, check for the 'if then
12049 // else' case. there is an instruction before the branch.
12050 StoreInst *OtherStore = 0;
12051 if (OtherBr->isUnconditional()) {
12053 // Skip over debugging info.
12054 while (isa<DbgInfoIntrinsic>(BBI) ||
12055 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12056 if (BBI==OtherBB->begin())
12060 // If this isn't a store, or isn't a store to the same location, bail out.
12061 OtherStore = dyn_cast<StoreInst>(BBI);
12062 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12065 // Otherwise, the other block ended with a conditional branch. If one of the
12066 // destinations is StoreBB, then we have the if/then case.
12067 if (OtherBr->getSuccessor(0) != StoreBB &&
12068 OtherBr->getSuccessor(1) != StoreBB)
12071 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12072 // if/then triangle. See if there is a store to the same ptr as SI that
12073 // lives in OtherBB.
12075 // Check to see if we find the matching store.
12076 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12077 if (OtherStore->getOperand(1) != SI.getOperand(1))
12081 // If we find something that may be using or overwriting the stored
12082 // value, or if we run out of instructions, we can't do the xform.
12083 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12084 BBI == OtherBB->begin())
12088 // In order to eliminate the store in OtherBr, we have to
12089 // make sure nothing reads or overwrites the stored value in
12091 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12092 // FIXME: This should really be AA driven.
12093 if (I->mayReadFromMemory() || I->mayWriteToMemory())
12098 // Insert a PHI node now if we need it.
12099 Value *MergedVal = OtherStore->getOperand(0);
12100 if (MergedVal != SI.getOperand(0)) {
12101 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12102 PN->reserveOperandSpace(2);
12103 PN->addIncoming(SI.getOperand(0), SI.getParent());
12104 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12105 MergedVal = InsertNewInstBefore(PN, DestBB->front());
12108 // Advance to a place where it is safe to insert the new store and
12110 BBI = DestBB->getFirstNonPHI();
12111 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12112 OtherStore->isVolatile()), *BBI);
12114 // Nuke the old stores.
12115 EraseInstFromFunction(SI);
12116 EraseInstFromFunction(*OtherStore);
12122 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12123 // Change br (not X), label True, label False to: br X, label False, True
12125 BasicBlock *TrueDest;
12126 BasicBlock *FalseDest;
12127 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
12128 !isa<Constant>(X)) {
12129 // Swap Destinations and condition...
12130 BI.setCondition(X);
12131 BI.setSuccessor(0, FalseDest);
12132 BI.setSuccessor(1, TrueDest);
12136 // Cannonicalize fcmp_one -> fcmp_oeq
12137 FCmpInst::Predicate FPred; Value *Y;
12138 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
12139 TrueDest, FalseDest)))
12140 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12141 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12142 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12143 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12144 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12145 NewSCC->takeName(I);
12146 // Swap Destinations and condition...
12147 BI.setCondition(NewSCC);
12148 BI.setSuccessor(0, FalseDest);
12149 BI.setSuccessor(1, TrueDest);
12150 RemoveFromWorkList(I);
12151 I->eraseFromParent();
12152 AddToWorkList(NewSCC);
12156 // Cannonicalize icmp_ne -> icmp_eq
12157 ICmpInst::Predicate IPred;
12158 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12159 TrueDest, FalseDest)))
12160 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12161 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12162 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12163 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12164 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12165 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12166 NewSCC->takeName(I);
12167 // Swap Destinations and condition...
12168 BI.setCondition(NewSCC);
12169 BI.setSuccessor(0, FalseDest);
12170 BI.setSuccessor(1, TrueDest);
12171 RemoveFromWorkList(I);
12172 I->eraseFromParent();;
12173 AddToWorkList(NewSCC);
12180 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12181 Value *Cond = SI.getCondition();
12182 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12183 if (I->getOpcode() == Instruction::Add)
12184 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12185 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12186 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12188 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12190 SI.setOperand(0, I->getOperand(0));
12198 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12199 Value *Agg = EV.getAggregateOperand();
12201 if (!EV.hasIndices())
12202 return ReplaceInstUsesWith(EV, Agg);
12204 if (Constant *C = dyn_cast<Constant>(Agg)) {
12205 if (isa<UndefValue>(C))
12206 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12208 if (isa<ConstantAggregateZero>(C))
12209 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12211 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12212 // Extract the element indexed by the first index out of the constant
12213 Value *V = C->getOperand(*EV.idx_begin());
12214 if (EV.getNumIndices() > 1)
12215 // Extract the remaining indices out of the constant indexed by the
12217 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12219 return ReplaceInstUsesWith(EV, V);
12221 return 0; // Can't handle other constants
12223 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12224 // We're extracting from an insertvalue instruction, compare the indices
12225 const unsigned *exti, *exte, *insi, *inse;
12226 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12227 exte = EV.idx_end(), inse = IV->idx_end();
12228 exti != exte && insi != inse;
12230 if (*insi != *exti)
12231 // The insert and extract both reference distinctly different elements.
12232 // This means the extract is not influenced by the insert, and we can
12233 // replace the aggregate operand of the extract with the aggregate
12234 // operand of the insert. i.e., replace
12235 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12236 // %E = extractvalue { i32, { i32 } } %I, 0
12238 // %E = extractvalue { i32, { i32 } } %A, 0
12239 return ExtractValueInst::Create(IV->getAggregateOperand(),
12240 EV.idx_begin(), EV.idx_end());
12242 if (exti == exte && insi == inse)
12243 // Both iterators are at the end: Index lists are identical. Replace
12244 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12245 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12247 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12248 if (exti == exte) {
12249 // The extract list is a prefix of the insert list. i.e. replace
12250 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12251 // %E = extractvalue { i32, { i32 } } %I, 1
12253 // %X = extractvalue { i32, { i32 } } %A, 1
12254 // %E = insertvalue { i32 } %X, i32 42, 0
12255 // by switching the order of the insert and extract (though the
12256 // insertvalue should be left in, since it may have other uses).
12257 Value *NewEV = InsertNewInstBefore(
12258 ExtractValueInst::Create(IV->getAggregateOperand(),
12259 EV.idx_begin(), EV.idx_end()),
12261 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12265 // The insert list is a prefix of the extract list
12266 // We can simply remove the common indices from the extract and make it
12267 // operate on the inserted value instead of the insertvalue result.
12269 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12270 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12272 // %E extractvalue { i32 } { i32 42 }, 0
12273 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12276 // Can't simplify extracts from other values. Note that nested extracts are
12277 // already simplified implicitely by the above (extract ( extract (insert) )
12278 // will be translated into extract ( insert ( extract ) ) first and then just
12279 // the value inserted, if appropriate).
12283 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12284 /// is to leave as a vector operation.
12285 static bool CheapToScalarize(Value *V, bool isConstant) {
12286 if (isa<ConstantAggregateZero>(V))
12288 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12289 if (isConstant) return true;
12290 // If all elts are the same, we can extract.
12291 Constant *Op0 = C->getOperand(0);
12292 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12293 if (C->getOperand(i) != Op0)
12297 Instruction *I = dyn_cast<Instruction>(V);
12298 if (!I) return false;
12300 // Insert element gets simplified to the inserted element or is deleted if
12301 // this is constant idx extract element and its a constant idx insertelt.
12302 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12303 isa<ConstantInt>(I->getOperand(2)))
12305 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12307 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12308 if (BO->hasOneUse() &&
12309 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12310 CheapToScalarize(BO->getOperand(1), isConstant)))
12312 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12313 if (CI->hasOneUse() &&
12314 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12315 CheapToScalarize(CI->getOperand(1), isConstant)))
12321 /// Read and decode a shufflevector mask.
12323 /// It turns undef elements into values that are larger than the number of
12324 /// elements in the input.
12325 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12326 unsigned NElts = SVI->getType()->getNumElements();
12327 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12328 return std::vector<unsigned>(NElts, 0);
12329 if (isa<UndefValue>(SVI->getOperand(2)))
12330 return std::vector<unsigned>(NElts, 2*NElts);
12332 std::vector<unsigned> Result;
12333 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12334 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12335 if (isa<UndefValue>(*i))
12336 Result.push_back(NElts*2); // undef -> 8
12338 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12342 /// FindScalarElement - Given a vector and an element number, see if the scalar
12343 /// value is already around as a register, for example if it were inserted then
12344 /// extracted from the vector.
12345 static Value *FindScalarElement(Value *V, unsigned EltNo,
12346 LLVMContext *Context) {
12347 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12348 const VectorType *PTy = cast<VectorType>(V->getType());
12349 unsigned Width = PTy->getNumElements();
12350 if (EltNo >= Width) // Out of range access.
12351 return UndefValue::get(PTy->getElementType());
12353 if (isa<UndefValue>(V))
12354 return UndefValue::get(PTy->getElementType());
12355 else if (isa<ConstantAggregateZero>(V))
12356 return Constant::getNullValue(PTy->getElementType());
12357 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12358 return CP->getOperand(EltNo);
12359 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12360 // If this is an insert to a variable element, we don't know what it is.
12361 if (!isa<ConstantInt>(III->getOperand(2)))
12363 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12365 // If this is an insert to the element we are looking for, return the
12367 if (EltNo == IIElt)
12368 return III->getOperand(1);
12370 // Otherwise, the insertelement doesn't modify the value, recurse on its
12372 return FindScalarElement(III->getOperand(0), EltNo, Context);
12373 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12374 unsigned LHSWidth =
12375 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12376 unsigned InEl = getShuffleMask(SVI)[EltNo];
12377 if (InEl < LHSWidth)
12378 return FindScalarElement(SVI->getOperand(0), InEl, Context);
12379 else if (InEl < LHSWidth*2)
12380 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12382 return UndefValue::get(PTy->getElementType());
12385 // Otherwise, we don't know.
12389 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12390 // If vector val is undef, replace extract with scalar undef.
12391 if (isa<UndefValue>(EI.getOperand(0)))
12392 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12394 // If vector val is constant 0, replace extract with scalar 0.
12395 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12396 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12398 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12399 // If vector val is constant with all elements the same, replace EI with
12400 // that element. When the elements are not identical, we cannot replace yet
12401 // (we do that below, but only when the index is constant).
12402 Constant *op0 = C->getOperand(0);
12403 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12404 if (C->getOperand(i) != op0) {
12409 return ReplaceInstUsesWith(EI, op0);
12412 // If extracting a specified index from the vector, see if we can recursively
12413 // find a previously computed scalar that was inserted into the vector.
12414 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12415 unsigned IndexVal = IdxC->getZExtValue();
12416 unsigned VectorWidth =
12417 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12419 // If this is extracting an invalid index, turn this into undef, to avoid
12420 // crashing the code below.
12421 if (IndexVal >= VectorWidth)
12422 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12424 // This instruction only demands the single element from the input vector.
12425 // If the input vector has a single use, simplify it based on this use
12427 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12428 APInt UndefElts(VectorWidth, 0);
12429 APInt DemandedMask(VectorWidth, 1 << IndexVal);
12430 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12431 DemandedMask, UndefElts)) {
12432 EI.setOperand(0, V);
12437 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12438 return ReplaceInstUsesWith(EI, Elt);
12440 // If the this extractelement is directly using a bitcast from a vector of
12441 // the same number of elements, see if we can find the source element from
12442 // it. In this case, we will end up needing to bitcast the scalars.
12443 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12444 if (const VectorType *VT =
12445 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12446 if (VT->getNumElements() == VectorWidth)
12447 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12448 IndexVal, Context))
12449 return new BitCastInst(Elt, EI.getType());
12453 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12454 if (I->hasOneUse()) {
12455 // Push extractelement into predecessor operation if legal and
12456 // profitable to do so
12457 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12458 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12459 if (CheapToScalarize(BO, isConstantElt)) {
12460 ExtractElementInst *newEI0 =
12461 ExtractElementInst::Create(BO->getOperand(0), EI.getOperand(1),
12462 EI.getName()+".lhs");
12463 ExtractElementInst *newEI1 =
12464 ExtractElementInst::Create(BO->getOperand(1), EI.getOperand(1),
12465 EI.getName()+".rhs");
12466 InsertNewInstBefore(newEI0, EI);
12467 InsertNewInstBefore(newEI1, EI);
12468 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12470 } else if (isa<LoadInst>(I)) {
12472 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12473 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12474 PointerType::get(EI.getType(), AS),*I);
12475 GetElementPtrInst *GEP =
12476 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12477 cast<GEPOperator>(GEP)->setIsInBounds(true);
12478 InsertNewInstBefore(GEP, *I);
12479 LoadInst* Load = new LoadInst(GEP, "tmp");
12480 InsertNewInstBefore(Load, *I);
12481 return ReplaceInstUsesWith(EI, Load);
12484 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12485 // Extracting the inserted element?
12486 if (IE->getOperand(2) == EI.getOperand(1))
12487 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12488 // If the inserted and extracted elements are constants, they must not
12489 // be the same value, extract from the pre-inserted value instead.
12490 if (isa<Constant>(IE->getOperand(2)) &&
12491 isa<Constant>(EI.getOperand(1))) {
12492 AddUsesToWorkList(EI);
12493 EI.setOperand(0, IE->getOperand(0));
12496 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12497 // If this is extracting an element from a shufflevector, figure out where
12498 // it came from and extract from the appropriate input element instead.
12499 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12500 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12502 unsigned LHSWidth =
12503 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12505 if (SrcIdx < LHSWidth)
12506 Src = SVI->getOperand(0);
12507 else if (SrcIdx < LHSWidth*2) {
12508 SrcIdx -= LHSWidth;
12509 Src = SVI->getOperand(1);
12511 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12513 return ExtractElementInst::Create(Src,
12514 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx, false));
12517 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12522 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12523 /// elements from either LHS or RHS, return the shuffle mask and true.
12524 /// Otherwise, return false.
12525 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12526 std::vector<Constant*> &Mask,
12527 LLVMContext *Context) {
12528 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12529 "Invalid CollectSingleShuffleElements");
12530 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12532 if (isa<UndefValue>(V)) {
12533 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12535 } else if (V == LHS) {
12536 for (unsigned i = 0; i != NumElts; ++i)
12537 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12539 } else if (V == RHS) {
12540 for (unsigned i = 0; i != NumElts; ++i)
12541 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12543 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12544 // If this is an insert of an extract from some other vector, include it.
12545 Value *VecOp = IEI->getOperand(0);
12546 Value *ScalarOp = IEI->getOperand(1);
12547 Value *IdxOp = IEI->getOperand(2);
12549 if (!isa<ConstantInt>(IdxOp))
12551 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12553 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12554 // Okay, we can handle this if the vector we are insertinting into is
12555 // transitively ok.
12556 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12557 // If so, update the mask to reflect the inserted undef.
12558 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12561 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12562 if (isa<ConstantInt>(EI->getOperand(1)) &&
12563 EI->getOperand(0)->getType() == V->getType()) {
12564 unsigned ExtractedIdx =
12565 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12567 // This must be extracting from either LHS or RHS.
12568 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12569 // Okay, we can handle this if the vector we are insertinting into is
12570 // transitively ok.
12571 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12572 // If so, update the mask to reflect the inserted value.
12573 if (EI->getOperand(0) == LHS) {
12574 Mask[InsertedIdx % NumElts] =
12575 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12577 assert(EI->getOperand(0) == RHS);
12578 Mask[InsertedIdx % NumElts] =
12579 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12588 // TODO: Handle shufflevector here!
12593 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12594 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12595 /// that computes V and the LHS value of the shuffle.
12596 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12597 Value *&RHS, LLVMContext *Context) {
12598 assert(isa<VectorType>(V->getType()) &&
12599 (RHS == 0 || V->getType() == RHS->getType()) &&
12600 "Invalid shuffle!");
12601 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12603 if (isa<UndefValue>(V)) {
12604 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12606 } else if (isa<ConstantAggregateZero>(V)) {
12607 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12609 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12610 // If this is an insert of an extract from some other vector, include it.
12611 Value *VecOp = IEI->getOperand(0);
12612 Value *ScalarOp = IEI->getOperand(1);
12613 Value *IdxOp = IEI->getOperand(2);
12615 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12616 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12617 EI->getOperand(0)->getType() == V->getType()) {
12618 unsigned ExtractedIdx =
12619 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12620 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12622 // Either the extracted from or inserted into vector must be RHSVec,
12623 // otherwise we'd end up with a shuffle of three inputs.
12624 if (EI->getOperand(0) == RHS || RHS == 0) {
12625 RHS = EI->getOperand(0);
12626 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12627 Mask[InsertedIdx % NumElts] =
12628 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12632 if (VecOp == RHS) {
12633 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12635 // Everything but the extracted element is replaced with the RHS.
12636 for (unsigned i = 0; i != NumElts; ++i) {
12637 if (i != InsertedIdx)
12638 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12643 // If this insertelement is a chain that comes from exactly these two
12644 // vectors, return the vector and the effective shuffle.
12645 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12647 return EI->getOperand(0);
12652 // TODO: Handle shufflevector here!
12654 // Otherwise, can't do anything fancy. Return an identity vector.
12655 for (unsigned i = 0; i != NumElts; ++i)
12656 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12660 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12661 Value *VecOp = IE.getOperand(0);
12662 Value *ScalarOp = IE.getOperand(1);
12663 Value *IdxOp = IE.getOperand(2);
12665 // Inserting an undef or into an undefined place, remove this.
12666 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12667 ReplaceInstUsesWith(IE, VecOp);
12669 // If the inserted element was extracted from some other vector, and if the
12670 // indexes are constant, try to turn this into a shufflevector operation.
12671 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12672 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12673 EI->getOperand(0)->getType() == IE.getType()) {
12674 unsigned NumVectorElts = IE.getType()->getNumElements();
12675 unsigned ExtractedIdx =
12676 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12677 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12679 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12680 return ReplaceInstUsesWith(IE, VecOp);
12682 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12683 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12685 // If we are extracting a value from a vector, then inserting it right
12686 // back into the same place, just use the input vector.
12687 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12688 return ReplaceInstUsesWith(IE, VecOp);
12690 // We could theoretically do this for ANY input. However, doing so could
12691 // turn chains of insertelement instructions into a chain of shufflevector
12692 // instructions, and right now we do not merge shufflevectors. As such,
12693 // only do this in a situation where it is clear that there is benefit.
12694 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12695 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12696 // the values of VecOp, except then one read from EIOp0.
12697 // Build a new shuffle mask.
12698 std::vector<Constant*> Mask;
12699 if (isa<UndefValue>(VecOp))
12700 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
12702 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12703 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
12706 Mask[InsertedIdx] =
12707 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12708 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12709 ConstantVector::get(Mask));
12712 // If this insertelement isn't used by some other insertelement, turn it
12713 // (and any insertelements it points to), into one big shuffle.
12714 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12715 std::vector<Constant*> Mask;
12717 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12718 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12719 // We now have a shuffle of LHS, RHS, Mask.
12720 return new ShuffleVectorInst(LHS, RHS,
12721 ConstantVector::get(Mask));
12726 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12727 APInt UndefElts(VWidth, 0);
12728 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12729 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12736 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12737 Value *LHS = SVI.getOperand(0);
12738 Value *RHS = SVI.getOperand(1);
12739 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12741 bool MadeChange = false;
12743 // Undefined shuffle mask -> undefined value.
12744 if (isa<UndefValue>(SVI.getOperand(2)))
12745 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12747 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12749 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12752 APInt UndefElts(VWidth, 0);
12753 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12754 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12755 LHS = SVI.getOperand(0);
12756 RHS = SVI.getOperand(1);
12760 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12761 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12762 if (LHS == RHS || isa<UndefValue>(LHS)) {
12763 if (isa<UndefValue>(LHS) && LHS == RHS) {
12764 // shuffle(undef,undef,mask) -> undef.
12765 return ReplaceInstUsesWith(SVI, LHS);
12768 // Remap any references to RHS to use LHS.
12769 std::vector<Constant*> Elts;
12770 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12771 if (Mask[i] >= 2*e)
12772 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12774 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12775 (Mask[i] < e && isa<UndefValue>(LHS))) {
12776 Mask[i] = 2*e; // Turn into undef.
12777 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12779 Mask[i] = Mask[i] % e; // Force to LHS.
12780 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12784 SVI.setOperand(0, SVI.getOperand(1));
12785 SVI.setOperand(1, UndefValue::get(RHS->getType()));
12786 SVI.setOperand(2, ConstantVector::get(Elts));
12787 LHS = SVI.getOperand(0);
12788 RHS = SVI.getOperand(1);
12792 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12793 bool isLHSID = true, isRHSID = true;
12795 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12796 if (Mask[i] >= e*2) continue; // Ignore undef values.
12797 // Is this an identity shuffle of the LHS value?
12798 isLHSID &= (Mask[i] == i);
12800 // Is this an identity shuffle of the RHS value?
12801 isRHSID &= (Mask[i]-e == i);
12804 // Eliminate identity shuffles.
12805 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12806 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12808 // If the LHS is a shufflevector itself, see if we can combine it with this
12809 // one without producing an unusual shuffle. Here we are really conservative:
12810 // we are absolutely afraid of producing a shuffle mask not in the input
12811 // program, because the code gen may not be smart enough to turn a merged
12812 // shuffle into two specific shuffles: it may produce worse code. As such,
12813 // we only merge two shuffles if the result is one of the two input shuffle
12814 // masks. In this case, merging the shuffles just removes one instruction,
12815 // which we know is safe. This is good for things like turning:
12816 // (splat(splat)) -> splat.
12817 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12818 if (isa<UndefValue>(RHS)) {
12819 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12821 std::vector<unsigned> NewMask;
12822 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12823 if (Mask[i] >= 2*e)
12824 NewMask.push_back(2*e);
12826 NewMask.push_back(LHSMask[Mask[i]]);
12828 // If the result mask is equal to the src shuffle or this shuffle mask, do
12829 // the replacement.
12830 if (NewMask == LHSMask || NewMask == Mask) {
12831 unsigned LHSInNElts =
12832 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12833 std::vector<Constant*> Elts;
12834 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12835 if (NewMask[i] >= LHSInNElts*2) {
12836 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12838 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
12841 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12842 LHSSVI->getOperand(1),
12843 ConstantVector::get(Elts));
12848 return MadeChange ? &SVI : 0;
12854 /// TryToSinkInstruction - Try to move the specified instruction from its
12855 /// current block into the beginning of DestBlock, which can only happen if it's
12856 /// safe to move the instruction past all of the instructions between it and the
12857 /// end of its block.
12858 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12859 assert(I->hasOneUse() && "Invariants didn't hold!");
12861 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12862 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12865 // Do not sink alloca instructions out of the entry block.
12866 if (isa<AllocaInst>(I) && I->getParent() ==
12867 &DestBlock->getParent()->getEntryBlock())
12870 // We can only sink load instructions if there is nothing between the load and
12871 // the end of block that could change the value.
12872 if (I->mayReadFromMemory()) {
12873 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12875 if (Scan->mayWriteToMemory())
12879 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12881 CopyPrecedingStopPoint(I, InsertPos);
12882 I->moveBefore(InsertPos);
12888 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12889 /// all reachable code to the worklist.
12891 /// This has a couple of tricks to make the code faster and more powerful. In
12892 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12893 /// them to the worklist (this significantly speeds up instcombine on code where
12894 /// many instructions are dead or constant). Additionally, if we find a branch
12895 /// whose condition is a known constant, we only visit the reachable successors.
12897 static void AddReachableCodeToWorklist(BasicBlock *BB,
12898 SmallPtrSet<BasicBlock*, 64> &Visited,
12900 const TargetData *TD) {
12901 SmallVector<BasicBlock*, 256> Worklist;
12902 Worklist.push_back(BB);
12904 while (!Worklist.empty()) {
12905 BB = Worklist.back();
12906 Worklist.pop_back();
12908 // We have now visited this block! If we've already been here, ignore it.
12909 if (!Visited.insert(BB)) continue;
12911 DbgInfoIntrinsic *DBI_Prev = NULL;
12912 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12913 Instruction *Inst = BBI++;
12915 // DCE instruction if trivially dead.
12916 if (isInstructionTriviallyDead(Inst)) {
12918 DOUT << "IC: DCE: " << *Inst << '\n';
12919 Inst->eraseFromParent();
12923 // ConstantProp instruction if trivially constant.
12924 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12925 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst << '\n';
12926 Inst->replaceAllUsesWith(C);
12928 Inst->eraseFromParent();
12932 // If there are two consecutive llvm.dbg.stoppoint calls then
12933 // it is likely that the optimizer deleted code in between these
12935 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12938 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12939 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12940 IC.RemoveFromWorkList(DBI_Prev);
12941 DBI_Prev->eraseFromParent();
12943 DBI_Prev = DBI_Next;
12948 IC.AddToWorkList(Inst);
12951 // Recursively visit successors. If this is a branch or switch on a
12952 // constant, only visit the reachable successor.
12953 TerminatorInst *TI = BB->getTerminator();
12954 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12955 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12956 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12957 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12958 Worklist.push_back(ReachableBB);
12961 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12962 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12963 // See if this is an explicit destination.
12964 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12965 if (SI->getCaseValue(i) == Cond) {
12966 BasicBlock *ReachableBB = SI->getSuccessor(i);
12967 Worklist.push_back(ReachableBB);
12971 // Otherwise it is the default destination.
12972 Worklist.push_back(SI->getSuccessor(0));
12977 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12978 Worklist.push_back(TI->getSuccessor(i));
12982 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12983 bool Changed = false;
12984 TD = getAnalysisIfAvailable<TargetData>();
12986 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12987 << F.getNameStr() << "\n");
12990 // Do a depth-first traversal of the function, populate the worklist with
12991 // the reachable instructions. Ignore blocks that are not reachable. Keep
12992 // track of which blocks we visit.
12993 SmallPtrSet<BasicBlock*, 64> Visited;
12994 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12996 // Do a quick scan over the function. If we find any blocks that are
12997 // unreachable, remove any instructions inside of them. This prevents
12998 // the instcombine code from having to deal with some bad special cases.
12999 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13000 if (!Visited.count(BB)) {
13001 Instruction *Term = BB->getTerminator();
13002 while (Term != BB->begin()) { // Remove instrs bottom-up
13003 BasicBlock::iterator I = Term; --I;
13005 DOUT << "IC: DCE: " << *I << '\n';
13006 // A debug intrinsic shouldn't force another iteration if we weren't
13007 // going to do one without it.
13008 if (!isa<DbgInfoIntrinsic>(I)) {
13012 if (!I->use_empty())
13013 I->replaceAllUsesWith(UndefValue::get(I->getType()));
13014 I->eraseFromParent();
13019 while (!Worklist.empty()) {
13020 Instruction *I = RemoveOneFromWorkList();
13021 if (I == 0) continue; // skip null values.
13023 // Check to see if we can DCE the instruction.
13024 if (isInstructionTriviallyDead(I)) {
13025 // Add operands to the worklist.
13026 if (I->getNumOperands() < 4)
13027 AddUsesToWorkList(*I);
13030 DOUT << "IC: DCE: " << *I << '\n';
13032 I->eraseFromParent();
13033 RemoveFromWorkList(I);
13038 // Instruction isn't dead, see if we can constant propagate it.
13039 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
13040 DOUT << "IC: ConstFold to: " << *C << " from: " << *I << '\n';
13042 // Add operands to the worklist.
13043 AddUsesToWorkList(*I);
13044 ReplaceInstUsesWith(*I, C);
13047 I->eraseFromParent();
13048 RemoveFromWorkList(I);
13054 // See if we can constant fold its operands.
13055 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13056 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
13057 if (Constant *NewC = ConstantFoldConstantExpression(CE,
13058 F.getContext(), TD))
13065 // See if we can trivially sink this instruction to a successor basic block.
13066 if (I->hasOneUse()) {
13067 BasicBlock *BB = I->getParent();
13068 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13069 if (UserParent != BB) {
13070 bool UserIsSuccessor = false;
13071 // See if the user is one of our successors.
13072 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13073 if (*SI == UserParent) {
13074 UserIsSuccessor = true;
13078 // If the user is one of our immediate successors, and if that successor
13079 // only has us as a predecessors (we'd have to split the critical edge
13080 // otherwise), we can keep going.
13081 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13082 next(pred_begin(UserParent)) == pred_end(UserParent))
13083 // Okay, the CFG is simple enough, try to sink this instruction.
13084 Changed |= TryToSinkInstruction(I, UserParent);
13088 // Now that we have an instruction, try combining it to simplify it...
13092 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13093 if (Instruction *Result = visit(*I)) {
13095 // Should we replace the old instruction with a new one?
13097 DOUT << "IC: Old = " << *I << '\n'
13098 << " New = " << *Result << '\n';
13100 // Everything uses the new instruction now.
13101 I->replaceAllUsesWith(Result);
13103 // Push the new instruction and any users onto the worklist.
13104 AddToWorkList(Result);
13105 AddUsersToWorkList(*Result);
13107 // Move the name to the new instruction first.
13108 Result->takeName(I);
13110 // Insert the new instruction into the basic block...
13111 BasicBlock *InstParent = I->getParent();
13112 BasicBlock::iterator InsertPos = I;
13114 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13115 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13118 InstParent->getInstList().insert(InsertPos, Result);
13120 // Make sure that we reprocess all operands now that we reduced their
13122 AddUsesToWorkList(*I);
13124 // Instructions can end up on the worklist more than once. Make sure
13125 // we do not process an instruction that has been deleted.
13126 RemoveFromWorkList(I);
13128 // Erase the old instruction.
13129 InstParent->getInstList().erase(I);
13132 DOUT << "IC: Mod = " << OrigI << '\n'
13133 << " New = " << *I << '\n';
13136 // If the instruction was modified, it's possible that it is now dead.
13137 // if so, remove it.
13138 if (isInstructionTriviallyDead(I)) {
13139 // Make sure we process all operands now that we are reducing their
13141 AddUsesToWorkList(*I);
13143 // Instructions may end up in the worklist more than once. Erase all
13144 // occurrences of this instruction.
13145 RemoveFromWorkList(I);
13146 I->eraseFromParent();
13149 AddUsersToWorkList(*I);
13156 assert(WorklistMap.empty() && "Worklist empty, but map not?");
13158 // Do an explicit clear, this shrinks the map if needed.
13159 WorklistMap.clear();
13164 bool InstCombiner::runOnFunction(Function &F) {
13165 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13166 Context = &F.getContext();
13168 bool EverMadeChange = false;
13170 // Iterate while there is work to do.
13171 unsigned Iteration = 0;
13172 while (DoOneIteration(F, Iteration++))
13173 EverMadeChange = true;
13174 return EverMadeChange;
13177 FunctionPass *llvm::createInstructionCombiningPass() {
13178 return new InstCombiner();