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/IRBuilder.h"
56 #include "llvm/Support/MathExtras.h"
57 #include "llvm/Support/PatternMatch.h"
58 #include "llvm/Support/Compiler.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include "llvm/ADT/DenseMap.h"
61 #include "llvm/ADT/SmallVector.h"
62 #include "llvm/ADT/SmallPtrSet.h"
63 #include "llvm/ADT/Statistic.h"
64 #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 /// InstCombineWorklist - This is the worklist management logic for
79 class InstCombineWorklist {
80 SmallVector<Instruction*, 256> Worklist;
81 DenseMap<Instruction*, unsigned> WorklistMap;
83 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
84 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
86 InstCombineWorklist() {}
88 bool isEmpty() const { return Worklist.empty(); }
90 /// Add - Add the specified instruction to the worklist if it isn't already
92 void Add(Instruction *I) {
93 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
94 Worklist.push_back(I);
97 void AddValue(Value *V) {
98 if (Instruction *I = dyn_cast<Instruction>(V))
102 // Remove - remove I from the worklist if it exists.
103 void Remove(Instruction *I) {
104 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
105 if (It == WorklistMap.end()) return; // Not in worklist.
107 // Don't bother moving everything down, just null out the slot.
108 Worklist[It->second] = 0;
110 WorklistMap.erase(It);
113 Instruction *RemoveOne() {
114 Instruction *I = Worklist.back();
116 WorklistMap.erase(I);
120 /// AddUsersToWorkList - When an instruction is simplified, add all users of
121 /// the instruction to the work lists because they might get more simplified
124 void AddUsersToWorkList(Instruction &I) {
125 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
127 Add(cast<Instruction>(*UI));
131 /// Zap - check that the worklist is empty and nuke the backing store for
132 /// the map if it is large.
134 assert(WorklistMap.empty() && "Worklist empty, but map not?");
136 // Do an explicit clear, this shrinks the map if needed.
140 } // end anonymous namespace.
144 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
145 /// just like the normal insertion helper, but also adds any new instructions
146 /// to the instcombine worklist.
147 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
148 InstCombineWorklist &Worklist;
150 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
152 void InsertHelper(Instruction *I, const Twine &Name,
153 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
154 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
158 } // end anonymous namespace
162 class VISIBILITY_HIDDEN InstCombiner
163 : public FunctionPass,
164 public InstVisitor<InstCombiner, Instruction*> {
166 bool MustPreserveLCSSA;
168 /// Worklist - All of the instructions that need to be simplified.
169 InstCombineWorklist Worklist;
171 /// Builder - This is an IRBuilder that automatically inserts new
172 /// instructions into the worklist when they are created.
173 typedef IRBuilder<true, ConstantFolder, InstCombineIRInserter> BuilderTy;
176 static char ID; // Pass identification, replacement for typeid
177 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
179 LLVMContext *Context;
180 LLVMContext *getContext() const { return Context; }
183 virtual bool runOnFunction(Function &F);
185 bool DoOneIteration(Function &F, unsigned ItNum);
187 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
188 AU.addPreservedID(LCSSAID);
189 AU.setPreservesCFG();
192 TargetData *getTargetData() const { return TD; }
194 // Visitation implementation - Implement instruction combining for different
195 // instruction types. The semantics are as follows:
197 // null - No change was made
198 // I - Change was made, I is still valid, I may be dead though
199 // otherwise - Change was made, replace I with returned instruction
201 Instruction *visitAdd(BinaryOperator &I);
202 Instruction *visitFAdd(BinaryOperator &I);
203 Instruction *visitSub(BinaryOperator &I);
204 Instruction *visitFSub(BinaryOperator &I);
205 Instruction *visitMul(BinaryOperator &I);
206 Instruction *visitFMul(BinaryOperator &I);
207 Instruction *visitURem(BinaryOperator &I);
208 Instruction *visitSRem(BinaryOperator &I);
209 Instruction *visitFRem(BinaryOperator &I);
210 bool SimplifyDivRemOfSelect(BinaryOperator &I);
211 Instruction *commonRemTransforms(BinaryOperator &I);
212 Instruction *commonIRemTransforms(BinaryOperator &I);
213 Instruction *commonDivTransforms(BinaryOperator &I);
214 Instruction *commonIDivTransforms(BinaryOperator &I);
215 Instruction *visitUDiv(BinaryOperator &I);
216 Instruction *visitSDiv(BinaryOperator &I);
217 Instruction *visitFDiv(BinaryOperator &I);
218 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
219 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
220 Instruction *visitAnd(BinaryOperator &I);
221 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
222 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
223 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
224 Value *A, Value *B, Value *C);
225 Instruction *visitOr (BinaryOperator &I);
226 Instruction *visitXor(BinaryOperator &I);
227 Instruction *visitShl(BinaryOperator &I);
228 Instruction *visitAShr(BinaryOperator &I);
229 Instruction *visitLShr(BinaryOperator &I);
230 Instruction *commonShiftTransforms(BinaryOperator &I);
231 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
233 Instruction *visitFCmpInst(FCmpInst &I);
234 Instruction *visitICmpInst(ICmpInst &I);
235 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
236 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
239 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
240 ConstantInt *DivRHS);
242 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
243 ICmpInst::Predicate Cond, Instruction &I);
244 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
246 Instruction *commonCastTransforms(CastInst &CI);
247 Instruction *commonIntCastTransforms(CastInst &CI);
248 Instruction *commonPointerCastTransforms(CastInst &CI);
249 Instruction *visitTrunc(TruncInst &CI);
250 Instruction *visitZExt(ZExtInst &CI);
251 Instruction *visitSExt(SExtInst &CI);
252 Instruction *visitFPTrunc(FPTruncInst &CI);
253 Instruction *visitFPExt(CastInst &CI);
254 Instruction *visitFPToUI(FPToUIInst &FI);
255 Instruction *visitFPToSI(FPToSIInst &FI);
256 Instruction *visitUIToFP(CastInst &CI);
257 Instruction *visitSIToFP(CastInst &CI);
258 Instruction *visitPtrToInt(PtrToIntInst &CI);
259 Instruction *visitIntToPtr(IntToPtrInst &CI);
260 Instruction *visitBitCast(BitCastInst &CI);
261 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
263 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
264 Instruction *visitSelectInst(SelectInst &SI);
265 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
266 Instruction *visitCallInst(CallInst &CI);
267 Instruction *visitInvokeInst(InvokeInst &II);
268 Instruction *visitPHINode(PHINode &PN);
269 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
270 Instruction *visitAllocationInst(AllocationInst &AI);
271 Instruction *visitFreeInst(FreeInst &FI);
272 Instruction *visitLoadInst(LoadInst &LI);
273 Instruction *visitStoreInst(StoreInst &SI);
274 Instruction *visitBranchInst(BranchInst &BI);
275 Instruction *visitSwitchInst(SwitchInst &SI);
276 Instruction *visitInsertElementInst(InsertElementInst &IE);
277 Instruction *visitExtractElementInst(ExtractElementInst &EI);
278 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
279 Instruction *visitExtractValueInst(ExtractValueInst &EV);
281 // visitInstruction - Specify what to return for unhandled instructions...
282 Instruction *visitInstruction(Instruction &I) { return 0; }
285 Instruction *visitCallSite(CallSite CS);
286 bool transformConstExprCastCall(CallSite CS);
287 Instruction *transformCallThroughTrampoline(CallSite CS);
288 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
289 bool DoXform = true);
290 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
291 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
295 // InsertNewInstBefore - insert an instruction New before instruction Old
296 // in the program. Add the new instruction to the worklist.
298 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
299 assert(New && New->getParent() == 0 &&
300 "New instruction already inserted into a basic block!");
301 BasicBlock *BB = Old.getParent();
302 BB->getInstList().insert(&Old, New); // Insert inst
307 // ReplaceInstUsesWith - This method is to be used when an instruction is
308 // found to be dead, replacable with another preexisting expression. Here
309 // we add all uses of I to the worklist, replace all uses of I with the new
310 // value, then return I, so that the inst combiner will know that I was
313 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
314 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
316 // If we are replacing the instruction with itself, this must be in a
317 // segment of unreachable code, so just clobber the instruction.
319 V = UndefValue::get(I.getType());
321 I.replaceAllUsesWith(V);
325 // EraseInstFromFunction - When dealing with an instruction that has side
326 // effects or produces a void value, we can't rely on DCE to delete the
327 // instruction. Instead, visit methods should return the value returned by
329 Instruction *EraseInstFromFunction(Instruction &I) {
330 assert(I.use_empty() && "Cannot erase instruction that is used!");
331 // Make sure that we reprocess all operands now that we reduced their
333 if (I.getNumOperands() < 8) {
334 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
335 if (Instruction *Op = dyn_cast<Instruction>(*i))
340 return 0; // Don't do anything with FI
343 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
344 APInt &KnownOne, unsigned Depth = 0) const {
345 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
348 bool MaskedValueIsZero(Value *V, const APInt &Mask,
349 unsigned Depth = 0) const {
350 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
352 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
353 return llvm::ComputeNumSignBits(Op, TD, Depth);
358 /// SimplifyCommutative - This performs a few simplifications for
359 /// commutative operators.
360 bool SimplifyCommutative(BinaryOperator &I);
362 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
363 /// most-complex to least-complex order.
364 bool SimplifyCompare(CmpInst &I);
366 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
367 /// based on the demanded bits.
368 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
369 APInt& KnownZero, APInt& KnownOne,
371 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
372 APInt& KnownZero, APInt& KnownOne,
375 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
376 /// SimplifyDemandedBits knows about. See if the instruction has any
377 /// properties that allow us to simplify its operands.
378 bool SimplifyDemandedInstructionBits(Instruction &Inst);
380 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
381 APInt& UndefElts, unsigned Depth = 0);
383 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
384 // PHI node as operand #0, see if we can fold the instruction into the PHI
385 // (which is only possible if all operands to the PHI are constants).
386 Instruction *FoldOpIntoPhi(Instruction &I);
388 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
389 // operator and they all are only used by the PHI, PHI together their
390 // inputs, and do the operation once, to the result of the PHI.
391 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
392 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
393 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
396 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
397 ConstantInt *AndRHS, BinaryOperator &TheAnd);
399 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
400 bool isSub, Instruction &I);
401 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
402 bool isSigned, bool Inside, Instruction &IB);
403 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
404 Instruction *MatchBSwap(BinaryOperator &I);
405 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
406 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
407 Instruction *SimplifyMemSet(MemSetInst *MI);
410 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
412 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
413 unsigned CastOpc, int &NumCastsRemoved);
414 unsigned GetOrEnforceKnownAlignment(Value *V,
415 unsigned PrefAlign = 0);
418 } // end anonymous namespace
420 char InstCombiner::ID = 0;
421 static RegisterPass<InstCombiner>
422 X("instcombine", "Combine redundant instructions");
424 // getComplexity: Assign a complexity or rank value to LLVM Values...
425 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
426 static unsigned getComplexity(Value *V) {
427 if (isa<Instruction>(V)) {
428 if (BinaryOperator::isNeg(V) ||
429 BinaryOperator::isFNeg(V) ||
430 BinaryOperator::isNot(V))
434 if (isa<Argument>(V)) return 3;
435 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
438 // isOnlyUse - Return true if this instruction will be deleted if we stop using
440 static bool isOnlyUse(Value *V) {
441 return V->hasOneUse() || isa<Constant>(V);
444 // getPromotedType - Return the specified type promoted as it would be to pass
445 // though a va_arg area...
446 static const Type *getPromotedType(const Type *Ty) {
447 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
448 if (ITy->getBitWidth() < 32)
449 return Type::getInt32Ty(Ty->getContext());
454 /// getBitCastOperand - If the specified operand is a CastInst, a constant
455 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
456 /// operand value, otherwise return null.
457 static Value *getBitCastOperand(Value *V) {
458 if (Operator *O = dyn_cast<Operator>(V)) {
459 if (O->getOpcode() == Instruction::BitCast)
460 return O->getOperand(0);
461 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
462 if (GEP->hasAllZeroIndices())
463 return GEP->getPointerOperand();
468 /// This function is a wrapper around CastInst::isEliminableCastPair. It
469 /// simply extracts arguments and returns what that function returns.
470 static Instruction::CastOps
471 isEliminableCastPair(
472 const CastInst *CI, ///< The first cast instruction
473 unsigned opcode, ///< The opcode of the second cast instruction
474 const Type *DstTy, ///< The target type for the second cast instruction
475 TargetData *TD ///< The target data for pointer size
478 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
479 const Type *MidTy = CI->getType(); // B from above
481 // Get the opcodes of the two Cast instructions
482 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
483 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
485 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
487 TD ? TD->getIntPtrType(CI->getContext()) : 0);
489 // We don't want to form an inttoptr or ptrtoint that converts to an integer
490 // type that differs from the pointer size.
491 if ((Res == Instruction::IntToPtr &&
492 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
493 (Res == Instruction::PtrToInt &&
494 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
497 return Instruction::CastOps(Res);
500 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
501 /// in any code being generated. It does not require codegen if V is simple
502 /// enough or if the cast can be folded into other casts.
503 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
504 const Type *Ty, TargetData *TD) {
505 if (V->getType() == Ty || isa<Constant>(V)) return false;
507 // If this is another cast that can be eliminated, it isn't codegen either.
508 if (const CastInst *CI = dyn_cast<CastInst>(V))
509 if (isEliminableCastPair(CI, opcode, Ty, TD))
514 // SimplifyCommutative - This performs a few simplifications for commutative
517 // 1. Order operands such that they are listed from right (least complex) to
518 // left (most complex). This puts constants before unary operators before
521 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
522 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
524 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
525 bool Changed = false;
526 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
527 Changed = !I.swapOperands();
529 if (!I.isAssociative()) return Changed;
530 Instruction::BinaryOps Opcode = I.getOpcode();
531 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
532 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
533 if (isa<Constant>(I.getOperand(1))) {
534 Constant *Folded = ConstantExpr::get(I.getOpcode(),
535 cast<Constant>(I.getOperand(1)),
536 cast<Constant>(Op->getOperand(1)));
537 I.setOperand(0, Op->getOperand(0));
538 I.setOperand(1, Folded);
540 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
541 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
542 isOnlyUse(Op) && isOnlyUse(Op1)) {
543 Constant *C1 = cast<Constant>(Op->getOperand(1));
544 Constant *C2 = cast<Constant>(Op1->getOperand(1));
546 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
547 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
548 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
552 I.setOperand(0, New);
553 I.setOperand(1, Folded);
560 /// SimplifyCompare - For a CmpInst this function just orders the operands
561 /// so that theyare listed from right (least complex) to left (most complex).
562 /// This puts constants before unary operators before binary operators.
563 bool InstCombiner::SimplifyCompare(CmpInst &I) {
564 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
567 // Compare instructions are not associative so there's nothing else we can do.
571 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
572 // if the LHS is a constant zero (which is the 'negate' form).
574 static inline Value *dyn_castNegVal(Value *V) {
575 if (BinaryOperator::isNeg(V))
576 return BinaryOperator::getNegArgument(V);
578 // Constants can be considered to be negated values if they can be folded.
579 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
580 return ConstantExpr::getNeg(C);
582 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
583 if (C->getType()->getElementType()->isInteger())
584 return ConstantExpr::getNeg(C);
589 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
590 // instruction if the LHS is a constant negative zero (which is the 'negate'
593 static inline Value *dyn_castFNegVal(Value *V) {
594 if (BinaryOperator::isFNeg(V))
595 return BinaryOperator::getFNegArgument(V);
597 // Constants can be considered to be negated values if they can be folded.
598 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
599 return ConstantExpr::getFNeg(C);
601 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
602 if (C->getType()->getElementType()->isFloatingPoint())
603 return ConstantExpr::getFNeg(C);
608 static inline Value *dyn_castNotVal(Value *V) {
609 if (BinaryOperator::isNot(V))
610 return BinaryOperator::getNotArgument(V);
612 // Constants can be considered to be not'ed values...
613 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
614 return ConstantInt::get(C->getType(), ~C->getValue());
618 // dyn_castFoldableMul - If this value is a multiply that can be folded into
619 // other computations (because it has a constant operand), return the
620 // non-constant operand of the multiply, and set CST to point to the multiplier.
621 // Otherwise, return null.
623 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
624 if (V->hasOneUse() && V->getType()->isInteger())
625 if (Instruction *I = dyn_cast<Instruction>(V)) {
626 if (I->getOpcode() == Instruction::Mul)
627 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
628 return I->getOperand(0);
629 if (I->getOpcode() == Instruction::Shl)
630 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
631 // The multiplier is really 1 << CST.
632 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
633 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
634 CST = ConstantInt::get(V->getType()->getContext(),
635 APInt(BitWidth, 1).shl(CSTVal));
636 return I->getOperand(0);
642 /// AddOne - Add one to a ConstantInt
643 static Constant *AddOne(Constant *C) {
644 return ConstantExpr::getAdd(C,
645 ConstantInt::get(C->getType(), 1));
647 /// SubOne - Subtract one from a ConstantInt
648 static Constant *SubOne(ConstantInt *C) {
649 return ConstantExpr::getSub(C,
650 ConstantInt::get(C->getType(), 1));
652 /// MultiplyOverflows - True if the multiply can not be expressed in an int
654 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
655 uint32_t W = C1->getBitWidth();
656 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
665 APInt MulExt = LHSExt * RHSExt;
668 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
669 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
670 return MulExt.slt(Min) || MulExt.sgt(Max);
672 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
676 /// ShrinkDemandedConstant - Check to see if the specified operand of the
677 /// specified instruction is a constant integer. If so, check to see if there
678 /// are any bits set in the constant that are not demanded. If so, shrink the
679 /// constant and return true.
680 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
682 assert(I && "No instruction?");
683 assert(OpNo < I->getNumOperands() && "Operand index too large");
685 // If the operand is not a constant integer, nothing to do.
686 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
687 if (!OpC) return false;
689 // If there are no bits set that aren't demanded, nothing to do.
690 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
691 if ((~Demanded & OpC->getValue()) == 0)
694 // This instruction is producing bits that are not demanded. Shrink the RHS.
695 Demanded &= OpC->getValue();
696 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
700 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
701 // set of known zero and one bits, compute the maximum and minimum values that
702 // could have the specified known zero and known one bits, returning them in
704 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
705 const APInt& KnownOne,
706 APInt& Min, APInt& Max) {
707 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
708 KnownZero.getBitWidth() == Min.getBitWidth() &&
709 KnownZero.getBitWidth() == Max.getBitWidth() &&
710 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
711 APInt UnknownBits = ~(KnownZero|KnownOne);
713 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
714 // bit if it is unknown.
716 Max = KnownOne|UnknownBits;
718 if (UnknownBits.isNegative()) { // Sign bit is unknown
719 Min.set(Min.getBitWidth()-1);
720 Max.clear(Max.getBitWidth()-1);
724 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
725 // a set of known zero and one bits, compute the maximum and minimum values that
726 // could have the specified known zero and known one bits, returning them in
728 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
729 const APInt &KnownOne,
730 APInt &Min, APInt &Max) {
731 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
732 KnownZero.getBitWidth() == Min.getBitWidth() &&
733 KnownZero.getBitWidth() == Max.getBitWidth() &&
734 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
735 APInt UnknownBits = ~(KnownZero|KnownOne);
737 // The minimum value is when the unknown bits are all zeros.
739 // The maximum value is when the unknown bits are all ones.
740 Max = KnownOne|UnknownBits;
743 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
744 /// SimplifyDemandedBits knows about. See if the instruction has any
745 /// properties that allow us to simplify its operands.
746 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
747 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
748 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
749 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
751 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
752 KnownZero, KnownOne, 0);
753 if (V == 0) return false;
754 if (V == &Inst) return true;
755 ReplaceInstUsesWith(Inst, V);
759 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
760 /// specified instruction operand if possible, updating it in place. It returns
761 /// true if it made any change and false otherwise.
762 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
763 APInt &KnownZero, APInt &KnownOne,
765 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
766 KnownZero, KnownOne, Depth);
767 if (NewVal == 0) return false;
773 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
774 /// value based on the demanded bits. When this function is called, it is known
775 /// that only the bits set in DemandedMask of the result of V are ever used
776 /// downstream. Consequently, depending on the mask and V, it may be possible
777 /// to replace V with a constant or one of its operands. In such cases, this
778 /// function does the replacement and returns true. In all other cases, it
779 /// returns false after analyzing the expression and setting KnownOne and known
780 /// to be one in the expression. KnownZero contains all the bits that are known
781 /// to be zero in the expression. These are provided to potentially allow the
782 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
783 /// the expression. KnownOne and KnownZero always follow the invariant that
784 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
785 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
786 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
787 /// and KnownOne must all be the same.
789 /// This returns null if it did not change anything and it permits no
790 /// simplification. This returns V itself if it did some simplification of V's
791 /// operands based on the information about what bits are demanded. This returns
792 /// some other non-null value if it found out that V is equal to another value
793 /// in the context where the specified bits are demanded, but not for all users.
794 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
795 APInt &KnownZero, APInt &KnownOne,
797 assert(V != 0 && "Null pointer of Value???");
798 assert(Depth <= 6 && "Limit Search Depth");
799 uint32_t BitWidth = DemandedMask.getBitWidth();
800 const Type *VTy = V->getType();
801 assert((TD || !isa<PointerType>(VTy)) &&
802 "SimplifyDemandedBits needs to know bit widths!");
803 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
804 (!VTy->isIntOrIntVector() ||
805 VTy->getScalarSizeInBits() == BitWidth) &&
806 KnownZero.getBitWidth() == BitWidth &&
807 KnownOne.getBitWidth() == BitWidth &&
808 "Value *V, DemandedMask, KnownZero and KnownOne "
809 "must have same BitWidth");
810 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
811 // We know all of the bits for a constant!
812 KnownOne = CI->getValue() & DemandedMask;
813 KnownZero = ~KnownOne & DemandedMask;
816 if (isa<ConstantPointerNull>(V)) {
817 // We know all of the bits for a constant!
819 KnownZero = DemandedMask;
825 if (DemandedMask == 0) { // Not demanding any bits from V.
826 if (isa<UndefValue>(V))
828 return UndefValue::get(VTy);
831 if (Depth == 6) // Limit search depth.
834 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
835 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
837 Instruction *I = dyn_cast<Instruction>(V);
839 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
840 return 0; // Only analyze instructions.
843 // If there are multiple uses of this value and we aren't at the root, then
844 // we can't do any simplifications of the operands, because DemandedMask
845 // only reflects the bits demanded by *one* of the users.
846 if (Depth != 0 && !I->hasOneUse()) {
847 // Despite the fact that we can't simplify this instruction in all User's
848 // context, we can at least compute the knownzero/knownone bits, and we can
849 // do simplifications that apply to *just* the one user if we know that
850 // this instruction has a simpler value in that context.
851 if (I->getOpcode() == Instruction::And) {
852 // If either the LHS or the RHS are Zero, the result is zero.
853 ComputeMaskedBits(I->getOperand(1), DemandedMask,
854 RHSKnownZero, RHSKnownOne, Depth+1);
855 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
856 LHSKnownZero, LHSKnownOne, Depth+1);
858 // If all of the demanded bits are known 1 on one side, return the other.
859 // These bits cannot contribute to the result of the 'and' in this
861 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
862 (DemandedMask & ~LHSKnownZero))
863 return I->getOperand(0);
864 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
865 (DemandedMask & ~RHSKnownZero))
866 return I->getOperand(1);
868 // If all of the demanded bits in the inputs are known zeros, return zero.
869 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
870 return Constant::getNullValue(VTy);
872 } else if (I->getOpcode() == Instruction::Or) {
873 // We can simplify (X|Y) -> X or Y in the user's context if we know that
874 // only bits from X or Y are demanded.
876 // If either the LHS or the RHS are One, the result is One.
877 ComputeMaskedBits(I->getOperand(1), DemandedMask,
878 RHSKnownZero, RHSKnownOne, Depth+1);
879 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
880 LHSKnownZero, LHSKnownOne, Depth+1);
882 // If all of the demanded bits are known zero on one side, return the
883 // other. These bits cannot contribute to the result of the 'or' in this
885 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
886 (DemandedMask & ~LHSKnownOne))
887 return I->getOperand(0);
888 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
889 (DemandedMask & ~RHSKnownOne))
890 return I->getOperand(1);
892 // If all of the potentially set bits on one side are known to be set on
893 // the other side, just use the 'other' side.
894 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
895 (DemandedMask & (~RHSKnownZero)))
896 return I->getOperand(0);
897 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
898 (DemandedMask & (~LHSKnownZero)))
899 return I->getOperand(1);
902 // Compute the KnownZero/KnownOne bits to simplify things downstream.
903 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
907 // If this is the root being simplified, allow it to have multiple uses,
908 // just set the DemandedMask to all bits so that we can try to simplify the
909 // operands. This allows visitTruncInst (for example) to simplify the
910 // operand of a trunc without duplicating all the logic below.
911 if (Depth == 0 && !V->hasOneUse())
912 DemandedMask = APInt::getAllOnesValue(BitWidth);
914 switch (I->getOpcode()) {
916 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
918 case Instruction::And:
919 // If either the LHS or the RHS are Zero, the result is zero.
920 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
921 RHSKnownZero, RHSKnownOne, Depth+1) ||
922 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
923 LHSKnownZero, LHSKnownOne, Depth+1))
925 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
926 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
928 // If all of the demanded bits are known 1 on one side, return the other.
929 // These bits cannot contribute to the result of the 'and'.
930 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
931 (DemandedMask & ~LHSKnownZero))
932 return I->getOperand(0);
933 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
934 (DemandedMask & ~RHSKnownZero))
935 return I->getOperand(1);
937 // If all of the demanded bits in the inputs are known zeros, return zero.
938 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
939 return Constant::getNullValue(VTy);
941 // If the RHS is a constant, see if we can simplify it.
942 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
945 // Output known-1 bits are only known if set in both the LHS & RHS.
946 RHSKnownOne &= LHSKnownOne;
947 // Output known-0 are known to be clear if zero in either the LHS | RHS.
948 RHSKnownZero |= LHSKnownZero;
950 case Instruction::Or:
951 // If either the LHS or the RHS are One, the result is One.
952 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
953 RHSKnownZero, RHSKnownOne, Depth+1) ||
954 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
955 LHSKnownZero, LHSKnownOne, Depth+1))
957 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
958 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
960 // If all of the demanded bits are known zero on one side, return the other.
961 // These bits cannot contribute to the result of the 'or'.
962 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
963 (DemandedMask & ~LHSKnownOne))
964 return I->getOperand(0);
965 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
966 (DemandedMask & ~RHSKnownOne))
967 return I->getOperand(1);
969 // If all of the potentially set bits on one side are known to be set on
970 // the other side, just use the 'other' side.
971 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
972 (DemandedMask & (~RHSKnownZero)))
973 return I->getOperand(0);
974 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
975 (DemandedMask & (~LHSKnownZero)))
976 return I->getOperand(1);
978 // If the RHS is a constant, see if we can simplify it.
979 if (ShrinkDemandedConstant(I, 1, DemandedMask))
982 // Output known-0 bits are only known if clear in both the LHS & RHS.
983 RHSKnownZero &= LHSKnownZero;
984 // Output known-1 are known to be set if set in either the LHS | RHS.
985 RHSKnownOne |= LHSKnownOne;
987 case Instruction::Xor: {
988 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
989 RHSKnownZero, RHSKnownOne, Depth+1) ||
990 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
991 LHSKnownZero, LHSKnownOne, Depth+1))
993 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
994 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
996 // If all of the demanded bits are known zero on one side, return the other.
997 // These bits cannot contribute to the result of the 'xor'.
998 if ((DemandedMask & RHSKnownZero) == DemandedMask)
999 return I->getOperand(0);
1000 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1001 return I->getOperand(1);
1003 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1004 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1005 (RHSKnownOne & LHSKnownOne);
1006 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1007 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1008 (RHSKnownOne & LHSKnownZero);
1010 // If all of the demanded bits are known to be zero on one side or the
1011 // other, turn this into an *inclusive* or.
1012 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1013 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1015 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1017 return InsertNewInstBefore(Or, *I);
1020 // If all of the demanded bits on one side are known, and all of the set
1021 // bits on that side are also known to be set on the other side, turn this
1022 // into an AND, as we know the bits will be cleared.
1023 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1024 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1026 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1027 Constant *AndC = Constant::getIntegerValue(VTy,
1028 ~RHSKnownOne & DemandedMask);
1030 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1031 return InsertNewInstBefore(And, *I);
1035 // If the RHS is a constant, see if we can simplify it.
1036 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1037 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1040 RHSKnownZero = KnownZeroOut;
1041 RHSKnownOne = KnownOneOut;
1044 case Instruction::Select:
1045 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1046 RHSKnownZero, RHSKnownOne, Depth+1) ||
1047 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1048 LHSKnownZero, LHSKnownOne, Depth+1))
1050 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1051 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
1053 // If the operands are constants, see if we can simplify them.
1054 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1055 ShrinkDemandedConstant(I, 2, DemandedMask))
1058 // Only known if known in both the LHS and RHS.
1059 RHSKnownOne &= LHSKnownOne;
1060 RHSKnownZero &= LHSKnownZero;
1062 case Instruction::Trunc: {
1063 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1064 DemandedMask.zext(truncBf);
1065 RHSKnownZero.zext(truncBf);
1066 RHSKnownOne.zext(truncBf);
1067 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1068 RHSKnownZero, RHSKnownOne, Depth+1))
1070 DemandedMask.trunc(BitWidth);
1071 RHSKnownZero.trunc(BitWidth);
1072 RHSKnownOne.trunc(BitWidth);
1073 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1076 case Instruction::BitCast:
1077 if (!I->getOperand(0)->getType()->isIntOrIntVector())
1078 return false; // vector->int or fp->int?
1080 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1081 if (const VectorType *SrcVTy =
1082 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1083 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1084 // Don't touch a bitcast between vectors of different element counts.
1087 // Don't touch a scalar-to-vector bitcast.
1089 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1090 // Don't touch a vector-to-scalar bitcast.
1093 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1094 RHSKnownZero, RHSKnownOne, Depth+1))
1096 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1098 case Instruction::ZExt: {
1099 // Compute the bits in the result that are not present in the input.
1100 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1102 DemandedMask.trunc(SrcBitWidth);
1103 RHSKnownZero.trunc(SrcBitWidth);
1104 RHSKnownOne.trunc(SrcBitWidth);
1105 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1106 RHSKnownZero, RHSKnownOne, Depth+1))
1108 DemandedMask.zext(BitWidth);
1109 RHSKnownZero.zext(BitWidth);
1110 RHSKnownOne.zext(BitWidth);
1111 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1112 // The top bits are known to be zero.
1113 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1116 case Instruction::SExt: {
1117 // Compute the bits in the result that are not present in the input.
1118 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1120 APInt InputDemandedBits = DemandedMask &
1121 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1123 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1124 // If any of the sign extended bits are demanded, we know that the sign
1126 if ((NewBits & DemandedMask) != 0)
1127 InputDemandedBits.set(SrcBitWidth-1);
1129 InputDemandedBits.trunc(SrcBitWidth);
1130 RHSKnownZero.trunc(SrcBitWidth);
1131 RHSKnownOne.trunc(SrcBitWidth);
1132 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1133 RHSKnownZero, RHSKnownOne, Depth+1))
1135 InputDemandedBits.zext(BitWidth);
1136 RHSKnownZero.zext(BitWidth);
1137 RHSKnownOne.zext(BitWidth);
1138 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1140 // If the sign bit of the input is known set or clear, then we know the
1141 // top bits of the result.
1143 // If the input sign bit is known zero, or if the NewBits are not demanded
1144 // convert this into a zero extension.
1145 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1146 // Convert to ZExt cast
1147 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1148 return InsertNewInstBefore(NewCast, *I);
1149 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1150 RHSKnownOne |= NewBits;
1154 case Instruction::Add: {
1155 // Figure out what the input bits are. If the top bits of the and result
1156 // are not demanded, then the add doesn't demand them from its input
1158 unsigned NLZ = DemandedMask.countLeadingZeros();
1160 // If there is a constant on the RHS, there are a variety of xformations
1162 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1163 // If null, this should be simplified elsewhere. Some of the xforms here
1164 // won't work if the RHS is zero.
1168 // If the top bit of the output is demanded, demand everything from the
1169 // input. Otherwise, we demand all the input bits except NLZ top bits.
1170 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1172 // Find information about known zero/one bits in the input.
1173 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
1174 LHSKnownZero, LHSKnownOne, Depth+1))
1177 // If the RHS of the add has bits set that can't affect the input, reduce
1179 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1182 // Avoid excess work.
1183 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1186 // Turn it into OR if input bits are zero.
1187 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1189 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1191 return InsertNewInstBefore(Or, *I);
1194 // We can say something about the output known-zero and known-one bits,
1195 // depending on potential carries from the input constant and the
1196 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1197 // bits set and the RHS constant is 0x01001, then we know we have a known
1198 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1200 // To compute this, we first compute the potential carry bits. These are
1201 // the bits which may be modified. I'm not aware of a better way to do
1203 const APInt &RHSVal = RHS->getValue();
1204 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1206 // Now that we know which bits have carries, compute the known-1/0 sets.
1208 // Bits are known one if they are known zero in one operand and one in the
1209 // other, and there is no input carry.
1210 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1211 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1213 // Bits are known zero if they are known zero in both operands and there
1214 // is no input carry.
1215 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1217 // If the high-bits of this ADD are not demanded, then it does not demand
1218 // the high bits of its LHS or RHS.
1219 if (DemandedMask[BitWidth-1] == 0) {
1220 // Right fill the mask of bits for this ADD to demand the most
1221 // significant bit and all those below it.
1222 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1223 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1224 LHSKnownZero, LHSKnownOne, Depth+1) ||
1225 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1226 LHSKnownZero, LHSKnownOne, Depth+1))
1232 case Instruction::Sub:
1233 // If the high-bits of this SUB are not demanded, then it does not demand
1234 // the high bits of its LHS or RHS.
1235 if (DemandedMask[BitWidth-1] == 0) {
1236 // Right fill the mask of bits for this SUB to demand the most
1237 // significant bit and all those below it.
1238 uint32_t NLZ = DemandedMask.countLeadingZeros();
1239 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1240 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1241 LHSKnownZero, LHSKnownOne, Depth+1) ||
1242 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1243 LHSKnownZero, LHSKnownOne, Depth+1))
1246 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1247 // the known zeros and ones.
1248 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1250 case Instruction::Shl:
1251 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1252 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1253 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1254 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1255 RHSKnownZero, RHSKnownOne, Depth+1))
1257 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1258 RHSKnownZero <<= ShiftAmt;
1259 RHSKnownOne <<= ShiftAmt;
1260 // low bits known zero.
1262 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1265 case Instruction::LShr:
1266 // For a logical shift right
1267 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1268 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1270 // Unsigned shift right.
1271 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1272 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1273 RHSKnownZero, RHSKnownOne, Depth+1))
1275 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1276 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1277 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1279 // Compute the new bits that are at the top now.
1280 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1281 RHSKnownZero |= HighBits; // high bits known zero.
1285 case Instruction::AShr:
1286 // If this is an arithmetic shift right and only the low-bit is set, we can
1287 // always convert this into a logical shr, even if the shift amount is
1288 // variable. The low bit of the shift cannot be an input sign bit unless
1289 // the shift amount is >= the size of the datatype, which is undefined.
1290 if (DemandedMask == 1) {
1291 // Perform the logical shift right.
1292 Instruction *NewVal = BinaryOperator::CreateLShr(
1293 I->getOperand(0), I->getOperand(1), I->getName());
1294 return InsertNewInstBefore(NewVal, *I);
1297 // If the sign bit is the only bit demanded by this ashr, then there is no
1298 // need to do it, the shift doesn't change the high bit.
1299 if (DemandedMask.isSignBit())
1300 return I->getOperand(0);
1302 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1303 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1305 // Signed shift right.
1306 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1307 // If any of the "high bits" are demanded, we should set the sign bit as
1309 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1310 DemandedMaskIn.set(BitWidth-1);
1311 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1312 RHSKnownZero, RHSKnownOne, Depth+1))
1314 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1315 // Compute the new bits that are at the top now.
1316 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1317 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1318 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1320 // Handle the sign bits.
1321 APInt SignBit(APInt::getSignBit(BitWidth));
1322 // Adjust to where it is now in the mask.
1323 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1325 // If the input sign bit is known to be zero, or if none of the top bits
1326 // are demanded, turn this into an unsigned shift right.
1327 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
1328 (HighBits & ~DemandedMask) == HighBits) {
1329 // Perform the logical shift right.
1330 Instruction *NewVal = BinaryOperator::CreateLShr(
1331 I->getOperand(0), SA, I->getName());
1332 return InsertNewInstBefore(NewVal, *I);
1333 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1334 RHSKnownOne |= HighBits;
1338 case Instruction::SRem:
1339 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1340 APInt RA = Rem->getValue().abs();
1341 if (RA.isPowerOf2()) {
1342 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
1343 return I->getOperand(0);
1345 APInt LowBits = RA - 1;
1346 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1347 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1348 LHSKnownZero, LHSKnownOne, Depth+1))
1351 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1352 LHSKnownZero |= ~LowBits;
1354 KnownZero |= LHSKnownZero & DemandedMask;
1356 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
1360 case Instruction::URem: {
1361 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1362 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1363 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1364 KnownZero2, KnownOne2, Depth+1) ||
1365 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1366 KnownZero2, KnownOne2, Depth+1))
1369 unsigned Leaders = KnownZero2.countLeadingOnes();
1370 Leaders = std::max(Leaders,
1371 KnownZero2.countLeadingOnes());
1372 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1375 case Instruction::Call:
1376 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1377 switch (II->getIntrinsicID()) {
1379 case Intrinsic::bswap: {
1380 // If the only bits demanded come from one byte of the bswap result,
1381 // just shift the input byte into position to eliminate the bswap.
1382 unsigned NLZ = DemandedMask.countLeadingZeros();
1383 unsigned NTZ = DemandedMask.countTrailingZeros();
1385 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1386 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1387 // have 14 leading zeros, round to 8.
1390 // If we need exactly one byte, we can do this transformation.
1391 if (BitWidth-NLZ-NTZ == 8) {
1392 unsigned ResultBit = NTZ;
1393 unsigned InputBit = BitWidth-NTZ-8;
1395 // Replace this with either a left or right shift to get the byte into
1397 Instruction *NewVal;
1398 if (InputBit > ResultBit)
1399 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1400 ConstantInt::get(I->getType(), InputBit-ResultBit));
1402 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1403 ConstantInt::get(I->getType(), ResultBit-InputBit));
1404 NewVal->takeName(I);
1405 return InsertNewInstBefore(NewVal, *I);
1408 // TODO: Could compute known zero/one bits based on the input.
1413 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1417 // If the client is only demanding bits that we know, return the known
1419 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1420 return Constant::getIntegerValue(VTy, RHSKnownOne);
1425 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1426 /// any number of elements. DemandedElts contains the set of elements that are
1427 /// actually used by the caller. This method analyzes which elements of the
1428 /// operand are undef and returns that information in UndefElts.
1430 /// If the information about demanded elements can be used to simplify the
1431 /// operation, the operation is simplified, then the resultant value is
1432 /// returned. This returns null if no change was made.
1433 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1436 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1437 APInt EltMask(APInt::getAllOnesValue(VWidth));
1438 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1440 if (isa<UndefValue>(V)) {
1441 // If the entire vector is undefined, just return this info.
1442 UndefElts = EltMask;
1444 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1445 UndefElts = EltMask;
1446 return UndefValue::get(V->getType());
1450 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1451 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1452 Constant *Undef = UndefValue::get(EltTy);
1454 std::vector<Constant*> Elts;
1455 for (unsigned i = 0; i != VWidth; ++i)
1456 if (!DemandedElts[i]) { // If not demanded, set to undef.
1457 Elts.push_back(Undef);
1459 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1460 Elts.push_back(Undef);
1462 } else { // Otherwise, defined.
1463 Elts.push_back(CP->getOperand(i));
1466 // If we changed the constant, return it.
1467 Constant *NewCP = ConstantVector::get(Elts);
1468 return NewCP != CP ? NewCP : 0;
1469 } else if (isa<ConstantAggregateZero>(V)) {
1470 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1473 // Check if this is identity. If so, return 0 since we are not simplifying
1475 if (DemandedElts == ((1ULL << VWidth) -1))
1478 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1479 Constant *Zero = Constant::getNullValue(EltTy);
1480 Constant *Undef = UndefValue::get(EltTy);
1481 std::vector<Constant*> Elts;
1482 for (unsigned i = 0; i != VWidth; ++i) {
1483 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1484 Elts.push_back(Elt);
1486 UndefElts = DemandedElts ^ EltMask;
1487 return ConstantVector::get(Elts);
1490 // Limit search depth.
1494 // If multiple users are using the root value, procede with
1495 // simplification conservatively assuming that all elements
1497 if (!V->hasOneUse()) {
1498 // Quit if we find multiple users of a non-root value though.
1499 // They'll be handled when it's their turn to be visited by
1500 // the main instcombine process.
1502 // TODO: Just compute the UndefElts information recursively.
1505 // Conservatively assume that all elements are needed.
1506 DemandedElts = EltMask;
1509 Instruction *I = dyn_cast<Instruction>(V);
1510 if (!I) return 0; // Only analyze instructions.
1512 bool MadeChange = false;
1513 APInt UndefElts2(VWidth, 0);
1515 switch (I->getOpcode()) {
1518 case Instruction::InsertElement: {
1519 // If this is a variable index, we don't know which element it overwrites.
1520 // demand exactly the same input as we produce.
1521 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1523 // Note that we can't propagate undef elt info, because we don't know
1524 // which elt is getting updated.
1525 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1526 UndefElts2, Depth+1);
1527 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1531 // If this is inserting an element that isn't demanded, remove this
1533 unsigned IdxNo = Idx->getZExtValue();
1534 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1536 return I->getOperand(0);
1539 // Otherwise, the element inserted overwrites whatever was there, so the
1540 // input demanded set is simpler than the output set.
1541 APInt DemandedElts2 = DemandedElts;
1542 DemandedElts2.clear(IdxNo);
1543 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1544 UndefElts, Depth+1);
1545 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1547 // The inserted element is defined.
1548 UndefElts.clear(IdxNo);
1551 case Instruction::ShuffleVector: {
1552 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1553 uint64_t LHSVWidth =
1554 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1555 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1556 for (unsigned i = 0; i < VWidth; i++) {
1557 if (DemandedElts[i]) {
1558 unsigned MaskVal = Shuffle->getMaskValue(i);
1559 if (MaskVal != -1u) {
1560 assert(MaskVal < LHSVWidth * 2 &&
1561 "shufflevector mask index out of range!");
1562 if (MaskVal < LHSVWidth)
1563 LeftDemanded.set(MaskVal);
1565 RightDemanded.set(MaskVal - LHSVWidth);
1570 APInt UndefElts4(LHSVWidth, 0);
1571 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1572 UndefElts4, Depth+1);
1573 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1575 APInt UndefElts3(LHSVWidth, 0);
1576 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1577 UndefElts3, Depth+1);
1578 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1580 bool NewUndefElts = false;
1581 for (unsigned i = 0; i < VWidth; i++) {
1582 unsigned MaskVal = Shuffle->getMaskValue(i);
1583 if (MaskVal == -1u) {
1585 } else if (MaskVal < LHSVWidth) {
1586 if (UndefElts4[MaskVal]) {
1587 NewUndefElts = true;
1591 if (UndefElts3[MaskVal - LHSVWidth]) {
1592 NewUndefElts = true;
1599 // Add additional discovered undefs.
1600 std::vector<Constant*> Elts;
1601 for (unsigned i = 0; i < VWidth; ++i) {
1603 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1605 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1606 Shuffle->getMaskValue(i)));
1608 I->setOperand(2, ConstantVector::get(Elts));
1613 case Instruction::BitCast: {
1614 // Vector->vector casts only.
1615 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1617 unsigned InVWidth = VTy->getNumElements();
1618 APInt InputDemandedElts(InVWidth, 0);
1621 if (VWidth == InVWidth) {
1622 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1623 // elements as are demanded of us.
1625 InputDemandedElts = DemandedElts;
1626 } else if (VWidth > InVWidth) {
1630 // If there are more elements in the result than there are in the source,
1631 // then an input element is live if any of the corresponding output
1632 // elements are live.
1633 Ratio = VWidth/InVWidth;
1634 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1635 if (DemandedElts[OutIdx])
1636 InputDemandedElts.set(OutIdx/Ratio);
1642 // If there are more elements in the source than there are in the result,
1643 // then an input element is live if the corresponding output element is
1645 Ratio = InVWidth/VWidth;
1646 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1647 if (DemandedElts[InIdx/Ratio])
1648 InputDemandedElts.set(InIdx);
1651 // div/rem demand all inputs, because they don't want divide by zero.
1652 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1653 UndefElts2, Depth+1);
1655 I->setOperand(0, TmpV);
1659 UndefElts = UndefElts2;
1660 if (VWidth > InVWidth) {
1661 llvm_unreachable("Unimp");
1662 // If there are more elements in the result than there are in the source,
1663 // then an output element is undef if the corresponding input element is
1665 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1666 if (UndefElts2[OutIdx/Ratio])
1667 UndefElts.set(OutIdx);
1668 } else if (VWidth < InVWidth) {
1669 llvm_unreachable("Unimp");
1670 // If there are more elements in the source than there are in the result,
1671 // then a result element is undef if all of the corresponding input
1672 // elements are undef.
1673 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1674 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1675 if (!UndefElts2[InIdx]) // Not undef?
1676 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
1680 case Instruction::And:
1681 case Instruction::Or:
1682 case Instruction::Xor:
1683 case Instruction::Add:
1684 case Instruction::Sub:
1685 case Instruction::Mul:
1686 // div/rem demand all inputs, because they don't want divide by zero.
1687 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1688 UndefElts, Depth+1);
1689 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1690 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1691 UndefElts2, Depth+1);
1692 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1694 // Output elements are undefined if both are undefined. Consider things
1695 // like undef&0. The result is known zero, not undef.
1696 UndefElts &= UndefElts2;
1699 case Instruction::Call: {
1700 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1702 switch (II->getIntrinsicID()) {
1705 // Binary vector operations that work column-wise. A dest element is a
1706 // function of the corresponding input elements from the two inputs.
1707 case Intrinsic::x86_sse_sub_ss:
1708 case Intrinsic::x86_sse_mul_ss:
1709 case Intrinsic::x86_sse_min_ss:
1710 case Intrinsic::x86_sse_max_ss:
1711 case Intrinsic::x86_sse2_sub_sd:
1712 case Intrinsic::x86_sse2_mul_sd:
1713 case Intrinsic::x86_sse2_min_sd:
1714 case Intrinsic::x86_sse2_max_sd:
1715 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1716 UndefElts, Depth+1);
1717 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1718 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1719 UndefElts2, Depth+1);
1720 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1722 // If only the low elt is demanded and this is a scalarizable intrinsic,
1723 // scalarize it now.
1724 if (DemandedElts == 1) {
1725 switch (II->getIntrinsicID()) {
1727 case Intrinsic::x86_sse_sub_ss:
1728 case Intrinsic::x86_sse_mul_ss:
1729 case Intrinsic::x86_sse2_sub_sd:
1730 case Intrinsic::x86_sse2_mul_sd:
1731 // TODO: Lower MIN/MAX/ABS/etc
1732 Value *LHS = II->getOperand(1);
1733 Value *RHS = II->getOperand(2);
1734 // Extract the element as scalars.
1735 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
1736 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1737 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1738 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1740 switch (II->getIntrinsicID()) {
1741 default: llvm_unreachable("Case stmts out of sync!");
1742 case Intrinsic::x86_sse_sub_ss:
1743 case Intrinsic::x86_sse2_sub_sd:
1744 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1745 II->getName()), *II);
1747 case Intrinsic::x86_sse_mul_ss:
1748 case Intrinsic::x86_sse2_mul_sd:
1749 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1750 II->getName()), *II);
1755 InsertElementInst::Create(
1756 UndefValue::get(II->getType()), TmpV,
1757 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1758 InsertNewInstBefore(New, *II);
1763 // Output elements are undefined if both are undefined. Consider things
1764 // like undef&0. The result is known zero, not undef.
1765 UndefElts &= UndefElts2;
1771 return MadeChange ? I : 0;
1775 /// AssociativeOpt - Perform an optimization on an associative operator. This
1776 /// function is designed to check a chain of associative operators for a
1777 /// potential to apply a certain optimization. Since the optimization may be
1778 /// applicable if the expression was reassociated, this checks the chain, then
1779 /// reassociates the expression as necessary to expose the optimization
1780 /// opportunity. This makes use of a special Functor, which must define
1781 /// 'shouldApply' and 'apply' methods.
1783 template<typename Functor>
1784 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1785 unsigned Opcode = Root.getOpcode();
1786 Value *LHS = Root.getOperand(0);
1788 // Quick check, see if the immediate LHS matches...
1789 if (F.shouldApply(LHS))
1790 return F.apply(Root);
1792 // Otherwise, if the LHS is not of the same opcode as the root, return.
1793 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1794 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1795 // Should we apply this transform to the RHS?
1796 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1798 // If not to the RHS, check to see if we should apply to the LHS...
1799 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1800 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1804 // If the functor wants to apply the optimization to the RHS of LHSI,
1805 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1807 // Now all of the instructions are in the current basic block, go ahead
1808 // and perform the reassociation.
1809 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1811 // First move the selected RHS to the LHS of the root...
1812 Root.setOperand(0, LHSI->getOperand(1));
1814 // Make what used to be the LHS of the root be the user of the root...
1815 Value *ExtraOperand = TmpLHSI->getOperand(1);
1816 if (&Root == TmpLHSI) {
1817 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1820 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1821 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1822 BasicBlock::iterator ARI = &Root; ++ARI;
1823 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
1826 // Now propagate the ExtraOperand down the chain of instructions until we
1828 while (TmpLHSI != LHSI) {
1829 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1830 // Move the instruction to immediately before the chain we are
1831 // constructing to avoid breaking dominance properties.
1832 NextLHSI->moveBefore(ARI);
1835 Value *NextOp = NextLHSI->getOperand(1);
1836 NextLHSI->setOperand(1, ExtraOperand);
1838 ExtraOperand = NextOp;
1841 // Now that the instructions are reassociated, have the functor perform
1842 // the transformation...
1843 return F.apply(Root);
1846 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1853 // AddRHS - Implements: X + X --> X << 1
1856 explicit AddRHS(Value *rhs) : RHS(rhs) {}
1857 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1858 Instruction *apply(BinaryOperator &Add) const {
1859 return BinaryOperator::CreateShl(Add.getOperand(0),
1860 ConstantInt::get(Add.getType(), 1));
1864 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1866 struct AddMaskingAnd {
1868 explicit AddMaskingAnd(Constant *c) : C2(c) {}
1869 bool shouldApply(Value *LHS) const {
1871 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1872 ConstantExpr::getAnd(C1, C2)->isNullValue();
1874 Instruction *apply(BinaryOperator &Add) const {
1875 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1881 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1883 if (CastInst *CI = dyn_cast<CastInst>(&I))
1884 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
1886 // Figure out if the constant is the left or the right argument.
1887 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1888 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1890 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1892 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1893 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1896 Value *Op0 = SO, *Op1 = ConstOperand;
1898 std::swap(Op0, Op1);
1900 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1901 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1902 SO->getName()+".op");
1903 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1904 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1905 SO->getName()+".cmp");
1906 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1907 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1908 SO->getName()+".cmp");
1909 llvm_unreachable("Unknown binary instruction type!");
1912 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1913 // constant as the other operand, try to fold the binary operator into the
1914 // select arguments. This also works for Cast instructions, which obviously do
1915 // not have a second operand.
1916 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1918 // Don't modify shared select instructions
1919 if (!SI->hasOneUse()) return 0;
1920 Value *TV = SI->getOperand(1);
1921 Value *FV = SI->getOperand(2);
1923 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1924 // Bool selects with constant operands can be folded to logical ops.
1925 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
1927 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1928 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1930 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1937 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1938 /// node as operand #0, see if we can fold the instruction into the PHI (which
1939 /// is only possible if all operands to the PHI are constants).
1940 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1941 PHINode *PN = cast<PHINode>(I.getOperand(0));
1942 unsigned NumPHIValues = PN->getNumIncomingValues();
1943 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1945 // Check to see if all of the operands of the PHI are constants. If there is
1946 // one non-constant value, remember the BB it is. If there is more than one
1947 // or if *it* is a PHI, bail out.
1948 BasicBlock *NonConstBB = 0;
1949 for (unsigned i = 0; i != NumPHIValues; ++i)
1950 if (!isa<Constant>(PN->getIncomingValue(i))) {
1951 if (NonConstBB) return 0; // More than one non-const value.
1952 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1953 NonConstBB = PN->getIncomingBlock(i);
1955 // If the incoming non-constant value is in I's block, we have an infinite
1957 if (NonConstBB == I.getParent())
1961 // If there is exactly one non-constant value, we can insert a copy of the
1962 // operation in that block. However, if this is a critical edge, we would be
1963 // inserting the computation one some other paths (e.g. inside a loop). Only
1964 // do this if the pred block is unconditionally branching into the phi block.
1966 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1967 if (!BI || !BI->isUnconditional()) return 0;
1970 // Okay, we can do the transformation: create the new PHI node.
1971 PHINode *NewPN = PHINode::Create(I.getType(), "");
1972 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1973 InsertNewInstBefore(NewPN, *PN);
1974 NewPN->takeName(PN);
1976 // Next, add all of the operands to the PHI.
1977 if (I.getNumOperands() == 2) {
1978 Constant *C = cast<Constant>(I.getOperand(1));
1979 for (unsigned i = 0; i != NumPHIValues; ++i) {
1981 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1982 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1983 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1985 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1987 assert(PN->getIncomingBlock(i) == NonConstBB);
1988 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1989 InV = BinaryOperator::Create(BO->getOpcode(),
1990 PN->getIncomingValue(i), C, "phitmp",
1991 NonConstBB->getTerminator());
1992 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1993 InV = CmpInst::Create(CI->getOpcode(),
1995 PN->getIncomingValue(i), C, "phitmp",
1996 NonConstBB->getTerminator());
1998 llvm_unreachable("Unknown binop!");
2000 Worklist.Add(cast<Instruction>(InV));
2002 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2005 CastInst *CI = cast<CastInst>(&I);
2006 const Type *RetTy = CI->getType();
2007 for (unsigned i = 0; i != NumPHIValues; ++i) {
2009 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2010 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2012 assert(PN->getIncomingBlock(i) == NonConstBB);
2013 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
2014 I.getType(), "phitmp",
2015 NonConstBB->getTerminator());
2016 Worklist.Add(cast<Instruction>(InV));
2018 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2021 return ReplaceInstUsesWith(I, NewPN);
2025 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2026 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2027 /// This basically requires proving that the add in the original type would not
2028 /// overflow to change the sign bit or have a carry out.
2029 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2030 // There are different heuristics we can use for this. Here are some simple
2033 // Add has the property that adding any two 2's complement numbers can only
2034 // have one carry bit which can change a sign. As such, if LHS and RHS each
2035 // have at least two sign bits, we know that the addition of the two values will
2036 // sign extend fine.
2037 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2041 // If one of the operands only has one non-zero bit, and if the other operand
2042 // has a known-zero bit in a more significant place than it (not including the
2043 // sign bit) the ripple may go up to and fill the zero, but won't change the
2044 // sign. For example, (X & ~4) + 1.
2052 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2053 bool Changed = SimplifyCommutative(I);
2054 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2056 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2057 // X + undef -> undef
2058 if (isa<UndefValue>(RHS))
2059 return ReplaceInstUsesWith(I, RHS);
2062 if (RHSC->isNullValue())
2063 return ReplaceInstUsesWith(I, LHS);
2065 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2066 // X + (signbit) --> X ^ signbit
2067 const APInt& Val = CI->getValue();
2068 uint32_t BitWidth = Val.getBitWidth();
2069 if (Val == APInt::getSignBit(BitWidth))
2070 return BinaryOperator::CreateXor(LHS, RHS);
2072 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2073 // (X & 254)+1 -> (X&254)|1
2074 if (SimplifyDemandedInstructionBits(I))
2077 // zext(bool) + C -> bool ? C + 1 : C
2078 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2079 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2080 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2083 if (isa<PHINode>(LHS))
2084 if (Instruction *NV = FoldOpIntoPhi(I))
2087 ConstantInt *XorRHS = 0;
2089 if (isa<ConstantInt>(RHSC) &&
2090 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2091 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2092 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2094 uint32_t Size = TySizeBits / 2;
2095 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2096 APInt CFF80Val(-C0080Val);
2098 if (TySizeBits > Size) {
2099 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2100 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2101 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2102 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2103 // This is a sign extend if the top bits are known zero.
2104 if (!MaskedValueIsZero(XorLHS,
2105 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2106 Size = 0; // Not a sign ext, but can't be any others either.
2111 C0080Val = APIntOps::lshr(C0080Val, Size);
2112 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2113 } while (Size >= 1);
2115 // FIXME: This shouldn't be necessary. When the backends can handle types
2116 // with funny bit widths then this switch statement should be removed. It
2117 // is just here to get the size of the "middle" type back up to something
2118 // that the back ends can handle.
2119 const Type *MiddleType = 0;
2122 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2123 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2124 case 8: MiddleType = Type::getInt8Ty(*Context); break;
2127 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
2128 return new SExtInst(NewTrunc, I.getType(), I.getName());
2133 if (I.getType() == Type::getInt1Ty(*Context))
2134 return BinaryOperator::CreateXor(LHS, RHS);
2137 if (I.getType()->isInteger()) {
2138 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2141 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2142 if (RHSI->getOpcode() == Instruction::Sub)
2143 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2144 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2146 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2147 if (LHSI->getOpcode() == Instruction::Sub)
2148 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2149 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2154 // -A + -B --> -(A + B)
2155 if (Value *LHSV = dyn_castNegVal(LHS)) {
2156 if (LHS->getType()->isIntOrIntVector()) {
2157 if (Value *RHSV = dyn_castNegVal(RHS)) {
2158 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
2159 return BinaryOperator::CreateNeg(NewAdd);
2163 return BinaryOperator::CreateSub(RHS, LHSV);
2167 if (!isa<Constant>(RHS))
2168 if (Value *V = dyn_castNegVal(RHS))
2169 return BinaryOperator::CreateSub(LHS, V);
2173 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2174 if (X == RHS) // X*C + X --> X * (C+1)
2175 return BinaryOperator::CreateMul(RHS, AddOne(C2));
2177 // X*C1 + X*C2 --> X * (C1+C2)
2179 if (X == dyn_castFoldableMul(RHS, C1))
2180 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2183 // X + X*C --> X * (C+1)
2184 if (dyn_castFoldableMul(RHS, C2) == LHS)
2185 return BinaryOperator::CreateMul(LHS, AddOne(C2));
2187 // X + ~X --> -1 since ~X = -X-1
2188 if (dyn_castNotVal(LHS) == RHS ||
2189 dyn_castNotVal(RHS) == LHS)
2190 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2193 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2194 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2195 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2198 // A+B --> A|B iff A and B have no bits set in common.
2199 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2200 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2201 APInt LHSKnownOne(IT->getBitWidth(), 0);
2202 APInt LHSKnownZero(IT->getBitWidth(), 0);
2203 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2204 if (LHSKnownZero != 0) {
2205 APInt RHSKnownOne(IT->getBitWidth(), 0);
2206 APInt RHSKnownZero(IT->getBitWidth(), 0);
2207 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2209 // No bits in common -> bitwise or.
2210 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2211 return BinaryOperator::CreateOr(LHS, RHS);
2215 // W*X + Y*Z --> W * (X+Z) iff W == Y
2216 if (I.getType()->isIntOrIntVector()) {
2217 Value *W, *X, *Y, *Z;
2218 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2219 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2223 } else if (Y == X) {
2225 } else if (X == Z) {
2232 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
2233 return BinaryOperator::CreateMul(W, NewAdd);
2238 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2240 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2241 return BinaryOperator::CreateSub(SubOne(CRHS), X);
2243 // (X & FF00) + xx00 -> (X+xx00) & FF00
2244 if (LHS->hasOneUse() &&
2245 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2246 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2247 if (Anded == CRHS) {
2248 // See if all bits from the first bit set in the Add RHS up are included
2249 // in the mask. First, get the rightmost bit.
2250 const APInt& AddRHSV = CRHS->getValue();
2252 // Form a mask of all bits from the lowest bit added through the top.
2253 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2255 // See if the and mask includes all of these bits.
2256 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2258 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2259 // Okay, the xform is safe. Insert the new add pronto.
2260 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
2261 return BinaryOperator::CreateAnd(NewAdd, C2);
2266 // Try to fold constant add into select arguments.
2267 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2268 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2272 // add (select X 0 (sub n A)) A --> select X A n
2274 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2277 SI = dyn_cast<SelectInst>(RHS);
2280 if (SI && SI->hasOneUse()) {
2281 Value *TV = SI->getTrueValue();
2282 Value *FV = SI->getFalseValue();
2285 // Can we fold the add into the argument of the select?
2286 // We check both true and false select arguments for a matching subtract.
2287 if (match(FV, m_Zero()) &&
2288 match(TV, m_Sub(m_Value(N), m_Specific(A))))
2289 // Fold the add into the true select value.
2290 return SelectInst::Create(SI->getCondition(), N, A);
2291 if (match(TV, m_Zero()) &&
2292 match(FV, m_Sub(m_Value(N), m_Specific(A))))
2293 // Fold the add into the false select value.
2294 return SelectInst::Create(SI->getCondition(), A, N);
2298 // Check for (add (sext x), y), see if we can merge this into an
2299 // integer add followed by a sext.
2300 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2301 // (add (sext x), cst) --> (sext (add x, cst'))
2302 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2304 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2305 if (LHSConv->hasOneUse() &&
2306 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2307 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2308 // Insert the new, smaller add.
2309 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2311 return new SExtInst(NewAdd, I.getType());
2315 // (add (sext x), (sext y)) --> (sext (add int x, y))
2316 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2317 // Only do this if x/y have the same type, if at last one of them has a
2318 // single use (so we don't increase the number of sexts), and if the
2319 // integer add will not overflow.
2320 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2321 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2322 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2323 RHSConv->getOperand(0))) {
2324 // Insert the new integer add.
2325 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2326 RHSConv->getOperand(0), "addconv");
2327 return new SExtInst(NewAdd, I.getType());
2332 return Changed ? &I : 0;
2335 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2336 bool Changed = SimplifyCommutative(I);
2337 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2339 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2341 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2342 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2343 (I.getType())->getValueAPF()))
2344 return ReplaceInstUsesWith(I, LHS);
2347 if (isa<PHINode>(LHS))
2348 if (Instruction *NV = FoldOpIntoPhi(I))
2353 // -A + -B --> -(A + B)
2354 if (Value *LHSV = dyn_castFNegVal(LHS))
2355 return BinaryOperator::CreateFSub(RHS, LHSV);
2358 if (!isa<Constant>(RHS))
2359 if (Value *V = dyn_castFNegVal(RHS))
2360 return BinaryOperator::CreateFSub(LHS, V);
2362 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2363 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2364 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2365 return ReplaceInstUsesWith(I, LHS);
2367 // Check for (add double (sitofp x), y), see if we can merge this into an
2368 // integer add followed by a promotion.
2369 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2370 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2371 // ... if the constant fits in the integer value. This is useful for things
2372 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2373 // requires a constant pool load, and generally allows the add to be better
2375 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2377 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2378 if (LHSConv->hasOneUse() &&
2379 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2380 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2381 // Insert the new integer add.
2382 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
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 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2399 RHSConv->getOperand(0), "addconv");
2400 return new SIToFPInst(NewAdd, I.getType());
2405 return Changed ? &I : 0;
2408 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2409 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2411 if (Op0 == Op1) // sub X, X -> 0
2412 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2414 // If this is a 'B = x-(-A)', change to B = x+A...
2415 if (Value *V = dyn_castNegVal(Op1))
2416 return BinaryOperator::CreateAdd(Op0, V);
2418 if (isa<UndefValue>(Op0))
2419 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2420 if (isa<UndefValue>(Op1))
2421 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2423 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2424 // Replace (-1 - A) with (~A)...
2425 if (C->isAllOnesValue())
2426 return BinaryOperator::CreateNot(Op1);
2428 // C - ~X == X + (1+C)
2430 if (match(Op1, m_Not(m_Value(X))))
2431 return BinaryOperator::CreateAdd(X, AddOne(C));
2433 // -(X >>u 31) -> (X >>s 31)
2434 // -(X >>s 31) -> (X >>u 31)
2436 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2437 if (SI->getOpcode() == Instruction::LShr) {
2438 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2439 // Check to see if we are shifting out everything but the sign bit.
2440 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2441 SI->getType()->getPrimitiveSizeInBits()-1) {
2442 // Ok, the transformation is safe. Insert AShr.
2443 return BinaryOperator::Create(Instruction::AShr,
2444 SI->getOperand(0), CU, SI->getName());
2448 else if (SI->getOpcode() == Instruction::AShr) {
2449 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2450 // Check to see if we are shifting out everything but the sign bit.
2451 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2452 SI->getType()->getPrimitiveSizeInBits()-1) {
2453 // Ok, the transformation is safe. Insert LShr.
2454 return BinaryOperator::CreateLShr(
2455 SI->getOperand(0), CU, SI->getName());
2462 // Try to fold constant sub into select arguments.
2463 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2464 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2467 // C - zext(bool) -> bool ? C - 1 : C
2468 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2469 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2470 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2473 if (I.getType() == Type::getInt1Ty(*Context))
2474 return BinaryOperator::CreateXor(Op0, Op1);
2476 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2477 if (Op1I->getOpcode() == Instruction::Add) {
2478 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2479 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2481 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2482 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2484 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2485 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2486 // C1-(X+C2) --> (C1-C2)-X
2487 return BinaryOperator::CreateSub(
2488 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2492 if (Op1I->hasOneUse()) {
2493 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2494 // is not used by anyone else...
2496 if (Op1I->getOpcode() == Instruction::Sub) {
2497 // Swap the two operands of the subexpr...
2498 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2499 Op1I->setOperand(0, IIOp1);
2500 Op1I->setOperand(1, IIOp0);
2502 // Create the new top level add instruction...
2503 return BinaryOperator::CreateAdd(Op0, Op1);
2506 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2508 if (Op1I->getOpcode() == Instruction::And &&
2509 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2510 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2512 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
2513 return BinaryOperator::CreateAnd(Op0, NewNot);
2516 // 0 - (X sdiv C) -> (X sdiv -C)
2517 if (Op1I->getOpcode() == Instruction::SDiv)
2518 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2520 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2521 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2522 ConstantExpr::getNeg(DivRHS));
2524 // X - X*C --> X * (1-C)
2525 ConstantInt *C2 = 0;
2526 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2528 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2530 return BinaryOperator::CreateMul(Op0, CP1);
2535 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2536 if (Op0I->getOpcode() == Instruction::Add) {
2537 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2538 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2539 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2540 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2541 } else if (Op0I->getOpcode() == Instruction::Sub) {
2542 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2543 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2549 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2550 if (X == Op1) // X*C - X --> X * (C-1)
2551 return BinaryOperator::CreateMul(Op1, SubOne(C1));
2553 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2554 if (X == dyn_castFoldableMul(Op1, C2))
2555 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2560 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2561 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2563 // If this is a 'B = x-(-A)', change to B = x+A...
2564 if (Value *V = dyn_castFNegVal(Op1))
2565 return BinaryOperator::CreateFAdd(Op0, V);
2567 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2568 if (Op1I->getOpcode() == Instruction::FAdd) {
2569 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2570 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2572 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2573 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2581 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2582 /// comparison only checks the sign bit. If it only checks the sign bit, set
2583 /// TrueIfSigned if the result of the comparison is true when the input value is
2585 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2586 bool &TrueIfSigned) {
2588 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2589 TrueIfSigned = true;
2590 return RHS->isZero();
2591 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2592 TrueIfSigned = true;
2593 return RHS->isAllOnesValue();
2594 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2595 TrueIfSigned = false;
2596 return RHS->isAllOnesValue();
2597 case ICmpInst::ICMP_UGT:
2598 // True if LHS u> RHS and RHS == high-bit-mask - 1
2599 TrueIfSigned = true;
2600 return RHS->getValue() ==
2601 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2602 case ICmpInst::ICMP_UGE:
2603 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2604 TrueIfSigned = true;
2605 return RHS->getValue().isSignBit();
2611 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2612 bool Changed = SimplifyCommutative(I);
2613 Value *Op0 = I.getOperand(0);
2615 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2616 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2618 // Simplify mul instructions with a constant RHS...
2619 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2620 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2622 // ((X << C1)*C2) == (X * (C2 << C1))
2623 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2624 if (SI->getOpcode() == Instruction::Shl)
2625 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2626 return BinaryOperator::CreateMul(SI->getOperand(0),
2627 ConstantExpr::getShl(CI, ShOp));
2630 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2631 if (CI->equalsInt(1)) // X * 1 == X
2632 return ReplaceInstUsesWith(I, Op0);
2633 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2634 return BinaryOperator::CreateNeg(Op0, I.getName());
2636 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2637 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2638 return BinaryOperator::CreateShl(Op0,
2639 ConstantInt::get(Op0->getType(), Val.logBase2()));
2641 } else if (isa<VectorType>(Op1->getType())) {
2642 if (Op1->isNullValue())
2643 return ReplaceInstUsesWith(I, Op1);
2645 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2646 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2647 return BinaryOperator::CreateNeg(Op0, I.getName());
2649 // As above, vector X*splat(1.0) -> X in all defined cases.
2650 if (Constant *Splat = Op1V->getSplatValue()) {
2651 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2652 if (CI->equalsInt(1))
2653 return ReplaceInstUsesWith(I, Op0);
2658 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2659 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2660 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2661 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2662 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1, "tmp");
2663 Value *C1C2 = Builder->CreateMul(Op1, Op0I->getOperand(1));
2664 return BinaryOperator::CreateAdd(Add, C1C2);
2668 // Try to fold constant mul into select arguments.
2669 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2670 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2673 if (isa<PHINode>(Op0))
2674 if (Instruction *NV = FoldOpIntoPhi(I))
2678 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2679 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2680 return BinaryOperator::CreateMul(Op0v, Op1v);
2682 // (X / Y) * Y = X - (X % Y)
2683 // (X / Y) * -Y = (X % Y) - X
2685 Value *Op1 = I.getOperand(1);
2686 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2688 (BO->getOpcode() != Instruction::UDiv &&
2689 BO->getOpcode() != Instruction::SDiv)) {
2691 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2693 Value *Neg = dyn_castNegVal(Op1);
2694 if (BO && BO->hasOneUse() &&
2695 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2696 (BO->getOpcode() == Instruction::UDiv ||
2697 BO->getOpcode() == Instruction::SDiv)) {
2698 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2700 // If the division is exact, X % Y is zero.
2701 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2702 if (SDiv->isExact()) {
2704 return ReplaceInstUsesWith(I, Op0BO);
2706 return BinaryOperator::CreateNeg(Op0BO);
2710 if (BO->getOpcode() == Instruction::UDiv)
2711 Rem = Builder->CreateURem(Op0BO, Op1BO);
2713 Rem = Builder->CreateSRem(Op0BO, Op1BO);
2717 return BinaryOperator::CreateSub(Op0BO, Rem);
2718 return BinaryOperator::CreateSub(Rem, Op0BO);
2722 if (I.getType() == Type::getInt1Ty(*Context))
2723 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2725 // If one of the operands of the multiply is a cast from a boolean value, then
2726 // we know the bool is either zero or one, so this is a 'masking' multiply.
2727 // See if we can simplify things based on how the boolean was originally
2729 CastInst *BoolCast = 0;
2730 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2731 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2734 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2735 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2738 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2739 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2740 const Type *SCOpTy = SCIOp0->getType();
2743 // If the icmp is true iff the sign bit of X is set, then convert this
2744 // multiply into a shift/and combination.
2745 if (isa<ConstantInt>(SCIOp1) &&
2746 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2748 // Shift the X value right to turn it into "all signbits".
2749 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2750 SCOpTy->getPrimitiveSizeInBits()-1);
2751 Value *V = Builder->CreateAShr(SCIOp0, Amt,
2752 BoolCast->getOperand(0)->getName()+".mask");
2754 // If the multiply type is not the same as the source type, sign extend
2755 // or truncate to the multiply type.
2756 if (I.getType() != V->getType())
2757 V = Builder->CreateIntCast(V, I.getType(), true);
2759 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2760 return BinaryOperator::CreateAnd(V, OtherOp);
2765 return Changed ? &I : 0;
2768 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2769 bool Changed = SimplifyCommutative(I);
2770 Value *Op0 = I.getOperand(0);
2772 // Simplify mul instructions with a constant RHS...
2773 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2774 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2775 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2776 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2777 if (Op1F->isExactlyValue(1.0))
2778 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2779 } else if (isa<VectorType>(Op1->getType())) {
2780 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2781 // As above, vector X*splat(1.0) -> X in all defined cases.
2782 if (Constant *Splat = Op1V->getSplatValue()) {
2783 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2784 if (F->isExactlyValue(1.0))
2785 return ReplaceInstUsesWith(I, Op0);
2790 // Try to fold constant mul into select arguments.
2791 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2792 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2795 if (isa<PHINode>(Op0))
2796 if (Instruction *NV = FoldOpIntoPhi(I))
2800 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2801 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2802 return BinaryOperator::CreateFMul(Op0v, Op1v);
2804 return Changed ? &I : 0;
2807 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2809 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2810 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2812 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2813 int NonNullOperand = -1;
2814 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2815 if (ST->isNullValue())
2817 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2818 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2819 if (ST->isNullValue())
2822 if (NonNullOperand == -1)
2825 Value *SelectCond = SI->getOperand(0);
2827 // Change the div/rem to use 'Y' instead of the select.
2828 I.setOperand(1, SI->getOperand(NonNullOperand));
2830 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2831 // problem. However, the select, or the condition of the select may have
2832 // multiple uses. Based on our knowledge that the operand must be non-zero,
2833 // propagate the known value for the select into other uses of it, and
2834 // propagate a known value of the condition into its other users.
2836 // If the select and condition only have a single use, don't bother with this,
2838 if (SI->use_empty() && SelectCond->hasOneUse())
2841 // Scan the current block backward, looking for other uses of SI.
2842 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2844 while (BBI != BBFront) {
2846 // If we found a call to a function, we can't assume it will return, so
2847 // information from below it cannot be propagated above it.
2848 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2851 // Replace uses of the select or its condition with the known values.
2852 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2855 *I = SI->getOperand(NonNullOperand);
2857 } else if (*I == SelectCond) {
2858 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2859 ConstantInt::getFalse(*Context);
2864 // If we past the instruction, quit looking for it.
2867 if (&*BBI == SelectCond)
2870 // If we ran out of things to eliminate, break out of the loop.
2871 if (SelectCond == 0 && SI == 0)
2879 /// This function implements the transforms on div instructions that work
2880 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2881 /// used by the visitors to those instructions.
2882 /// @brief Transforms common to all three div instructions
2883 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2884 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2886 // undef / X -> 0 for integer.
2887 // undef / X -> undef for FP (the undef could be a snan).
2888 if (isa<UndefValue>(Op0)) {
2889 if (Op0->getType()->isFPOrFPVector())
2890 return ReplaceInstUsesWith(I, Op0);
2891 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2894 // X / undef -> undef
2895 if (isa<UndefValue>(Op1))
2896 return ReplaceInstUsesWith(I, Op1);
2901 /// This function implements the transforms common to both integer division
2902 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2903 /// division instructions.
2904 /// @brief Common integer divide transforms
2905 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2906 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2908 // (sdiv X, X) --> 1 (udiv X, X) --> 1
2910 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2911 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2912 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2913 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2916 Constant *CI = ConstantInt::get(I.getType(), 1);
2917 return ReplaceInstUsesWith(I, CI);
2920 if (Instruction *Common = commonDivTransforms(I))
2923 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2924 // This does not apply for fdiv.
2925 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2928 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2930 if (RHS->equalsInt(1))
2931 return ReplaceInstUsesWith(I, Op0);
2933 // (X / C1) / C2 -> X / (C1*C2)
2934 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2935 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2936 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2937 if (MultiplyOverflows(RHS, LHSRHS,
2938 I.getOpcode()==Instruction::SDiv))
2939 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2941 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2942 ConstantExpr::getMul(RHS, LHSRHS));
2945 if (!RHS->isZero()) { // avoid X udiv 0
2946 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2947 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2949 if (isa<PHINode>(Op0))
2950 if (Instruction *NV = FoldOpIntoPhi(I))
2955 // 0 / X == 0, we don't need to preserve faults!
2956 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2957 if (LHS->equalsInt(0))
2958 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2960 // It can't be division by zero, hence it must be division by one.
2961 if (I.getType() == Type::getInt1Ty(*Context))
2962 return ReplaceInstUsesWith(I, Op0);
2964 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2965 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2968 return ReplaceInstUsesWith(I, Op0);
2974 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2975 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2977 // Handle the integer div common cases
2978 if (Instruction *Common = commonIDivTransforms(I))
2981 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2982 // X udiv C^2 -> X >> C
2983 // Check to see if this is an unsigned division with an exact power of 2,
2984 // if so, convert to a right shift.
2985 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
2986 return BinaryOperator::CreateLShr(Op0,
2987 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2989 // X udiv C, where C >= signbit
2990 if (C->getValue().isNegative()) {
2991 Value *IC = Builder->CreateICmpULT( Op0, C);
2992 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2993 ConstantInt::get(I.getType(), 1));
2997 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2998 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2999 if (RHSI->getOpcode() == Instruction::Shl &&
3000 isa<ConstantInt>(RHSI->getOperand(0))) {
3001 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3002 if (C1.isPowerOf2()) {
3003 Value *N = RHSI->getOperand(1);
3004 const Type *NTy = N->getType();
3005 if (uint32_t C2 = C1.logBase2())
3006 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
3007 return BinaryOperator::CreateLShr(Op0, N);
3012 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3013 // where C1&C2 are powers of two.
3014 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3015 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3016 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3017 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3018 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3019 // Compute the shift amounts
3020 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3021 // Construct the "on true" case of the select
3022 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3023 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
3025 // Construct the "on false" case of the select
3026 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
3027 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
3029 // construct the select instruction and return it.
3030 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3036 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3037 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3039 // Handle the integer div common cases
3040 if (Instruction *Common = commonIDivTransforms(I))
3043 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3045 if (RHS->isAllOnesValue())
3046 return BinaryOperator::CreateNeg(Op0);
3048 // sdiv X, C --> ashr X, log2(C)
3049 if (cast<SDivOperator>(&I)->isExact() &&
3050 RHS->getValue().isNonNegative() &&
3051 RHS->getValue().isPowerOf2()) {
3052 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3053 RHS->getValue().exactLogBase2());
3054 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3057 // -X/C --> X/-C provided the negation doesn't overflow.
3058 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3059 if (isa<Constant>(Sub->getOperand(0)) &&
3060 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3061 Sub->hasNoSignedWrap())
3062 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3063 ConstantExpr::getNeg(RHS));
3066 // If the sign bits of both operands are zero (i.e. we can prove they are
3067 // unsigned inputs), turn this into a udiv.
3068 if (I.getType()->isInteger()) {
3069 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3070 if (MaskedValueIsZero(Op0, Mask)) {
3071 if (MaskedValueIsZero(Op1, Mask)) {
3072 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3073 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3075 ConstantInt *ShiftedInt;
3076 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3077 ShiftedInt->getValue().isPowerOf2()) {
3078 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3079 // Safe because the only negative value (1 << Y) can take on is
3080 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3081 // the sign bit set.
3082 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3090 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3091 return commonDivTransforms(I);
3094 /// This function implements the transforms on rem instructions that work
3095 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3096 /// is used by the visitors to those instructions.
3097 /// @brief Transforms common to all three rem instructions
3098 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3099 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3101 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3102 if (I.getType()->isFPOrFPVector())
3103 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
3104 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3106 if (isa<UndefValue>(Op1))
3107 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3109 // Handle cases involving: rem X, (select Cond, Y, Z)
3110 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3116 /// This function implements the transforms common to both integer remainder
3117 /// instructions (urem and srem). It is called by the visitors to those integer
3118 /// remainder instructions.
3119 /// @brief Common integer remainder transforms
3120 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3121 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3123 if (Instruction *common = commonRemTransforms(I))
3126 // 0 % X == 0 for integer, we don't need to preserve faults!
3127 if (Constant *LHS = dyn_cast<Constant>(Op0))
3128 if (LHS->isNullValue())
3129 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3131 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3132 // X % 0 == undef, we don't need to preserve faults!
3133 if (RHS->equalsInt(0))
3134 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3136 if (RHS->equalsInt(1)) // X % 1 == 0
3137 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3139 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3140 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3141 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3143 } else if (isa<PHINode>(Op0I)) {
3144 if (Instruction *NV = FoldOpIntoPhi(I))
3148 // See if we can fold away this rem instruction.
3149 if (SimplifyDemandedInstructionBits(I))
3157 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3158 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3160 if (Instruction *common = commonIRemTransforms(I))
3163 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3164 // X urem C^2 -> X and C
3165 // Check to see if this is an unsigned remainder with an exact power of 2,
3166 // if so, convert to a bitwise and.
3167 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3168 if (C->getValue().isPowerOf2())
3169 return BinaryOperator::CreateAnd(Op0, SubOne(C));
3172 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3173 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3174 if (RHSI->getOpcode() == Instruction::Shl &&
3175 isa<ConstantInt>(RHSI->getOperand(0))) {
3176 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3177 Constant *N1 = Constant::getAllOnesValue(I.getType());
3178 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
3179 return BinaryOperator::CreateAnd(Op0, Add);
3184 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3185 // where C1&C2 are powers of two.
3186 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3187 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3188 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3189 // STO == 0 and SFO == 0 handled above.
3190 if ((STO->getValue().isPowerOf2()) &&
3191 (SFO->getValue().isPowerOf2())) {
3192 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3193 SI->getName()+".t");
3194 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3195 SI->getName()+".f");
3196 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3204 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3205 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3207 // Handle the integer rem common cases
3208 if (Instruction *Common = commonIRemTransforms(I))
3211 if (Value *RHSNeg = dyn_castNegVal(Op1))
3212 if (!isa<Constant>(RHSNeg) ||
3213 (isa<ConstantInt>(RHSNeg) &&
3214 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3216 Worklist.AddValue(I.getOperand(1));
3217 I.setOperand(1, RHSNeg);
3221 // If the sign bits of both operands are zero (i.e. we can prove they are
3222 // unsigned inputs), turn this into a urem.
3223 if (I.getType()->isInteger()) {
3224 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3225 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3226 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3227 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3231 // If it's a constant vector, flip any negative values positive.
3232 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3233 unsigned VWidth = RHSV->getNumOperands();
3235 bool hasNegative = false;
3236 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3237 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3238 if (RHS->getValue().isNegative())
3242 std::vector<Constant *> Elts(VWidth);
3243 for (unsigned i = 0; i != VWidth; ++i) {
3244 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3245 if (RHS->getValue().isNegative())
3246 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3252 Constant *NewRHSV = ConstantVector::get(Elts);
3253 if (NewRHSV != RHSV) {
3254 Worklist.AddValue(I.getOperand(1));
3255 I.setOperand(1, NewRHSV);
3264 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3265 return commonRemTransforms(I);
3268 // isOneBitSet - Return true if there is exactly one bit set in the specified
3270 static bool isOneBitSet(const ConstantInt *CI) {
3271 return CI->getValue().isPowerOf2();
3274 // isHighOnes - Return true if the constant is of the form 1+0+.
3275 // This is the same as lowones(~X).
3276 static bool isHighOnes(const ConstantInt *CI) {
3277 return (~CI->getValue() + 1).isPowerOf2();
3280 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3281 /// are carefully arranged to allow folding of expressions such as:
3283 /// (A < B) | (A > B) --> (A != B)
3285 /// Note that this is only valid if the first and second predicates have the
3286 /// same sign. Is illegal to do: (A u< B) | (A s> B)
3288 /// Three bits are used to represent the condition, as follows:
3293 /// <=> Value Definition
3294 /// 000 0 Always false
3301 /// 111 7 Always true
3303 static unsigned getICmpCode(const ICmpInst *ICI) {
3304 switch (ICI->getPredicate()) {
3306 case ICmpInst::ICMP_UGT: return 1; // 001
3307 case ICmpInst::ICMP_SGT: return 1; // 001
3308 case ICmpInst::ICMP_EQ: return 2; // 010
3309 case ICmpInst::ICMP_UGE: return 3; // 011
3310 case ICmpInst::ICMP_SGE: return 3; // 011
3311 case ICmpInst::ICMP_ULT: return 4; // 100
3312 case ICmpInst::ICMP_SLT: return 4; // 100
3313 case ICmpInst::ICMP_NE: return 5; // 101
3314 case ICmpInst::ICMP_ULE: return 6; // 110
3315 case ICmpInst::ICMP_SLE: return 6; // 110
3318 llvm_unreachable("Invalid ICmp predicate!");
3323 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3324 /// predicate into a three bit mask. It also returns whether it is an ordered
3325 /// predicate by reference.
3326 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3329 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3330 case FCmpInst::FCMP_UNO: return 0; // 000
3331 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3332 case FCmpInst::FCMP_UGT: return 1; // 001
3333 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3334 case FCmpInst::FCMP_UEQ: return 2; // 010
3335 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3336 case FCmpInst::FCMP_UGE: return 3; // 011
3337 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3338 case FCmpInst::FCMP_ULT: return 4; // 100
3339 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3340 case FCmpInst::FCMP_UNE: return 5; // 101
3341 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3342 case FCmpInst::FCMP_ULE: return 6; // 110
3345 // Not expecting FCMP_FALSE and FCMP_TRUE;
3346 llvm_unreachable("Unexpected FCmp predicate!");
3351 /// getICmpValue - This is the complement of getICmpCode, which turns an
3352 /// opcode and two operands into either a constant true or false, or a brand
3353 /// new ICmp instruction. The sign is passed in to determine which kind
3354 /// of predicate to use in the new icmp instruction.
3355 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3356 LLVMContext *Context) {
3358 default: llvm_unreachable("Illegal ICmp code!");
3359 case 0: return ConstantInt::getFalse(*Context);
3362 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3364 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3365 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3368 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3370 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3373 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3375 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3376 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3379 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3381 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3382 case 7: return ConstantInt::getTrue(*Context);
3386 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3387 /// opcode and two operands into either a FCmp instruction. isordered is passed
3388 /// in to determine which kind of predicate to use in the new fcmp instruction.
3389 static Value *getFCmpValue(bool isordered, unsigned code,
3390 Value *LHS, Value *RHS, LLVMContext *Context) {
3392 default: llvm_unreachable("Illegal FCmp code!");
3395 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3397 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3400 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3402 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3405 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3407 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3410 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3412 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3415 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3417 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3420 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3422 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3425 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3427 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3428 case 7: return ConstantInt::getTrue(*Context);
3432 /// PredicatesFoldable - Return true if both predicates match sign or if at
3433 /// least one of them is an equality comparison (which is signless).
3434 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3435 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3436 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3437 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3441 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3442 struct FoldICmpLogical {
3445 ICmpInst::Predicate pred;
3446 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3447 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3448 pred(ICI->getPredicate()) {}
3449 bool shouldApply(Value *V) const {
3450 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3451 if (PredicatesFoldable(pred, ICI->getPredicate()))
3452 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3453 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3456 Instruction *apply(Instruction &Log) const {
3457 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3458 if (ICI->getOperand(0) != LHS) {
3459 assert(ICI->getOperand(1) == LHS);
3460 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3463 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3464 unsigned LHSCode = getICmpCode(ICI);
3465 unsigned RHSCode = getICmpCode(RHSICI);
3467 switch (Log.getOpcode()) {
3468 case Instruction::And: Code = LHSCode & RHSCode; break;
3469 case Instruction::Or: Code = LHSCode | RHSCode; break;
3470 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3471 default: llvm_unreachable("Illegal logical opcode!"); return 0;
3474 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3475 ICmpInst::isSignedPredicate(ICI->getPredicate());
3477 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3478 if (Instruction *I = dyn_cast<Instruction>(RV))
3480 // Otherwise, it's a constant boolean value...
3481 return IC.ReplaceInstUsesWith(Log, RV);
3484 } // end anonymous namespace
3486 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3487 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3488 // guaranteed to be a binary operator.
3489 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3491 ConstantInt *AndRHS,
3492 BinaryOperator &TheAnd) {
3493 Value *X = Op->getOperand(0);
3494 Constant *Together = 0;
3496 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3498 switch (Op->getOpcode()) {
3499 case Instruction::Xor:
3500 if (Op->hasOneUse()) {
3501 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3502 Value *And = Builder->CreateAnd(X, AndRHS);
3504 return BinaryOperator::CreateXor(And, Together);
3507 case Instruction::Or:
3508 if (Together == AndRHS) // (X | C) & C --> C
3509 return ReplaceInstUsesWith(TheAnd, AndRHS);
3511 if (Op->hasOneUse() && Together != OpRHS) {
3512 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3513 Value *Or = Builder->CreateOr(X, Together);
3515 return BinaryOperator::CreateAnd(Or, AndRHS);
3518 case Instruction::Add:
3519 if (Op->hasOneUse()) {
3520 // Adding a one to a single bit bit-field should be turned into an XOR
3521 // of the bit. First thing to check is to see if this AND is with a
3522 // single bit constant.
3523 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3525 // If there is only one bit set...
3526 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3527 // Ok, at this point, we know that we are masking the result of the
3528 // ADD down to exactly one bit. If the constant we are adding has
3529 // no bits set below this bit, then we can eliminate the ADD.
3530 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3532 // Check to see if any bits below the one bit set in AndRHSV are set.
3533 if ((AddRHS & (AndRHSV-1)) == 0) {
3534 // If not, the only thing that can effect the output of the AND is
3535 // the bit specified by AndRHSV. If that bit is set, the effect of
3536 // the XOR is to toggle the bit. If it is clear, then the ADD has
3538 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3539 TheAnd.setOperand(0, X);
3542 // Pull the XOR out of the AND.
3543 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
3544 NewAnd->takeName(Op);
3545 return BinaryOperator::CreateXor(NewAnd, AndRHS);
3552 case Instruction::Shl: {
3553 // We know that the AND will not produce any of the bits shifted in, so if
3554 // the anded constant includes them, clear them now!
3556 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3557 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3558 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3559 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3561 if (CI->getValue() == ShlMask) {
3562 // Masking out bits that the shift already masks
3563 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3564 } else if (CI != AndRHS) { // Reducing bits set in and.
3565 TheAnd.setOperand(1, CI);
3570 case Instruction::LShr:
3572 // We know that the AND will not produce any of the bits shifted in, so if
3573 // the anded constant includes them, clear them now! This only applies to
3574 // unsigned shifts, because a signed shr may bring in set bits!
3576 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3577 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3578 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3579 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3581 if (CI->getValue() == ShrMask) {
3582 // Masking out bits that the shift already masks.
3583 return ReplaceInstUsesWith(TheAnd, Op);
3584 } else if (CI != AndRHS) {
3585 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3590 case Instruction::AShr:
3592 // See if this is shifting in some sign extension, then masking it out
3594 if (Op->hasOneUse()) {
3595 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3596 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3597 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3598 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3599 if (C == AndRHS) { // Masking out bits shifted in.
3600 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3601 // Make the argument unsigned.
3602 Value *ShVal = Op->getOperand(0);
3603 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
3604 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3613 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3614 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3615 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3616 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3617 /// insert new instructions.
3618 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3619 bool isSigned, bool Inside,
3621 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3622 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3623 "Lo is not <= Hi in range emission code!");
3626 if (Lo == Hi) // Trivially false.
3627 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3629 // V >= Min && V < Hi --> V < Hi
3630 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3631 ICmpInst::Predicate pred = (isSigned ?
3632 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3633 return new ICmpInst(pred, V, Hi);
3636 // Emit V-Lo <u Hi-Lo
3637 Constant *NegLo = ConstantExpr::getNeg(Lo);
3638 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3639 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3640 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3643 if (Lo == Hi) // Trivially true.
3644 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3646 // V < Min || V >= Hi -> V > Hi-1
3647 Hi = SubOne(cast<ConstantInt>(Hi));
3648 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3649 ICmpInst::Predicate pred = (isSigned ?
3650 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3651 return new ICmpInst(pred, V, Hi);
3654 // Emit V-Lo >u Hi-1-Lo
3655 // Note that Hi has already had one subtracted from it, above.
3656 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3657 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3658 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3659 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3662 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3663 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3664 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3665 // not, since all 1s are not contiguous.
3666 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3667 const APInt& V = Val->getValue();
3668 uint32_t BitWidth = Val->getType()->getBitWidth();
3669 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3671 // look for the first zero bit after the run of ones
3672 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3673 // look for the first non-zero bit
3674 ME = V.getActiveBits();
3678 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3679 /// where isSub determines whether the operator is a sub. If we can fold one of
3680 /// the following xforms:
3682 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3683 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3684 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3686 /// return (A +/- B).
3688 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3689 ConstantInt *Mask, bool isSub,
3691 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3692 if (!LHSI || LHSI->getNumOperands() != 2 ||
3693 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3695 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3697 switch (LHSI->getOpcode()) {
3699 case Instruction::And:
3700 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3701 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3702 if ((Mask->getValue().countLeadingZeros() +
3703 Mask->getValue().countPopulation()) ==
3704 Mask->getValue().getBitWidth())
3707 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3708 // part, we don't need any explicit masks to take them out of A. If that
3709 // is all N is, ignore it.
3710 uint32_t MB = 0, ME = 0;
3711 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3712 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3713 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3714 if (MaskedValueIsZero(RHS, Mask))
3719 case Instruction::Or:
3720 case Instruction::Xor:
3721 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3722 if ((Mask->getValue().countLeadingZeros() +
3723 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3724 && ConstantExpr::getAnd(N, Mask)->isNullValue())
3730 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3731 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
3734 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3735 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3736 ICmpInst *LHS, ICmpInst *RHS) {
3738 ConstantInt *LHSCst, *RHSCst;
3739 ICmpInst::Predicate LHSCC, RHSCC;
3741 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3742 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3743 m_ConstantInt(LHSCst))) ||
3744 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3745 m_ConstantInt(RHSCst))))
3748 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3749 // where C is a power of 2
3750 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3751 LHSCst->getValue().isPowerOf2()) {
3752 Value *NewOr = Builder->CreateOr(Val, Val2);
3753 return new ICmpInst(LHSCC, NewOr, LHSCst);
3756 // From here on, we only handle:
3757 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3758 if (Val != Val2) return 0;
3760 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3761 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3762 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3763 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3764 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3767 // We can't fold (ugt x, C) & (sgt x, C2).
3768 if (!PredicatesFoldable(LHSCC, RHSCC))
3771 // Ensure that the larger constant is on the RHS.
3773 if (ICmpInst::isSignedPredicate(LHSCC) ||
3774 (ICmpInst::isEquality(LHSCC) &&
3775 ICmpInst::isSignedPredicate(RHSCC)))
3776 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3778 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3781 std::swap(LHS, RHS);
3782 std::swap(LHSCst, RHSCst);
3783 std::swap(LHSCC, RHSCC);
3786 // At this point, we know we have have two icmp instructions
3787 // comparing a value against two constants and and'ing the result
3788 // together. Because of the above check, we know that we only have
3789 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3790 // (from the FoldICmpLogical check above), that the two constants
3791 // are not equal and that the larger constant is on the RHS
3792 assert(LHSCst != RHSCst && "Compares not folded above?");
3795 default: llvm_unreachable("Unknown integer condition code!");
3796 case ICmpInst::ICMP_EQ:
3798 default: llvm_unreachable("Unknown integer condition code!");
3799 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3800 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3801 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3802 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3803 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3804 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3805 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3806 return ReplaceInstUsesWith(I, LHS);
3808 case ICmpInst::ICMP_NE:
3810 default: llvm_unreachable("Unknown integer condition code!");
3811 case ICmpInst::ICMP_ULT:
3812 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3813 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3814 break; // (X != 13 & X u< 15) -> no change
3815 case ICmpInst::ICMP_SLT:
3816 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3817 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3818 break; // (X != 13 & X s< 15) -> no change
3819 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3820 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3821 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3822 return ReplaceInstUsesWith(I, RHS);
3823 case ICmpInst::ICMP_NE:
3824 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3825 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3826 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
3827 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3828 ConstantInt::get(Add->getType(), 1));
3830 break; // (X != 13 & X != 15) -> no change
3833 case ICmpInst::ICMP_ULT:
3835 default: llvm_unreachable("Unknown integer condition code!");
3836 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3837 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3838 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3839 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3841 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3842 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3843 return ReplaceInstUsesWith(I, LHS);
3844 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3848 case ICmpInst::ICMP_SLT:
3850 default: llvm_unreachable("Unknown integer condition code!");
3851 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3852 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3853 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3854 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3856 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3857 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3858 return ReplaceInstUsesWith(I, LHS);
3859 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3863 case ICmpInst::ICMP_UGT:
3865 default: llvm_unreachable("Unknown integer condition code!");
3866 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3867 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3868 return ReplaceInstUsesWith(I, RHS);
3869 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3871 case ICmpInst::ICMP_NE:
3872 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3873 return new ICmpInst(LHSCC, Val, RHSCst);
3874 break; // (X u> 13 & X != 15) -> no change
3875 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
3876 return InsertRangeTest(Val, AddOne(LHSCst),
3877 RHSCst, false, true, I);
3878 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3882 case ICmpInst::ICMP_SGT:
3884 default: llvm_unreachable("Unknown integer condition code!");
3885 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3886 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3887 return ReplaceInstUsesWith(I, RHS);
3888 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3890 case ICmpInst::ICMP_NE:
3891 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3892 return new ICmpInst(LHSCC, Val, RHSCst);
3893 break; // (X s> 13 & X != 15) -> no change
3894 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
3895 return InsertRangeTest(Val, AddOne(LHSCst),
3896 RHSCst, true, true, I);
3897 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3906 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3909 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3910 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3911 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3912 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3913 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3914 // If either of the constants are nans, then the whole thing returns
3916 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3917 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3918 return new FCmpInst(FCmpInst::FCMP_ORD,
3919 LHS->getOperand(0), RHS->getOperand(0));
3922 // Handle vector zeros. This occurs because the canonical form of
3923 // "fcmp ord x,x" is "fcmp ord x, 0".
3924 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3925 isa<ConstantAggregateZero>(RHS->getOperand(1)))
3926 return new FCmpInst(FCmpInst::FCMP_ORD,
3927 LHS->getOperand(0), RHS->getOperand(0));
3931 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3932 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3933 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3936 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3937 // Swap RHS operands to match LHS.
3938 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3939 std::swap(Op1LHS, Op1RHS);
3942 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3943 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3945 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3947 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
3948 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3949 if (Op0CC == FCmpInst::FCMP_TRUE)
3950 return ReplaceInstUsesWith(I, RHS);
3951 if (Op1CC == FCmpInst::FCMP_TRUE)
3952 return ReplaceInstUsesWith(I, LHS);
3956 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
3957 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
3959 std::swap(LHS, RHS);
3960 std::swap(Op0Pred, Op1Pred);
3961 std::swap(Op0Ordered, Op1Ordered);
3964 // uno && ueq -> uno && (uno || eq) -> ueq
3965 // ord && olt -> ord && (ord && lt) -> olt
3966 if (Op0Ordered == Op1Ordered)
3967 return ReplaceInstUsesWith(I, RHS);
3969 // uno && oeq -> uno && (ord && eq) -> false
3970 // uno && ord -> false
3972 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3973 // ord && ueq -> ord && (uno || eq) -> oeq
3974 return cast<Instruction>(getFCmpValue(true, Op1Pred,
3975 Op0LHS, Op0RHS, Context));
3983 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3984 bool Changed = SimplifyCommutative(I);
3985 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3987 if (isa<UndefValue>(Op1)) // X & undef -> 0
3988 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3992 return ReplaceInstUsesWith(I, Op1);
3994 // See if we can simplify any instructions used by the instruction whose sole
3995 // purpose is to compute bits we don't care about.
3996 if (SimplifyDemandedInstructionBits(I))
3998 if (isa<VectorType>(I.getType())) {
3999 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4000 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
4001 return ReplaceInstUsesWith(I, I.getOperand(0));
4002 } else if (isa<ConstantAggregateZero>(Op1)) {
4003 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
4007 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4008 const APInt& AndRHSMask = AndRHS->getValue();
4009 APInt NotAndRHS(~AndRHSMask);
4011 // Optimize a variety of ((val OP C1) & C2) combinations...
4012 if (isa<BinaryOperator>(Op0)) {
4013 Instruction *Op0I = cast<Instruction>(Op0);
4014 Value *Op0LHS = Op0I->getOperand(0);
4015 Value *Op0RHS = Op0I->getOperand(1);
4016 switch (Op0I->getOpcode()) {
4017 case Instruction::Xor:
4018 case Instruction::Or:
4019 // If the mask is only needed on one incoming arm, push it up.
4020 if (Op0I->hasOneUse()) {
4021 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4022 // Not masking anything out for the LHS, move to RHS.
4023 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4024 Op0RHS->getName()+".masked");
4025 return BinaryOperator::Create(
4026 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4028 if (!isa<Constant>(Op0RHS) &&
4029 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4030 // Not masking anything out for the RHS, move to LHS.
4031 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4032 Op0LHS->getName()+".masked");
4033 return BinaryOperator::Create(
4034 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4039 case Instruction::Add:
4040 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4041 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4042 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4043 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4044 return BinaryOperator::CreateAnd(V, AndRHS);
4045 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4046 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
4049 case Instruction::Sub:
4050 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4051 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4052 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4053 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4054 return BinaryOperator::CreateAnd(V, AndRHS);
4056 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4057 // has 1's for all bits that the subtraction with A might affect.
4058 if (Op0I->hasOneUse()) {
4059 uint32_t BitWidth = AndRHSMask.getBitWidth();
4060 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4061 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4063 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4064 if (!(A && A->isZero()) && // avoid infinite recursion.
4065 MaskedValueIsZero(Op0LHS, Mask)) {
4066 Value *NewNeg = Builder->CreateNeg(Op0RHS);
4067 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4072 case Instruction::Shl:
4073 case Instruction::LShr:
4074 // (1 << x) & 1 --> zext(x == 0)
4075 // (1 >> x) & 1 --> zext(x == 0)
4076 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4078 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
4079 return new ZExtInst(NewICmp, I.getType());
4084 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4085 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4087 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4088 // If this is an integer truncation or change from signed-to-unsigned, and
4089 // if the source is an and/or with immediate, transform it. This
4090 // frequently occurs for bitfield accesses.
4091 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4092 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4093 CastOp->getNumOperands() == 2)
4094 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4095 if (CastOp->getOpcode() == Instruction::And) {
4096 // Change: and (cast (and X, C1) to T), C2
4097 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4098 // This will fold the two constants together, which may allow
4099 // other simplifications.
4100 Value *NewCast = Builder->CreateTruncOrBitCast(
4101 CastOp->getOperand(0), I.getType(),
4102 CastOp->getName()+".shrunk");
4103 // trunc_or_bitcast(C1)&C2
4104 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4105 C3 = ConstantExpr::getAnd(C3, AndRHS);
4106 return BinaryOperator::CreateAnd(NewCast, C3);
4107 } else if (CastOp->getOpcode() == Instruction::Or) {
4108 // Change: and (cast (or X, C1) to T), C2
4109 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4110 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4111 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4113 return ReplaceInstUsesWith(I, AndRHS);
4119 // Try to fold constant and into select arguments.
4120 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4121 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4123 if (isa<PHINode>(Op0))
4124 if (Instruction *NV = FoldOpIntoPhi(I))
4128 Value *Op0NotVal = dyn_castNotVal(Op0);
4129 Value *Op1NotVal = dyn_castNotVal(Op1);
4131 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4132 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4134 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4135 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4136 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4137 I.getName()+".demorgan");
4138 return BinaryOperator::CreateNot(Or);
4142 Value *A = 0, *B = 0, *C = 0, *D = 0;
4143 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4144 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4145 return ReplaceInstUsesWith(I, Op1);
4147 // (A|B) & ~(A&B) -> A^B
4148 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4149 if ((A == C && B == D) || (A == D && B == C))
4150 return BinaryOperator::CreateXor(A, B);
4154 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4155 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4156 return ReplaceInstUsesWith(I, Op0);
4158 // ~(A&B) & (A|B) -> A^B
4159 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4160 if ((A == C && B == D) || (A == D && B == C))
4161 return BinaryOperator::CreateXor(A, B);
4165 if (Op0->hasOneUse() &&
4166 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4167 if (A == Op1) { // (A^B)&A -> A&(A^B)
4168 I.swapOperands(); // Simplify below
4169 std::swap(Op0, Op1);
4170 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4171 cast<BinaryOperator>(Op0)->swapOperands();
4172 I.swapOperands(); // Simplify below
4173 std::swap(Op0, Op1);
4177 if (Op1->hasOneUse() &&
4178 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4179 if (B == Op0) { // B&(A^B) -> B&(B^A)
4180 cast<BinaryOperator>(Op1)->swapOperands();
4183 if (A == Op0) // A&(A^B) -> A & ~B
4184 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
4187 // (A&((~A)|B)) -> A&B
4188 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4189 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4190 return BinaryOperator::CreateAnd(A, Op1);
4191 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4192 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4193 return BinaryOperator::CreateAnd(A, Op0);
4196 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4197 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4198 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4201 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4202 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4206 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4207 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4208 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4209 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4210 const Type *SrcTy = Op0C->getOperand(0)->getType();
4211 if (SrcTy == Op1C->getOperand(0)->getType() &&
4212 SrcTy->isIntOrIntVector() &&
4213 // Only do this if the casts both really cause code to be generated.
4214 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4216 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4218 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4219 Op1C->getOperand(0), I.getName());
4220 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4224 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4225 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4226 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4227 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4228 SI0->getOperand(1) == SI1->getOperand(1) &&
4229 (SI0->hasOneUse() || SI1->hasOneUse())) {
4231 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4233 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4234 SI1->getOperand(1));
4238 // If and'ing two fcmp, try combine them into one.
4239 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4240 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4241 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4245 return Changed ? &I : 0;
4248 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4249 /// capable of providing pieces of a bswap. The subexpression provides pieces
4250 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4251 /// the expression came from the corresponding "byte swapped" byte in some other
4252 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4253 /// we know that the expression deposits the low byte of %X into the high byte
4254 /// of the bswap result and that all other bytes are zero. This expression is
4255 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4258 /// This function returns true if the match was unsuccessful and false if so.
4259 /// On entry to the function the "OverallLeftShift" is a signed integer value
4260 /// indicating the number of bytes that the subexpression is later shifted. For
4261 /// example, if the expression is later right shifted by 16 bits, the
4262 /// OverallLeftShift value would be -2 on entry. This is used to specify which
4263 /// byte of ByteValues is actually being set.
4265 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4266 /// byte is masked to zero by a user. For example, in (X & 255), X will be
4267 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4268 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
4269 /// always in the local (OverallLeftShift) coordinate space.
4271 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4272 SmallVector<Value*, 8> &ByteValues) {
4273 if (Instruction *I = dyn_cast<Instruction>(V)) {
4274 // If this is an or instruction, it may be an inner node of the bswap.
4275 if (I->getOpcode() == Instruction::Or) {
4276 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4278 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4282 // If this is a logical shift by a constant multiple of 8, recurse with
4283 // OverallLeftShift and ByteMask adjusted.
4284 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4286 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4287 // Ensure the shift amount is defined and of a byte value.
4288 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4291 unsigned ByteShift = ShAmt >> 3;
4292 if (I->getOpcode() == Instruction::Shl) {
4293 // X << 2 -> collect(X, +2)
4294 OverallLeftShift += ByteShift;
4295 ByteMask >>= ByteShift;
4297 // X >>u 2 -> collect(X, -2)
4298 OverallLeftShift -= ByteShift;
4299 ByteMask <<= ByteShift;
4300 ByteMask &= (~0U >> (32-ByteValues.size()));
4303 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4304 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4306 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4310 // If this is a logical 'and' with a mask that clears bytes, clear the
4311 // corresponding bytes in ByteMask.
4312 if (I->getOpcode() == Instruction::And &&
4313 isa<ConstantInt>(I->getOperand(1))) {
4314 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4315 unsigned NumBytes = ByteValues.size();
4316 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4317 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4319 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4320 // If this byte is masked out by a later operation, we don't care what
4322 if ((ByteMask & (1 << i)) == 0)
4325 // If the AndMask is all zeros for this byte, clear the bit.
4326 APInt MaskB = AndMask & Byte;
4328 ByteMask &= ~(1U << i);
4332 // If the AndMask is not all ones for this byte, it's not a bytezap.
4336 // Otherwise, this byte is kept.
4339 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4344 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4345 // the input value to the bswap. Some observations: 1) if more than one byte
4346 // is demanded from this input, then it could not be successfully assembled
4347 // into a byteswap. At least one of the two bytes would not be aligned with
4348 // their ultimate destination.
4349 if (!isPowerOf2_32(ByteMask)) return true;
4350 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4352 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4353 // is demanded, it needs to go into byte 0 of the result. This means that the
4354 // byte needs to be shifted until it lands in the right byte bucket. The
4355 // shift amount depends on the position: if the byte is coming from the high
4356 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4357 // low part, it must be shifted left.
4358 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4359 if (InputByteNo < ByteValues.size()/2) {
4360 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4363 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4367 // If the destination byte value is already defined, the values are or'd
4368 // together, which isn't a bswap (unless it's an or of the same bits).
4369 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4371 ByteValues[DestByteNo] = V;
4375 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4376 /// If so, insert the new bswap intrinsic and return it.
4377 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4378 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4379 if (!ITy || ITy->getBitWidth() % 16 ||
4380 // ByteMask only allows up to 32-byte values.
4381 ITy->getBitWidth() > 32*8)
4382 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4384 /// ByteValues - For each byte of the result, we keep track of which value
4385 /// defines each byte.
4386 SmallVector<Value*, 8> ByteValues;
4387 ByteValues.resize(ITy->getBitWidth()/8);
4389 // Try to find all the pieces corresponding to the bswap.
4390 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4391 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4394 // Check to see if all of the bytes come from the same value.
4395 Value *V = ByteValues[0];
4396 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4398 // Check to make sure that all of the bytes come from the same value.
4399 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4400 if (ByteValues[i] != V)
4402 const Type *Tys[] = { ITy };
4403 Module *M = I.getParent()->getParent()->getParent();
4404 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4405 return CallInst::Create(F, V);
4408 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4409 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4410 /// we can simplify this expression to "cond ? C : D or B".
4411 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4413 LLVMContext *Context) {
4414 // If A is not a select of -1/0, this cannot match.
4416 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4419 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4420 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4421 return SelectInst::Create(Cond, C, B);
4422 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4423 return SelectInst::Create(Cond, C, B);
4424 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4425 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4426 return SelectInst::Create(Cond, C, D);
4427 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4428 return SelectInst::Create(Cond, C, D);
4432 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4433 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4434 ICmpInst *LHS, ICmpInst *RHS) {
4436 ConstantInt *LHSCst, *RHSCst;
4437 ICmpInst::Predicate LHSCC, RHSCC;
4439 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4440 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4441 m_ConstantInt(LHSCst))) ||
4442 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4443 m_ConstantInt(RHSCst))))
4446 // From here on, we only handle:
4447 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4448 if (Val != Val2) return 0;
4450 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4451 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4452 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4453 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4454 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4457 // We can't fold (ugt x, C) | (sgt x, C2).
4458 if (!PredicatesFoldable(LHSCC, RHSCC))
4461 // Ensure that the larger constant is on the RHS.
4463 if (ICmpInst::isSignedPredicate(LHSCC) ||
4464 (ICmpInst::isEquality(LHSCC) &&
4465 ICmpInst::isSignedPredicate(RHSCC)))
4466 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4468 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4471 std::swap(LHS, RHS);
4472 std::swap(LHSCst, RHSCst);
4473 std::swap(LHSCC, RHSCC);
4476 // At this point, we know we have have two icmp instructions
4477 // comparing a value against two constants and or'ing the result
4478 // together. Because of the above check, we know that we only have
4479 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4480 // FoldICmpLogical check above), that the two constants are not
4482 assert(LHSCst != RHSCst && "Compares not folded above?");
4485 default: llvm_unreachable("Unknown integer condition code!");
4486 case ICmpInst::ICMP_EQ:
4488 default: llvm_unreachable("Unknown integer condition code!");
4489 case ICmpInst::ICMP_EQ:
4490 if (LHSCst == SubOne(RHSCst)) {
4491 // (X == 13 | X == 14) -> X-13 <u 2
4492 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4493 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4494 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4495 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4497 break; // (X == 13 | X == 15) -> no change
4498 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4499 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4501 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4502 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4503 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4504 return ReplaceInstUsesWith(I, RHS);
4507 case ICmpInst::ICMP_NE:
4509 default: llvm_unreachable("Unknown integer condition code!");
4510 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4511 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4512 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4513 return ReplaceInstUsesWith(I, LHS);
4514 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4515 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4516 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4517 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4520 case ICmpInst::ICMP_ULT:
4522 default: llvm_unreachable("Unknown integer condition code!");
4523 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4525 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4526 // If RHSCst is [us]MAXINT, it is always false. Not handling
4527 // this can cause overflow.
4528 if (RHSCst->isMaxValue(false))
4529 return ReplaceInstUsesWith(I, LHS);
4530 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4532 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4534 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4535 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4536 return ReplaceInstUsesWith(I, RHS);
4537 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4541 case ICmpInst::ICMP_SLT:
4543 default: llvm_unreachable("Unknown integer condition code!");
4544 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4546 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4547 // If RHSCst is [us]MAXINT, it is always false. Not handling
4548 // this can cause overflow.
4549 if (RHSCst->isMaxValue(true))
4550 return ReplaceInstUsesWith(I, LHS);
4551 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4553 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4555 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4556 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4557 return ReplaceInstUsesWith(I, RHS);
4558 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4562 case ICmpInst::ICMP_UGT:
4564 default: llvm_unreachable("Unknown integer condition code!");
4565 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4566 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4567 return ReplaceInstUsesWith(I, LHS);
4568 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4570 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4571 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4572 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4573 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4577 case ICmpInst::ICMP_SGT:
4579 default: llvm_unreachable("Unknown integer condition code!");
4580 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4581 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4582 return ReplaceInstUsesWith(I, LHS);
4583 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4585 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4586 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4587 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4588 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4596 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4598 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4599 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4600 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4601 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4602 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4603 // If either of the constants are nans, then the whole thing returns
4605 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4606 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4608 // Otherwise, no need to compare the two constants, compare the
4610 return new FCmpInst(FCmpInst::FCMP_UNO,
4611 LHS->getOperand(0), RHS->getOperand(0));
4614 // Handle vector zeros. This occurs because the canonical form of
4615 // "fcmp uno x,x" is "fcmp uno x, 0".
4616 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4617 isa<ConstantAggregateZero>(RHS->getOperand(1)))
4618 return new FCmpInst(FCmpInst::FCMP_UNO,
4619 LHS->getOperand(0), RHS->getOperand(0));
4624 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4625 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4626 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4628 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4629 // Swap RHS operands to match LHS.
4630 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4631 std::swap(Op1LHS, Op1RHS);
4633 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4634 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4636 return new FCmpInst((FCmpInst::Predicate)Op0CC,
4638 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4639 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4640 if (Op0CC == FCmpInst::FCMP_FALSE)
4641 return ReplaceInstUsesWith(I, RHS);
4642 if (Op1CC == FCmpInst::FCMP_FALSE)
4643 return ReplaceInstUsesWith(I, LHS);
4646 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4647 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4648 if (Op0Ordered == Op1Ordered) {
4649 // If both are ordered or unordered, return a new fcmp with
4650 // or'ed predicates.
4651 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4652 Op0LHS, Op0RHS, Context);
4653 if (Instruction *I = dyn_cast<Instruction>(RV))
4655 // Otherwise, it's a constant boolean value...
4656 return ReplaceInstUsesWith(I, RV);
4662 /// FoldOrWithConstants - This helper function folds:
4664 /// ((A | B) & C1) | (B & C2)
4670 /// when the XOR of the two constants is "all ones" (-1).
4671 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4672 Value *A, Value *B, Value *C) {
4673 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4677 ConstantInt *CI2 = 0;
4678 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4680 APInt Xor = CI1->getValue() ^ CI2->getValue();
4681 if (!Xor.isAllOnesValue()) return 0;
4683 if (V1 == A || V1 == B) {
4684 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
4685 return BinaryOperator::CreateOr(NewOp, V1);
4691 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4692 bool Changed = SimplifyCommutative(I);
4693 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4695 if (isa<UndefValue>(Op1)) // X | undef -> -1
4696 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4700 return ReplaceInstUsesWith(I, Op0);
4702 // See if we can simplify any instructions used by the instruction whose sole
4703 // purpose is to compute bits we don't care about.
4704 if (SimplifyDemandedInstructionBits(I))
4706 if (isa<VectorType>(I.getType())) {
4707 if (isa<ConstantAggregateZero>(Op1)) {
4708 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4709 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4710 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4711 return ReplaceInstUsesWith(I, I.getOperand(1));
4716 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4717 ConstantInt *C1 = 0; Value *X = 0;
4718 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4719 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
4721 Value *Or = Builder->CreateOr(X, RHS);
4723 return BinaryOperator::CreateAnd(Or,
4724 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4727 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4728 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
4730 Value *Or = Builder->CreateOr(X, RHS);
4732 return BinaryOperator::CreateXor(Or,
4733 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4736 // Try to fold constant and into select arguments.
4737 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4738 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4740 if (isa<PHINode>(Op0))
4741 if (Instruction *NV = FoldOpIntoPhi(I))
4745 Value *A = 0, *B = 0;
4746 ConstantInt *C1 = 0, *C2 = 0;
4748 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4749 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4750 return ReplaceInstUsesWith(I, Op1);
4751 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4752 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4753 return ReplaceInstUsesWith(I, Op0);
4755 // (A | B) | C and A | (B | C) -> bswap if possible.
4756 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4757 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4758 match(Op1, m_Or(m_Value(), m_Value())) ||
4759 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4760 match(Op1, m_Shift(m_Value(), m_Value())))) {
4761 if (Instruction *BSwap = MatchBSwap(I))
4765 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4766 if (Op0->hasOneUse() &&
4767 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4768 MaskedValueIsZero(Op1, C1->getValue())) {
4769 Value *NOr = Builder->CreateOr(A, Op1);
4771 return BinaryOperator::CreateXor(NOr, C1);
4774 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4775 if (Op1->hasOneUse() &&
4776 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4777 MaskedValueIsZero(Op0, C1->getValue())) {
4778 Value *NOr = Builder->CreateOr(A, Op0);
4780 return BinaryOperator::CreateXor(NOr, C1);
4784 Value *C = 0, *D = 0;
4785 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4786 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4787 Value *V1 = 0, *V2 = 0, *V3 = 0;
4788 C1 = dyn_cast<ConstantInt>(C);
4789 C2 = dyn_cast<ConstantInt>(D);
4790 if (C1 && C2) { // (A & C1)|(B & C2)
4791 // If we have: ((V + N) & C1) | (V & C2)
4792 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4793 // replace with V+N.
4794 if (C1->getValue() == ~C2->getValue()) {
4795 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4796 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4797 // Add commutes, try both ways.
4798 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4799 return ReplaceInstUsesWith(I, A);
4800 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4801 return ReplaceInstUsesWith(I, A);
4803 // Or commutes, try both ways.
4804 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4805 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4806 // Add commutes, try both ways.
4807 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4808 return ReplaceInstUsesWith(I, B);
4809 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4810 return ReplaceInstUsesWith(I, B);
4813 V1 = 0; V2 = 0; V3 = 0;
4816 // Check to see if we have any common things being and'ed. If so, find the
4817 // terms for V1 & (V2|V3).
4818 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4819 if (A == B) // (A & C)|(A & D) == A & (C|D)
4820 V1 = A, V2 = C, V3 = D;
4821 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4822 V1 = A, V2 = B, V3 = C;
4823 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4824 V1 = C, V2 = A, V3 = D;
4825 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4826 V1 = C, V2 = A, V3 = B;
4829 Value *Or = Builder->CreateOr(V2, V3, "tmp");
4830 return BinaryOperator::CreateAnd(V1, Or);
4834 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
4835 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4837 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4839 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4841 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4844 // ((A&~B)|(~A&B)) -> A^B
4845 if ((match(C, m_Not(m_Specific(D))) &&
4846 match(B, m_Not(m_Specific(A)))))
4847 return BinaryOperator::CreateXor(A, D);
4848 // ((~B&A)|(~A&B)) -> A^B
4849 if ((match(A, m_Not(m_Specific(D))) &&
4850 match(B, m_Not(m_Specific(C)))))
4851 return BinaryOperator::CreateXor(C, D);
4852 // ((A&~B)|(B&~A)) -> A^B
4853 if ((match(C, m_Not(m_Specific(B))) &&
4854 match(D, m_Not(m_Specific(A)))))
4855 return BinaryOperator::CreateXor(A, B);
4856 // ((~B&A)|(B&~A)) -> A^B
4857 if ((match(A, m_Not(m_Specific(B))) &&
4858 match(D, m_Not(m_Specific(C)))))
4859 return BinaryOperator::CreateXor(C, B);
4862 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4863 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4864 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4865 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4866 SI0->getOperand(1) == SI1->getOperand(1) &&
4867 (SI0->hasOneUse() || SI1->hasOneUse())) {
4868 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4870 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4871 SI1->getOperand(1));
4875 // ((A|B)&1)|(B&-2) -> (A&1) | B
4876 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4877 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4878 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4879 if (Ret) return Ret;
4881 // (B&-2)|((A|B)&1) -> (A&1) | B
4882 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4883 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4884 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4885 if (Ret) return Ret;
4888 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4889 if (A == Op1) // ~A | A == -1
4890 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4894 // Note, A is still live here!
4895 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4897 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4899 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4900 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4901 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
4902 return BinaryOperator::CreateNot(And);
4906 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4907 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4908 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4911 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4912 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4916 // fold (or (cast A), (cast B)) -> (cast (or A, B))
4917 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4918 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4919 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4920 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4921 !isa<ICmpInst>(Op1C->getOperand(0))) {
4922 const Type *SrcTy = Op0C->getOperand(0)->getType();
4923 if (SrcTy == Op1C->getOperand(0)->getType() &&
4924 SrcTy->isIntOrIntVector() &&
4925 // Only do this if the casts both really cause code to be
4927 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4929 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4931 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
4932 Op1C->getOperand(0), I.getName());
4933 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4940 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4941 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4942 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4943 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4947 return Changed ? &I : 0;
4952 // XorSelf - Implements: X ^ X --> 0
4955 XorSelf(Value *rhs) : RHS(rhs) {}
4956 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4957 Instruction *apply(BinaryOperator &Xor) const {
4964 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4965 bool Changed = SimplifyCommutative(I);
4966 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4968 if (isa<UndefValue>(Op1)) {
4969 if (isa<UndefValue>(Op0))
4970 // Handle undef ^ undef -> 0 special case. This is a common
4972 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4973 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4976 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4977 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
4978 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
4979 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4982 // See if we can simplify any instructions used by the instruction whose sole
4983 // purpose is to compute bits we don't care about.
4984 if (SimplifyDemandedInstructionBits(I))
4986 if (isa<VectorType>(I.getType()))
4987 if (isa<ConstantAggregateZero>(Op1))
4988 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4990 // Is this a ~ operation?
4991 if (Value *NotOp = dyn_castNotVal(&I)) {
4992 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4993 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4994 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4995 if (Op0I->getOpcode() == Instruction::And ||
4996 Op0I->getOpcode() == Instruction::Or) {
4997 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4998 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5000 Builder->CreateNot(Op0I->getOperand(1),
5001 Op0I->getOperand(1)->getName()+".not");
5002 if (Op0I->getOpcode() == Instruction::And)
5003 return BinaryOperator::CreateOr(Op0NotVal, NotY);
5004 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5011 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5012 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
5013 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5014 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5015 return new ICmpInst(ICI->getInversePredicate(),
5016 ICI->getOperand(0), ICI->getOperand(1));
5018 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5019 return new FCmpInst(FCI->getInversePredicate(),
5020 FCI->getOperand(0), FCI->getOperand(1));
5023 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5024 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5025 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5026 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5027 Instruction::CastOps Opcode = Op0C->getOpcode();
5028 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5029 (RHS == ConstantExpr::getCast(Opcode,
5030 ConstantInt::getTrue(*Context),
5031 Op0C->getDestTy()))) {
5032 CI->setPredicate(CI->getInversePredicate());
5033 return CastInst::Create(Opcode, CI, Op0C->getType());
5039 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5040 // ~(c-X) == X-c-1 == X+(-c-1)
5041 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5042 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5043 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5044 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5045 ConstantInt::get(I.getType(), 1));
5046 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5049 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5050 if (Op0I->getOpcode() == Instruction::Add) {
5051 // ~(X-c) --> (-c-1)-X
5052 if (RHS->isAllOnesValue()) {
5053 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5054 return BinaryOperator::CreateSub(
5055 ConstantExpr::getSub(NegOp0CI,
5056 ConstantInt::get(I.getType(), 1)),
5057 Op0I->getOperand(0));
5058 } else if (RHS->getValue().isSignBit()) {
5059 // (X + C) ^ signbit -> (X + C + signbit)
5060 Constant *C = ConstantInt::get(*Context,
5061 RHS->getValue() + Op0CI->getValue());
5062 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5065 } else if (Op0I->getOpcode() == Instruction::Or) {
5066 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5067 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5068 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5069 // Anything in both C1 and C2 is known to be zero, remove it from
5071 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5072 NewRHS = ConstantExpr::getAnd(NewRHS,
5073 ConstantExpr::getNot(CommonBits));
5075 I.setOperand(0, Op0I->getOperand(0));
5076 I.setOperand(1, NewRHS);
5083 // Try to fold constant and into select arguments.
5084 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5085 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5087 if (isa<PHINode>(Op0))
5088 if (Instruction *NV = FoldOpIntoPhi(I))
5092 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
5094 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5096 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
5098 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5101 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5104 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5105 if (A == Op0) { // B^(B|A) == (A|B)^B
5106 Op1I->swapOperands();
5108 std::swap(Op0, Op1);
5109 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5110 I.swapOperands(); // Simplified below.
5111 std::swap(Op0, Op1);
5113 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5114 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5115 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5116 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
5117 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
5119 if (A == Op0) { // A^(A&B) -> A^(B&A)
5120 Op1I->swapOperands();
5123 if (B == Op0) { // A^(B&A) -> (B&A)^A
5124 I.swapOperands(); // Simplified below.
5125 std::swap(Op0, Op1);
5130 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5133 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5134 Op0I->hasOneUse()) {
5135 if (A == Op1) // (B|A)^B == (A|B)^B
5137 if (B == Op1) // (A|B)^B == A & ~B
5138 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
5139 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5140 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5141 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5142 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
5143 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5145 if (A == Op1) // (A&B)^A -> (B&A)^A
5147 if (B == Op1 && // (B&A)^A == ~B & A
5148 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5149 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
5154 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5155 if (Op0I && Op1I && Op0I->isShift() &&
5156 Op0I->getOpcode() == Op1I->getOpcode() &&
5157 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5158 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5160 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5162 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
5163 Op1I->getOperand(1));
5167 Value *A, *B, *C, *D;
5168 // (A & B)^(A | B) -> A ^ B
5169 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5170 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5171 if ((A == C && B == D) || (A == D && B == C))
5172 return BinaryOperator::CreateXor(A, B);
5174 // (A | B)^(A & B) -> A ^ B
5175 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5176 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5177 if ((A == C && B == D) || (A == D && B == C))
5178 return BinaryOperator::CreateXor(A, B);
5182 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5183 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5184 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5185 // (X & Y)^(X & Y) -> (Y^Z) & X
5186 Value *X = 0, *Y = 0, *Z = 0;
5188 X = A, Y = B, Z = D;
5190 X = A, Y = B, Z = C;
5192 X = B, Y = A, Z = D;
5194 X = B, Y = A, Z = C;
5197 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
5198 return BinaryOperator::CreateAnd(NewOp, X);
5203 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5204 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5205 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5208 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5209 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5210 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5211 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5212 const Type *SrcTy = Op0C->getOperand(0)->getType();
5213 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5214 // Only do this if the casts both really cause code to be generated.
5215 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5217 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5219 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5220 Op1C->getOperand(0), I.getName());
5221 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5226 return Changed ? &I : 0;
5229 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5230 LLVMContext *Context) {
5231 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5234 static bool HasAddOverflow(ConstantInt *Result,
5235 ConstantInt *In1, ConstantInt *In2,
5238 if (In2->getValue().isNegative())
5239 return Result->getValue().sgt(In1->getValue());
5241 return Result->getValue().slt(In1->getValue());
5243 return Result->getValue().ult(In1->getValue());
5246 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5247 /// overflowed for this type.
5248 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5249 Constant *In2, LLVMContext *Context,
5250 bool IsSigned = false) {
5251 Result = ConstantExpr::getAdd(In1, In2);
5253 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5254 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5255 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5256 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5257 ExtractElement(In1, Idx, Context),
5258 ExtractElement(In2, Idx, Context),
5265 return HasAddOverflow(cast<ConstantInt>(Result),
5266 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5270 static bool HasSubOverflow(ConstantInt *Result,
5271 ConstantInt *In1, ConstantInt *In2,
5274 if (In2->getValue().isNegative())
5275 return Result->getValue().slt(In1->getValue());
5277 return Result->getValue().sgt(In1->getValue());
5279 return Result->getValue().ugt(In1->getValue());
5282 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5283 /// overflowed for this type.
5284 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5285 Constant *In2, LLVMContext *Context,
5286 bool IsSigned = false) {
5287 Result = ConstantExpr::getSub(In1, In2);
5289 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5290 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5291 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5292 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5293 ExtractElement(In1, Idx, Context),
5294 ExtractElement(In2, Idx, Context),
5301 return HasSubOverflow(cast<ConstantInt>(Result),
5302 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5306 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5307 /// code necessary to compute the offset from the base pointer (without adding
5308 /// in the base pointer). Return the result as a signed integer of intptr size.
5309 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5310 TargetData &TD = *IC.getTargetData();
5311 gep_type_iterator GTI = gep_type_begin(GEP);
5312 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
5313 Value *Result = Constant::getNullValue(IntPtrTy);
5315 // Build a mask for high order bits.
5316 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5317 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5319 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5322 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5323 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5324 if (OpC->isZero()) continue;
5326 // Handle a struct index, which adds its field offset to the pointer.
5327 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5328 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5330 Result = IC.Builder->CreateAdd(Result,
5331 ConstantInt::get(IntPtrTy, Size),
5332 GEP->getName()+".offs");
5336 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5338 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5339 Scale = ConstantExpr::getMul(OC, Scale);
5340 // Emit an add instruction.
5341 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
5344 // Convert to correct type.
5345 if (Op->getType() != IntPtrTy)
5346 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
5348 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5349 // We'll let instcombine(mul) convert this to a shl if possible.
5350 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
5353 // Emit an add instruction.
5354 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
5360 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5361 /// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5362 /// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5363 /// be complex, and scales are involved. The above expression would also be
5364 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5365 /// This later form is less amenable to optimization though, and we are allowed
5366 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5368 /// If we can't emit an optimized form for this expression, this returns null.
5370 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5372 TargetData &TD = *IC.getTargetData();
5373 gep_type_iterator GTI = gep_type_begin(GEP);
5375 // Check to see if this gep only has a single variable index. If so, and if
5376 // any constant indices are a multiple of its scale, then we can compute this
5377 // in terms of the scale of the variable index. For example, if the GEP
5378 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5379 // because the expression will cross zero at the same point.
5380 unsigned i, e = GEP->getNumOperands();
5382 for (i = 1; i != e; ++i, ++GTI) {
5383 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5384 // Compute the aggregate offset of constant indices.
5385 if (CI->isZero()) continue;
5387 // Handle a struct index, which adds its field offset to the pointer.
5388 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5389 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5391 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5392 Offset += Size*CI->getSExtValue();
5395 // Found our variable index.
5400 // If there are no variable indices, we must have a constant offset, just
5401 // evaluate it the general way.
5402 if (i == e) return 0;
5404 Value *VariableIdx = GEP->getOperand(i);
5405 // Determine the scale factor of the variable element. For example, this is
5406 // 4 if the variable index is into an array of i32.
5407 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5409 // Verify that there are no other variable indices. If so, emit the hard way.
5410 for (++i, ++GTI; i != e; ++i, ++GTI) {
5411 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5414 // Compute the aggregate offset of constant indices.
5415 if (CI->isZero()) continue;
5417 // Handle a struct index, which adds its field offset to the pointer.
5418 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5419 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5421 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5422 Offset += Size*CI->getSExtValue();
5426 // Okay, we know we have a single variable index, which must be a
5427 // pointer/array/vector index. If there is no offset, life is simple, return
5429 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5431 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5432 // we don't need to bother extending: the extension won't affect where the
5433 // computation crosses zero.
5434 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5435 VariableIdx = new TruncInst(VariableIdx,
5436 TD.getIntPtrType(VariableIdx->getContext()),
5437 VariableIdx->getName(), &I);
5441 // Otherwise, there is an index. The computation we will do will be modulo
5442 // the pointer size, so get it.
5443 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5445 Offset &= PtrSizeMask;
5446 VariableScale &= PtrSizeMask;
5448 // To do this transformation, any constant index must be a multiple of the
5449 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5450 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5451 // multiple of the variable scale.
5452 int64_t NewOffs = Offset / (int64_t)VariableScale;
5453 if (Offset != NewOffs*(int64_t)VariableScale)
5456 // Okay, we can do this evaluation. Start by converting the index to intptr.
5457 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
5458 if (VariableIdx->getType() != IntPtrTy)
5459 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5461 VariableIdx->getName(), &I);
5462 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5463 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5467 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5468 /// else. At this point we know that the GEP is on the LHS of the comparison.
5469 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5470 ICmpInst::Predicate Cond,
5472 // Look through bitcasts.
5473 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5474 RHS = BCI->getOperand(0);
5476 Value *PtrBase = GEPLHS->getOperand(0);
5477 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5478 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
5479 // This transformation (ignoring the base and scales) is valid because we
5480 // know pointers can't overflow since the gep is inbounds. See if we can
5481 // output an optimized form.
5482 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5484 // If not, synthesize the offset the hard way.
5486 Offset = EmitGEPOffset(GEPLHS, I, *this);
5487 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5488 Constant::getNullValue(Offset->getType()));
5489 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5490 // If the base pointers are different, but the indices are the same, just
5491 // compare the base pointer.
5492 if (PtrBase != GEPRHS->getOperand(0)) {
5493 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5494 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5495 GEPRHS->getOperand(0)->getType();
5497 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5498 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5499 IndicesTheSame = false;
5503 // If all indices are the same, just compare the base pointers.
5505 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5506 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5508 // Otherwise, the base pointers are different and the indices are
5509 // different, bail out.
5513 // If one of the GEPs has all zero indices, recurse.
5514 bool AllZeros = true;
5515 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5516 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5517 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5522 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5523 ICmpInst::getSwappedPredicate(Cond), I);
5525 // If the other GEP has all zero indices, recurse.
5527 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5528 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5529 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5534 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5536 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5537 // If the GEPs only differ by one index, compare it.
5538 unsigned NumDifferences = 0; // Keep track of # differences.
5539 unsigned DiffOperand = 0; // The operand that differs.
5540 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5541 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5542 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5543 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5544 // Irreconcilable differences.
5548 if (NumDifferences++) break;
5553 if (NumDifferences == 0) // SAME GEP?
5554 return ReplaceInstUsesWith(I, // No comparison is needed here.
5555 ConstantInt::get(Type::getInt1Ty(*Context),
5556 ICmpInst::isTrueWhenEqual(Cond)));
5558 else if (NumDifferences == 1) {
5559 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5560 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5561 // Make sure we do a signed comparison here.
5562 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5566 // Only lower this if the icmp is the only user of the GEP or if we expect
5567 // the result to fold to a constant!
5569 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5570 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5571 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5572 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5573 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5574 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5580 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5582 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5585 if (!isa<ConstantFP>(RHSC)) return 0;
5586 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5588 // Get the width of the mantissa. We don't want to hack on conversions that
5589 // might lose information from the integer, e.g. "i64 -> float"
5590 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5591 if (MantissaWidth == -1) return 0; // Unknown.
5593 // Check to see that the input is converted from an integer type that is small
5594 // enough that preserves all bits. TODO: check here for "known" sign bits.
5595 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5596 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5598 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5599 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5603 // If the conversion would lose info, don't hack on this.
5604 if ((int)InputSize > MantissaWidth)
5607 // Otherwise, we can potentially simplify the comparison. We know that it
5608 // will always come through as an integer value and we know the constant is
5609 // not a NAN (it would have been previously simplified).
5610 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5612 ICmpInst::Predicate Pred;
5613 switch (I.getPredicate()) {
5614 default: llvm_unreachable("Unexpected predicate!");
5615 case FCmpInst::FCMP_UEQ:
5616 case FCmpInst::FCMP_OEQ:
5617 Pred = ICmpInst::ICMP_EQ;
5619 case FCmpInst::FCMP_UGT:
5620 case FCmpInst::FCMP_OGT:
5621 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5623 case FCmpInst::FCMP_UGE:
5624 case FCmpInst::FCMP_OGE:
5625 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5627 case FCmpInst::FCMP_ULT:
5628 case FCmpInst::FCMP_OLT:
5629 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5631 case FCmpInst::FCMP_ULE:
5632 case FCmpInst::FCMP_OLE:
5633 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5635 case FCmpInst::FCMP_UNE:
5636 case FCmpInst::FCMP_ONE:
5637 Pred = ICmpInst::ICMP_NE;
5639 case FCmpInst::FCMP_ORD:
5640 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5641 case FCmpInst::FCMP_UNO:
5642 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5645 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5647 // Now we know that the APFloat is a normal number, zero or inf.
5649 // See if the FP constant is too large for the integer. For example,
5650 // comparing an i8 to 300.0.
5651 unsigned IntWidth = IntTy->getScalarSizeInBits();
5654 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5655 // and large values.
5656 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5657 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5658 APFloat::rmNearestTiesToEven);
5659 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5660 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5661 Pred == ICmpInst::ICMP_SLE)
5662 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5663 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5666 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5667 // +INF and large values.
5668 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5669 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5670 APFloat::rmNearestTiesToEven);
5671 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5672 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5673 Pred == ICmpInst::ICMP_ULE)
5674 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5675 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5680 // See if the RHS value is < SignedMin.
5681 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5682 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5683 APFloat::rmNearestTiesToEven);
5684 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5685 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5686 Pred == ICmpInst::ICMP_SGE)
5687 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5688 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5692 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5693 // [0, UMAX], but it may still be fractional. See if it is fractional by
5694 // casting the FP value to the integer value and back, checking for equality.
5695 // Don't do this for zero, because -0.0 is not fractional.
5696 Constant *RHSInt = LHSUnsigned
5697 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5698 : ConstantExpr::getFPToSI(RHSC, IntTy);
5699 if (!RHS.isZero()) {
5700 bool Equal = LHSUnsigned
5701 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5702 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5704 // If we had a comparison against a fractional value, we have to adjust
5705 // the compare predicate and sometimes the value. RHSC is rounded towards
5706 // zero at this point.
5708 default: llvm_unreachable("Unexpected integer comparison!");
5709 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5710 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5711 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5712 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5713 case ICmpInst::ICMP_ULE:
5714 // (float)int <= 4.4 --> int <= 4
5715 // (float)int <= -4.4 --> false
5716 if (RHS.isNegative())
5717 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5719 case ICmpInst::ICMP_SLE:
5720 // (float)int <= 4.4 --> int <= 4
5721 // (float)int <= -4.4 --> int < -4
5722 if (RHS.isNegative())
5723 Pred = ICmpInst::ICMP_SLT;
5725 case ICmpInst::ICMP_ULT:
5726 // (float)int < -4.4 --> false
5727 // (float)int < 4.4 --> int <= 4
5728 if (RHS.isNegative())
5729 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5730 Pred = ICmpInst::ICMP_ULE;
5732 case ICmpInst::ICMP_SLT:
5733 // (float)int < -4.4 --> int < -4
5734 // (float)int < 4.4 --> int <= 4
5735 if (!RHS.isNegative())
5736 Pred = ICmpInst::ICMP_SLE;
5738 case ICmpInst::ICMP_UGT:
5739 // (float)int > 4.4 --> int > 4
5740 // (float)int > -4.4 --> true
5741 if (RHS.isNegative())
5742 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5744 case ICmpInst::ICMP_SGT:
5745 // (float)int > 4.4 --> int > 4
5746 // (float)int > -4.4 --> int >= -4
5747 if (RHS.isNegative())
5748 Pred = ICmpInst::ICMP_SGE;
5750 case ICmpInst::ICMP_UGE:
5751 // (float)int >= -4.4 --> true
5752 // (float)int >= 4.4 --> int > 4
5753 if (!RHS.isNegative())
5754 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5755 Pred = ICmpInst::ICMP_UGT;
5757 case ICmpInst::ICMP_SGE:
5758 // (float)int >= -4.4 --> int >= -4
5759 // (float)int >= 4.4 --> int > 4
5760 if (!RHS.isNegative())
5761 Pred = ICmpInst::ICMP_SGT;
5767 // Lower this FP comparison into an appropriate integer version of the
5769 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5772 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5773 bool Changed = SimplifyCompare(I);
5774 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5776 // Fold trivial predicates.
5777 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5778 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5779 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5780 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5782 // Simplify 'fcmp pred X, X'
5784 switch (I.getPredicate()) {
5785 default: llvm_unreachable("Unknown predicate!");
5786 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5787 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5788 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5789 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5790 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5791 case FCmpInst::FCMP_OLT: // True if ordered and less than
5792 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5793 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5795 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5796 case FCmpInst::FCMP_ULT: // True if unordered or less than
5797 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5798 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5799 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5800 I.setPredicate(FCmpInst::FCMP_UNO);
5801 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5804 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5805 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5806 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5807 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5808 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5809 I.setPredicate(FCmpInst::FCMP_ORD);
5810 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5815 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5816 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
5818 // Handle fcmp with constant RHS
5819 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5820 // If the constant is a nan, see if we can fold the comparison based on it.
5821 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5822 if (CFP->getValueAPF().isNaN()) {
5823 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5824 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5825 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5826 "Comparison must be either ordered or unordered!");
5827 // True if unordered.
5828 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5832 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5833 switch (LHSI->getOpcode()) {
5834 case Instruction::PHI:
5835 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5836 // block. If in the same block, we're encouraging jump threading. If
5837 // not, we are just pessimizing the code by making an i1 phi.
5838 if (LHSI->getParent() == I.getParent())
5839 if (Instruction *NV = FoldOpIntoPhi(I))
5842 case Instruction::SIToFP:
5843 case Instruction::UIToFP:
5844 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5847 case Instruction::Select:
5848 // If either operand of the select is a constant, we can fold the
5849 // comparison into the select arms, which will cause one to be
5850 // constant folded and the select turned into a bitwise or.
5851 Value *Op1 = 0, *Op2 = 0;
5852 if (LHSI->hasOneUse()) {
5853 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5854 // Fold the known value into the constant operand.
5855 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5856 // Insert a new FCmp of the other select operand.
5857 Op2 = Builder->CreateFCmp(I.getPredicate(),
5858 LHSI->getOperand(2), RHSC, I.getName());
5859 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5860 // Fold the known value into the constant operand.
5861 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5862 // Insert a new FCmp of the other select operand.
5863 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5869 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5874 return Changed ? &I : 0;
5877 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5878 bool Changed = SimplifyCompare(I);
5879 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5880 const Type *Ty = Op0->getType();
5884 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
5885 I.isTrueWhenEqual()));
5887 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5888 return ReplaceInstUsesWith(I, UndefValue::get(Type::getInt1Ty(*Context)));
5890 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5891 // addresses never equal each other! We already know that Op0 != Op1.
5892 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5893 isa<ConstantPointerNull>(Op0)) &&
5894 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5895 isa<ConstantPointerNull>(Op1)))
5896 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
5897 !I.isTrueWhenEqual()));
5899 // icmp's with boolean values can always be turned into bitwise operations
5900 if (Ty == Type::getInt1Ty(*Context)) {
5901 switch (I.getPredicate()) {
5902 default: llvm_unreachable("Invalid icmp instruction!");
5903 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
5904 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
5905 return BinaryOperator::CreateNot(Xor);
5907 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
5908 return BinaryOperator::CreateXor(Op0, Op1);
5910 case ICmpInst::ICMP_UGT:
5911 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
5913 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
5914 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
5915 return BinaryOperator::CreateAnd(Not, Op1);
5917 case ICmpInst::ICMP_SGT:
5918 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
5920 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5921 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
5922 return BinaryOperator::CreateAnd(Not, Op0);
5924 case ICmpInst::ICMP_UGE:
5925 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5927 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
5928 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
5929 return BinaryOperator::CreateOr(Not, Op1);
5931 case ICmpInst::ICMP_SGE:
5932 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5934 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5935 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
5936 return BinaryOperator::CreateOr(Not, Op0);
5941 unsigned BitWidth = 0;
5943 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5944 else if (Ty->isIntOrIntVector())
5945 BitWidth = Ty->getScalarSizeInBits();
5947 bool isSignBit = false;
5949 // See if we are doing a comparison with a constant.
5950 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5951 Value *A = 0, *B = 0;
5953 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5954 if (I.isEquality() && CI->isNullValue() &&
5955 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5956 // (icmp cond A B) if cond is equality
5957 return new ICmpInst(I.getPredicate(), A, B);
5960 // If we have an icmp le or icmp ge instruction, turn it into the
5961 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5962 // them being folded in the code below.
5963 switch (I.getPredicate()) {
5965 case ICmpInst::ICMP_ULE:
5966 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5967 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5968 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
5970 case ICmpInst::ICMP_SLE:
5971 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5972 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5973 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5975 case ICmpInst::ICMP_UGE:
5976 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5977 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5978 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
5980 case ICmpInst::ICMP_SGE:
5981 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5982 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5983 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5987 // If this comparison is a normal comparison, it demands all
5988 // bits, if it is a sign bit comparison, it only demands the sign bit.
5990 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5993 // See if we can fold the comparison based on range information we can get
5994 // by checking whether bits are known to be zero or one in the input.
5995 if (BitWidth != 0) {
5996 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
5997 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
5999 if (SimplifyDemandedBits(I.getOperandUse(0),
6000 isSignBit ? APInt::getSignBit(BitWidth)
6001 : APInt::getAllOnesValue(BitWidth),
6002 Op0KnownZero, Op0KnownOne, 0))
6004 if (SimplifyDemandedBits(I.getOperandUse(1),
6005 APInt::getAllOnesValue(BitWidth),
6006 Op1KnownZero, Op1KnownOne, 0))
6009 // Given the known and unknown bits, compute a range that the LHS could be
6010 // in. Compute the Min, Max and RHS values based on the known bits. For the
6011 // EQ and NE we use unsigned values.
6012 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6013 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6014 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6015 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6017 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6020 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6022 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6026 // If Min and Max are known to be the same, then SimplifyDemandedBits
6027 // figured out that the LHS is a constant. Just constant fold this now so
6028 // that code below can assume that Min != Max.
6029 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6030 return new ICmpInst(I.getPredicate(),
6031 ConstantInt::get(*Context, Op0Min), Op1);
6032 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6033 return new ICmpInst(I.getPredicate(), Op0,
6034 ConstantInt::get(*Context, Op1Min));
6036 // Based on the range information we know about the LHS, see if we can
6037 // simplify this comparison. For example, (x&4) < 8 is always true.
6038 switch (I.getPredicate()) {
6039 default: llvm_unreachable("Unknown icmp opcode!");
6040 case ICmpInst::ICMP_EQ:
6041 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6042 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6044 case ICmpInst::ICMP_NE:
6045 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6046 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6048 case ICmpInst::ICMP_ULT:
6049 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
6050 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6051 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
6052 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6053 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
6054 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6055 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6056 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
6057 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6060 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6061 if (CI->isMinValue(true))
6062 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6063 Constant::getAllOnesValue(Op0->getType()));
6066 case ICmpInst::ICMP_UGT:
6067 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
6068 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6069 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
6070 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6072 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
6073 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6074 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6075 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
6076 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6079 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6080 if (CI->isMaxValue(true))
6081 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6082 Constant::getNullValue(Op0->getType()));
6085 case ICmpInst::ICMP_SLT:
6086 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
6087 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6088 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
6089 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6090 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
6091 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6092 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6093 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
6094 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6098 case ICmpInst::ICMP_SGT:
6099 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
6100 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6101 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
6102 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6104 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
6105 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6106 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6107 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
6108 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6112 case ICmpInst::ICMP_SGE:
6113 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6114 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
6115 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6116 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
6117 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6119 case ICmpInst::ICMP_SLE:
6120 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6121 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
6122 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6123 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
6124 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6126 case ICmpInst::ICMP_UGE:
6127 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6128 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
6129 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6130 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
6131 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6133 case ICmpInst::ICMP_ULE:
6134 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6135 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
6136 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6137 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
6138 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6142 // Turn a signed comparison into an unsigned one if both operands
6143 // are known to have the same sign.
6144 if (I.isSignedPredicate() &&
6145 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6146 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6147 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6150 // Test if the ICmpInst instruction is used exclusively by a select as
6151 // part of a minimum or maximum operation. If so, refrain from doing
6152 // any other folding. This helps out other analyses which understand
6153 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6154 // and CodeGen. And in this case, at least one of the comparison
6155 // operands has at least one user besides the compare (the select),
6156 // which would often largely negate the benefit of folding anyway.
6158 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6159 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6160 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6163 // See if we are doing a comparison between a constant and an instruction that
6164 // can be folded into the comparison.
6165 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6166 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6167 // instruction, see if that instruction also has constants so that the
6168 // instruction can be folded into the icmp
6169 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6170 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6174 // Handle icmp with constant (but not simple integer constant) RHS
6175 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6176 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6177 switch (LHSI->getOpcode()) {
6178 case Instruction::GetElementPtr:
6179 if (RHSC->isNullValue()) {
6180 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6181 bool isAllZeros = true;
6182 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6183 if (!isa<Constant>(LHSI->getOperand(i)) ||
6184 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6189 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6190 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6194 case Instruction::PHI:
6195 // Only fold icmp into the PHI if the phi and fcmp are in the same
6196 // block. If in the same block, we're encouraging jump threading. If
6197 // not, we are just pessimizing the code by making an i1 phi.
6198 if (LHSI->getParent() == I.getParent())
6199 if (Instruction *NV = FoldOpIntoPhi(I))
6202 case Instruction::Select: {
6203 // If either operand of the select is a constant, we can fold the
6204 // comparison into the select arms, which will cause one to be
6205 // constant folded and the select turned into a bitwise or.
6206 Value *Op1 = 0, *Op2 = 0;
6207 if (LHSI->hasOneUse()) {
6208 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6209 // Fold the known value into the constant operand.
6210 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6211 // Insert a new ICmp of the other select operand.
6212 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6214 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6215 // Fold the known value into the constant operand.
6216 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6217 // Insert a new ICmp of the other select operand.
6218 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6224 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6227 case Instruction::Malloc:
6228 // If we have (malloc != null), and if the malloc has a single use, we
6229 // can assume it is successful and remove the malloc.
6230 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6232 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
6233 !I.isTrueWhenEqual()));
6239 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6240 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6241 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6243 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6244 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6245 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6248 // Test to see if the operands of the icmp are casted versions of other
6249 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6251 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6252 if (isa<PointerType>(Op0->getType()) &&
6253 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6254 // We keep moving the cast from the left operand over to the right
6255 // operand, where it can often be eliminated completely.
6256 Op0 = CI->getOperand(0);
6258 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6259 // so eliminate it as well.
6260 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6261 Op1 = CI2->getOperand(0);
6263 // If Op1 is a constant, we can fold the cast into the constant.
6264 if (Op0->getType() != Op1->getType()) {
6265 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6266 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6268 // Otherwise, cast the RHS right before the icmp
6269 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6272 return new ICmpInst(I.getPredicate(), Op0, Op1);
6276 if (isa<CastInst>(Op0)) {
6277 // Handle the special case of: icmp (cast bool to X), <cst>
6278 // This comes up when you have code like
6281 // For generality, we handle any zero-extension of any operand comparison
6282 // with a constant or another cast from the same type.
6283 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6284 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6288 // See if it's the same type of instruction on the left and right.
6289 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6290 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6291 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6292 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6293 switch (Op0I->getOpcode()) {
6295 case Instruction::Add:
6296 case Instruction::Sub:
6297 case Instruction::Xor:
6298 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
6299 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6300 Op1I->getOperand(0));
6301 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6302 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6303 if (CI->getValue().isSignBit()) {
6304 ICmpInst::Predicate Pred = I.isSignedPredicate()
6305 ? I.getUnsignedPredicate()
6306 : I.getSignedPredicate();
6307 return new ICmpInst(Pred, Op0I->getOperand(0),
6308 Op1I->getOperand(0));
6311 if (CI->getValue().isMaxSignedValue()) {
6312 ICmpInst::Predicate Pred = I.isSignedPredicate()
6313 ? I.getUnsignedPredicate()
6314 : I.getSignedPredicate();
6315 Pred = I.getSwappedPredicate(Pred);
6316 return new ICmpInst(Pred, Op0I->getOperand(0),
6317 Op1I->getOperand(0));
6321 case Instruction::Mul:
6322 if (!I.isEquality())
6325 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6326 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6327 // Mask = -1 >> count-trailing-zeros(Cst).
6328 if (!CI->isZero() && !CI->isOne()) {
6329 const APInt &AP = CI->getValue();
6330 ConstantInt *Mask = ConstantInt::get(*Context,
6331 APInt::getLowBitsSet(AP.getBitWidth(),
6333 AP.countTrailingZeros()));
6334 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6335 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6336 return new ICmpInst(I.getPredicate(), And1, And2);
6345 // ~x < ~y --> y < x
6347 if (match(Op0, m_Not(m_Value(A))) &&
6348 match(Op1, m_Not(m_Value(B))))
6349 return new ICmpInst(I.getPredicate(), B, A);
6352 if (I.isEquality()) {
6353 Value *A, *B, *C, *D;
6355 // -x == -y --> x == y
6356 if (match(Op0, m_Neg(m_Value(A))) &&
6357 match(Op1, m_Neg(m_Value(B))))
6358 return new ICmpInst(I.getPredicate(), A, B);
6360 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6361 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6362 Value *OtherVal = A == Op1 ? B : A;
6363 return new ICmpInst(I.getPredicate(), OtherVal,
6364 Constant::getNullValue(A->getType()));
6367 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6368 // A^c1 == C^c2 --> A == C^(c1^c2)
6369 ConstantInt *C1, *C2;
6370 if (match(B, m_ConstantInt(C1)) &&
6371 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6373 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6374 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6375 return new ICmpInst(I.getPredicate(), A, Xor);
6378 // A^B == A^D -> B == D
6379 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6380 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6381 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6382 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6386 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6387 (A == Op0 || B == Op0)) {
6388 // A == (A^B) -> B == 0
6389 Value *OtherVal = A == Op0 ? B : A;
6390 return new ICmpInst(I.getPredicate(), OtherVal,
6391 Constant::getNullValue(A->getType()));
6394 // (A-B) == A -> B == 0
6395 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6396 return new ICmpInst(I.getPredicate(), B,
6397 Constant::getNullValue(B->getType()));
6399 // A == (A-B) -> B == 0
6400 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6401 return new ICmpInst(I.getPredicate(), B,
6402 Constant::getNullValue(B->getType()));
6404 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6405 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6406 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6407 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6408 Value *X = 0, *Y = 0, *Z = 0;
6411 X = B; Y = D; Z = A;
6412 } else if (A == D) {
6413 X = B; Y = C; Z = A;
6414 } else if (B == C) {
6415 X = A; Y = D; Z = B;
6416 } else if (B == D) {
6417 X = A; Y = C; Z = B;
6420 if (X) { // Build (X^Y) & Z
6421 Op1 = Builder->CreateXor(X, Y, "tmp");
6422 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6423 I.setOperand(0, Op1);
6424 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6429 return Changed ? &I : 0;
6433 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6434 /// and CmpRHS are both known to be integer constants.
6435 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6436 ConstantInt *DivRHS) {
6437 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6438 const APInt &CmpRHSV = CmpRHS->getValue();
6440 // FIXME: If the operand types don't match the type of the divide
6441 // then don't attempt this transform. The code below doesn't have the
6442 // logic to deal with a signed divide and an unsigned compare (and
6443 // vice versa). This is because (x /s C1) <s C2 produces different
6444 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6445 // (x /u C1) <u C2. Simply casting the operands and result won't
6446 // work. :( The if statement below tests that condition and bails
6448 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6449 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6451 if (DivRHS->isZero())
6452 return 0; // The ProdOV computation fails on divide by zero.
6453 if (DivIsSigned && DivRHS->isAllOnesValue())
6454 return 0; // The overflow computation also screws up here
6455 if (DivRHS->isOne())
6456 return 0; // Not worth bothering, and eliminates some funny cases
6459 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6460 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6461 // C2 (CI). By solving for X we can turn this into a range check
6462 // instead of computing a divide.
6463 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6465 // Determine if the product overflows by seeing if the product is
6466 // not equal to the divide. Make sure we do the same kind of divide
6467 // as in the LHS instruction that we're folding.
6468 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6469 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6471 // Get the ICmp opcode
6472 ICmpInst::Predicate Pred = ICI.getPredicate();
6474 // Figure out the interval that is being checked. For example, a comparison
6475 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6476 // Compute this interval based on the constants involved and the signedness of
6477 // the compare/divide. This computes a half-open interval, keeping track of
6478 // whether either value in the interval overflows. After analysis each
6479 // overflow variable is set to 0 if it's corresponding bound variable is valid
6480 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6481 int LoOverflow = 0, HiOverflow = 0;
6482 Constant *LoBound = 0, *HiBound = 0;
6484 if (!DivIsSigned) { // udiv
6485 // e.g. X/5 op 3 --> [15, 20)
6487 HiOverflow = LoOverflow = ProdOV;
6489 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6490 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6491 if (CmpRHSV == 0) { // (X / pos) op 0
6492 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
6493 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6495 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
6496 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6497 HiOverflow = LoOverflow = ProdOV;
6499 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6500 } else { // (X / pos) op neg
6501 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
6502 HiBound = AddOne(Prod);
6503 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6505 ConstantInt* DivNeg =
6506 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6507 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6511 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6512 if (CmpRHSV == 0) { // (X / neg) op 0
6513 // e.g. X/-5 op 0 --> [-4, 5)
6514 LoBound = AddOne(DivRHS);
6515 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6516 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6517 HiOverflow = 1; // [INTMIN+1, overflow)
6518 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6520 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
6521 // e.g. X/-5 op 3 --> [-19, -14)
6522 HiBound = AddOne(Prod);
6523 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6525 LoOverflow = AddWithOverflow(LoBound, HiBound,
6526 DivRHS, Context, true) ? -1 : 0;
6527 } else { // (X / neg) op neg
6528 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6529 LoOverflow = HiOverflow = ProdOV;
6531 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6534 // Dividing by a negative swaps the condition. LT <-> GT
6535 Pred = ICmpInst::getSwappedPredicate(Pred);
6538 Value *X = DivI->getOperand(0);
6540 default: llvm_unreachable("Unhandled icmp opcode!");
6541 case ICmpInst::ICMP_EQ:
6542 if (LoOverflow && HiOverflow)
6543 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6544 else if (HiOverflow)
6545 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6546 ICmpInst::ICMP_UGE, X, LoBound);
6547 else if (LoOverflow)
6548 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6549 ICmpInst::ICMP_ULT, X, HiBound);
6551 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6552 case ICmpInst::ICMP_NE:
6553 if (LoOverflow && HiOverflow)
6554 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6555 else if (HiOverflow)
6556 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6557 ICmpInst::ICMP_ULT, X, LoBound);
6558 else if (LoOverflow)
6559 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6560 ICmpInst::ICMP_UGE, X, HiBound);
6562 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6563 case ICmpInst::ICMP_ULT:
6564 case ICmpInst::ICMP_SLT:
6565 if (LoOverflow == +1) // Low bound is greater than input range.
6566 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6567 if (LoOverflow == -1) // Low bound is less than input range.
6568 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6569 return new ICmpInst(Pred, X, LoBound);
6570 case ICmpInst::ICMP_UGT:
6571 case ICmpInst::ICMP_SGT:
6572 if (HiOverflow == +1) // High bound greater than input range.
6573 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6574 else if (HiOverflow == -1) // High bound less than input range.
6575 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6576 if (Pred == ICmpInst::ICMP_UGT)
6577 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6579 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6584 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6586 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6589 const APInt &RHSV = RHS->getValue();
6591 switch (LHSI->getOpcode()) {
6592 case Instruction::Trunc:
6593 if (ICI.isEquality() && LHSI->hasOneUse()) {
6594 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6595 // of the high bits truncated out of x are known.
6596 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6597 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6598 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6599 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6600 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6602 // If all the high bits are known, we can do this xform.
6603 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6604 // Pull in the high bits from known-ones set.
6605 APInt NewRHS(RHS->getValue());
6606 NewRHS.zext(SrcBits);
6608 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6609 ConstantInt::get(*Context, NewRHS));
6614 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6615 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6616 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6618 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6619 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6620 Value *CompareVal = LHSI->getOperand(0);
6622 // If the sign bit of the XorCST is not set, there is no change to
6623 // the operation, just stop using the Xor.
6624 if (!XorCST->getValue().isNegative()) {
6625 ICI.setOperand(0, CompareVal);
6630 // Was the old condition true if the operand is positive?
6631 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6633 // If so, the new one isn't.
6634 isTrueIfPositive ^= true;
6636 if (isTrueIfPositive)
6637 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6640 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6644 if (LHSI->hasOneUse()) {
6645 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6646 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6647 const APInt &SignBit = XorCST->getValue();
6648 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6649 ? ICI.getUnsignedPredicate()
6650 : ICI.getSignedPredicate();
6651 return new ICmpInst(Pred, LHSI->getOperand(0),
6652 ConstantInt::get(*Context, RHSV ^ SignBit));
6655 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6656 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6657 const APInt &NotSignBit = XorCST->getValue();
6658 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6659 ? ICI.getUnsignedPredicate()
6660 : ICI.getSignedPredicate();
6661 Pred = ICI.getSwappedPredicate(Pred);
6662 return new ICmpInst(Pred, LHSI->getOperand(0),
6663 ConstantInt::get(*Context, RHSV ^ NotSignBit));
6668 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6669 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6670 LHSI->getOperand(0)->hasOneUse()) {
6671 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6673 // If the LHS is an AND of a truncating cast, we can widen the
6674 // and/compare to be the input width without changing the value
6675 // produced, eliminating a cast.
6676 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6677 // We can do this transformation if either the AND constant does not
6678 // have its sign bit set or if it is an equality comparison.
6679 // Extending a relational comparison when we're checking the sign
6680 // bit would not work.
6681 if (Cast->hasOneUse() &&
6682 (ICI.isEquality() ||
6683 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6685 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6686 APInt NewCST = AndCST->getValue();
6687 NewCST.zext(BitWidth);
6689 NewCI.zext(BitWidth);
6691 Builder->CreateAnd(Cast->getOperand(0),
6692 ConstantInt::get(*Context, NewCST), LHSI->getName());
6693 return new ICmpInst(ICI.getPredicate(), NewAnd,
6694 ConstantInt::get(*Context, NewCI));
6698 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6699 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6700 // happens a LOT in code produced by the C front-end, for bitfield
6702 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6703 if (Shift && !Shift->isShift())
6707 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6708 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6709 const Type *AndTy = AndCST->getType(); // Type of the and.
6711 // We can fold this as long as we can't shift unknown bits
6712 // into the mask. This can only happen with signed shift
6713 // rights, as they sign-extend.
6715 bool CanFold = Shift->isLogicalShift();
6717 // To test for the bad case of the signed shr, see if any
6718 // of the bits shifted in could be tested after the mask.
6719 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6720 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6722 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6723 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6724 AndCST->getValue()) == 0)
6730 if (Shift->getOpcode() == Instruction::Shl)
6731 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6733 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6735 // Check to see if we are shifting out any of the bits being
6737 if (ConstantExpr::get(Shift->getOpcode(),
6738 NewCst, ShAmt) != RHS) {
6739 // If we shifted bits out, the fold is not going to work out.
6740 // As a special case, check to see if this means that the
6741 // result is always true or false now.
6742 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6743 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6744 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6745 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6747 ICI.setOperand(1, NewCst);
6748 Constant *NewAndCST;
6749 if (Shift->getOpcode() == Instruction::Shl)
6750 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6752 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6753 LHSI->setOperand(1, NewAndCST);
6754 LHSI->setOperand(0, Shift->getOperand(0));
6755 Worklist.Add(Shift); // Shift is dead.
6761 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6762 // preferable because it allows the C<<Y expression to be hoisted out
6763 // of a loop if Y is invariant and X is not.
6764 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6765 ICI.isEquality() && !Shift->isArithmeticShift() &&
6766 !isa<Constant>(Shift->getOperand(0))) {
6769 if (Shift->getOpcode() == Instruction::LShr) {
6770 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
6772 // Insert a logical shift.
6773 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
6776 // Compute X & (C << Y).
6778 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6780 ICI.setOperand(0, NewAnd);
6786 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6787 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6790 uint32_t TypeBits = RHSV.getBitWidth();
6792 // Check that the shift amount is in range. If not, don't perform
6793 // undefined shifts. When the shift is visited it will be
6795 if (ShAmt->uge(TypeBits))
6798 if (ICI.isEquality()) {
6799 // If we are comparing against bits always shifted out, the
6800 // comparison cannot succeed.
6802 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6804 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6805 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6806 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6807 return ReplaceInstUsesWith(ICI, Cst);
6810 if (LHSI->hasOneUse()) {
6811 // Otherwise strength reduce the shift into an and.
6812 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6814 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
6815 TypeBits-ShAmtVal));
6818 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
6819 return new ICmpInst(ICI.getPredicate(), And,
6820 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6824 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6825 bool TrueIfSigned = false;
6826 if (LHSI->hasOneUse() &&
6827 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6828 // (X << 31) <s 0 --> (X&1) != 0
6829 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6830 (TypeBits-ShAmt->getZExtValue()-1));
6832 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
6833 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6834 And, Constant::getNullValue(And->getType()));
6839 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6840 case Instruction::AShr: {
6841 // Only handle equality comparisons of shift-by-constant.
6842 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6843 if (!ShAmt || !ICI.isEquality()) break;
6845 // Check that the shift amount is in range. If not, don't perform
6846 // undefined shifts. When the shift is visited it will be
6848 uint32_t TypeBits = RHSV.getBitWidth();
6849 if (ShAmt->uge(TypeBits))
6852 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6854 // If we are comparing against bits always shifted out, the
6855 // comparison cannot succeed.
6856 APInt Comp = RHSV << ShAmtVal;
6857 if (LHSI->getOpcode() == Instruction::LShr)
6858 Comp = Comp.lshr(ShAmtVal);
6860 Comp = Comp.ashr(ShAmtVal);
6862 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6863 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6864 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6865 return ReplaceInstUsesWith(ICI, Cst);
6868 // Otherwise, check to see if the bits shifted out are known to be zero.
6869 // If so, we can compare against the unshifted value:
6870 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
6871 if (LHSI->hasOneUse() &&
6872 MaskedValueIsZero(LHSI->getOperand(0),
6873 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6874 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6875 ConstantExpr::getShl(RHS, ShAmt));
6878 if (LHSI->hasOneUse()) {
6879 // Otherwise strength reduce the shift into an and.
6880 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6881 Constant *Mask = ConstantInt::get(*Context, Val);
6883 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6884 Mask, LHSI->getName()+".mask");
6885 return new ICmpInst(ICI.getPredicate(), And,
6886 ConstantExpr::getShl(RHS, ShAmt));
6891 case Instruction::SDiv:
6892 case Instruction::UDiv:
6893 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6894 // Fold this div into the comparison, producing a range check.
6895 // Determine, based on the divide type, what the range is being
6896 // checked. If there is an overflow on the low or high side, remember
6897 // it, otherwise compute the range [low, hi) bounding the new value.
6898 // See: InsertRangeTest above for the kinds of replacements possible.
6899 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6900 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6905 case Instruction::Add:
6906 // Fold: icmp pred (add, X, C1), C2
6908 if (!ICI.isEquality()) {
6909 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6911 const APInt &LHSV = LHSC->getValue();
6913 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6916 if (ICI.isSignedPredicate()) {
6917 if (CR.getLower().isSignBit()) {
6918 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6919 ConstantInt::get(*Context, CR.getUpper()));
6920 } else if (CR.getUpper().isSignBit()) {
6921 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6922 ConstantInt::get(*Context, CR.getLower()));
6925 if (CR.getLower().isMinValue()) {
6926 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6927 ConstantInt::get(*Context, CR.getUpper()));
6928 } else if (CR.getUpper().isMinValue()) {
6929 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6930 ConstantInt::get(*Context, CR.getLower()));
6937 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6938 if (ICI.isEquality()) {
6939 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6941 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6942 // the second operand is a constant, simplify a bit.
6943 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6944 switch (BO->getOpcode()) {
6945 case Instruction::SRem:
6946 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6947 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6948 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6949 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6951 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
6953 return new ICmpInst(ICI.getPredicate(), NewRem,
6954 Constant::getNullValue(BO->getType()));
6958 case Instruction::Add:
6959 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6960 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6961 if (BO->hasOneUse())
6962 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6963 ConstantExpr::getSub(RHS, BOp1C));
6964 } else if (RHSV == 0) {
6965 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6966 // efficiently invertible, or if the add has just this one use.
6967 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6969 if (Value *NegVal = dyn_castNegVal(BOp1))
6970 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6971 else if (Value *NegVal = dyn_castNegVal(BOp0))
6972 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6973 else if (BO->hasOneUse()) {
6974 Value *Neg = Builder->CreateNeg(BOp1);
6976 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6980 case Instruction::Xor:
6981 // For the xor case, we can xor two constants together, eliminating
6982 // the explicit xor.
6983 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6984 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6985 ConstantExpr::getXor(RHS, BOC));
6988 case Instruction::Sub:
6989 // Replace (([sub|xor] A, B) != 0) with (A != B)
6991 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6995 case Instruction::Or:
6996 // If bits are being or'd in that are not present in the constant we
6997 // are comparing against, then the comparison could never succeed!
6998 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6999 Constant *NotCI = ConstantExpr::getNot(RHS);
7000 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7001 return ReplaceInstUsesWith(ICI,
7002 ConstantInt::get(Type::getInt1Ty(*Context),
7007 case Instruction::And:
7008 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7009 // If bits are being compared against that are and'd out, then the
7010 // comparison can never succeed!
7011 if ((RHSV & ~BOC->getValue()) != 0)
7012 return ReplaceInstUsesWith(ICI,
7013 ConstantInt::get(Type::getInt1Ty(*Context),
7016 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7017 if (RHS == BOC && RHSV.isPowerOf2())
7018 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7019 ICmpInst::ICMP_NE, LHSI,
7020 Constant::getNullValue(RHS->getType()));
7022 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7023 if (BOC->getValue().isSignBit()) {
7024 Value *X = BO->getOperand(0);
7025 Constant *Zero = Constant::getNullValue(X->getType());
7026 ICmpInst::Predicate pred = isICMP_NE ?
7027 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7028 return new ICmpInst(pred, X, Zero);
7031 // ((X & ~7) == 0) --> X < 8
7032 if (RHSV == 0 && isHighOnes(BOC)) {
7033 Value *X = BO->getOperand(0);
7034 Constant *NegX = ConstantExpr::getNeg(BOC);
7035 ICmpInst::Predicate pred = isICMP_NE ?
7036 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7037 return new ICmpInst(pred, X, NegX);
7042 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7043 // Handle icmp {eq|ne} <intrinsic>, intcst.
7044 if (II->getIntrinsicID() == Intrinsic::bswap) {
7046 ICI.setOperand(0, II->getOperand(1));
7047 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7055 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7056 /// We only handle extending casts so far.
7058 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7059 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7060 Value *LHSCIOp = LHSCI->getOperand(0);
7061 const Type *SrcTy = LHSCIOp->getType();
7062 const Type *DestTy = LHSCI->getType();
7065 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7066 // integer type is the same size as the pointer type.
7067 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7068 TD->getPointerSizeInBits() ==
7069 cast<IntegerType>(DestTy)->getBitWidth()) {
7071 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7072 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7073 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7074 RHSOp = RHSC->getOperand(0);
7075 // If the pointer types don't match, insert a bitcast.
7076 if (LHSCIOp->getType() != RHSOp->getType())
7077 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7081 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7084 // The code below only handles extension cast instructions, so far.
7086 if (LHSCI->getOpcode() != Instruction::ZExt &&
7087 LHSCI->getOpcode() != Instruction::SExt)
7090 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7091 bool isSignedCmp = ICI.isSignedPredicate();
7093 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7094 // Not an extension from the same type?
7095 RHSCIOp = CI->getOperand(0);
7096 if (RHSCIOp->getType() != LHSCIOp->getType())
7099 // If the signedness of the two casts doesn't agree (i.e. one is a sext
7100 // and the other is a zext), then we can't handle this.
7101 if (CI->getOpcode() != LHSCI->getOpcode())
7104 // Deal with equality cases early.
7105 if (ICI.isEquality())
7106 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7108 // A signed comparison of sign extended values simplifies into a
7109 // signed comparison.
7110 if (isSignedCmp && isSignedExt)
7111 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7113 // The other three cases all fold into an unsigned comparison.
7114 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7117 // If we aren't dealing with a constant on the RHS, exit early
7118 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7122 // Compute the constant that would happen if we truncated to SrcTy then
7123 // reextended to DestTy.
7124 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7125 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7128 // If the re-extended constant didn't change...
7130 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7131 // For example, we might have:
7132 // %A = sext i16 %X to i32
7133 // %B = icmp ugt i32 %A, 1330
7134 // It is incorrect to transform this into
7135 // %B = icmp ugt i16 %X, 1330
7136 // because %A may have negative value.
7138 // However, we allow this when the compare is EQ/NE, because they are
7140 if (isSignedExt == isSignedCmp || ICI.isEquality())
7141 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7145 // The re-extended constant changed so the constant cannot be represented
7146 // in the shorter type. Consequently, we cannot emit a simple comparison.
7148 // First, handle some easy cases. We know the result cannot be equal at this
7149 // point so handle the ICI.isEquality() cases
7150 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7151 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7152 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7153 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7155 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7156 // should have been folded away previously and not enter in here.
7159 // We're performing a signed comparison.
7160 if (cast<ConstantInt>(CI)->getValue().isNegative())
7161 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
7163 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
7165 // We're performing an unsigned comparison.
7167 // We're performing an unsigned comp with a sign extended value.
7168 // This is true if the input is >= 0. [aka >s -1]
7169 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7170 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7172 // Unsigned extend & unsigned compare -> always true.
7173 Result = ConstantInt::getTrue(*Context);
7177 // Finally, return the value computed.
7178 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7179 ICI.getPredicate() == ICmpInst::ICMP_SLT)
7180 return ReplaceInstUsesWith(ICI, Result);
7182 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7183 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7184 "ICmp should be folded!");
7185 if (Constant *CI = dyn_cast<Constant>(Result))
7186 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7187 return BinaryOperator::CreateNot(Result);
7190 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7191 return commonShiftTransforms(I);
7194 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7195 return commonShiftTransforms(I);
7198 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7199 if (Instruction *R = commonShiftTransforms(I))
7202 Value *Op0 = I.getOperand(0);
7204 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7205 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7206 if (CSI->isAllOnesValue())
7207 return ReplaceInstUsesWith(I, CSI);
7209 // See if we can turn a signed shr into an unsigned shr.
7210 if (MaskedValueIsZero(Op0,
7211 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7212 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7214 // Arithmetic shifting an all-sign-bit value is a no-op.
7215 unsigned NumSignBits = ComputeNumSignBits(Op0);
7216 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7217 return ReplaceInstUsesWith(I, Op0);
7222 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7223 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7224 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7226 // shl X, 0 == X and shr X, 0 == X
7227 // shl 0, X == 0 and shr 0, X == 0
7228 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7229 Op0 == Constant::getNullValue(Op0->getType()))
7230 return ReplaceInstUsesWith(I, Op0);
7232 if (isa<UndefValue>(Op0)) {
7233 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7234 return ReplaceInstUsesWith(I, Op0);
7235 else // undef << X -> 0, undef >>u X -> 0
7236 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7238 if (isa<UndefValue>(Op1)) {
7239 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7240 return ReplaceInstUsesWith(I, Op0);
7241 else // X << undef, X >>u undef -> 0
7242 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7245 // See if we can fold away this shift.
7246 if (SimplifyDemandedInstructionBits(I))
7249 // Try to fold constant and into select arguments.
7250 if (isa<Constant>(Op0))
7251 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7252 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7255 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7256 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7261 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7262 BinaryOperator &I) {
7263 bool isLeftShift = I.getOpcode() == Instruction::Shl;
7265 // See if we can simplify any instructions used by the instruction whose sole
7266 // purpose is to compute bits we don't care about.
7267 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7269 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7272 if (Op1->uge(TypeBits)) {
7273 if (I.getOpcode() != Instruction::AShr)
7274 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7276 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7281 // ((X*C1) << C2) == (X * (C1 << C2))
7282 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7283 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7284 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7285 return BinaryOperator::CreateMul(BO->getOperand(0),
7286 ConstantExpr::getShl(BOOp, Op1));
7288 // Try to fold constant and into select arguments.
7289 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7290 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7292 if (isa<PHINode>(Op0))
7293 if (Instruction *NV = FoldOpIntoPhi(I))
7296 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7297 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7298 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7299 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7300 // place. Don't try to do this transformation in this case. Also, we
7301 // require that the input operand is a shift-by-constant so that we have
7302 // confidence that the shifts will get folded together. We could do this
7303 // xform in more cases, but it is unlikely to be profitable.
7304 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7305 isa<ConstantInt>(TrOp->getOperand(1))) {
7306 // Okay, we'll do this xform. Make the shift of shift.
7307 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7308 // (shift2 (shift1 & 0x00FF), c2)
7309 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7311 // For logical shifts, the truncation has the effect of making the high
7312 // part of the register be zeros. Emulate this by inserting an AND to
7313 // clear the top bits as needed. This 'and' will usually be zapped by
7314 // other xforms later if dead.
7315 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7316 unsigned DstSize = TI->getType()->getScalarSizeInBits();
7317 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7319 // The mask we constructed says what the trunc would do if occurring
7320 // between the shifts. We want to know the effect *after* the second
7321 // shift. We know that it is a logical shift by a constant, so adjust the
7322 // mask as appropriate.
7323 if (I.getOpcode() == Instruction::Shl)
7324 MaskV <<= Op1->getZExtValue();
7326 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7327 MaskV = MaskV.lshr(Op1->getZExtValue());
7331 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7334 // Return the value truncated to the interesting size.
7335 return new TruncInst(And, I.getType());
7339 if (Op0->hasOneUse()) {
7340 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7341 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7344 switch (Op0BO->getOpcode()) {
7346 case Instruction::Add:
7347 case Instruction::And:
7348 case Instruction::Or:
7349 case Instruction::Xor: {
7350 // These operators commute.
7351 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7352 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7353 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7354 m_Specific(Op1)))) {
7355 Value *YS = // (Y << C)
7356 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7358 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7359 Op0BO->getOperand(1)->getName());
7360 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7361 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7362 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7365 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7366 Value *Op0BOOp1 = Op0BO->getOperand(1);
7367 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7369 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7370 m_ConstantInt(CC))) &&
7371 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7372 Value *YS = // (Y << C)
7373 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7376 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7377 V1->getName()+".mask");
7378 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7383 case Instruction::Sub: {
7384 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7385 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7386 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7387 m_Specific(Op1)))) {
7388 Value *YS = // (Y << C)
7389 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7391 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7392 Op0BO->getOperand(0)->getName());
7393 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7394 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7395 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7398 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7399 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7400 match(Op0BO->getOperand(0),
7401 m_And(m_Shr(m_Value(V1), m_Value(V2)),
7402 m_ConstantInt(CC))) && V2 == Op1 &&
7403 cast<BinaryOperator>(Op0BO->getOperand(0))
7404 ->getOperand(0)->hasOneUse()) {
7405 Value *YS = // (Y << C)
7406 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7408 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7409 V1->getName()+".mask");
7411 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7419 // If the operand is an bitwise operator with a constant RHS, and the
7420 // shift is the only use, we can pull it out of the shift.
7421 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7422 bool isValid = true; // Valid only for And, Or, Xor
7423 bool highBitSet = false; // Transform if high bit of constant set?
7425 switch (Op0BO->getOpcode()) {
7426 default: isValid = false; break; // Do not perform transform!
7427 case Instruction::Add:
7428 isValid = isLeftShift;
7430 case Instruction::Or:
7431 case Instruction::Xor:
7434 case Instruction::And:
7439 // If this is a signed shift right, and the high bit is modified
7440 // by the logical operation, do not perform the transformation.
7441 // The highBitSet boolean indicates the value of the high bit of
7442 // the constant which would cause it to be modified for this
7445 if (isValid && I.getOpcode() == Instruction::AShr)
7446 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7449 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7452 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
7453 NewShift->takeName(Op0BO);
7455 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7462 // Find out if this is a shift of a shift by a constant.
7463 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7464 if (ShiftOp && !ShiftOp->isShift())
7467 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7468 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7469 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7470 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7471 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7472 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7473 Value *X = ShiftOp->getOperand(0);
7475 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
7477 const IntegerType *Ty = cast<IntegerType>(I.getType());
7479 // Check for (X << c1) << c2 and (X >> c1) >> c2
7480 if (I.getOpcode() == ShiftOp->getOpcode()) {
7481 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7483 if (AmtSum >= TypeBits) {
7484 if (I.getOpcode() != Instruction::AShr)
7485 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7486 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7489 return BinaryOperator::Create(I.getOpcode(), X,
7490 ConstantInt::get(Ty, AmtSum));
7493 if (ShiftOp->getOpcode() == Instruction::LShr &&
7494 I.getOpcode() == Instruction::AShr) {
7495 if (AmtSum >= TypeBits)
7496 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7498 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
7499 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7502 if (ShiftOp->getOpcode() == Instruction::AShr &&
7503 I.getOpcode() == Instruction::LShr) {
7504 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7505 if (AmtSum >= TypeBits)
7506 AmtSum = TypeBits-1;
7508 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7510 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7511 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7514 // Okay, if we get here, one shift must be left, and the other shift must be
7515 // right. See if the amounts are equal.
7516 if (ShiftAmt1 == ShiftAmt2) {
7517 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7518 if (I.getOpcode() == Instruction::Shl) {
7519 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7520 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7522 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7523 if (I.getOpcode() == Instruction::LShr) {
7524 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7525 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7527 // We can simplify ((X << C) >>s C) into a trunc + sext.
7528 // NOTE: we could do this for any C, but that would make 'unusual' integer
7529 // types. For now, just stick to ones well-supported by the code
7531 const Type *SExtType = 0;
7532 switch (Ty->getBitWidth() - ShiftAmt1) {
7539 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7544 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
7545 // Otherwise, we can't handle it yet.
7546 } else if (ShiftAmt1 < ShiftAmt2) {
7547 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7549 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7550 if (I.getOpcode() == Instruction::Shl) {
7551 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7552 ShiftOp->getOpcode() == Instruction::AShr);
7553 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7555 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7556 return BinaryOperator::CreateAnd(Shift,
7557 ConstantInt::get(*Context, Mask));
7560 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7561 if (I.getOpcode() == Instruction::LShr) {
7562 assert(ShiftOp->getOpcode() == Instruction::Shl);
7563 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7565 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7566 return BinaryOperator::CreateAnd(Shift,
7567 ConstantInt::get(*Context, Mask));
7570 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7572 assert(ShiftAmt2 < ShiftAmt1);
7573 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7575 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7576 if (I.getOpcode() == Instruction::Shl) {
7577 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7578 ShiftOp->getOpcode() == Instruction::AShr);
7579 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7580 ConstantInt::get(Ty, ShiftDiff));
7582 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7583 return BinaryOperator::CreateAnd(Shift,
7584 ConstantInt::get(*Context, Mask));
7587 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7588 if (I.getOpcode() == Instruction::LShr) {
7589 assert(ShiftOp->getOpcode() == Instruction::Shl);
7590 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7592 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7593 return BinaryOperator::CreateAnd(Shift,
7594 ConstantInt::get(*Context, Mask));
7597 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7604 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7605 /// expression. If so, decompose it, returning some value X, such that Val is
7608 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7609 int &Offset, LLVMContext *Context) {
7610 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7611 "Unexpected allocation size type!");
7612 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7613 Offset = CI->getZExtValue();
7615 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7616 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7617 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7618 if (I->getOpcode() == Instruction::Shl) {
7619 // This is a value scaled by '1 << the shift amt'.
7620 Scale = 1U << RHS->getZExtValue();
7622 return I->getOperand(0);
7623 } else if (I->getOpcode() == Instruction::Mul) {
7624 // This value is scaled by 'RHS'.
7625 Scale = RHS->getZExtValue();
7627 return I->getOperand(0);
7628 } else if (I->getOpcode() == Instruction::Add) {
7629 // We have X+C. Check to see if we really have (X*C2)+C1,
7630 // where C1 is divisible by C2.
7633 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7635 Offset += RHS->getZExtValue();
7642 // Otherwise, we can't look past this.
7649 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7650 /// try to eliminate the cast by moving the type information into the alloc.
7651 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7652 AllocationInst &AI) {
7653 const PointerType *PTy = cast<PointerType>(CI.getType());
7655 BuilderTy AllocaBuilder(*Builder);
7656 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7658 // Remove any uses of AI that are dead.
7659 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7661 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7662 Instruction *User = cast<Instruction>(*UI++);
7663 if (isInstructionTriviallyDead(User)) {
7664 while (UI != E && *UI == User)
7665 ++UI; // If this instruction uses AI more than once, don't break UI.
7668 DEBUG(errs() << "IC: DCE: " << *User << '\n');
7669 EraseInstFromFunction(*User);
7673 // This requires TargetData to get the alloca alignment and size information.
7676 // Get the type really allocated and the type casted to.
7677 const Type *AllocElTy = AI.getAllocatedType();
7678 const Type *CastElTy = PTy->getElementType();
7679 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7681 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7682 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7683 if (CastElTyAlign < AllocElTyAlign) return 0;
7685 // If the allocation has multiple uses, only promote it if we are strictly
7686 // increasing the alignment of the resultant allocation. If we keep it the
7687 // same, we open the door to infinite loops of various kinds. (A reference
7688 // from a dbg.declare doesn't count as a use for this purpose.)
7689 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7690 CastElTyAlign == AllocElTyAlign) return 0;
7692 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7693 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7694 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7696 // See if we can satisfy the modulus by pulling a scale out of the array
7698 unsigned ArraySizeScale;
7700 Value *NumElements = // See if the array size is a decomposable linear expr.
7701 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7702 ArrayOffset, Context);
7704 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7706 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7707 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7709 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7714 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7715 // Insert before the alloca, not before the cast.
7716 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
7719 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7720 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7721 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
7724 AllocationInst *New;
7725 if (isa<MallocInst>(AI))
7726 New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
7728 New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7729 New->setAlignment(AI.getAlignment());
7732 // If the allocation has one real use plus a dbg.declare, just remove the
7734 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7735 EraseInstFromFunction(*DI);
7737 // If the allocation has multiple real uses, insert a cast and change all
7738 // things that used it to use the new cast. This will also hack on CI, but it
7740 else if (!AI.hasOneUse()) {
7741 // New is the allocation instruction, pointer typed. AI is the original
7742 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7743 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
7744 AI.replaceAllUsesWith(NewCast);
7746 return ReplaceInstUsesWith(CI, New);
7749 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7750 /// and return it as type Ty without inserting any new casts and without
7751 /// changing the computed value. This is used by code that tries to decide
7752 /// whether promoting or shrinking integer operations to wider or smaller types
7753 /// will allow us to eliminate a truncate or extend.
7755 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7756 /// extension operation if Ty is larger.
7758 /// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7759 /// should return true if trunc(V) can be computed by computing V in the smaller
7760 /// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7761 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7762 /// efficiently truncated.
7764 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7765 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7766 /// the final result.
7767 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7769 int &NumCastsRemoved){
7770 // We can always evaluate constants in another type.
7771 if (isa<Constant>(V))
7774 Instruction *I = dyn_cast<Instruction>(V);
7775 if (!I) return false;
7777 const Type *OrigTy = V->getType();
7779 // If this is an extension or truncate, we can often eliminate it.
7780 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7781 // If this is a cast from the destination type, we can trivially eliminate
7782 // it, and this will remove a cast overall.
7783 if (I->getOperand(0)->getType() == Ty) {
7784 // If the first operand is itself a cast, and is eliminable, do not count
7785 // this as an eliminable cast. We would prefer to eliminate those two
7787 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7793 // We can't extend or shrink something that has multiple uses: doing so would
7794 // require duplicating the instruction in general, which isn't profitable.
7795 if (!I->hasOneUse()) return false;
7797 unsigned Opc = I->getOpcode();
7799 case Instruction::Add:
7800 case Instruction::Sub:
7801 case Instruction::Mul:
7802 case Instruction::And:
7803 case Instruction::Or:
7804 case Instruction::Xor:
7805 // These operators can all arbitrarily be extended or truncated.
7806 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7808 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7811 case Instruction::UDiv:
7812 case Instruction::URem: {
7813 // UDiv and URem can be truncated if all the truncated bits are zero.
7814 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7815 uint32_t BitWidth = Ty->getScalarSizeInBits();
7816 if (BitWidth < OrigBitWidth) {
7817 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7818 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7819 MaskedValueIsZero(I->getOperand(1), Mask)) {
7820 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7822 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7828 case Instruction::Shl:
7829 // If we are truncating the result of this SHL, and if it's a shift of a
7830 // constant amount, we can always perform a SHL in a smaller type.
7831 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7832 uint32_t BitWidth = Ty->getScalarSizeInBits();
7833 if (BitWidth < OrigTy->getScalarSizeInBits() &&
7834 CI->getLimitedValue(BitWidth) < BitWidth)
7835 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7839 case Instruction::LShr:
7840 // If this is a truncate of a logical shr, we can truncate it to a smaller
7841 // lshr iff we know that the bits we would otherwise be shifting in are
7843 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7844 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7845 uint32_t BitWidth = Ty->getScalarSizeInBits();
7846 if (BitWidth < OrigBitWidth &&
7847 MaskedValueIsZero(I->getOperand(0),
7848 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7849 CI->getLimitedValue(BitWidth) < BitWidth) {
7850 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7855 case Instruction::ZExt:
7856 case Instruction::SExt:
7857 case Instruction::Trunc:
7858 // If this is the same kind of case as our original (e.g. zext+zext), we
7859 // can safely replace it. Note that replacing it does not reduce the number
7860 // of casts in the input.
7864 // sext (zext ty1), ty2 -> zext ty2
7865 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7868 case Instruction::Select: {
7869 SelectInst *SI = cast<SelectInst>(I);
7870 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7872 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7875 case Instruction::PHI: {
7876 // We can change a phi if we can change all operands.
7877 PHINode *PN = cast<PHINode>(I);
7878 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7879 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7885 // TODO: Can handle more cases here.
7892 /// EvaluateInDifferentType - Given an expression that
7893 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7894 /// evaluate the expression.
7895 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7897 if (Constant *C = dyn_cast<Constant>(V))
7898 return ConstantExpr::getIntegerCast(C, Ty,
7899 isSigned /*Sext or ZExt*/);
7901 // Otherwise, it must be an instruction.
7902 Instruction *I = cast<Instruction>(V);
7903 Instruction *Res = 0;
7904 unsigned Opc = I->getOpcode();
7906 case Instruction::Add:
7907 case Instruction::Sub:
7908 case Instruction::Mul:
7909 case Instruction::And:
7910 case Instruction::Or:
7911 case Instruction::Xor:
7912 case Instruction::AShr:
7913 case Instruction::LShr:
7914 case Instruction::Shl:
7915 case Instruction::UDiv:
7916 case Instruction::URem: {
7917 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7918 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7919 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7922 case Instruction::Trunc:
7923 case Instruction::ZExt:
7924 case Instruction::SExt:
7925 // If the source type of the cast is the type we're trying for then we can
7926 // just return the source. There's no need to insert it because it is not
7928 if (I->getOperand(0)->getType() == Ty)
7929 return I->getOperand(0);
7931 // Otherwise, must be the same type of cast, so just reinsert a new one.
7932 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7935 case Instruction::Select: {
7936 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7937 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7938 Res = SelectInst::Create(I->getOperand(0), True, False);
7941 case Instruction::PHI: {
7942 PHINode *OPN = cast<PHINode>(I);
7943 PHINode *NPN = PHINode::Create(Ty);
7944 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7945 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7946 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7952 // TODO: Can handle more cases here.
7953 llvm_unreachable("Unreachable!");
7958 return InsertNewInstBefore(Res, *I);
7961 /// @brief Implement the transforms common to all CastInst visitors.
7962 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7963 Value *Src = CI.getOperand(0);
7965 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7966 // eliminate it now.
7967 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7968 if (Instruction::CastOps opc =
7969 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7970 // The first cast (CSrc) is eliminable so we need to fix up or replace
7971 // the second cast (CI). CSrc will then have a good chance of being dead.
7972 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
7976 // If we are casting a select then fold the cast into the select
7977 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7978 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7981 // If we are casting a PHI then fold the cast into the PHI
7982 if (isa<PHINode>(Src))
7983 if (Instruction *NV = FoldOpIntoPhi(CI))
7989 /// FindElementAtOffset - Given a type and a constant offset, determine whether
7990 /// or not there is a sequence of GEP indices into the type that will land us at
7991 /// the specified offset. If so, fill them into NewIndices and return the
7992 /// resultant element type, otherwise return null.
7993 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
7994 SmallVectorImpl<Value*> &NewIndices,
7995 const TargetData *TD,
7996 LLVMContext *Context) {
7998 if (!Ty->isSized()) return 0;
8000 // Start with the index over the outer type. Note that the type size
8001 // might be zero (even if the offset isn't zero) if the indexed type
8002 // is something like [0 x {int, int}]
8003 const Type *IntPtrTy = TD->getIntPtrType(*Context);
8004 int64_t FirstIdx = 0;
8005 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8006 FirstIdx = Offset/TySize;
8007 Offset -= FirstIdx*TySize;
8009 // Handle hosts where % returns negative instead of values [0..TySize).
8013 assert(Offset >= 0);
8015 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8018 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8020 // Index into the types. If we fail, set OrigBase to null.
8022 // Indexing into tail padding between struct/array elements.
8023 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8026 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8027 const StructLayout *SL = TD->getStructLayout(STy);
8028 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8029 "Offset must stay within the indexed type");
8031 unsigned Elt = SL->getElementContainingOffset(Offset);
8032 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8034 Offset -= SL->getElementOffset(Elt);
8035 Ty = STy->getElementType(Elt);
8036 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8037 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8038 assert(EltSize && "Cannot index into a zero-sized array");
8039 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8041 Ty = AT->getElementType();
8043 // Otherwise, we can't index into the middle of this atomic type, bail.
8051 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8052 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8053 Value *Src = CI.getOperand(0);
8055 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8056 // If casting the result of a getelementptr instruction with no offset, turn
8057 // this into a cast of the original pointer!
8058 if (GEP->hasAllZeroIndices()) {
8059 // Changing the cast operand is usually not a good idea but it is safe
8060 // here because the pointer operand is being replaced with another
8061 // pointer operand so the opcode doesn't need to change.
8063 CI.setOperand(0, GEP->getOperand(0));
8067 // If the GEP has a single use, and the base pointer is a bitcast, and the
8068 // GEP computes a constant offset, see if we can convert these three
8069 // instructions into fewer. This typically happens with unions and other
8070 // non-type-safe code.
8071 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8072 if (GEP->hasAllConstantIndices()) {
8073 // We are guaranteed to get a constant from EmitGEPOffset.
8074 ConstantInt *OffsetV =
8075 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8076 int64_t Offset = OffsetV->getSExtValue();
8078 // Get the base pointer input of the bitcast, and the type it points to.
8079 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8080 const Type *GEPIdxTy =
8081 cast<PointerType>(OrigBase->getType())->getElementType();
8082 SmallVector<Value*, 8> NewIndices;
8083 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8084 // If we were able to index down into an element, create the GEP
8085 // and bitcast the result. This eliminates one bitcast, potentially
8087 Value *NGEP = Builder->CreateGEP(OrigBase, NewIndices.begin(),
8089 NGEP->takeName(GEP);
8090 if (isa<Instruction>(NGEP) && cast<GEPOperator>(GEP)->isInBounds())
8091 cast<GEPOperator>(NGEP)->setIsInBounds(true);
8093 if (isa<BitCastInst>(CI))
8094 return new BitCastInst(NGEP, CI.getType());
8095 assert(isa<PtrToIntInst>(CI));
8096 return new PtrToIntInst(NGEP, CI.getType());
8102 return commonCastTransforms(CI);
8105 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8106 /// type like i42. We don't want to introduce operations on random non-legal
8107 /// integer types where they don't already exist in the code. In the future,
8108 /// we should consider making this based off target-data, so that 32-bit targets
8109 /// won't get i64 operations etc.
8110 static bool isSafeIntegerType(const Type *Ty) {
8111 switch (Ty->getPrimitiveSizeInBits()) {
8122 /// commonIntCastTransforms - This function implements the common transforms
8123 /// for trunc, zext, and sext.
8124 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8125 if (Instruction *Result = commonCastTransforms(CI))
8128 Value *Src = CI.getOperand(0);
8129 const Type *SrcTy = Src->getType();
8130 const Type *DestTy = CI.getType();
8131 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8132 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8134 // See if we can simplify any instructions used by the LHS whose sole
8135 // purpose is to compute bits we don't care about.
8136 if (SimplifyDemandedInstructionBits(CI))
8139 // If the source isn't an instruction or has more than one use then we
8140 // can't do anything more.
8141 Instruction *SrcI = dyn_cast<Instruction>(Src);
8142 if (!SrcI || !Src->hasOneUse())
8145 // Attempt to propagate the cast into the instruction for int->int casts.
8146 int NumCastsRemoved = 0;
8147 // Only do this if the dest type is a simple type, don't convert the
8148 // expression tree to something weird like i93 unless the source is also
8150 if ((isSafeIntegerType(DestTy->getScalarType()) ||
8151 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8152 CanEvaluateInDifferentType(SrcI, DestTy,
8153 CI.getOpcode(), NumCastsRemoved)) {
8154 // If this cast is a truncate, evaluting in a different type always
8155 // eliminates the cast, so it is always a win. If this is a zero-extension,
8156 // we need to do an AND to maintain the clear top-part of the computation,
8157 // so we require that the input have eliminated at least one cast. If this
8158 // is a sign extension, we insert two new casts (to do the extension) so we
8159 // require that two casts have been eliminated.
8160 bool DoXForm = false;
8161 bool JustReplace = false;
8162 switch (CI.getOpcode()) {
8164 // All the others use floating point so we shouldn't actually
8165 // get here because of the check above.
8166 llvm_unreachable("Unknown cast type");
8167 case Instruction::Trunc:
8170 case Instruction::ZExt: {
8171 DoXForm = NumCastsRemoved >= 1;
8172 if (!DoXForm && 0) {
8173 // If it's unnecessary to issue an AND to clear the high bits, it's
8174 // always profitable to do this xform.
8175 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8176 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8177 if (MaskedValueIsZero(TryRes, Mask))
8178 return ReplaceInstUsesWith(CI, TryRes);
8180 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8181 if (TryI->use_empty())
8182 EraseInstFromFunction(*TryI);
8186 case Instruction::SExt: {
8187 DoXForm = NumCastsRemoved >= 2;
8188 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8189 // If we do not have to emit the truncate + sext pair, then it's always
8190 // profitable to do this xform.
8192 // It's not safe to eliminate the trunc + sext pair if one of the
8193 // eliminated cast is a truncate. e.g.
8194 // t2 = trunc i32 t1 to i16
8195 // t3 = sext i16 t2 to i32
8198 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8199 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8200 if (NumSignBits > (DestBitSize - SrcBitSize))
8201 return ReplaceInstUsesWith(CI, TryRes);
8203 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8204 if (TryI->use_empty())
8205 EraseInstFromFunction(*TryI);
8212 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8213 " to avoid cast: " << CI);
8214 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8215 CI.getOpcode() == Instruction::SExt);
8217 // Just replace this cast with the result.
8218 return ReplaceInstUsesWith(CI, Res);
8220 assert(Res->getType() == DestTy);
8221 switch (CI.getOpcode()) {
8222 default: llvm_unreachable("Unknown cast type!");
8223 case Instruction::Trunc:
8224 // Just replace this cast with the result.
8225 return ReplaceInstUsesWith(CI, Res);
8226 case Instruction::ZExt: {
8227 assert(SrcBitSize < DestBitSize && "Not a zext?");
8229 // If the high bits are already zero, just replace this cast with the
8231 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8232 if (MaskedValueIsZero(Res, Mask))
8233 return ReplaceInstUsesWith(CI, Res);
8235 // We need to emit an AND to clear the high bits.
8236 Constant *C = ConstantInt::get(*Context,
8237 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8238 return BinaryOperator::CreateAnd(Res, C);
8240 case Instruction::SExt: {
8241 // If the high bits are already filled with sign bit, just replace this
8242 // cast with the result.
8243 unsigned NumSignBits = ComputeNumSignBits(Res);
8244 if (NumSignBits > (DestBitSize - SrcBitSize))
8245 return ReplaceInstUsesWith(CI, Res);
8247 // We need to emit a cast to truncate, then a cast to sext.
8248 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8254 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8255 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8257 switch (SrcI->getOpcode()) {
8258 case Instruction::Add:
8259 case Instruction::Mul:
8260 case Instruction::And:
8261 case Instruction::Or:
8262 case Instruction::Xor:
8263 // If we are discarding information, rewrite.
8264 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8265 // Don't insert two casts unless at least one can be eliminated.
8266 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8267 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8268 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8269 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8270 return BinaryOperator::Create(
8271 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8275 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8276 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8277 SrcI->getOpcode() == Instruction::Xor &&
8278 Op1 == ConstantInt::getTrue(*Context) &&
8279 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8280 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8281 return BinaryOperator::CreateXor(New,
8282 ConstantInt::get(CI.getType(), 1));
8286 case Instruction::Shl: {
8287 // Canonicalize trunc inside shl, if we can.
8288 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8289 if (CI && DestBitSize < SrcBitSize &&
8290 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8291 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8292 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8293 return BinaryOperator::CreateShl(Op0c, Op1c);
8301 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8302 if (Instruction *Result = commonIntCastTransforms(CI))
8305 Value *Src = CI.getOperand(0);
8306 const Type *Ty = CI.getType();
8307 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8308 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8310 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8311 if (DestBitWidth == 1) {
8312 Constant *One = ConstantInt::get(Src->getType(), 1);
8313 Src = Builder->CreateAnd(Src, One, "tmp");
8314 Value *Zero = Constant::getNullValue(Src->getType());
8315 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8318 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8319 ConstantInt *ShAmtV = 0;
8321 if (Src->hasOneUse() &&
8322 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8323 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8325 // Get a mask for the bits shifting in.
8326 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8327 if (MaskedValueIsZero(ShiftOp, Mask)) {
8328 if (ShAmt >= DestBitWidth) // All zeros.
8329 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8331 // Okay, we can shrink this. Truncate the input, then return a new
8333 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8334 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8335 return BinaryOperator::CreateLShr(V1, V2);
8342 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8343 /// in order to eliminate the icmp.
8344 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8346 // If we are just checking for a icmp eq of a single bit and zext'ing it
8347 // to an integer, then shift the bit to the appropriate place and then
8348 // cast to integer to avoid the comparison.
8349 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8350 const APInt &Op1CV = Op1C->getValue();
8352 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8353 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8354 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8355 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8356 if (!DoXform) return ICI;
8358 Value *In = ICI->getOperand(0);
8359 Value *Sh = ConstantInt::get(In->getType(),
8360 In->getType()->getScalarSizeInBits()-1);
8361 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8362 if (In->getType() != CI.getType())
8363 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8365 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8366 Constant *One = ConstantInt::get(In->getType(), 1);
8367 In = Builder->CreateXor(In, One, In->getName()+".not");
8370 return ReplaceInstUsesWith(CI, In);
8375 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8376 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8377 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8378 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8379 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8380 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8381 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8382 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8383 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8384 // This only works for EQ and NE
8385 ICI->isEquality()) {
8386 // If Op1C some other power of two, convert:
8387 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8388 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8389 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8390 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8392 APInt KnownZeroMask(~KnownZero);
8393 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8394 if (!DoXform) return ICI;
8396 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8397 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8398 // (X&4) == 2 --> false
8399 // (X&4) != 2 --> true
8400 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8401 Res = ConstantExpr::getZExt(Res, CI.getType());
8402 return ReplaceInstUsesWith(CI, Res);
8405 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8406 Value *In = ICI->getOperand(0);
8408 // Perform a logical shr by shiftamt.
8409 // Insert the shift to put the result in the low bit.
8410 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8411 In->getName()+".lobit");
8414 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8415 Constant *One = ConstantInt::get(In->getType(), 1);
8416 In = Builder->CreateXor(In, One, "tmp");
8419 if (CI.getType() == In->getType())
8420 return ReplaceInstUsesWith(CI, In);
8422 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8430 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8431 // If one of the common conversion will work ..
8432 if (Instruction *Result = commonIntCastTransforms(CI))
8435 Value *Src = CI.getOperand(0);
8437 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8438 // types and if the sizes are just right we can convert this into a logical
8439 // 'and' which will be much cheaper than the pair of casts.
8440 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8441 // Get the sizes of the types involved. We know that the intermediate type
8442 // will be smaller than A or C, but don't know the relation between A and C.
8443 Value *A = CSrc->getOperand(0);
8444 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8445 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8446 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8447 // If we're actually extending zero bits, then if
8448 // SrcSize < DstSize: zext(a & mask)
8449 // SrcSize == DstSize: a & mask
8450 // SrcSize > DstSize: trunc(a) & mask
8451 if (SrcSize < DstSize) {
8452 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8453 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8454 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
8455 return new ZExtInst(And, CI.getType());
8458 if (SrcSize == DstSize) {
8459 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8460 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8463 if (SrcSize > DstSize) {
8464 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
8465 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8466 return BinaryOperator::CreateAnd(Trunc,
8467 ConstantInt::get(Trunc->getType(),
8472 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8473 return transformZExtICmp(ICI, CI);
8475 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8476 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8477 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8478 // of the (zext icmp) will be transformed.
8479 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8480 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8481 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8482 (transformZExtICmp(LHS, CI, false) ||
8483 transformZExtICmp(RHS, CI, false))) {
8484 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8485 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
8486 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8490 // zext(trunc(t) & C) -> (t & zext(C)).
8491 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8492 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8493 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8494 Value *TI0 = TI->getOperand(0);
8495 if (TI0->getType() == CI.getType())
8497 BinaryOperator::CreateAnd(TI0,
8498 ConstantExpr::getZExt(C, CI.getType()));
8501 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8502 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8503 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8504 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8505 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8506 And->getOperand(1) == C)
8507 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8508 Value *TI0 = TI->getOperand(0);
8509 if (TI0->getType() == CI.getType()) {
8510 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8511 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
8512 return BinaryOperator::CreateXor(NewAnd, ZC);
8519 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8520 if (Instruction *I = commonIntCastTransforms(CI))
8523 Value *Src = CI.getOperand(0);
8525 // Canonicalize sign-extend from i1 to a select.
8526 if (Src->getType() == Type::getInt1Ty(*Context))
8527 return SelectInst::Create(Src,
8528 Constant::getAllOnesValue(CI.getType()),
8529 Constant::getNullValue(CI.getType()));
8531 // See if the value being truncated is already sign extended. If so, just
8532 // eliminate the trunc/sext pair.
8533 if (Operator::getOpcode(Src) == Instruction::Trunc) {
8534 Value *Op = cast<User>(Src)->getOperand(0);
8535 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8536 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8537 unsigned DestBits = CI.getType()->getScalarSizeInBits();
8538 unsigned NumSignBits = ComputeNumSignBits(Op);
8540 if (OpBits == DestBits) {
8541 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8542 // bits, it is already ready.
8543 if (NumSignBits > DestBits-MidBits)
8544 return ReplaceInstUsesWith(CI, Op);
8545 } else if (OpBits < DestBits) {
8546 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8547 // bits, just sext from i32.
8548 if (NumSignBits > OpBits-MidBits)
8549 return new SExtInst(Op, CI.getType(), "tmp");
8551 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8552 // bits, just truncate to i32.
8553 if (NumSignBits > OpBits-MidBits)
8554 return new TruncInst(Op, CI.getType(), "tmp");
8558 // If the input is a shl/ashr pair of a same constant, then this is a sign
8559 // extension from a smaller value. If we could trust arbitrary bitwidth
8560 // integers, we could turn this into a truncate to the smaller bit and then
8561 // use a sext for the whole extension. Since we don't, look deeper and check
8562 // for a truncate. If the source and dest are the same type, eliminate the
8563 // trunc and extend and just do shifts. For example, turn:
8564 // %a = trunc i32 %i to i8
8565 // %b = shl i8 %a, 6
8566 // %c = ashr i8 %b, 6
8567 // %d = sext i8 %c to i32
8569 // %a = shl i32 %i, 30
8570 // %d = ashr i32 %a, 30
8572 ConstantInt *BA = 0, *CA = 0;
8573 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8574 m_ConstantInt(CA))) &&
8575 BA == CA && isa<TruncInst>(A)) {
8576 Value *I = cast<TruncInst>(A)->getOperand(0);
8577 if (I->getType() == CI.getType()) {
8578 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8579 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8580 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8581 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8582 I = Builder->CreateShl(I, ShAmtV, CI.getName());
8583 return BinaryOperator::CreateAShr(I, ShAmtV);
8590 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8591 /// in the specified FP type without changing its value.
8592 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8593 LLVMContext *Context) {
8595 APFloat F = CFP->getValueAPF();
8596 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8598 return ConstantFP::get(*Context, F);
8602 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8603 /// through it until we get the source value.
8604 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8605 if (Instruction *I = dyn_cast<Instruction>(V))
8606 if (I->getOpcode() == Instruction::FPExt)
8607 return LookThroughFPExtensions(I->getOperand(0), Context);
8609 // If this value is a constant, return the constant in the smallest FP type
8610 // that can accurately represent it. This allows us to turn
8611 // (float)((double)X+2.0) into x+2.0f.
8612 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8613 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8614 return V; // No constant folding of this.
8615 // See if the value can be truncated to float and then reextended.
8616 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8618 if (CFP->getType() == Type::getDoubleTy(*Context))
8619 return V; // Won't shrink.
8620 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8622 // Don't try to shrink to various long double types.
8628 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8629 if (Instruction *I = commonCastTransforms(CI))
8632 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8633 // smaller than the destination type, we can eliminate the truncate by doing
8634 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
8635 // many builtins (sqrt, etc).
8636 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8637 if (OpI && OpI->hasOneUse()) {
8638 switch (OpI->getOpcode()) {
8640 case Instruction::FAdd:
8641 case Instruction::FSub:
8642 case Instruction::FMul:
8643 case Instruction::FDiv:
8644 case Instruction::FRem:
8645 const Type *SrcTy = OpI->getType();
8646 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8647 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8648 if (LHSTrunc->getType() != SrcTy &&
8649 RHSTrunc->getType() != SrcTy) {
8650 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8651 // If the source types were both smaller than the destination type of
8652 // the cast, do this xform.
8653 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8654 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8655 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8656 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
8657 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8666 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8667 return commonCastTransforms(CI);
8670 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8671 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8673 return commonCastTransforms(FI);
8675 // fptoui(uitofp(X)) --> X
8676 // fptoui(sitofp(X)) --> X
8677 // This is safe if the intermediate type has enough bits in its mantissa to
8678 // accurately represent all values of X. For example, do not do this with
8679 // i64->float->i64. This is also safe for sitofp case, because any negative
8680 // 'X' value would cause an undefined result for the fptoui.
8681 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8682 OpI->getOperand(0)->getType() == FI.getType() &&
8683 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8684 OpI->getType()->getFPMantissaWidth())
8685 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8687 return commonCastTransforms(FI);
8690 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8691 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8693 return commonCastTransforms(FI);
8695 // fptosi(sitofp(X)) --> X
8696 // fptosi(uitofp(X)) --> X
8697 // This is safe if the intermediate type has enough bits in its mantissa to
8698 // accurately represent all values of X. For example, do not do this with
8699 // i64->float->i64. This is also safe for sitofp case, because any negative
8700 // 'X' value would cause an undefined result for the fptoui.
8701 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8702 OpI->getOperand(0)->getType() == FI.getType() &&
8703 (int)FI.getType()->getScalarSizeInBits() <=
8704 OpI->getType()->getFPMantissaWidth())
8705 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8707 return commonCastTransforms(FI);
8710 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8711 return commonCastTransforms(CI);
8714 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8715 return commonCastTransforms(CI);
8718 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8719 // If the destination integer type is smaller than the intptr_t type for
8720 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8721 // trunc to be exposed to other transforms. Don't do this for extending
8722 // ptrtoint's, because we don't know if the target sign or zero extends its
8725 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8726 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8727 TD->getIntPtrType(CI.getContext()),
8729 return new TruncInst(P, CI.getType());
8732 return commonPointerCastTransforms(CI);
8735 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8736 // If the source integer type is larger than the intptr_t type for
8737 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8738 // allows the trunc to be exposed to other transforms. Don't do this for
8739 // extending inttoptr's, because we don't know if the target sign or zero
8740 // extends to pointers.
8741 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
8742 TD->getPointerSizeInBits()) {
8743 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8744 TD->getIntPtrType(CI.getContext()), "tmp");
8745 return new IntToPtrInst(P, CI.getType());
8748 if (Instruction *I = commonCastTransforms(CI))
8754 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8755 // If the operands are integer typed then apply the integer transforms,
8756 // otherwise just apply the common ones.
8757 Value *Src = CI.getOperand(0);
8758 const Type *SrcTy = Src->getType();
8759 const Type *DestTy = CI.getType();
8761 if (isa<PointerType>(SrcTy)) {
8762 if (Instruction *I = commonPointerCastTransforms(CI))
8765 if (Instruction *Result = commonCastTransforms(CI))
8770 // Get rid of casts from one type to the same type. These are useless and can
8771 // be replaced by the operand.
8772 if (DestTy == Src->getType())
8773 return ReplaceInstUsesWith(CI, Src);
8775 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8776 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8777 const Type *DstElTy = DstPTy->getElementType();
8778 const Type *SrcElTy = SrcPTy->getElementType();
8780 // If the address spaces don't match, don't eliminate the bitcast, which is
8781 // required for changing types.
8782 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8785 // If we are casting a malloc or alloca to a pointer to a type of the same
8786 // size, rewrite the allocation instruction to allocate the "right" type.
8787 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8788 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8791 // If the source and destination are pointers, and this cast is equivalent
8792 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8793 // This can enhance SROA and other transforms that want type-safe pointers.
8794 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8795 unsigned NumZeros = 0;
8796 while (SrcElTy != DstElTy &&
8797 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8798 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8799 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8803 // If we found a path from the src to dest, create the getelementptr now.
8804 if (SrcElTy == DstElTy) {
8805 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8806 Instruction *GEP = GetElementPtrInst::Create(Src,
8807 Idxs.begin(), Idxs.end(), "",
8808 ((Instruction*) NULL));
8809 cast<GEPOperator>(GEP)->setIsInBounds(true);
8814 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8815 if (DestVTy->getNumElements() == 1) {
8816 if (!isa<VectorType>(SrcTy)) {
8817 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
8818 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
8819 Constant::getNullValue(Type::getInt32Ty(*Context)));
8821 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8825 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8826 if (SrcVTy->getNumElements() == 1) {
8827 if (!isa<VectorType>(DestTy)) {
8829 Builder->CreateExtractElement(Src,
8830 Constant::getNullValue(Type::getInt32Ty(*Context)));
8831 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8836 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8837 if (SVI->hasOneUse()) {
8838 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8839 // a bitconvert to a vector with the same # elts.
8840 if (isa<VectorType>(DestTy) &&
8841 cast<VectorType>(DestTy)->getNumElements() ==
8842 SVI->getType()->getNumElements() &&
8843 SVI->getType()->getNumElements() ==
8844 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8846 // If either of the operands is a cast from CI.getType(), then
8847 // evaluating the shuffle in the casted destination's type will allow
8848 // us to eliminate at least one cast.
8849 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8850 Tmp->getOperand(0)->getType() == DestTy) ||
8851 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8852 Tmp->getOperand(0)->getType() == DestTy)) {
8853 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8854 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
8855 // Return a new shuffle vector. Use the same element ID's, as we
8856 // know the vector types match #elts.
8857 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8865 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8867 /// %D = select %cond, %C, %A
8869 /// %C = select %cond, %B, 0
8872 /// Assuming that the specified instruction is an operand to the select, return
8873 /// a bitmask indicating which operands of this instruction are foldable if they
8874 /// equal the other incoming value of the select.
8876 static unsigned GetSelectFoldableOperands(Instruction *I) {
8877 switch (I->getOpcode()) {
8878 case Instruction::Add:
8879 case Instruction::Mul:
8880 case Instruction::And:
8881 case Instruction::Or:
8882 case Instruction::Xor:
8883 return 3; // Can fold through either operand.
8884 case Instruction::Sub: // Can only fold on the amount subtracted.
8885 case Instruction::Shl: // Can only fold on the shift amount.
8886 case Instruction::LShr:
8887 case Instruction::AShr:
8890 return 0; // Cannot fold
8894 /// GetSelectFoldableConstant - For the same transformation as the previous
8895 /// function, return the identity constant that goes into the select.
8896 static Constant *GetSelectFoldableConstant(Instruction *I,
8897 LLVMContext *Context) {
8898 switch (I->getOpcode()) {
8899 default: llvm_unreachable("This cannot happen!");
8900 case Instruction::Add:
8901 case Instruction::Sub:
8902 case Instruction::Or:
8903 case Instruction::Xor:
8904 case Instruction::Shl:
8905 case Instruction::LShr:
8906 case Instruction::AShr:
8907 return Constant::getNullValue(I->getType());
8908 case Instruction::And:
8909 return Constant::getAllOnesValue(I->getType());
8910 case Instruction::Mul:
8911 return ConstantInt::get(I->getType(), 1);
8915 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8916 /// have the same opcode and only one use each. Try to simplify this.
8917 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8919 if (TI->getNumOperands() == 1) {
8920 // If this is a non-volatile load or a cast from the same type,
8923 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8926 return 0; // unknown unary op.
8929 // Fold this by inserting a select from the input values.
8930 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8931 FI->getOperand(0), SI.getName()+".v");
8932 InsertNewInstBefore(NewSI, SI);
8933 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
8937 // Only handle binary operators here.
8938 if (!isa<BinaryOperator>(TI))
8941 // Figure out if the operations have any operands in common.
8942 Value *MatchOp, *OtherOpT, *OtherOpF;
8944 if (TI->getOperand(0) == FI->getOperand(0)) {
8945 MatchOp = TI->getOperand(0);
8946 OtherOpT = TI->getOperand(1);
8947 OtherOpF = FI->getOperand(1);
8948 MatchIsOpZero = true;
8949 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8950 MatchOp = TI->getOperand(1);
8951 OtherOpT = TI->getOperand(0);
8952 OtherOpF = FI->getOperand(0);
8953 MatchIsOpZero = false;
8954 } else if (!TI->isCommutative()) {
8956 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8957 MatchOp = TI->getOperand(0);
8958 OtherOpT = TI->getOperand(1);
8959 OtherOpF = FI->getOperand(0);
8960 MatchIsOpZero = true;
8961 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8962 MatchOp = TI->getOperand(1);
8963 OtherOpT = TI->getOperand(0);
8964 OtherOpF = FI->getOperand(1);
8965 MatchIsOpZero = true;
8970 // If we reach here, they do have operations in common.
8971 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8972 OtherOpF, SI.getName()+".v");
8973 InsertNewInstBefore(NewSI, SI);
8975 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8977 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
8979 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
8981 llvm_unreachable("Shouldn't get here");
8985 static bool isSelect01(Constant *C1, Constant *C2) {
8986 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
8989 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
8992 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
8995 /// FoldSelectIntoOp - Try fold the select into one of the operands to
8996 /// facilitate further optimization.
8997 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
8999 // See the comment above GetSelectFoldableOperands for a description of the
9000 // transformation we are doing here.
9001 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9002 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9003 !isa<Constant>(FalseVal)) {
9004 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9005 unsigned OpToFold = 0;
9006 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9008 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9013 Constant *C = GetSelectFoldableConstant(TVI, Context);
9014 Value *OOp = TVI->getOperand(2-OpToFold);
9015 // Avoid creating select between 2 constants unless it's selecting
9017 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9018 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9019 InsertNewInstBefore(NewSel, SI);
9020 NewSel->takeName(TVI);
9021 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9022 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9023 llvm_unreachable("Unknown instruction!!");
9030 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9031 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9032 !isa<Constant>(TrueVal)) {
9033 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9034 unsigned OpToFold = 0;
9035 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9037 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9042 Constant *C = GetSelectFoldableConstant(FVI, Context);
9043 Value *OOp = FVI->getOperand(2-OpToFold);
9044 // Avoid creating select between 2 constants unless it's selecting
9046 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9047 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9048 InsertNewInstBefore(NewSel, SI);
9049 NewSel->takeName(FVI);
9050 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9051 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9052 llvm_unreachable("Unknown instruction!!");
9062 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9063 /// ICmpInst as its first operand.
9065 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9067 bool Changed = false;
9068 ICmpInst::Predicate Pred = ICI->getPredicate();
9069 Value *CmpLHS = ICI->getOperand(0);
9070 Value *CmpRHS = ICI->getOperand(1);
9071 Value *TrueVal = SI.getTrueValue();
9072 Value *FalseVal = SI.getFalseValue();
9074 // Check cases where the comparison is with a constant that
9075 // can be adjusted to fit the min/max idiom. We may edit ICI in
9076 // place here, so make sure the select is the only user.
9077 if (ICI->hasOneUse())
9078 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9081 case ICmpInst::ICMP_ULT:
9082 case ICmpInst::ICMP_SLT: {
9083 // X < MIN ? T : F --> F
9084 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9085 return ReplaceInstUsesWith(SI, FalseVal);
9086 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
9087 Constant *AdjustedRHS = SubOne(CI);
9088 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9089 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9090 Pred = ICmpInst::getSwappedPredicate(Pred);
9091 CmpRHS = AdjustedRHS;
9092 std::swap(FalseVal, TrueVal);
9093 ICI->setPredicate(Pred);
9094 ICI->setOperand(1, CmpRHS);
9095 SI.setOperand(1, TrueVal);
9096 SI.setOperand(2, FalseVal);
9101 case ICmpInst::ICMP_UGT:
9102 case ICmpInst::ICMP_SGT: {
9103 // X > MAX ? T : F --> F
9104 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9105 return ReplaceInstUsesWith(SI, FalseVal);
9106 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
9107 Constant *AdjustedRHS = AddOne(CI);
9108 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9109 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9110 Pred = ICmpInst::getSwappedPredicate(Pred);
9111 CmpRHS = AdjustedRHS;
9112 std::swap(FalseVal, TrueVal);
9113 ICI->setPredicate(Pred);
9114 ICI->setOperand(1, CmpRHS);
9115 SI.setOperand(1, TrueVal);
9116 SI.setOperand(2, FalseVal);
9123 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9124 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
9125 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9126 if (match(TrueVal, m_ConstantInt<-1>()) &&
9127 match(FalseVal, m_ConstantInt<0>()))
9128 Pred = ICI->getPredicate();
9129 else if (match(TrueVal, m_ConstantInt<0>()) &&
9130 match(FalseVal, m_ConstantInt<-1>()))
9131 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9133 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9134 // If we are just checking for a icmp eq of a single bit and zext'ing it
9135 // to an integer, then shift the bit to the appropriate place and then
9136 // cast to integer to avoid the comparison.
9137 const APInt &Op1CV = CI->getValue();
9139 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9140 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9141 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9142 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9143 Value *In = ICI->getOperand(0);
9144 Value *Sh = ConstantInt::get(In->getType(),
9145 In->getType()->getScalarSizeInBits()-1);
9146 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9147 In->getName()+".lobit"),
9149 if (In->getType() != SI.getType())
9150 In = CastInst::CreateIntegerCast(In, SI.getType(),
9151 true/*SExt*/, "tmp", ICI);
9153 if (Pred == ICmpInst::ICMP_SGT)
9154 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9155 In->getName()+".not"), *ICI);
9157 return ReplaceInstUsesWith(SI, In);
9162 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9163 // Transform (X == Y) ? X : Y -> Y
9164 if (Pred == ICmpInst::ICMP_EQ)
9165 return ReplaceInstUsesWith(SI, FalseVal);
9166 // Transform (X != Y) ? X : Y -> X
9167 if (Pred == ICmpInst::ICMP_NE)
9168 return ReplaceInstUsesWith(SI, TrueVal);
9169 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9171 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9172 // Transform (X == Y) ? Y : X -> X
9173 if (Pred == ICmpInst::ICMP_EQ)
9174 return ReplaceInstUsesWith(SI, FalseVal);
9175 // Transform (X != Y) ? Y : X -> Y
9176 if (Pred == ICmpInst::ICMP_NE)
9177 return ReplaceInstUsesWith(SI, TrueVal);
9178 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9181 /// NOTE: if we wanted to, this is where to detect integer ABS
9183 return Changed ? &SI : 0;
9186 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9187 Value *CondVal = SI.getCondition();
9188 Value *TrueVal = SI.getTrueValue();
9189 Value *FalseVal = SI.getFalseValue();
9191 // select true, X, Y -> X
9192 // select false, X, Y -> Y
9193 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9194 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9196 // select C, X, X -> X
9197 if (TrueVal == FalseVal)
9198 return ReplaceInstUsesWith(SI, TrueVal);
9200 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9201 return ReplaceInstUsesWith(SI, FalseVal);
9202 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9203 return ReplaceInstUsesWith(SI, TrueVal);
9204 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9205 if (isa<Constant>(TrueVal))
9206 return ReplaceInstUsesWith(SI, TrueVal);
9208 return ReplaceInstUsesWith(SI, FalseVal);
9211 if (SI.getType() == Type::getInt1Ty(*Context)) {
9212 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9213 if (C->getZExtValue()) {
9214 // Change: A = select B, true, C --> A = or B, C
9215 return BinaryOperator::CreateOr(CondVal, FalseVal);
9217 // Change: A = select B, false, C --> A = and !B, C
9219 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9220 "not."+CondVal->getName()), SI);
9221 return BinaryOperator::CreateAnd(NotCond, FalseVal);
9223 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9224 if (C->getZExtValue() == false) {
9225 // Change: A = select B, C, false --> A = and B, C
9226 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9228 // Change: A = select B, C, true --> A = or !B, C
9230 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9231 "not."+CondVal->getName()), SI);
9232 return BinaryOperator::CreateOr(NotCond, TrueVal);
9236 // select a, b, a -> a&b
9237 // select a, a, b -> a|b
9238 if (CondVal == TrueVal)
9239 return BinaryOperator::CreateOr(CondVal, FalseVal);
9240 else if (CondVal == FalseVal)
9241 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9244 // Selecting between two integer constants?
9245 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9246 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9247 // select C, 1, 0 -> zext C to int
9248 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9249 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9250 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9251 // select C, 0, 1 -> zext !C to int
9253 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9254 "not."+CondVal->getName()), SI);
9255 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9258 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9259 // If one of the constants is zero (we know they can't both be) and we
9260 // have an icmp instruction with zero, and we have an 'and' with the
9261 // non-constant value, eliminate this whole mess. This corresponds to
9262 // cases like this: ((X & 27) ? 27 : 0)
9263 if (TrueValC->isZero() || FalseValC->isZero())
9264 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9265 cast<Constant>(IC->getOperand(1))->isNullValue())
9266 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9267 if (ICA->getOpcode() == Instruction::And &&
9268 isa<ConstantInt>(ICA->getOperand(1)) &&
9269 (ICA->getOperand(1) == TrueValC ||
9270 ICA->getOperand(1) == FalseValC) &&
9271 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9272 // Okay, now we know that everything is set up, we just don't
9273 // know whether we have a icmp_ne or icmp_eq and whether the
9274 // true or false val is the zero.
9275 bool ShouldNotVal = !TrueValC->isZero();
9276 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9279 V = InsertNewInstBefore(BinaryOperator::Create(
9280 Instruction::Xor, V, ICA->getOperand(1)), SI);
9281 return ReplaceInstUsesWith(SI, V);
9286 // See if we are selecting two values based on a comparison of the two values.
9287 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9288 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9289 // Transform (X == Y) ? X : Y -> Y
9290 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9291 // This is not safe in general for floating point:
9292 // consider X== -0, Y== +0.
9293 // It becomes safe if either operand is a nonzero constant.
9294 ConstantFP *CFPt, *CFPf;
9295 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9296 !CFPt->getValueAPF().isZero()) ||
9297 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9298 !CFPf->getValueAPF().isZero()))
9299 return ReplaceInstUsesWith(SI, FalseVal);
9301 // Transform (X != Y) ? X : Y -> X
9302 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9303 return ReplaceInstUsesWith(SI, TrueVal);
9304 // NOTE: if we wanted to, this is where to detect MIN/MAX
9306 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9307 // Transform (X == Y) ? Y : X -> X
9308 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9309 // This is not safe in general for floating point:
9310 // consider X== -0, Y== +0.
9311 // It becomes safe if either operand is a nonzero constant.
9312 ConstantFP *CFPt, *CFPf;
9313 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9314 !CFPt->getValueAPF().isZero()) ||
9315 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9316 !CFPf->getValueAPF().isZero()))
9317 return ReplaceInstUsesWith(SI, FalseVal);
9319 // Transform (X != Y) ? Y : X -> Y
9320 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9321 return ReplaceInstUsesWith(SI, TrueVal);
9322 // NOTE: if we wanted to, this is where to detect MIN/MAX
9324 // NOTE: if we wanted to, this is where to detect ABS
9327 // See if we are selecting two values based on a comparison of the two values.
9328 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9329 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9332 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9333 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9334 if (TI->hasOneUse() && FI->hasOneUse()) {
9335 Instruction *AddOp = 0, *SubOp = 0;
9337 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9338 if (TI->getOpcode() == FI->getOpcode())
9339 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9342 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9343 // even legal for FP.
9344 if ((TI->getOpcode() == Instruction::Sub &&
9345 FI->getOpcode() == Instruction::Add) ||
9346 (TI->getOpcode() == Instruction::FSub &&
9347 FI->getOpcode() == Instruction::FAdd)) {
9348 AddOp = FI; SubOp = TI;
9349 } else if ((FI->getOpcode() == Instruction::Sub &&
9350 TI->getOpcode() == Instruction::Add) ||
9351 (FI->getOpcode() == Instruction::FSub &&
9352 TI->getOpcode() == Instruction::FAdd)) {
9353 AddOp = TI; SubOp = FI;
9357 Value *OtherAddOp = 0;
9358 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9359 OtherAddOp = AddOp->getOperand(1);
9360 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9361 OtherAddOp = AddOp->getOperand(0);
9365 // So at this point we know we have (Y -> OtherAddOp):
9366 // select C, (add X, Y), (sub X, Z)
9367 Value *NegVal; // Compute -Z
9368 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9369 NegVal = ConstantExpr::getNeg(C);
9371 NegVal = InsertNewInstBefore(
9372 BinaryOperator::CreateNeg(SubOp->getOperand(1),
9376 Value *NewTrueOp = OtherAddOp;
9377 Value *NewFalseOp = NegVal;
9379 std::swap(NewTrueOp, NewFalseOp);
9380 Instruction *NewSel =
9381 SelectInst::Create(CondVal, NewTrueOp,
9382 NewFalseOp, SI.getName() + ".p");
9384 NewSel = InsertNewInstBefore(NewSel, SI);
9385 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9390 // See if we can fold the select into one of our operands.
9391 if (SI.getType()->isInteger()) {
9392 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9397 if (BinaryOperator::isNot(CondVal)) {
9398 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9399 SI.setOperand(1, FalseVal);
9400 SI.setOperand(2, TrueVal);
9407 /// EnforceKnownAlignment - If the specified pointer points to an object that
9408 /// we control, modify the object's alignment to PrefAlign. This isn't
9409 /// often possible though. If alignment is important, a more reliable approach
9410 /// is to simply align all global variables and allocation instructions to
9411 /// their preferred alignment from the beginning.
9413 static unsigned EnforceKnownAlignment(Value *V,
9414 unsigned Align, unsigned PrefAlign) {
9416 User *U = dyn_cast<User>(V);
9417 if (!U) return Align;
9419 switch (Operator::getOpcode(U)) {
9421 case Instruction::BitCast:
9422 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9423 case Instruction::GetElementPtr: {
9424 // If all indexes are zero, it is just the alignment of the base pointer.
9425 bool AllZeroOperands = true;
9426 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9427 if (!isa<Constant>(*i) ||
9428 !cast<Constant>(*i)->isNullValue()) {
9429 AllZeroOperands = false;
9433 if (AllZeroOperands) {
9434 // Treat this like a bitcast.
9435 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9441 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9442 // If there is a large requested alignment and we can, bump up the alignment
9444 if (!GV->isDeclaration()) {
9445 if (GV->getAlignment() >= PrefAlign)
9446 Align = GV->getAlignment();
9448 GV->setAlignment(PrefAlign);
9452 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9453 // If there is a requested alignment and if this is an alloca, round up. We
9454 // don't do this for malloc, because some systems can't respect the request.
9455 if (isa<AllocaInst>(AI)) {
9456 if (AI->getAlignment() >= PrefAlign)
9457 Align = AI->getAlignment();
9459 AI->setAlignment(PrefAlign);
9468 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9469 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9470 /// and it is more than the alignment of the ultimate object, see if we can
9471 /// increase the alignment of the ultimate object, making this check succeed.
9472 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9473 unsigned PrefAlign) {
9474 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9475 sizeof(PrefAlign) * CHAR_BIT;
9476 APInt Mask = APInt::getAllOnesValue(BitWidth);
9477 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9478 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9479 unsigned TrailZ = KnownZero.countTrailingOnes();
9480 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9482 if (PrefAlign > Align)
9483 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9485 // We don't need to make any adjustment.
9489 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9490 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9491 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9492 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9493 unsigned CopyAlign = MI->getAlignment();
9495 if (CopyAlign < MinAlign) {
9496 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9501 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9503 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9504 if (MemOpLength == 0) return 0;
9506 // Source and destination pointer types are always "i8*" for intrinsic. See
9507 // if the size is something we can handle with a single primitive load/store.
9508 // A single load+store correctly handles overlapping memory in the memmove
9510 unsigned Size = MemOpLength->getZExtValue();
9511 if (Size == 0) return MI; // Delete this mem transfer.
9513 if (Size > 8 || (Size&(Size-1)))
9514 return 0; // If not 1/2/4/8 bytes, exit.
9516 // Use an integer load+store unless we can find something better.
9518 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9520 // Memcpy forces the use of i8* for the source and destination. That means
9521 // that if you're using memcpy to move one double around, you'll get a cast
9522 // from double* to i8*. We'd much rather use a double load+store rather than
9523 // an i64 load+store, here because this improves the odds that the source or
9524 // dest address will be promotable. See if we can find a better type than the
9525 // integer datatype.
9526 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9527 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9528 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9529 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9530 // down through these levels if so.
9531 while (!SrcETy->isSingleValueType()) {
9532 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9533 if (STy->getNumElements() == 1)
9534 SrcETy = STy->getElementType(0);
9537 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9538 if (ATy->getNumElements() == 1)
9539 SrcETy = ATy->getElementType();
9546 if (SrcETy->isSingleValueType())
9547 NewPtrTy = PointerType::getUnqual(SrcETy);
9552 // If the memcpy/memmove provides better alignment info than we can
9554 SrcAlign = std::max(SrcAlign, CopyAlign);
9555 DstAlign = std::max(DstAlign, CopyAlign);
9557 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9558 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
9559 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9560 InsertNewInstBefore(L, *MI);
9561 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9563 // Set the size of the copy to 0, it will be deleted on the next iteration.
9564 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9568 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9569 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9570 if (MI->getAlignment() < Alignment) {
9571 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9576 // Extract the length and alignment and fill if they are constant.
9577 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9578 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9579 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9581 uint64_t Len = LenC->getZExtValue();
9582 Alignment = MI->getAlignment();
9584 // If the length is zero, this is a no-op
9585 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9587 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9588 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9589 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
9591 Value *Dest = MI->getDest();
9592 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
9594 // Alignment 0 is identity for alignment 1 for memset, but not store.
9595 if (Alignment == 0) Alignment = 1;
9597 // Extract the fill value and store.
9598 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9599 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9600 Dest, false, Alignment), *MI);
9602 // Set the size of the copy to 0, it will be deleted on the next iteration.
9603 MI->setLength(Constant::getNullValue(LenC->getType()));
9611 /// visitCallInst - CallInst simplification. This mostly only handles folding
9612 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9613 /// the heavy lifting.
9615 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9616 // If the caller function is nounwind, mark the call as nounwind, even if the
9618 if (CI.getParent()->getParent()->doesNotThrow() &&
9619 !CI.doesNotThrow()) {
9620 CI.setDoesNotThrow();
9624 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9625 if (!II) return visitCallSite(&CI);
9627 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9629 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9630 bool Changed = false;
9632 // memmove/cpy/set of zero bytes is a noop.
9633 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9634 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9636 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9637 if (CI->getZExtValue() == 1) {
9638 // Replace the instruction with just byte operations. We would
9639 // transform other cases to loads/stores, but we don't know if
9640 // alignment is sufficient.
9644 // If we have a memmove and the source operation is a constant global,
9645 // then the source and dest pointers can't alias, so we can change this
9646 // into a call to memcpy.
9647 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9648 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9649 if (GVSrc->isConstant()) {
9650 Module *M = CI.getParent()->getParent()->getParent();
9651 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9653 Tys[0] = CI.getOperand(3)->getType();
9655 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9659 // memmove(x,x,size) -> noop.
9660 if (MMI->getSource() == MMI->getDest())
9661 return EraseInstFromFunction(CI);
9664 // If we can determine a pointer alignment that is bigger than currently
9665 // set, update the alignment.
9666 if (isa<MemTransferInst>(MI)) {
9667 if (Instruction *I = SimplifyMemTransfer(MI))
9669 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9670 if (Instruction *I = SimplifyMemSet(MSI))
9674 if (Changed) return II;
9677 switch (II->getIntrinsicID()) {
9679 case Intrinsic::bswap:
9680 // bswap(bswap(x)) -> x
9681 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9682 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9683 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9685 case Intrinsic::ppc_altivec_lvx:
9686 case Intrinsic::ppc_altivec_lvxl:
9687 case Intrinsic::x86_sse_loadu_ps:
9688 case Intrinsic::x86_sse2_loadu_pd:
9689 case Intrinsic::x86_sse2_loadu_dq:
9690 // Turn PPC lvx -> load if the pointer is known aligned.
9691 // Turn X86 loadups -> load if the pointer is known aligned.
9692 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9693 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9694 PointerType::getUnqual(II->getType()));
9695 return new LoadInst(Ptr);
9698 case Intrinsic::ppc_altivec_stvx:
9699 case Intrinsic::ppc_altivec_stvxl:
9700 // Turn stvx -> store if the pointer is known aligned.
9701 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9702 const Type *OpPtrTy =
9703 PointerType::getUnqual(II->getOperand(1)->getType());
9704 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
9705 return new StoreInst(II->getOperand(1), Ptr);
9708 case Intrinsic::x86_sse_storeu_ps:
9709 case Intrinsic::x86_sse2_storeu_pd:
9710 case Intrinsic::x86_sse2_storeu_dq:
9711 // Turn X86 storeu -> store if the pointer is known aligned.
9712 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9713 const Type *OpPtrTy =
9714 PointerType::getUnqual(II->getOperand(2)->getType());
9715 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
9716 return new StoreInst(II->getOperand(2), Ptr);
9720 case Intrinsic::x86_sse_cvttss2si: {
9721 // These intrinsics only demands the 0th element of its input vector. If
9722 // we can simplify the input based on that, do so now.
9724 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9725 APInt DemandedElts(VWidth, 1);
9726 APInt UndefElts(VWidth, 0);
9727 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9729 II->setOperand(1, V);
9735 case Intrinsic::ppc_altivec_vperm:
9736 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9737 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9738 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9740 // Check that all of the elements are integer constants or undefs.
9741 bool AllEltsOk = true;
9742 for (unsigned i = 0; i != 16; ++i) {
9743 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9744 !isa<UndefValue>(Mask->getOperand(i))) {
9751 // Cast the input vectors to byte vectors.
9752 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9753 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
9754 Value *Result = UndefValue::get(Op0->getType());
9756 // Only extract each element once.
9757 Value *ExtractedElts[32];
9758 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9760 for (unsigned i = 0; i != 16; ++i) {
9761 if (isa<UndefValue>(Mask->getOperand(i)))
9763 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9764 Idx &= 31; // Match the hardware behavior.
9766 if (ExtractedElts[Idx] == 0) {
9767 ExtractedElts[Idx] =
9768 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9769 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9773 // Insert this value into the result vector.
9774 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9775 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9778 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9783 case Intrinsic::stackrestore: {
9784 // If the save is right next to the restore, remove the restore. This can
9785 // happen when variable allocas are DCE'd.
9786 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9787 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9788 BasicBlock::iterator BI = SS;
9790 return EraseInstFromFunction(CI);
9794 // Scan down this block to see if there is another stack restore in the
9795 // same block without an intervening call/alloca.
9796 BasicBlock::iterator BI = II;
9797 TerminatorInst *TI = II->getParent()->getTerminator();
9798 bool CannotRemove = false;
9799 for (++BI; &*BI != TI; ++BI) {
9800 if (isa<AllocaInst>(BI)) {
9801 CannotRemove = true;
9804 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9805 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9806 // If there is a stackrestore below this one, remove this one.
9807 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9808 return EraseInstFromFunction(CI);
9809 // Otherwise, ignore the intrinsic.
9811 // If we found a non-intrinsic call, we can't remove the stack
9813 CannotRemove = true;
9819 // If the stack restore is in a return/unwind block and if there are no
9820 // allocas or calls between the restore and the return, nuke the restore.
9821 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9822 return EraseInstFromFunction(CI);
9827 return visitCallSite(II);
9830 // InvokeInst simplification
9832 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9833 return visitCallSite(&II);
9836 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
9837 /// passed through the varargs area, we can eliminate the use of the cast.
9838 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9839 const CastInst * const CI,
9840 const TargetData * const TD,
9842 if (!CI->isLosslessCast())
9845 // The size of ByVal arguments is derived from the type, so we
9846 // can't change to a type with a different size. If the size were
9847 // passed explicitly we could avoid this check.
9848 if (!CS.paramHasAttr(ix, Attribute::ByVal))
9852 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9853 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9854 if (!SrcTy->isSized() || !DstTy->isSized())
9856 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
9861 // visitCallSite - Improvements for call and invoke instructions.
9863 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9864 bool Changed = false;
9866 // If the callee is a constexpr cast of a function, attempt to move the cast
9867 // to the arguments of the call/invoke.
9868 if (transformConstExprCastCall(CS)) return 0;
9870 Value *Callee = CS.getCalledValue();
9872 if (Function *CalleeF = dyn_cast<Function>(Callee))
9873 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9874 Instruction *OldCall = CS.getInstruction();
9875 // If the call and callee calling conventions don't match, this call must
9876 // be unreachable, as the call is undefined.
9877 new StoreInst(ConstantInt::getTrue(*Context),
9878 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
9880 if (!OldCall->use_empty())
9881 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9882 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9883 return EraseInstFromFunction(*OldCall);
9887 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9888 // This instruction is not reachable, just remove it. We insert a store to
9889 // undef so that we know that this code is not reachable, despite the fact
9890 // that we can't modify the CFG here.
9891 new StoreInst(ConstantInt::getTrue(*Context),
9892 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
9893 CS.getInstruction());
9895 if (!CS.getInstruction()->use_empty())
9896 CS.getInstruction()->
9897 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9899 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9900 // Don't break the CFG, insert a dummy cond branch.
9901 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9902 ConstantInt::getTrue(*Context), II);
9904 return EraseInstFromFunction(*CS.getInstruction());
9907 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9908 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9909 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9910 return transformCallThroughTrampoline(CS);
9912 const PointerType *PTy = cast<PointerType>(Callee->getType());
9913 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9914 if (FTy->isVarArg()) {
9915 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9916 // See if we can optimize any arguments passed through the varargs area of
9918 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9919 E = CS.arg_end(); I != E; ++I, ++ix) {
9920 CastInst *CI = dyn_cast<CastInst>(*I);
9921 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9922 *I = CI->getOperand(0);
9928 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
9929 // Inline asm calls cannot throw - mark them 'nounwind'.
9930 CS.setDoesNotThrow();
9934 return Changed ? CS.getInstruction() : 0;
9937 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
9938 // attempt to move the cast to the arguments of the call/invoke.
9940 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9941 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9942 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9943 if (CE->getOpcode() != Instruction::BitCast ||
9944 !isa<Function>(CE->getOperand(0)))
9946 Function *Callee = cast<Function>(CE->getOperand(0));
9947 Instruction *Caller = CS.getInstruction();
9948 const AttrListPtr &CallerPAL = CS.getAttributes();
9950 // Okay, this is a cast from a function to a different type. Unless doing so
9951 // would cause a type conversion of one of our arguments, change this call to
9952 // be a direct call with arguments casted to the appropriate types.
9954 const FunctionType *FT = Callee->getFunctionType();
9955 const Type *OldRetTy = Caller->getType();
9956 const Type *NewRetTy = FT->getReturnType();
9958 if (isa<StructType>(NewRetTy))
9959 return false; // TODO: Handle multiple return values.
9961 // Check to see if we are changing the return type...
9962 if (OldRetTy != NewRetTy) {
9963 if (Callee->isDeclaration() &&
9964 // Conversion is ok if changing from one pointer type to another or from
9965 // a pointer to an integer of the same size.
9966 !((isa<PointerType>(OldRetTy) || !TD ||
9967 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
9968 (isa<PointerType>(NewRetTy) || !TD ||
9969 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
9970 return false; // Cannot transform this return value.
9972 if (!Caller->use_empty() &&
9973 // void -> non-void is handled specially
9974 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
9975 return false; // Cannot transform this return value.
9977 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
9978 Attributes RAttrs = CallerPAL.getRetAttributes();
9979 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
9980 return false; // Attribute not compatible with transformed value.
9983 // If the callsite is an invoke instruction, and the return value is used by
9984 // a PHI node in a successor, we cannot change the return type of the call
9985 // because there is no place to put the cast instruction (without breaking
9986 // the critical edge). Bail out in this case.
9987 if (!Caller->use_empty())
9988 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9989 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9991 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9992 if (PN->getParent() == II->getNormalDest() ||
9993 PN->getParent() == II->getUnwindDest())
9997 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9998 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10000 CallSite::arg_iterator AI = CS.arg_begin();
10001 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10002 const Type *ParamTy = FT->getParamType(i);
10003 const Type *ActTy = (*AI)->getType();
10005 if (!CastInst::isCastable(ActTy, ParamTy))
10006 return false; // Cannot transform this parameter value.
10008 if (CallerPAL.getParamAttributes(i + 1)
10009 & Attribute::typeIncompatible(ParamTy))
10010 return false; // Attribute not compatible with transformed value.
10012 // Converting from one pointer type to another or between a pointer and an
10013 // integer of the same size is safe even if we do not have a body.
10014 bool isConvertible = ActTy == ParamTy ||
10015 (TD && ((isa<PointerType>(ParamTy) ||
10016 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10017 (isa<PointerType>(ActTy) ||
10018 ActTy == TD->getIntPtrType(Caller->getContext()))));
10019 if (Callee->isDeclaration() && !isConvertible) return false;
10022 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10023 Callee->isDeclaration())
10024 return false; // Do not delete arguments unless we have a function body.
10026 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10027 !CallerPAL.isEmpty())
10028 // In this case we have more arguments than the new function type, but we
10029 // won't be dropping them. Check that these extra arguments have attributes
10030 // that are compatible with being a vararg call argument.
10031 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10032 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10034 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10035 if (PAttrs & Attribute::VarArgsIncompatible)
10039 // Okay, we decided that this is a safe thing to do: go ahead and start
10040 // inserting cast instructions as necessary...
10041 std::vector<Value*> Args;
10042 Args.reserve(NumActualArgs);
10043 SmallVector<AttributeWithIndex, 8> attrVec;
10044 attrVec.reserve(NumCommonArgs);
10046 // Get any return attributes.
10047 Attributes RAttrs = CallerPAL.getRetAttributes();
10049 // If the return value is not being used, the type may not be compatible
10050 // with the existing attributes. Wipe out any problematic attributes.
10051 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10053 // Add the new return attributes.
10055 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10057 AI = CS.arg_begin();
10058 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10059 const Type *ParamTy = FT->getParamType(i);
10060 if ((*AI)->getType() == ParamTy) {
10061 Args.push_back(*AI);
10063 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10064 false, ParamTy, false);
10065 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10068 // Add any parameter attributes.
10069 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10070 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10073 // If the function takes more arguments than the call was taking, add them
10075 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10076 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10078 // If we are removing arguments to the function, emit an obnoxious warning.
10079 if (FT->getNumParams() < NumActualArgs) {
10080 if (!FT->isVarArg()) {
10081 errs() << "WARNING: While resolving call to function '"
10082 << Callee->getName() << "' arguments were dropped!\n";
10084 // Add all of the arguments in their promoted form to the arg list.
10085 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10086 const Type *PTy = getPromotedType((*AI)->getType());
10087 if (PTy != (*AI)->getType()) {
10088 // Must promote to pass through va_arg area!
10089 Instruction::CastOps opcode =
10090 CastInst::getCastOpcode(*AI, false, PTy, false);
10091 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10093 Args.push_back(*AI);
10096 // Add any parameter attributes.
10097 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10098 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10103 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10104 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10106 if (NewRetTy == Type::getVoidTy(*Context))
10107 Caller->setName(""); // Void type should not have a name.
10109 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10113 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10114 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10115 Args.begin(), Args.end(),
10116 Caller->getName(), Caller);
10117 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10118 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10120 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10121 Caller->getName(), Caller);
10122 CallInst *CI = cast<CallInst>(Caller);
10123 if (CI->isTailCall())
10124 cast<CallInst>(NC)->setTailCall();
10125 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10126 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10129 // Insert a cast of the return type as necessary.
10131 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10132 if (NV->getType() != Type::getVoidTy(*Context)) {
10133 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
10135 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10137 // If this is an invoke instruction, we should insert it after the first
10138 // non-phi, instruction in the normal successor block.
10139 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10140 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10141 InsertNewInstBefore(NC, *I);
10143 // Otherwise, it's a call, just insert cast right after the call instr
10144 InsertNewInstBefore(NC, *Caller);
10146 Worklist.AddUsersToWorkList(*Caller);
10148 NV = UndefValue::get(Caller->getType());
10152 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10153 Caller->replaceAllUsesWith(NV);
10154 Caller->eraseFromParent();
10155 Worklist.Remove(Caller);
10159 // transformCallThroughTrampoline - Turn a call to a function created by the
10160 // init_trampoline intrinsic into a direct call to the underlying function.
10162 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10163 Value *Callee = CS.getCalledValue();
10164 const PointerType *PTy = cast<PointerType>(Callee->getType());
10165 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10166 const AttrListPtr &Attrs = CS.getAttributes();
10168 // If the call already has the 'nest' attribute somewhere then give up -
10169 // otherwise 'nest' would occur twice after splicing in the chain.
10170 if (Attrs.hasAttrSomewhere(Attribute::Nest))
10173 IntrinsicInst *Tramp =
10174 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10176 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10177 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10178 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10180 const AttrListPtr &NestAttrs = NestF->getAttributes();
10181 if (!NestAttrs.isEmpty()) {
10182 unsigned NestIdx = 1;
10183 const Type *NestTy = 0;
10184 Attributes NestAttr = Attribute::None;
10186 // Look for a parameter marked with the 'nest' attribute.
10187 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10188 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10189 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10190 // Record the parameter type and any other attributes.
10192 NestAttr = NestAttrs.getParamAttributes(NestIdx);
10197 Instruction *Caller = CS.getInstruction();
10198 std::vector<Value*> NewArgs;
10199 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10201 SmallVector<AttributeWithIndex, 8> NewAttrs;
10202 NewAttrs.reserve(Attrs.getNumSlots() + 1);
10204 // Insert the nest argument into the call argument list, which may
10205 // mean appending it. Likewise for attributes.
10207 // Add any result attributes.
10208 if (Attributes Attr = Attrs.getRetAttributes())
10209 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10213 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10215 if (Idx == NestIdx) {
10216 // Add the chain argument and attributes.
10217 Value *NestVal = Tramp->getOperand(3);
10218 if (NestVal->getType() != NestTy)
10219 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10220 NewArgs.push_back(NestVal);
10221 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10227 // Add the original argument and attributes.
10228 NewArgs.push_back(*I);
10229 if (Attributes Attr = Attrs.getParamAttributes(Idx))
10231 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10237 // Add any function attributes.
10238 if (Attributes Attr = Attrs.getFnAttributes())
10239 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10241 // The trampoline may have been bitcast to a bogus type (FTy).
10242 // Handle this by synthesizing a new function type, equal to FTy
10243 // with the chain parameter inserted.
10245 std::vector<const Type*> NewTypes;
10246 NewTypes.reserve(FTy->getNumParams()+1);
10248 // Insert the chain's type into the list of parameter types, which may
10249 // mean appending it.
10252 FunctionType::param_iterator I = FTy->param_begin(),
10253 E = FTy->param_end();
10256 if (Idx == NestIdx)
10257 // Add the chain's type.
10258 NewTypes.push_back(NestTy);
10263 // Add the original type.
10264 NewTypes.push_back(*I);
10270 // Replace the trampoline call with a direct call. Let the generic
10271 // code sort out any function type mismatches.
10272 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
10274 Constant *NewCallee =
10275 NestF->getType() == PointerType::getUnqual(NewFTy) ?
10276 NestF : ConstantExpr::getBitCast(NestF,
10277 PointerType::getUnqual(NewFTy));
10278 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10281 Instruction *NewCaller;
10282 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10283 NewCaller = InvokeInst::Create(NewCallee,
10284 II->getNormalDest(), II->getUnwindDest(),
10285 NewArgs.begin(), NewArgs.end(),
10286 Caller->getName(), Caller);
10287 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10288 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10290 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10291 Caller->getName(), Caller);
10292 if (cast<CallInst>(Caller)->isTailCall())
10293 cast<CallInst>(NewCaller)->setTailCall();
10294 cast<CallInst>(NewCaller)->
10295 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10296 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10298 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10299 Caller->replaceAllUsesWith(NewCaller);
10300 Caller->eraseFromParent();
10301 Worklist.Remove(Caller);
10306 // Replace the trampoline call with a direct call. Since there is no 'nest'
10307 // parameter, there is no need to adjust the argument list. Let the generic
10308 // code sort out any function type mismatches.
10309 Constant *NewCallee =
10310 NestF->getType() == PTy ? NestF :
10311 ConstantExpr::getBitCast(NestF, PTy);
10312 CS.setCalledFunction(NewCallee);
10313 return CS.getInstruction();
10316 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10317 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10318 /// and a single binop.
10319 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10320 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10321 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10322 unsigned Opc = FirstInst->getOpcode();
10323 Value *LHSVal = FirstInst->getOperand(0);
10324 Value *RHSVal = FirstInst->getOperand(1);
10326 const Type *LHSType = LHSVal->getType();
10327 const Type *RHSType = RHSVal->getType();
10329 // Scan to see if all operands are the same opcode, all have one use, and all
10330 // kill their operands (i.e. the operands have one use).
10331 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10332 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10333 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10334 // Verify type of the LHS matches so we don't fold cmp's of different
10335 // types or GEP's with different index types.
10336 I->getOperand(0)->getType() != LHSType ||
10337 I->getOperand(1)->getType() != RHSType)
10340 // If they are CmpInst instructions, check their predicates
10341 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10342 if (cast<CmpInst>(I)->getPredicate() !=
10343 cast<CmpInst>(FirstInst)->getPredicate())
10346 // Keep track of which operand needs a phi node.
10347 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10348 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10351 // Otherwise, this is safe to transform!
10353 Value *InLHS = FirstInst->getOperand(0);
10354 Value *InRHS = FirstInst->getOperand(1);
10355 PHINode *NewLHS = 0, *NewRHS = 0;
10357 NewLHS = PHINode::Create(LHSType,
10358 FirstInst->getOperand(0)->getName() + ".pn");
10359 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10360 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10361 InsertNewInstBefore(NewLHS, PN);
10366 NewRHS = PHINode::Create(RHSType,
10367 FirstInst->getOperand(1)->getName() + ".pn");
10368 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10369 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10370 InsertNewInstBefore(NewRHS, PN);
10374 // Add all operands to the new PHIs.
10375 if (NewLHS || NewRHS) {
10376 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10377 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10379 Value *NewInLHS = InInst->getOperand(0);
10380 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10383 Value *NewInRHS = InInst->getOperand(1);
10384 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10389 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10390 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10391 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10392 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10396 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10397 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10399 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10400 FirstInst->op_end());
10401 // This is true if all GEP bases are allocas and if all indices into them are
10403 bool AllBasePointersAreAllocas = true;
10405 // Scan to see if all operands are the same opcode, all have one use, and all
10406 // kill their operands (i.e. the operands have one use).
10407 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10408 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10409 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10410 GEP->getNumOperands() != FirstInst->getNumOperands())
10413 // Keep track of whether or not all GEPs are of alloca pointers.
10414 if (AllBasePointersAreAllocas &&
10415 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10416 !GEP->hasAllConstantIndices()))
10417 AllBasePointersAreAllocas = false;
10419 // Compare the operand lists.
10420 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10421 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10424 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10425 // if one of the PHIs has a constant for the index. The index may be
10426 // substantially cheaper to compute for the constants, so making it a
10427 // variable index could pessimize the path. This also handles the case
10428 // for struct indices, which must always be constant.
10429 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10430 isa<ConstantInt>(GEP->getOperand(op)))
10433 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10435 FixedOperands[op] = 0; // Needs a PHI.
10439 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10440 // bother doing this transformation. At best, this will just save a bit of
10441 // offset calculation, but all the predecessors will have to materialize the
10442 // stack address into a register anyway. We'd actually rather *clone* the
10443 // load up into the predecessors so that we have a load of a gep of an alloca,
10444 // which can usually all be folded into the load.
10445 if (AllBasePointersAreAllocas)
10448 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10449 // that is variable.
10450 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10452 bool HasAnyPHIs = false;
10453 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10454 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10455 Value *FirstOp = FirstInst->getOperand(i);
10456 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10457 FirstOp->getName()+".pn");
10458 InsertNewInstBefore(NewPN, PN);
10460 NewPN->reserveOperandSpace(e);
10461 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10462 OperandPhis[i] = NewPN;
10463 FixedOperands[i] = NewPN;
10468 // Add all operands to the new PHIs.
10470 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10471 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10472 BasicBlock *InBB = PN.getIncomingBlock(i);
10474 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10475 if (PHINode *OpPhi = OperandPhis[op])
10476 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10480 Value *Base = FixedOperands[0];
10481 GetElementPtrInst *GEP =
10482 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10483 FixedOperands.end());
10484 if (cast<GEPOperator>(FirstInst)->isInBounds())
10485 cast<GEPOperator>(GEP)->setIsInBounds(true);
10490 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10491 /// sink the load out of the block that defines it. This means that it must be
10492 /// obvious the value of the load is not changed from the point of the load to
10493 /// the end of the block it is in.
10495 /// Finally, it is safe, but not profitable, to sink a load targetting a
10496 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
10498 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10499 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10501 for (++BBI; BBI != E; ++BBI)
10502 if (BBI->mayWriteToMemory())
10505 // Check for non-address taken alloca. If not address-taken already, it isn't
10506 // profitable to do this xform.
10507 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10508 bool isAddressTaken = false;
10509 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10511 if (isa<LoadInst>(UI)) continue;
10512 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10513 // If storing TO the alloca, then the address isn't taken.
10514 if (SI->getOperand(1) == AI) continue;
10516 isAddressTaken = true;
10520 if (!isAddressTaken && AI->isStaticAlloca())
10524 // If this load is a load from a GEP with a constant offset from an alloca,
10525 // then we don't want to sink it. In its present form, it will be
10526 // load [constant stack offset]. Sinking it will cause us to have to
10527 // materialize the stack addresses in each predecessor in a register only to
10528 // do a shared load from register in the successor.
10529 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10530 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10531 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10538 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10539 // operator and they all are only used by the PHI, PHI together their
10540 // inputs, and do the operation once, to the result of the PHI.
10541 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10542 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10544 // Scan the instruction, looking for input operations that can be folded away.
10545 // If all input operands to the phi are the same instruction (e.g. a cast from
10546 // the same type or "+42") we can pull the operation through the PHI, reducing
10547 // code size and simplifying code.
10548 Constant *ConstantOp = 0;
10549 const Type *CastSrcTy = 0;
10550 bool isVolatile = false;
10551 if (isa<CastInst>(FirstInst)) {
10552 CastSrcTy = FirstInst->getOperand(0)->getType();
10553 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10554 // Can fold binop, compare or shift here if the RHS is a constant,
10555 // otherwise call FoldPHIArgBinOpIntoPHI.
10556 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10557 if (ConstantOp == 0)
10558 return FoldPHIArgBinOpIntoPHI(PN);
10559 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10560 isVolatile = LI->isVolatile();
10561 // We can't sink the load if the loaded value could be modified between the
10562 // load and the PHI.
10563 if (LI->getParent() != PN.getIncomingBlock(0) ||
10564 !isSafeAndProfitableToSinkLoad(LI))
10567 // If the PHI is of volatile loads and the load block has multiple
10568 // successors, sinking it would remove a load of the volatile value from
10569 // the path through the other successor.
10571 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10574 } else if (isa<GetElementPtrInst>(FirstInst)) {
10575 return FoldPHIArgGEPIntoPHI(PN);
10577 return 0; // Cannot fold this operation.
10580 // Check to see if all arguments are the same operation.
10581 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10582 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10583 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10584 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10587 if (I->getOperand(0)->getType() != CastSrcTy)
10588 return 0; // Cast operation must match.
10589 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10590 // We can't sink the load if the loaded value could be modified between
10591 // the load and the PHI.
10592 if (LI->isVolatile() != isVolatile ||
10593 LI->getParent() != PN.getIncomingBlock(i) ||
10594 !isSafeAndProfitableToSinkLoad(LI))
10597 // If the PHI is of volatile loads and the load block has multiple
10598 // successors, sinking it would remove a load of the volatile value from
10599 // the path through the other successor.
10601 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10604 } else if (I->getOperand(1) != ConstantOp) {
10609 // Okay, they are all the same operation. Create a new PHI node of the
10610 // correct type, and PHI together all of the LHS's of the instructions.
10611 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10612 PN.getName()+".in");
10613 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10615 Value *InVal = FirstInst->getOperand(0);
10616 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10618 // Add all operands to the new PHI.
10619 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10620 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10621 if (NewInVal != InVal)
10623 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10628 // The new PHI unions all of the same values together. This is really
10629 // common, so we handle it intelligently here for compile-time speed.
10633 InsertNewInstBefore(NewPN, PN);
10637 // Insert and return the new operation.
10638 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10639 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10640 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10641 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10642 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10643 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10644 PhiVal, ConstantOp);
10645 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10647 // If this was a volatile load that we are merging, make sure to loop through
10648 // and mark all the input loads as non-volatile. If we don't do this, we will
10649 // insert a new volatile load and the old ones will not be deletable.
10651 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10652 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10654 return new LoadInst(PhiVal, "", isVolatile);
10657 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10659 static bool DeadPHICycle(PHINode *PN,
10660 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10661 if (PN->use_empty()) return true;
10662 if (!PN->hasOneUse()) return false;
10664 // Remember this node, and if we find the cycle, return.
10665 if (!PotentiallyDeadPHIs.insert(PN))
10668 // Don't scan crazily complex things.
10669 if (PotentiallyDeadPHIs.size() == 16)
10672 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10673 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10678 /// PHIsEqualValue - Return true if this phi node is always equal to
10679 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10680 /// z = some value; x = phi (y, z); y = phi (x, z)
10681 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10682 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10683 // See if we already saw this PHI node.
10684 if (!ValueEqualPHIs.insert(PN))
10687 // Don't scan crazily complex things.
10688 if (ValueEqualPHIs.size() == 16)
10691 // Scan the operands to see if they are either phi nodes or are equal to
10693 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10694 Value *Op = PN->getIncomingValue(i);
10695 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10696 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10698 } else if (Op != NonPhiInVal)
10706 // PHINode simplification
10708 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10709 // If LCSSA is around, don't mess with Phi nodes
10710 if (MustPreserveLCSSA) return 0;
10712 if (Value *V = PN.hasConstantValue())
10713 return ReplaceInstUsesWith(PN, V);
10715 // If all PHI operands are the same operation, pull them through the PHI,
10716 // reducing code size.
10717 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10718 isa<Instruction>(PN.getIncomingValue(1)) &&
10719 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10720 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10721 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10722 // than themselves more than once.
10723 PN.getIncomingValue(0)->hasOneUse())
10724 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10727 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10728 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10729 // PHI)... break the cycle.
10730 if (PN.hasOneUse()) {
10731 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10732 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10733 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10734 PotentiallyDeadPHIs.insert(&PN);
10735 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10736 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10739 // If this phi has a single use, and if that use just computes a value for
10740 // the next iteration of a loop, delete the phi. This occurs with unused
10741 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10742 // common case here is good because the only other things that catch this
10743 // are induction variable analysis (sometimes) and ADCE, which is only run
10745 if (PHIUser->hasOneUse() &&
10746 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10747 PHIUser->use_back() == &PN) {
10748 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10752 // We sometimes end up with phi cycles that non-obviously end up being the
10753 // same value, for example:
10754 // z = some value; x = phi (y, z); y = phi (x, z)
10755 // where the phi nodes don't necessarily need to be in the same block. Do a
10756 // quick check to see if the PHI node only contains a single non-phi value, if
10757 // so, scan to see if the phi cycle is actually equal to that value.
10759 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10760 // Scan for the first non-phi operand.
10761 while (InValNo != NumOperandVals &&
10762 isa<PHINode>(PN.getIncomingValue(InValNo)))
10765 if (InValNo != NumOperandVals) {
10766 Value *NonPhiInVal = PN.getOperand(InValNo);
10768 // Scan the rest of the operands to see if there are any conflicts, if so
10769 // there is no need to recursively scan other phis.
10770 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10771 Value *OpVal = PN.getIncomingValue(InValNo);
10772 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10776 // If we scanned over all operands, then we have one unique value plus
10777 // phi values. Scan PHI nodes to see if they all merge in each other or
10779 if (InValNo == NumOperandVals) {
10780 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10781 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10782 return ReplaceInstUsesWith(PN, NonPhiInVal);
10789 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10790 Value *PtrOp = GEP.getOperand(0);
10791 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
10792 if (GEP.getNumOperands() == 1)
10793 return ReplaceInstUsesWith(GEP, PtrOp);
10795 if (isa<UndefValue>(GEP.getOperand(0)))
10796 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10798 bool HasZeroPointerIndex = false;
10799 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10800 HasZeroPointerIndex = C->isNullValue();
10802 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10803 return ReplaceInstUsesWith(GEP, PtrOp);
10805 // Eliminate unneeded casts for indices.
10807 bool MadeChange = false;
10808 unsigned PtrSize = TD->getPointerSizeInBits();
10810 gep_type_iterator GTI = gep_type_begin(GEP);
10811 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10812 I != E; ++I, ++GTI) {
10813 if (!isa<SequentialType>(*GTI)) continue;
10815 // If we are using a wider index than needed for this platform, shrink it
10816 // to what we need. If narrower, sign-extend it to what we need. This
10817 // explicit cast can make subsequent optimizations more obvious.
10818 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
10819 if (OpBits == PtrSize)
10822 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
10825 if (MadeChange) return &GEP;
10828 // Combine Indices - If the source pointer to this getelementptr instruction
10829 // is a getelementptr instruction, combine the indices of the two
10830 // getelementptr instructions into a single instruction.
10832 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
10833 // Note that if our source is a gep chain itself that we wait for that
10834 // chain to be resolved before we perform this transformation. This
10835 // avoids us creating a TON of code in some cases.
10837 if (GetElementPtrInst *SrcGEP =
10838 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10839 if (SrcGEP->getNumOperands() == 2)
10840 return 0; // Wait until our source is folded to completion.
10842 SmallVector<Value*, 8> Indices;
10844 // Find out whether the last index in the source GEP is a sequential idx.
10845 bool EndsWithSequential = false;
10846 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10848 EndsWithSequential = !isa<StructType>(*I);
10850 // Can we combine the two pointer arithmetics offsets?
10851 if (EndsWithSequential) {
10852 // Replace: gep (gep %P, long B), long A, ...
10853 // With: T = long A+B; gep %P, T, ...
10856 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10857 Value *GO1 = GEP.getOperand(1);
10858 if (SO1 == Constant::getNullValue(SO1->getType())) {
10860 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10863 // If they aren't the same type, then the input hasn't been processed
10864 // by the loop above yet (which canonicalizes sequential index types to
10865 // intptr_t). Just avoid transforming this until the input has been
10867 if (SO1->getType() != GO1->getType())
10869 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10872 // Update the GEP in place if possible.
10873 if (Src->getNumOperands() == 2) {
10874 GEP.setOperand(0, Src->getOperand(0));
10875 GEP.setOperand(1, Sum);
10878 Indices.append(Src->op_begin()+1, Src->op_end()-1);
10879 Indices.push_back(Sum);
10880 Indices.append(GEP.op_begin()+2, GEP.op_end());
10881 } else if (isa<Constant>(*GEP.idx_begin()) &&
10882 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10883 Src->getNumOperands() != 1) {
10884 // Otherwise we can do the fold if the first index of the GEP is a zero
10885 Indices.append(Src->op_begin()+1, Src->op_end());
10886 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
10889 if (!Indices.empty()) {
10890 GetElementPtrInst *NewGEP =
10891 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
10892 Indices.end(), GEP.getName());
10893 if (cast<GEPOperator>(&GEP)->isInBounds() && Src->isInBounds())
10894 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10899 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
10900 if (Value *X = getBitCastOperand(PtrOp)) {
10901 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
10903 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
10904 // want to change the gep until the bitcasts are eliminated.
10905 if (getBitCastOperand(X)) {
10906 Worklist.AddValue(PtrOp);
10910 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10911 // into : GEP [10 x i8]* X, i32 0, ...
10913 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
10914 // into : GEP i8* X, ...
10916 // This occurs when the program declares an array extern like "int X[];"
10917 if (HasZeroPointerIndex) {
10918 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10919 const PointerType *XTy = cast<PointerType>(X->getType());
10920 if (const ArrayType *CATy =
10921 dyn_cast<ArrayType>(CPTy->getElementType())) {
10922 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
10923 if (CATy->getElementType() == XTy->getElementType()) {
10924 // -> GEP i8* X, ...
10925 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
10926 GetElementPtrInst *NewGEP =
10927 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
10929 if (cast<GEPOperator>(&GEP)->isInBounds())
10930 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10934 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
10935 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
10936 if (CATy->getElementType() == XATy->getElementType()) {
10937 // -> GEP [10 x i8]* X, i32 0, ...
10938 // At this point, we know that the cast source type is a pointer
10939 // to an array of the same type as the destination pointer
10940 // array. Because the array type is never stepped over (there
10941 // is a leading zero) we can fold the cast into this GEP.
10942 GEP.setOperand(0, X);
10947 } else if (GEP.getNumOperands() == 2) {
10948 // Transform things like:
10949 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10950 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
10951 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10952 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10953 if (TD && isa<ArrayType>(SrcElTy) &&
10954 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10955 TD->getTypeAllocSize(ResElTy)) {
10957 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
10958 Idx[1] = GEP.getOperand(1);
10960 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
10961 if (cast<GEPOperator>(&GEP)->isInBounds())
10962 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
10963 // V and GEP are both pointer types --> BitCast
10964 return new BitCastInst(NewGEP, GEP.getType());
10967 // Transform things like:
10968 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
10969 // (where tmp = 8*tmp2) into:
10970 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
10972 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
10973 uint64_t ArrayEltSize =
10974 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
10976 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10977 // allow either a mul, shift, or constant here.
10979 ConstantInt *Scale = 0;
10980 if (ArrayEltSize == 1) {
10981 NewIdx = GEP.getOperand(1);
10982 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
10983 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10984 NewIdx = ConstantInt::get(CI->getType(), 1);
10986 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10987 if (Inst->getOpcode() == Instruction::Shl &&
10988 isa<ConstantInt>(Inst->getOperand(1))) {
10989 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10990 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10991 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
10993 NewIdx = Inst->getOperand(0);
10994 } else if (Inst->getOpcode() == Instruction::Mul &&
10995 isa<ConstantInt>(Inst->getOperand(1))) {
10996 Scale = cast<ConstantInt>(Inst->getOperand(1));
10997 NewIdx = Inst->getOperand(0);
11001 // If the index will be to exactly the right offset with the scale taken
11002 // out, perform the transformation. Note, we don't know whether Scale is
11003 // signed or not. We'll use unsigned version of division/modulo
11004 // operation after making sure Scale doesn't have the sign bit set.
11005 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11006 Scale->getZExtValue() % ArrayEltSize == 0) {
11007 Scale = ConstantInt::get(Scale->getType(),
11008 Scale->getZExtValue() / ArrayEltSize);
11009 if (Scale->getZExtValue() != 1) {
11010 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11012 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
11015 // Insert the new GEP instruction.
11017 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11019 Value *NewGEP = Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11020 if (cast<GEPOperator>(&GEP)->isInBounds())
11021 cast<GEPOperator>(NewGEP)->setIsInBounds(true);
11022 // The NewGEP must be pointer typed, so must the old one -> BitCast
11023 return new BitCastInst(NewGEP, GEP.getType());
11029 /// See if we can simplify:
11030 /// X = bitcast A* to B*
11031 /// Y = gep X, <...constant indices...>
11032 /// into a gep of the original struct. This is important for SROA and alias
11033 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
11034 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11036 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11037 // Determine how much the GEP moves the pointer. We are guaranteed to get
11038 // a constant back from EmitGEPOffset.
11039 ConstantInt *OffsetV =
11040 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11041 int64_t Offset = OffsetV->getSExtValue();
11043 // If this GEP instruction doesn't move the pointer, just replace the GEP
11044 // with a bitcast of the real input to the dest type.
11046 // If the bitcast is of an allocation, and the allocation will be
11047 // converted to match the type of the cast, don't touch this.
11048 if (isa<AllocationInst>(BCI->getOperand(0))) {
11049 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11050 if (Instruction *I = visitBitCast(*BCI)) {
11053 BCI->getParent()->getInstList().insert(BCI, I);
11054 ReplaceInstUsesWith(*BCI, I);
11059 return new BitCastInst(BCI->getOperand(0), GEP.getType());
11062 // Otherwise, if the offset is non-zero, we need to find out if there is a
11063 // field at Offset in 'A's type. If so, we can pull the cast through the
11065 SmallVector<Value*, 8> NewIndices;
11067 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11068 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11069 Value *NGEP = Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11071 if (cast<GEPOperator>(&GEP)->isInBounds())
11072 cast<GEPOperator>(NGEP)->setIsInBounds(true);
11074 if (NGEP->getType() == GEP.getType())
11075 return ReplaceInstUsesWith(GEP, NGEP);
11076 NGEP->takeName(&GEP);
11077 return new BitCastInst(NGEP, GEP.getType());
11085 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11086 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11087 if (AI.isArrayAllocation()) { // Check C != 1
11088 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11089 const Type *NewTy =
11090 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11091 AllocationInst *New = 0;
11093 // Create and insert the replacement instruction...
11094 if (isa<MallocInst>(AI))
11095 New = Builder->CreateMalloc(NewTy, 0, AI.getName());
11097 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11098 New = Builder->CreateAlloca(NewTy, 0, AI.getName());
11100 New->setAlignment(AI.getAlignment());
11102 // Scan to the end of the allocation instructions, to skip over a block of
11103 // allocas if possible...also skip interleaved debug info
11105 BasicBlock::iterator It = New;
11106 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11108 // Now that I is pointing to the first non-allocation-inst in the block,
11109 // insert our getelementptr instruction...
11111 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11115 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11116 New->getName()+".sub", It);
11117 cast<GEPOperator>(V)->setIsInBounds(true);
11119 // Now make everything use the getelementptr instead of the original
11121 return ReplaceInstUsesWith(AI, V);
11122 } else if (isa<UndefValue>(AI.getArraySize())) {
11123 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11127 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11128 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11129 // Note that we only do this for alloca's, because malloc should allocate
11130 // and return a unique pointer, even for a zero byte allocation.
11131 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11132 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11134 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11135 if (AI.getAlignment() == 0)
11136 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11142 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11143 Value *Op = FI.getOperand(0);
11145 // free undef -> unreachable.
11146 if (isa<UndefValue>(Op)) {
11147 // Insert a new store to null because we cannot modify the CFG here.
11148 new StoreInst(ConstantInt::getTrue(*Context),
11149 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
11150 return EraseInstFromFunction(FI);
11153 // If we have 'free null' delete the instruction. This can happen in stl code
11154 // when lots of inlining happens.
11155 if (isa<ConstantPointerNull>(Op))
11156 return EraseInstFromFunction(FI);
11158 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11159 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11160 FI.setOperand(0, CI->getOperand(0));
11164 // Change free (gep X, 0,0,0,0) into free(X)
11165 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11166 if (GEPI->hasAllZeroIndices()) {
11167 Worklist.Add(GEPI);
11168 FI.setOperand(0, GEPI->getOperand(0));
11173 // Change free(malloc) into nothing, if the malloc has a single use.
11174 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11175 if (MI->hasOneUse()) {
11176 EraseInstFromFunction(FI);
11177 return EraseInstFromFunction(*MI);
11184 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11185 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11186 const TargetData *TD) {
11187 User *CI = cast<User>(LI.getOperand(0));
11188 Value *CastOp = CI->getOperand(0);
11189 LLVMContext *Context = IC.getContext();
11192 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11193 // Instead of loading constant c string, use corresponding integer value
11194 // directly if string length is small enough.
11196 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11197 unsigned len = Str.length();
11198 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11199 unsigned numBits = Ty->getPrimitiveSizeInBits();
11200 // Replace LI with immediate integer store.
11201 if ((numBits >> 3) == len + 1) {
11202 APInt StrVal(numBits, 0);
11203 APInt SingleChar(numBits, 0);
11204 if (TD->isLittleEndian()) {
11205 for (signed i = len-1; i >= 0; i--) {
11206 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11207 StrVal = (StrVal << 8) | SingleChar;
11210 for (unsigned i = 0; i < len; i++) {
11211 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11212 StrVal = (StrVal << 8) | SingleChar;
11214 // Append NULL at the end.
11216 StrVal = (StrVal << 8) | SingleChar;
11218 Value *NL = ConstantInt::get(*Context, StrVal);
11219 return IC.ReplaceInstUsesWith(LI, NL);
11225 const PointerType *DestTy = cast<PointerType>(CI->getType());
11226 const Type *DestPTy = DestTy->getElementType();
11227 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11229 // If the address spaces don't match, don't eliminate the cast.
11230 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11233 const Type *SrcPTy = SrcTy->getElementType();
11235 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11236 isa<VectorType>(DestPTy)) {
11237 // If the source is an array, the code below will not succeed. Check to
11238 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11240 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11241 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11242 if (ASrcTy->getNumElements() != 0) {
11244 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
11245 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11246 SrcTy = cast<PointerType>(CastOp->getType());
11247 SrcPTy = SrcTy->getElementType();
11250 if (IC.getTargetData() &&
11251 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
11252 isa<VectorType>(SrcPTy)) &&
11253 // Do not allow turning this into a load of an integer, which is then
11254 // casted to a pointer, this pessimizes pointer analysis a lot.
11255 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11256 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11257 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11259 // Okay, we are casting from one integer or pointer type to another of
11260 // the same size. Instead of casting the pointer before the load, cast
11261 // the result of the loaded value.
11263 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
11264 // Now cast the result of the load.
11265 return new BitCastInst(NewLoad, LI.getType());
11272 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11273 Value *Op = LI.getOperand(0);
11275 // Attempt to improve the alignment.
11277 unsigned KnownAlign =
11278 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11280 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11281 LI.getAlignment()))
11282 LI.setAlignment(KnownAlign);
11285 // load (cast X) --> cast (load X) iff safe.
11286 if (isa<CastInst>(Op))
11287 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11290 // None of the following transforms are legal for volatile loads.
11291 if (LI.isVolatile()) return 0;
11293 // Do really simple store-to-load forwarding and load CSE, to catch cases
11294 // where there are several consequtive memory accesses to the same location,
11295 // separated by a few arithmetic operations.
11296 BasicBlock::iterator BBI = &LI;
11297 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11298 return ReplaceInstUsesWith(LI, AvailableVal);
11300 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11301 const Value *GEPI0 = GEPI->getOperand(0);
11302 // TODO: Consider a target hook for valid address spaces for this xform.
11303 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
11304 // Insert a new store to null instruction before the load to indicate
11305 // that this code is not reachable. We do this instead of inserting
11306 // an unreachable instruction directly because we cannot modify the
11308 new StoreInst(UndefValue::get(LI.getType()),
11309 Constant::getNullValue(Op->getType()), &LI);
11310 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11314 if (Constant *C = dyn_cast<Constant>(Op)) {
11315 // load null/undef -> undef
11316 // TODO: Consider a target hook for valid address spaces for this xform.
11317 if (isa<UndefValue>(C) ||
11318 (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
11319 // Insert a new store to null instruction before the load to indicate that
11320 // this code is not reachable. We do this instead of inserting an
11321 // unreachable instruction directly because we cannot modify the CFG.
11322 new StoreInst(UndefValue::get(LI.getType()),
11323 Constant::getNullValue(Op->getType()), &LI);
11324 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11327 // Instcombine load (constant global) into the value loaded.
11328 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11329 if (GV->isConstant() && GV->hasDefinitiveInitializer())
11330 return ReplaceInstUsesWith(LI, GV->getInitializer());
11332 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11333 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11334 if (CE->getOpcode() == Instruction::GetElementPtr) {
11335 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11336 if (GV->isConstant() && GV->hasDefinitiveInitializer())
11338 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
11340 return ReplaceInstUsesWith(LI, V);
11341 if (CE->getOperand(0)->isNullValue()) {
11342 // Insert a new store to null instruction before the load to indicate
11343 // that this code is not reachable. We do this instead of inserting
11344 // an unreachable instruction directly because we cannot modify the
11346 new StoreInst(UndefValue::get(LI.getType()),
11347 Constant::getNullValue(Op->getType()), &LI);
11348 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11351 } else if (CE->isCast()) {
11352 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11358 // If this load comes from anywhere in a constant global, and if the global
11359 // is all undef or zero, we know what it loads.
11360 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11361 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11362 if (GV->getInitializer()->isNullValue())
11363 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11364 else if (isa<UndefValue>(GV->getInitializer()))
11365 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11369 if (Op->hasOneUse()) {
11370 // Change select and PHI nodes to select values instead of addresses: this
11371 // helps alias analysis out a lot, allows many others simplifications, and
11372 // exposes redundancy in the code.
11374 // Note that we cannot do the transformation unless we know that the
11375 // introduced loads cannot trap! Something like this is valid as long as
11376 // the condition is always false: load (select bool %C, int* null, int* %G),
11377 // but it would not be valid if we transformed it to load from null
11378 // unconditionally.
11380 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11381 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11382 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11383 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11384 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11385 SI->getOperand(1)->getName()+".val");
11386 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11387 SI->getOperand(2)->getName()+".val");
11388 return SelectInst::Create(SI->getCondition(), V1, V2);
11391 // load (select (cond, null, P)) -> load P
11392 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11393 if (C->isNullValue()) {
11394 LI.setOperand(0, SI->getOperand(2));
11398 // load (select (cond, P, null)) -> load P
11399 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11400 if (C->isNullValue()) {
11401 LI.setOperand(0, SI->getOperand(1));
11409 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11410 /// when possible. This makes it generally easy to do alias analysis and/or
11411 /// SROA/mem2reg of the memory object.
11412 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11413 User *CI = cast<User>(SI.getOperand(1));
11414 Value *CastOp = CI->getOperand(0);
11416 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11417 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11418 if (SrcTy == 0) return 0;
11420 const Type *SrcPTy = SrcTy->getElementType();
11422 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11425 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11426 /// to its first element. This allows us to handle things like:
11427 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11428 /// on 32-bit hosts.
11429 SmallVector<Value*, 4> NewGEPIndices;
11431 // If the source is an array, the code below will not succeed. Check to
11432 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11434 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11435 // Index through pointer.
11436 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11437 NewGEPIndices.push_back(Zero);
11440 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11441 if (!STy->getNumElements()) /* Struct can be empty {} */
11443 NewGEPIndices.push_back(Zero);
11444 SrcPTy = STy->getElementType(0);
11445 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11446 NewGEPIndices.push_back(Zero);
11447 SrcPTy = ATy->getElementType();
11453 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11456 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11459 // If the pointers point into different address spaces or if they point to
11460 // values with different sizes, we can't do the transformation.
11461 if (!IC.getTargetData() ||
11462 SrcTy->getAddressSpace() !=
11463 cast<PointerType>(CI->getType())->getAddressSpace() ||
11464 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11465 IC.getTargetData()->getTypeSizeInBits(DestPTy))
11468 // Okay, we are casting from one integer or pointer type to another of
11469 // the same size. Instead of casting the pointer before
11470 // the store, cast the value to be stored.
11472 Value *SIOp0 = SI.getOperand(0);
11473 Instruction::CastOps opcode = Instruction::BitCast;
11474 const Type* CastSrcTy = SIOp0->getType();
11475 const Type* CastDstTy = SrcPTy;
11476 if (isa<PointerType>(CastDstTy)) {
11477 if (CastSrcTy->isInteger())
11478 opcode = Instruction::IntToPtr;
11479 } else if (isa<IntegerType>(CastDstTy)) {
11480 if (isa<PointerType>(SIOp0->getType()))
11481 opcode = Instruction::PtrToInt;
11484 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11485 // emit a GEP to index into its first field.
11486 if (!NewGEPIndices.empty()) {
11487 CastOp = IC.Builder->CreateGEP(CastOp, NewGEPIndices.begin(),
11488 NewGEPIndices.end());
11489 cast<GEPOperator>(CastOp)->setIsInBounds(true);
11492 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11493 SIOp0->getName()+".c");
11494 return new StoreInst(NewCast, CastOp);
11497 /// equivalentAddressValues - Test if A and B will obviously have the same
11498 /// value. This includes recognizing that %t0 and %t1 will have the same
11499 /// value in code like this:
11500 /// %t0 = getelementptr \@a, 0, 3
11501 /// store i32 0, i32* %t0
11502 /// %t1 = getelementptr \@a, 0, 3
11503 /// %t2 = load i32* %t1
11505 static bool equivalentAddressValues(Value *A, Value *B) {
11506 // Test if the values are trivially equivalent.
11507 if (A == B) return true;
11509 // Test if the values come form identical arithmetic instructions.
11510 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11511 // its only used to compare two uses within the same basic block, which
11512 // means that they'll always either have the same value or one of them
11513 // will have an undefined value.
11514 if (isa<BinaryOperator>(A) ||
11515 isa<CastInst>(A) ||
11517 isa<GetElementPtrInst>(A))
11518 if (Instruction *BI = dyn_cast<Instruction>(B))
11519 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
11522 // Otherwise they may not be equivalent.
11526 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11527 // return the llvm.dbg.declare.
11528 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11529 if (!V->hasNUses(2))
11531 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11533 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11535 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11536 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11543 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11544 Value *Val = SI.getOperand(0);
11545 Value *Ptr = SI.getOperand(1);
11547 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11548 EraseInstFromFunction(SI);
11553 // If the RHS is an alloca with a single use, zapify the store, making the
11555 // If the RHS is an alloca with a two uses, the other one being a
11556 // llvm.dbg.declare, zapify the store and the declare, making the
11557 // alloca dead. We must do this to prevent declare's from affecting
11559 if (!SI.isVolatile()) {
11560 if (Ptr->hasOneUse()) {
11561 if (isa<AllocaInst>(Ptr)) {
11562 EraseInstFromFunction(SI);
11566 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11567 if (isa<AllocaInst>(GEP->getOperand(0))) {
11568 if (GEP->getOperand(0)->hasOneUse()) {
11569 EraseInstFromFunction(SI);
11573 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11574 EraseInstFromFunction(*DI);
11575 EraseInstFromFunction(SI);
11582 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11583 EraseInstFromFunction(*DI);
11584 EraseInstFromFunction(SI);
11590 // Attempt to improve the alignment.
11592 unsigned KnownAlign =
11593 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11595 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11596 SI.getAlignment()))
11597 SI.setAlignment(KnownAlign);
11600 // Do really simple DSE, to catch cases where there are several consecutive
11601 // stores to the same location, separated by a few arithmetic operations. This
11602 // situation often occurs with bitfield accesses.
11603 BasicBlock::iterator BBI = &SI;
11604 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11607 // Don't count debug info directives, lest they affect codegen,
11608 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11609 // It is necessary for correctness to skip those that feed into a
11610 // llvm.dbg.declare, as these are not present when debugging is off.
11611 if (isa<DbgInfoIntrinsic>(BBI) ||
11612 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11617 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11618 // Prev store isn't volatile, and stores to the same location?
11619 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11620 SI.getOperand(1))) {
11623 EraseInstFromFunction(*PrevSI);
11629 // If this is a load, we have to stop. However, if the loaded value is from
11630 // the pointer we're loading and is producing the pointer we're storing,
11631 // then *this* store is dead (X = load P; store X -> P).
11632 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11633 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11634 !SI.isVolatile()) {
11635 EraseInstFromFunction(SI);
11639 // Otherwise, this is a load from some other location. Stores before it
11640 // may not be dead.
11644 // Don't skip over loads or things that can modify memory.
11645 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11650 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11652 // store X, null -> turns into 'unreachable' in SimplifyCFG
11653 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
11654 if (!isa<UndefValue>(Val)) {
11655 SI.setOperand(0, UndefValue::get(Val->getType()));
11656 if (Instruction *U = dyn_cast<Instruction>(Val))
11657 Worklist.Add(U); // Dropped a use.
11660 return 0; // Do not modify these!
11663 // store undef, Ptr -> noop
11664 if (isa<UndefValue>(Val)) {
11665 EraseInstFromFunction(SI);
11670 // If the pointer destination is a cast, see if we can fold the cast into the
11672 if (isa<CastInst>(Ptr))
11673 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11675 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11677 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11681 // If this store is the last instruction in the basic block (possibly
11682 // excepting debug info instructions and the pointer bitcasts that feed
11683 // into them), and if the block ends with an unconditional branch, try
11684 // to move it to the successor block.
11688 } while (isa<DbgInfoIntrinsic>(BBI) ||
11689 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11690 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11691 if (BI->isUnconditional())
11692 if (SimplifyStoreAtEndOfBlock(SI))
11693 return 0; // xform done!
11698 /// SimplifyStoreAtEndOfBlock - Turn things like:
11699 /// if () { *P = v1; } else { *P = v2 }
11700 /// into a phi node with a store in the successor.
11702 /// Simplify things like:
11703 /// *P = v1; if () { *P = v2; }
11704 /// into a phi node with a store in the successor.
11706 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11707 BasicBlock *StoreBB = SI.getParent();
11709 // Check to see if the successor block has exactly two incoming edges. If
11710 // so, see if the other predecessor contains a store to the same location.
11711 // if so, insert a PHI node (if needed) and move the stores down.
11712 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11714 // Determine whether Dest has exactly two predecessors and, if so, compute
11715 // the other predecessor.
11716 pred_iterator PI = pred_begin(DestBB);
11717 BasicBlock *OtherBB = 0;
11718 if (*PI != StoreBB)
11721 if (PI == pred_end(DestBB))
11724 if (*PI != StoreBB) {
11729 if (++PI != pred_end(DestBB))
11732 // Bail out if all the relevant blocks aren't distinct (this can happen,
11733 // for example, if SI is in an infinite loop)
11734 if (StoreBB == DestBB || OtherBB == DestBB)
11737 // Verify that the other block ends in a branch and is not otherwise empty.
11738 BasicBlock::iterator BBI = OtherBB->getTerminator();
11739 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11740 if (!OtherBr || BBI == OtherBB->begin())
11743 // If the other block ends in an unconditional branch, check for the 'if then
11744 // else' case. there is an instruction before the branch.
11745 StoreInst *OtherStore = 0;
11746 if (OtherBr->isUnconditional()) {
11748 // Skip over debugging info.
11749 while (isa<DbgInfoIntrinsic>(BBI) ||
11750 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11751 if (BBI==OtherBB->begin())
11755 // If this isn't a store, or isn't a store to the same location, bail out.
11756 OtherStore = dyn_cast<StoreInst>(BBI);
11757 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11760 // Otherwise, the other block ended with a conditional branch. If one of the
11761 // destinations is StoreBB, then we have the if/then case.
11762 if (OtherBr->getSuccessor(0) != StoreBB &&
11763 OtherBr->getSuccessor(1) != StoreBB)
11766 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11767 // if/then triangle. See if there is a store to the same ptr as SI that
11768 // lives in OtherBB.
11770 // Check to see if we find the matching store.
11771 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11772 if (OtherStore->getOperand(1) != SI.getOperand(1))
11776 // If we find something that may be using or overwriting the stored
11777 // value, or if we run out of instructions, we can't do the xform.
11778 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11779 BBI == OtherBB->begin())
11783 // In order to eliminate the store in OtherBr, we have to
11784 // make sure nothing reads or overwrites the stored value in
11786 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11787 // FIXME: This should really be AA driven.
11788 if (I->mayReadFromMemory() || I->mayWriteToMemory())
11793 // Insert a PHI node now if we need it.
11794 Value *MergedVal = OtherStore->getOperand(0);
11795 if (MergedVal != SI.getOperand(0)) {
11796 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11797 PN->reserveOperandSpace(2);
11798 PN->addIncoming(SI.getOperand(0), SI.getParent());
11799 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11800 MergedVal = InsertNewInstBefore(PN, DestBB->front());
11803 // Advance to a place where it is safe to insert the new store and
11805 BBI = DestBB->getFirstNonPHI();
11806 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11807 OtherStore->isVolatile()), *BBI);
11809 // Nuke the old stores.
11810 EraseInstFromFunction(SI);
11811 EraseInstFromFunction(*OtherStore);
11817 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11818 // Change br (not X), label True, label False to: br X, label False, True
11820 BasicBlock *TrueDest;
11821 BasicBlock *FalseDest;
11822 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11823 !isa<Constant>(X)) {
11824 // Swap Destinations and condition...
11825 BI.setCondition(X);
11826 BI.setSuccessor(0, FalseDest);
11827 BI.setSuccessor(1, TrueDest);
11831 // Cannonicalize fcmp_one -> fcmp_oeq
11832 FCmpInst::Predicate FPred; Value *Y;
11833 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11834 TrueDest, FalseDest)) &&
11835 BI.getCondition()->hasOneUse())
11836 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11837 FPred == FCmpInst::FCMP_OGE) {
11838 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11839 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11841 // Swap Destinations and condition.
11842 BI.setSuccessor(0, FalseDest);
11843 BI.setSuccessor(1, TrueDest);
11844 Worklist.Add(Cond);
11848 // Cannonicalize icmp_ne -> icmp_eq
11849 ICmpInst::Predicate IPred;
11850 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11851 TrueDest, FalseDest)) &&
11852 BI.getCondition()->hasOneUse())
11853 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11854 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11855 IPred == ICmpInst::ICMP_SGE) {
11856 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11857 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11858 // Swap Destinations and condition.
11859 BI.setSuccessor(0, FalseDest);
11860 BI.setSuccessor(1, TrueDest);
11861 Worklist.Add(Cond);
11868 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11869 Value *Cond = SI.getCondition();
11870 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11871 if (I->getOpcode() == Instruction::Add)
11872 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11873 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11874 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11876 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11878 SI.setOperand(0, I->getOperand(0));
11886 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11887 Value *Agg = EV.getAggregateOperand();
11889 if (!EV.hasIndices())
11890 return ReplaceInstUsesWith(EV, Agg);
11892 if (Constant *C = dyn_cast<Constant>(Agg)) {
11893 if (isa<UndefValue>(C))
11894 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11896 if (isa<ConstantAggregateZero>(C))
11897 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11899 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11900 // Extract the element indexed by the first index out of the constant
11901 Value *V = C->getOperand(*EV.idx_begin());
11902 if (EV.getNumIndices() > 1)
11903 // Extract the remaining indices out of the constant indexed by the
11905 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11907 return ReplaceInstUsesWith(EV, V);
11909 return 0; // Can't handle other constants
11911 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11912 // We're extracting from an insertvalue instruction, compare the indices
11913 const unsigned *exti, *exte, *insi, *inse;
11914 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11915 exte = EV.idx_end(), inse = IV->idx_end();
11916 exti != exte && insi != inse;
11918 if (*insi != *exti)
11919 // The insert and extract both reference distinctly different elements.
11920 // This means the extract is not influenced by the insert, and we can
11921 // replace the aggregate operand of the extract with the aggregate
11922 // operand of the insert. i.e., replace
11923 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11924 // %E = extractvalue { i32, { i32 } } %I, 0
11926 // %E = extractvalue { i32, { i32 } } %A, 0
11927 return ExtractValueInst::Create(IV->getAggregateOperand(),
11928 EV.idx_begin(), EV.idx_end());
11930 if (exti == exte && insi == inse)
11931 // Both iterators are at the end: Index lists are identical. Replace
11932 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11933 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11935 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11936 if (exti == exte) {
11937 // The extract list is a prefix of the insert list. i.e. replace
11938 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11939 // %E = extractvalue { i32, { i32 } } %I, 1
11941 // %X = extractvalue { i32, { i32 } } %A, 1
11942 // %E = insertvalue { i32 } %X, i32 42, 0
11943 // by switching the order of the insert and extract (though the
11944 // insertvalue should be left in, since it may have other uses).
11945 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
11946 EV.idx_begin(), EV.idx_end());
11947 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11951 // The insert list is a prefix of the extract list
11952 // We can simply remove the common indices from the extract and make it
11953 // operate on the inserted value instead of the insertvalue result.
11955 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11956 // %E = extractvalue { i32, { i32 } } %I, 1, 0
11958 // %E extractvalue { i32 } { i32 42 }, 0
11959 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
11962 // Can't simplify extracts from other values. Note that nested extracts are
11963 // already simplified implicitely by the above (extract ( extract (insert) )
11964 // will be translated into extract ( insert ( extract ) ) first and then just
11965 // the value inserted, if appropriate).
11969 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11970 /// is to leave as a vector operation.
11971 static bool CheapToScalarize(Value *V, bool isConstant) {
11972 if (isa<ConstantAggregateZero>(V))
11974 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11975 if (isConstant) return true;
11976 // If all elts are the same, we can extract.
11977 Constant *Op0 = C->getOperand(0);
11978 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11979 if (C->getOperand(i) != Op0)
11983 Instruction *I = dyn_cast<Instruction>(V);
11984 if (!I) return false;
11986 // Insert element gets simplified to the inserted element or is deleted if
11987 // this is constant idx extract element and its a constant idx insertelt.
11988 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11989 isa<ConstantInt>(I->getOperand(2)))
11991 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11993 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11994 if (BO->hasOneUse() &&
11995 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11996 CheapToScalarize(BO->getOperand(1), isConstant)))
11998 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11999 if (CI->hasOneUse() &&
12000 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12001 CheapToScalarize(CI->getOperand(1), isConstant)))
12007 /// Read and decode a shufflevector mask.
12009 /// It turns undef elements into values that are larger than the number of
12010 /// elements in the input.
12011 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12012 unsigned NElts = SVI->getType()->getNumElements();
12013 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12014 return std::vector<unsigned>(NElts, 0);
12015 if (isa<UndefValue>(SVI->getOperand(2)))
12016 return std::vector<unsigned>(NElts, 2*NElts);
12018 std::vector<unsigned> Result;
12019 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12020 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12021 if (isa<UndefValue>(*i))
12022 Result.push_back(NElts*2); // undef -> 8
12024 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12028 /// FindScalarElement - Given a vector and an element number, see if the scalar
12029 /// value is already around as a register, for example if it were inserted then
12030 /// extracted from the vector.
12031 static Value *FindScalarElement(Value *V, unsigned EltNo,
12032 LLVMContext *Context) {
12033 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12034 const VectorType *PTy = cast<VectorType>(V->getType());
12035 unsigned Width = PTy->getNumElements();
12036 if (EltNo >= Width) // Out of range access.
12037 return UndefValue::get(PTy->getElementType());
12039 if (isa<UndefValue>(V))
12040 return UndefValue::get(PTy->getElementType());
12041 else if (isa<ConstantAggregateZero>(V))
12042 return Constant::getNullValue(PTy->getElementType());
12043 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12044 return CP->getOperand(EltNo);
12045 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12046 // If this is an insert to a variable element, we don't know what it is.
12047 if (!isa<ConstantInt>(III->getOperand(2)))
12049 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12051 // If this is an insert to the element we are looking for, return the
12053 if (EltNo == IIElt)
12054 return III->getOperand(1);
12056 // Otherwise, the insertelement doesn't modify the value, recurse on its
12058 return FindScalarElement(III->getOperand(0), EltNo, Context);
12059 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12060 unsigned LHSWidth =
12061 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12062 unsigned InEl = getShuffleMask(SVI)[EltNo];
12063 if (InEl < LHSWidth)
12064 return FindScalarElement(SVI->getOperand(0), InEl, Context);
12065 else if (InEl < LHSWidth*2)
12066 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12068 return UndefValue::get(PTy->getElementType());
12071 // Otherwise, we don't know.
12075 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12076 // If vector val is undef, replace extract with scalar undef.
12077 if (isa<UndefValue>(EI.getOperand(0)))
12078 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12080 // If vector val is constant 0, replace extract with scalar 0.
12081 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12082 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12084 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12085 // If vector val is constant with all elements the same, replace EI with
12086 // that element. When the elements are not identical, we cannot replace yet
12087 // (we do that below, but only when the index is constant).
12088 Constant *op0 = C->getOperand(0);
12089 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12090 if (C->getOperand(i) != op0) {
12095 return ReplaceInstUsesWith(EI, op0);
12098 // If extracting a specified index from the vector, see if we can recursively
12099 // find a previously computed scalar that was inserted into the vector.
12100 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12101 unsigned IndexVal = IdxC->getZExtValue();
12102 unsigned VectorWidth =
12103 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12105 // If this is extracting an invalid index, turn this into undef, to avoid
12106 // crashing the code below.
12107 if (IndexVal >= VectorWidth)
12108 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12110 // This instruction only demands the single element from the input vector.
12111 // If the input vector has a single use, simplify it based on this use
12113 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12114 APInt UndefElts(VectorWidth, 0);
12115 APInt DemandedMask(VectorWidth, 1 << IndexVal);
12116 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12117 DemandedMask, UndefElts)) {
12118 EI.setOperand(0, V);
12123 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12124 return ReplaceInstUsesWith(EI, Elt);
12126 // If the this extractelement is directly using a bitcast from a vector of
12127 // the same number of elements, see if we can find the source element from
12128 // it. In this case, we will end up needing to bitcast the scalars.
12129 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12130 if (const VectorType *VT =
12131 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12132 if (VT->getNumElements() == VectorWidth)
12133 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12134 IndexVal, Context))
12135 return new BitCastInst(Elt, EI.getType());
12139 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12140 if (I->hasOneUse()) {
12141 // Push extractelement into predecessor operation if legal and
12142 // profitable to do so
12143 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12144 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12145 if (CheapToScalarize(BO, isConstantElt)) {
12147 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12148 EI.getName()+".lhs");
12150 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12151 EI.getName()+".rhs");
12152 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12154 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
12155 unsigned AS = LI->getPointerAddressSpace();
12156 Value *Ptr = Builder->CreateBitCast(I->getOperand(0),
12157 PointerType::get(EI.getType(), AS),
12158 I->getOperand(0)->getName());
12160 Builder->CreateGEP(Ptr, EI.getOperand(1), I->getName()+".gep");
12161 cast<GEPOperator>(GEP)->setIsInBounds(true);
12163 LoadInst *Load = Builder->CreateLoad(GEP, "tmp");
12165 // Make sure the Load goes before the load instruction in the source,
12166 // not wherever the extract happens to be.
12167 if (Instruction *P = dyn_cast<Instruction>(Ptr))
12169 if (Instruction *G = dyn_cast<Instruction>(GEP))
12171 Load->moveBefore(I);
12173 return ReplaceInstUsesWith(EI, Load);
12176 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12177 // Extracting the inserted element?
12178 if (IE->getOperand(2) == EI.getOperand(1))
12179 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12180 // If the inserted and extracted elements are constants, they must not
12181 // be the same value, extract from the pre-inserted value instead.
12182 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
12183 Worklist.AddValue(EI.getOperand(0));
12184 EI.setOperand(0, IE->getOperand(0));
12187 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12188 // If this is extracting an element from a shufflevector, figure out where
12189 // it came from and extract from the appropriate input element instead.
12190 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12191 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12193 unsigned LHSWidth =
12194 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12196 if (SrcIdx < LHSWidth)
12197 Src = SVI->getOperand(0);
12198 else if (SrcIdx < LHSWidth*2) {
12199 SrcIdx -= LHSWidth;
12200 Src = SVI->getOperand(1);
12202 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12204 return ExtractElementInst::Create(Src,
12205 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12209 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12214 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12215 /// elements from either LHS or RHS, return the shuffle mask and true.
12216 /// Otherwise, return false.
12217 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12218 std::vector<Constant*> &Mask,
12219 LLVMContext *Context) {
12220 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12221 "Invalid CollectSingleShuffleElements");
12222 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12224 if (isa<UndefValue>(V)) {
12225 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12227 } else if (V == LHS) {
12228 for (unsigned i = 0; i != NumElts; ++i)
12229 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12231 } else if (V == RHS) {
12232 for (unsigned i = 0; i != NumElts; ++i)
12233 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12235 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12236 // If this is an insert of an extract from some other vector, include it.
12237 Value *VecOp = IEI->getOperand(0);
12238 Value *ScalarOp = IEI->getOperand(1);
12239 Value *IdxOp = IEI->getOperand(2);
12241 if (!isa<ConstantInt>(IdxOp))
12243 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12245 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12246 // Okay, we can handle this if the vector we are insertinting into is
12247 // transitively ok.
12248 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12249 // If so, update the mask to reflect the inserted undef.
12250 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12253 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12254 if (isa<ConstantInt>(EI->getOperand(1)) &&
12255 EI->getOperand(0)->getType() == V->getType()) {
12256 unsigned ExtractedIdx =
12257 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12259 // This must be extracting from either LHS or RHS.
12260 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12261 // Okay, we can handle this if the vector we are insertinting into is
12262 // transitively ok.
12263 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12264 // If so, update the mask to reflect the inserted value.
12265 if (EI->getOperand(0) == LHS) {
12266 Mask[InsertedIdx % NumElts] =
12267 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12269 assert(EI->getOperand(0) == RHS);
12270 Mask[InsertedIdx % NumElts] =
12271 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12280 // TODO: Handle shufflevector here!
12285 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12286 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12287 /// that computes V and the LHS value of the shuffle.
12288 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12289 Value *&RHS, LLVMContext *Context) {
12290 assert(isa<VectorType>(V->getType()) &&
12291 (RHS == 0 || V->getType() == RHS->getType()) &&
12292 "Invalid shuffle!");
12293 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12295 if (isa<UndefValue>(V)) {
12296 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12298 } else if (isa<ConstantAggregateZero>(V)) {
12299 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12301 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12302 // If this is an insert of an extract from some other vector, include it.
12303 Value *VecOp = IEI->getOperand(0);
12304 Value *ScalarOp = IEI->getOperand(1);
12305 Value *IdxOp = IEI->getOperand(2);
12307 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12308 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12309 EI->getOperand(0)->getType() == V->getType()) {
12310 unsigned ExtractedIdx =
12311 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12312 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12314 // Either the extracted from or inserted into vector must be RHSVec,
12315 // otherwise we'd end up with a shuffle of three inputs.
12316 if (EI->getOperand(0) == RHS || RHS == 0) {
12317 RHS = EI->getOperand(0);
12318 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12319 Mask[InsertedIdx % NumElts] =
12320 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12324 if (VecOp == RHS) {
12325 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12327 // Everything but the extracted element is replaced with the RHS.
12328 for (unsigned i = 0; i != NumElts; ++i) {
12329 if (i != InsertedIdx)
12330 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12335 // If this insertelement is a chain that comes from exactly these two
12336 // vectors, return the vector and the effective shuffle.
12337 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12339 return EI->getOperand(0);
12344 // TODO: Handle shufflevector here!
12346 // Otherwise, can't do anything fancy. Return an identity vector.
12347 for (unsigned i = 0; i != NumElts; ++i)
12348 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12352 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12353 Value *VecOp = IE.getOperand(0);
12354 Value *ScalarOp = IE.getOperand(1);
12355 Value *IdxOp = IE.getOperand(2);
12357 // Inserting an undef or into an undefined place, remove this.
12358 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12359 ReplaceInstUsesWith(IE, VecOp);
12361 // If the inserted element was extracted from some other vector, and if the
12362 // indexes are constant, try to turn this into a shufflevector operation.
12363 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12364 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12365 EI->getOperand(0)->getType() == IE.getType()) {
12366 unsigned NumVectorElts = IE.getType()->getNumElements();
12367 unsigned ExtractedIdx =
12368 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12369 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12371 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12372 return ReplaceInstUsesWith(IE, VecOp);
12374 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12375 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12377 // If we are extracting a value from a vector, then inserting it right
12378 // back into the same place, just use the input vector.
12379 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12380 return ReplaceInstUsesWith(IE, VecOp);
12382 // We could theoretically do this for ANY input. However, doing so could
12383 // turn chains of insertelement instructions into a chain of shufflevector
12384 // instructions, and right now we do not merge shufflevectors. As such,
12385 // only do this in a situation where it is clear that there is benefit.
12386 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12387 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12388 // the values of VecOp, except then one read from EIOp0.
12389 // Build a new shuffle mask.
12390 std::vector<Constant*> Mask;
12391 if (isa<UndefValue>(VecOp))
12392 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
12394 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12395 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
12398 Mask[InsertedIdx] =
12399 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12400 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12401 ConstantVector::get(Mask));
12404 // If this insertelement isn't used by some other insertelement, turn it
12405 // (and any insertelements it points to), into one big shuffle.
12406 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12407 std::vector<Constant*> Mask;
12409 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12410 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12411 // We now have a shuffle of LHS, RHS, Mask.
12412 return new ShuffleVectorInst(LHS, RHS,
12413 ConstantVector::get(Mask));
12418 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12419 APInt UndefElts(VWidth, 0);
12420 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12421 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12428 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12429 Value *LHS = SVI.getOperand(0);
12430 Value *RHS = SVI.getOperand(1);
12431 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12433 bool MadeChange = false;
12435 // Undefined shuffle mask -> undefined value.
12436 if (isa<UndefValue>(SVI.getOperand(2)))
12437 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12439 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12441 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12444 APInt UndefElts(VWidth, 0);
12445 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12446 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12447 LHS = SVI.getOperand(0);
12448 RHS = SVI.getOperand(1);
12452 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12453 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12454 if (LHS == RHS || isa<UndefValue>(LHS)) {
12455 if (isa<UndefValue>(LHS) && LHS == RHS) {
12456 // shuffle(undef,undef,mask) -> undef.
12457 return ReplaceInstUsesWith(SVI, LHS);
12460 // Remap any references to RHS to use LHS.
12461 std::vector<Constant*> Elts;
12462 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12463 if (Mask[i] >= 2*e)
12464 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12466 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12467 (Mask[i] < e && isa<UndefValue>(LHS))) {
12468 Mask[i] = 2*e; // Turn into undef.
12469 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12471 Mask[i] = Mask[i] % e; // Force to LHS.
12472 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12476 SVI.setOperand(0, SVI.getOperand(1));
12477 SVI.setOperand(1, UndefValue::get(RHS->getType()));
12478 SVI.setOperand(2, ConstantVector::get(Elts));
12479 LHS = SVI.getOperand(0);
12480 RHS = SVI.getOperand(1);
12484 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12485 bool isLHSID = true, isRHSID = true;
12487 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12488 if (Mask[i] >= e*2) continue; // Ignore undef values.
12489 // Is this an identity shuffle of the LHS value?
12490 isLHSID &= (Mask[i] == i);
12492 // Is this an identity shuffle of the RHS value?
12493 isRHSID &= (Mask[i]-e == i);
12496 // Eliminate identity shuffles.
12497 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12498 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12500 // If the LHS is a shufflevector itself, see if we can combine it with this
12501 // one without producing an unusual shuffle. Here we are really conservative:
12502 // we are absolutely afraid of producing a shuffle mask not in the input
12503 // program, because the code gen may not be smart enough to turn a merged
12504 // shuffle into two specific shuffles: it may produce worse code. As such,
12505 // we only merge two shuffles if the result is one of the two input shuffle
12506 // masks. In this case, merging the shuffles just removes one instruction,
12507 // which we know is safe. This is good for things like turning:
12508 // (splat(splat)) -> splat.
12509 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12510 if (isa<UndefValue>(RHS)) {
12511 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12513 std::vector<unsigned> NewMask;
12514 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12515 if (Mask[i] >= 2*e)
12516 NewMask.push_back(2*e);
12518 NewMask.push_back(LHSMask[Mask[i]]);
12520 // If the result mask is equal to the src shuffle or this shuffle mask, do
12521 // the replacement.
12522 if (NewMask == LHSMask || NewMask == Mask) {
12523 unsigned LHSInNElts =
12524 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12525 std::vector<Constant*> Elts;
12526 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12527 if (NewMask[i] >= LHSInNElts*2) {
12528 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12530 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
12533 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12534 LHSSVI->getOperand(1),
12535 ConstantVector::get(Elts));
12540 return MadeChange ? &SVI : 0;
12546 /// TryToSinkInstruction - Try to move the specified instruction from its
12547 /// current block into the beginning of DestBlock, which can only happen if it's
12548 /// safe to move the instruction past all of the instructions between it and the
12549 /// end of its block.
12550 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12551 assert(I->hasOneUse() && "Invariants didn't hold!");
12553 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12554 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12557 // Do not sink alloca instructions out of the entry block.
12558 if (isa<AllocaInst>(I) && I->getParent() ==
12559 &DestBlock->getParent()->getEntryBlock())
12562 // We can only sink load instructions if there is nothing between the load and
12563 // the end of block that could change the value.
12564 if (I->mayReadFromMemory()) {
12565 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12567 if (Scan->mayWriteToMemory())
12571 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12573 CopyPrecedingStopPoint(I, InsertPos);
12574 I->moveBefore(InsertPos);
12580 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12581 /// all reachable code to the worklist.
12583 /// This has a couple of tricks to make the code faster and more powerful. In
12584 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12585 /// them to the worklist (this significantly speeds up instcombine on code where
12586 /// many instructions are dead or constant). Additionally, if we find a branch
12587 /// whose condition is a known constant, we only visit the reachable successors.
12589 static void AddReachableCodeToWorklist(BasicBlock *BB,
12590 SmallPtrSet<BasicBlock*, 64> &Visited,
12592 const TargetData *TD) {
12593 SmallVector<BasicBlock*, 256> Worklist;
12594 Worklist.push_back(BB);
12596 while (!Worklist.empty()) {
12597 BB = Worklist.back();
12598 Worklist.pop_back();
12600 // We have now visited this block! If we've already been here, ignore it.
12601 if (!Visited.insert(BB)) continue;
12603 DbgInfoIntrinsic *DBI_Prev = NULL;
12604 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12605 Instruction *Inst = BBI++;
12607 // DCE instruction if trivially dead.
12608 if (isInstructionTriviallyDead(Inst)) {
12610 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
12611 Inst->eraseFromParent();
12615 // ConstantProp instruction if trivially constant.
12616 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12617 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12619 Inst->replaceAllUsesWith(C);
12621 Inst->eraseFromParent();
12625 // If there are two consecutive llvm.dbg.stoppoint calls then
12626 // it is likely that the optimizer deleted code in between these
12628 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12631 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12632 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12633 IC.Worklist.Remove(DBI_Prev);
12634 DBI_Prev->eraseFromParent();
12636 DBI_Prev = DBI_Next;
12641 IC.Worklist.Add(Inst);
12644 // Recursively visit successors. If this is a branch or switch on a
12645 // constant, only visit the reachable successor.
12646 TerminatorInst *TI = BB->getTerminator();
12647 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12648 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12649 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12650 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12651 Worklist.push_back(ReachableBB);
12654 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12655 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12656 // See if this is an explicit destination.
12657 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12658 if (SI->getCaseValue(i) == Cond) {
12659 BasicBlock *ReachableBB = SI->getSuccessor(i);
12660 Worklist.push_back(ReachableBB);
12664 // Otherwise it is the default destination.
12665 Worklist.push_back(SI->getSuccessor(0));
12670 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12671 Worklist.push_back(TI->getSuccessor(i));
12675 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12676 bool Changed = false;
12677 TD = getAnalysisIfAvailable<TargetData>();
12679 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12680 << F.getNameStr() << "\n");
12683 // Do a depth-first traversal of the function, populate the worklist with
12684 // the reachable instructions. Ignore blocks that are not reachable. Keep
12685 // track of which blocks we visit.
12686 SmallPtrSet<BasicBlock*, 64> Visited;
12687 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12689 // Do a quick scan over the function. If we find any blocks that are
12690 // unreachable, remove any instructions inside of them. This prevents
12691 // the instcombine code from having to deal with some bad special cases.
12692 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12693 if (!Visited.count(BB)) {
12694 Instruction *Term = BB->getTerminator();
12695 while (Term != BB->begin()) { // Remove instrs bottom-up
12696 BasicBlock::iterator I = Term; --I;
12698 DEBUG(errs() << "IC: DCE: " << *I << '\n');
12699 // A debug intrinsic shouldn't force another iteration if we weren't
12700 // going to do one without it.
12701 if (!isa<DbgInfoIntrinsic>(I)) {
12705 if (!I->use_empty())
12706 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12707 I->eraseFromParent();
12712 while (!Worklist.isEmpty()) {
12713 Instruction *I = Worklist.RemoveOne();
12714 if (I == 0) continue; // skip null values.
12716 // Check to see if we can DCE the instruction.
12717 if (isInstructionTriviallyDead(I)) {
12718 DEBUG(errs() << "IC: DCE: " << *I << '\n');
12719 EraseInstFromFunction(*I);
12725 // Instruction isn't dead, see if we can constant propagate it.
12726 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12727 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
12729 // Add operands to the worklist.
12730 ReplaceInstUsesWith(*I, C);
12732 EraseInstFromFunction(*I);
12738 // See if we can constant fold its operands.
12739 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12740 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12741 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12742 F.getContext(), TD))
12749 // See if we can trivially sink this instruction to a successor basic block.
12750 if (I->hasOneUse()) {
12751 BasicBlock *BB = I->getParent();
12752 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12753 if (UserParent != BB) {
12754 bool UserIsSuccessor = false;
12755 // See if the user is one of our successors.
12756 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12757 if (*SI == UserParent) {
12758 UserIsSuccessor = true;
12762 // If the user is one of our immediate successors, and if that successor
12763 // only has us as a predecessors (we'd have to split the critical edge
12764 // otherwise), we can keep going.
12765 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12766 next(pred_begin(UserParent)) == pred_end(UserParent))
12767 // Okay, the CFG is simple enough, try to sink this instruction.
12768 Changed |= TryToSinkInstruction(I, UserParent);
12772 // Now that we have an instruction, try combining it to simplify it.
12773 Builder->SetInsertPoint(I->getParent(), I);
12778 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
12780 if (Instruction *Result = visit(*I)) {
12782 // Should we replace the old instruction with a new one?
12784 DEBUG(errs() << "IC: Old = " << *I << '\n'
12785 << " New = " << *Result << '\n');
12787 // Everything uses the new instruction now.
12788 I->replaceAllUsesWith(Result);
12790 // Push the new instruction and any users onto the worklist.
12791 Worklist.Add(Result);
12792 Worklist.AddUsersToWorkList(*Result);
12794 // Move the name to the new instruction first.
12795 Result->takeName(I);
12797 // Insert the new instruction into the basic block...
12798 BasicBlock *InstParent = I->getParent();
12799 BasicBlock::iterator InsertPos = I;
12801 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12802 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12805 InstParent->getInstList().insert(InsertPos, Result);
12807 EraseInstFromFunction(*I);
12810 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12811 << " New = " << *I << '\n');
12814 // If the instruction was modified, it's possible that it is now dead.
12815 // if so, remove it.
12816 if (isInstructionTriviallyDead(I)) {
12817 EraseInstFromFunction(*I);
12820 Worklist.AddUsersToWorkList(*I);
12832 bool InstCombiner::runOnFunction(Function &F) {
12833 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12834 Context = &F.getContext();
12837 /// Builder - This is an IRBuilder that automatically inserts new
12838 /// instructions into the worklist when they are created.
12839 IRBuilder<true, ConstantFolder, InstCombineIRInserter>
12840 TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12841 InstCombineIRInserter(Worklist));
12842 Builder = &TheBuilder;
12844 bool EverMadeChange = false;
12846 // Iterate while there is work to do.
12847 unsigned Iteration = 0;
12848 while (DoOneIteration(F, Iteration++))
12849 EverMadeChange = true;
12852 return EverMadeChange;
12855 FunctionPass *llvm::createInstructionCombiningPass() {
12856 return new InstCombiner();