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/MallocHelper.h"
46 #include "llvm/Analysis/ValueTracking.h"
47 #include "llvm/Target/TargetData.h"
48 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
49 #include "llvm/Transforms/Utils/Local.h"
50 #include "llvm/Support/CallSite.h"
51 #include "llvm/Support/ConstantRange.h"
52 #include "llvm/Support/Debug.h"
53 #include "llvm/Support/ErrorHandling.h"
54 #include "llvm/Support/GetElementPtrTypeIterator.h"
55 #include "llvm/Support/InstVisitor.h"
56 #include "llvm/Support/IRBuilder.h"
57 #include "llvm/Support/MathExtras.h"
58 #include "llvm/Support/PatternMatch.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 DEBUG(errs() << "IC: ADD: " << *I << '\n');
94 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
95 Worklist.push_back(I);
98 void AddValue(Value *V) {
99 if (Instruction *I = dyn_cast<Instruction>(V))
103 // Remove - remove I from the worklist if it exists.
104 void Remove(Instruction *I) {
105 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
106 if (It == WorklistMap.end()) return; // Not in worklist.
108 // Don't bother moving everything down, just null out the slot.
109 Worklist[It->second] = 0;
111 WorklistMap.erase(It);
114 Instruction *RemoveOne() {
115 Instruction *I = Worklist.back();
117 WorklistMap.erase(I);
121 /// AddUsersToWorkList - When an instruction is simplified, add all users of
122 /// the instruction to the work lists because they might get more simplified
125 void AddUsersToWorkList(Instruction &I) {
126 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
128 Add(cast<Instruction>(*UI));
132 /// Zap - check that the worklist is empty and nuke the backing store for
133 /// the map if it is large.
135 assert(WorklistMap.empty() && "Worklist empty, but map not?");
137 // Do an explicit clear, this shrinks the map if needed.
141 } // end anonymous namespace.
145 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
146 /// just like the normal insertion helper, but also adds any new instructions
147 /// to the instcombine worklist.
148 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
149 InstCombineWorklist &Worklist;
151 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
153 void InsertHelper(Instruction *I, const Twine &Name,
154 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
155 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
159 } // end anonymous namespace
163 class InstCombiner : public FunctionPass,
164 public InstVisitor<InstCombiner, Instruction*> {
166 bool MustPreserveLCSSA;
169 /// Worklist - All of the instructions that need to be simplified.
170 InstCombineWorklist Worklist;
172 /// Builder - This is an IRBuilder that automatically inserts new
173 /// instructions into the worklist when they are created.
174 typedef IRBuilder<true, ConstantFolder, InstCombineIRInserter> BuilderTy;
177 static char ID; // Pass identification, replacement for typeid
178 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
180 LLVMContext *Context;
181 LLVMContext *getContext() const { return Context; }
184 virtual bool runOnFunction(Function &F);
186 bool DoOneIteration(Function &F, unsigned ItNum);
188 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
189 AU.addPreservedID(LCSSAID);
190 AU.setPreservesCFG();
193 TargetData *getTargetData() const { return TD; }
195 // Visitation implementation - Implement instruction combining for different
196 // instruction types. The semantics are as follows:
198 // null - No change was made
199 // I - Change was made, I is still valid, I may be dead though
200 // otherwise - Change was made, replace I with returned instruction
202 Instruction *visitAdd(BinaryOperator &I);
203 Instruction *visitFAdd(BinaryOperator &I);
204 Instruction *visitSub(BinaryOperator &I);
205 Instruction *visitFSub(BinaryOperator &I);
206 Instruction *visitMul(BinaryOperator &I);
207 Instruction *visitFMul(BinaryOperator &I);
208 Instruction *visitURem(BinaryOperator &I);
209 Instruction *visitSRem(BinaryOperator &I);
210 Instruction *visitFRem(BinaryOperator &I);
211 bool SimplifyDivRemOfSelect(BinaryOperator &I);
212 Instruction *commonRemTransforms(BinaryOperator &I);
213 Instruction *commonIRemTransforms(BinaryOperator &I);
214 Instruction *commonDivTransforms(BinaryOperator &I);
215 Instruction *commonIDivTransforms(BinaryOperator &I);
216 Instruction *visitUDiv(BinaryOperator &I);
217 Instruction *visitSDiv(BinaryOperator &I);
218 Instruction *visitFDiv(BinaryOperator &I);
219 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
220 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
221 Instruction *visitAnd(BinaryOperator &I);
222 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
223 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
224 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
225 Value *A, Value *B, Value *C);
226 Instruction *visitOr (BinaryOperator &I);
227 Instruction *visitXor(BinaryOperator &I);
228 Instruction *visitShl(BinaryOperator &I);
229 Instruction *visitAShr(BinaryOperator &I);
230 Instruction *visitLShr(BinaryOperator &I);
231 Instruction *commonShiftTransforms(BinaryOperator &I);
232 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
234 Instruction *visitFCmpInst(FCmpInst &I);
235 Instruction *visitICmpInst(ICmpInst &I);
236 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
237 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
240 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
241 ConstantInt *DivRHS);
243 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
244 ICmpInst::Predicate Cond, Instruction &I);
245 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
247 Instruction *commonCastTransforms(CastInst &CI);
248 Instruction *commonIntCastTransforms(CastInst &CI);
249 Instruction *commonPointerCastTransforms(CastInst &CI);
250 Instruction *visitTrunc(TruncInst &CI);
251 Instruction *visitZExt(ZExtInst &CI);
252 Instruction *visitSExt(SExtInst &CI);
253 Instruction *visitFPTrunc(FPTruncInst &CI);
254 Instruction *visitFPExt(CastInst &CI);
255 Instruction *visitFPToUI(FPToUIInst &FI);
256 Instruction *visitFPToSI(FPToSIInst &FI);
257 Instruction *visitUIToFP(CastInst &CI);
258 Instruction *visitSIToFP(CastInst &CI);
259 Instruction *visitPtrToInt(PtrToIntInst &CI);
260 Instruction *visitIntToPtr(IntToPtrInst &CI);
261 Instruction *visitBitCast(BitCastInst &CI);
262 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
264 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
265 Instruction *visitSelectInst(SelectInst &SI);
266 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
267 Instruction *visitCallInst(CallInst &CI);
268 Instruction *visitInvokeInst(InvokeInst &II);
269 Instruction *visitPHINode(PHINode &PN);
270 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
271 Instruction *visitAllocationInst(AllocationInst &AI);
272 Instruction *visitFreeInst(FreeInst &FI);
273 Instruction *visitLoadInst(LoadInst &LI);
274 Instruction *visitStoreInst(StoreInst &SI);
275 Instruction *visitBranchInst(BranchInst &BI);
276 Instruction *visitSwitchInst(SwitchInst &SI);
277 Instruction *visitInsertElementInst(InsertElementInst &IE);
278 Instruction *visitExtractElementInst(ExtractElementInst &EI);
279 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
280 Instruction *visitExtractValueInst(ExtractValueInst &EV);
282 // visitInstruction - Specify what to return for unhandled instructions...
283 Instruction *visitInstruction(Instruction &I) { return 0; }
286 Instruction *visitCallSite(CallSite CS);
287 bool transformConstExprCastCall(CallSite CS);
288 Instruction *transformCallThroughTrampoline(CallSite CS);
289 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
290 bool DoXform = true);
291 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
292 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
296 // InsertNewInstBefore - insert an instruction New before instruction Old
297 // in the program. Add the new instruction to the worklist.
299 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
300 assert(New && New->getParent() == 0 &&
301 "New instruction already inserted into a basic block!");
302 BasicBlock *BB = Old.getParent();
303 BB->getInstList().insert(&Old, New); // Insert inst
308 // ReplaceInstUsesWith - This method is to be used when an instruction is
309 // found to be dead, replacable with another preexisting expression. Here
310 // we add all uses of I to the worklist, replace all uses of I with the new
311 // value, then return I, so that the inst combiner will know that I was
314 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
315 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
317 // If we are replacing the instruction with itself, this must be in a
318 // segment of unreachable code, so just clobber the instruction.
320 V = UndefValue::get(I.getType());
322 I.replaceAllUsesWith(V);
326 // EraseInstFromFunction - When dealing with an instruction that has side
327 // effects or produces a void value, we can't rely on DCE to delete the
328 // instruction. Instead, visit methods should return the value returned by
330 Instruction *EraseInstFromFunction(Instruction &I) {
331 DEBUG(errs() << "IC: ERASE " << I << '\n');
333 assert(I.use_empty() && "Cannot erase instruction that is used!");
334 // Make sure that we reprocess all operands now that we reduced their
336 if (I.getNumOperands() < 8) {
337 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
338 if (Instruction *Op = dyn_cast<Instruction>(*i))
344 return 0; // Don't do anything with FI
347 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
348 APInt &KnownOne, unsigned Depth = 0) const {
349 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
352 bool MaskedValueIsZero(Value *V, const APInt &Mask,
353 unsigned Depth = 0) const {
354 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
356 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
357 return llvm::ComputeNumSignBits(Op, TD, Depth);
362 /// SimplifyCommutative - This performs a few simplifications for
363 /// commutative operators.
364 bool SimplifyCommutative(BinaryOperator &I);
366 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
367 /// most-complex to least-complex order.
368 bool SimplifyCompare(CmpInst &I);
370 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
371 /// based on the demanded bits.
372 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
373 APInt& KnownZero, APInt& KnownOne,
375 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
376 APInt& KnownZero, APInt& KnownOne,
379 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
380 /// SimplifyDemandedBits knows about. See if the instruction has any
381 /// properties that allow us to simplify its operands.
382 bool SimplifyDemandedInstructionBits(Instruction &Inst);
384 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
385 APInt& UndefElts, unsigned Depth = 0);
387 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
388 // which has a PHI node as operand #0, see if we can fold the instruction
389 // into the PHI (which is only possible if all operands to the PHI are
392 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
393 // that would normally be unprofitable because they strongly encourage jump
395 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
397 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
398 // operator and they all are only used by the PHI, PHI together their
399 // inputs, and do the operation once, to the result of the PHI.
400 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
401 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
402 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
405 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
406 ConstantInt *AndRHS, BinaryOperator &TheAnd);
408 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
409 bool isSub, Instruction &I);
410 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
411 bool isSigned, bool Inside, Instruction &IB);
412 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
413 Instruction *MatchBSwap(BinaryOperator &I);
414 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
415 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
416 Instruction *SimplifyMemSet(MemSetInst *MI);
419 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
421 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
422 unsigned CastOpc, int &NumCastsRemoved);
423 unsigned GetOrEnforceKnownAlignment(Value *V,
424 unsigned PrefAlign = 0);
427 } // end anonymous namespace
429 char InstCombiner::ID = 0;
430 static RegisterPass<InstCombiner>
431 X("instcombine", "Combine redundant instructions");
433 // getComplexity: Assign a complexity or rank value to LLVM Values...
434 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
435 static unsigned getComplexity(Value *V) {
436 if (isa<Instruction>(V)) {
437 if (BinaryOperator::isNeg(V) ||
438 BinaryOperator::isFNeg(V) ||
439 BinaryOperator::isNot(V))
443 if (isa<Argument>(V)) return 3;
444 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
447 // isOnlyUse - Return true if this instruction will be deleted if we stop using
449 static bool isOnlyUse(Value *V) {
450 return V->hasOneUse() || isa<Constant>(V);
453 // getPromotedType - Return the specified type promoted as it would be to pass
454 // though a va_arg area...
455 static const Type *getPromotedType(const Type *Ty) {
456 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
457 if (ITy->getBitWidth() < 32)
458 return Type::getInt32Ty(Ty->getContext());
463 /// getBitCastOperand - If the specified operand is a CastInst, a constant
464 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
465 /// operand value, otherwise return null.
466 static Value *getBitCastOperand(Value *V) {
467 if (Operator *O = dyn_cast<Operator>(V)) {
468 if (O->getOpcode() == Instruction::BitCast)
469 return O->getOperand(0);
470 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
471 if (GEP->hasAllZeroIndices())
472 return GEP->getPointerOperand();
477 /// This function is a wrapper around CastInst::isEliminableCastPair. It
478 /// simply extracts arguments and returns what that function returns.
479 static Instruction::CastOps
480 isEliminableCastPair(
481 const CastInst *CI, ///< The first cast instruction
482 unsigned opcode, ///< The opcode of the second cast instruction
483 const Type *DstTy, ///< The target type for the second cast instruction
484 TargetData *TD ///< The target data for pointer size
487 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
488 const Type *MidTy = CI->getType(); // B from above
490 // Get the opcodes of the two Cast instructions
491 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
492 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
494 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
496 TD ? TD->getIntPtrType(CI->getContext()) : 0);
498 // We don't want to form an inttoptr or ptrtoint that converts to an integer
499 // type that differs from the pointer size.
500 if ((Res == Instruction::IntToPtr &&
501 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
502 (Res == Instruction::PtrToInt &&
503 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
506 return Instruction::CastOps(Res);
509 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
510 /// in any code being generated. It does not require codegen if V is simple
511 /// enough or if the cast can be folded into other casts.
512 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
513 const Type *Ty, TargetData *TD) {
514 if (V->getType() == Ty || isa<Constant>(V)) return false;
516 // If this is another cast that can be eliminated, it isn't codegen either.
517 if (const CastInst *CI = dyn_cast<CastInst>(V))
518 if (isEliminableCastPair(CI, opcode, Ty, TD))
523 // SimplifyCommutative - This performs a few simplifications for commutative
526 // 1. Order operands such that they are listed from right (least complex) to
527 // left (most complex). This puts constants before unary operators before
530 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
531 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
533 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
534 bool Changed = false;
535 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
536 Changed = !I.swapOperands();
538 if (!I.isAssociative()) return Changed;
539 Instruction::BinaryOps Opcode = I.getOpcode();
540 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
541 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
542 if (isa<Constant>(I.getOperand(1))) {
543 Constant *Folded = ConstantExpr::get(I.getOpcode(),
544 cast<Constant>(I.getOperand(1)),
545 cast<Constant>(Op->getOperand(1)));
546 I.setOperand(0, Op->getOperand(0));
547 I.setOperand(1, Folded);
549 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
550 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
551 isOnlyUse(Op) && isOnlyUse(Op1)) {
552 Constant *C1 = cast<Constant>(Op->getOperand(1));
553 Constant *C2 = cast<Constant>(Op1->getOperand(1));
555 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
556 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
557 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
561 I.setOperand(0, New);
562 I.setOperand(1, Folded);
569 /// SimplifyCompare - For a CmpInst this function just orders the operands
570 /// so that theyare listed from right (least complex) to left (most complex).
571 /// This puts constants before unary operators before binary operators.
572 bool InstCombiner::SimplifyCompare(CmpInst &I) {
573 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
576 // Compare instructions are not associative so there's nothing else we can do.
580 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
581 // if the LHS is a constant zero (which is the 'negate' form).
583 static inline Value *dyn_castNegVal(Value *V) {
584 if (BinaryOperator::isNeg(V))
585 return BinaryOperator::getNegArgument(V);
587 // Constants can be considered to be negated values if they can be folded.
588 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
589 return ConstantExpr::getNeg(C);
591 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
592 if (C->getType()->getElementType()->isInteger())
593 return ConstantExpr::getNeg(C);
598 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
599 // instruction if the LHS is a constant negative zero (which is the 'negate'
602 static inline Value *dyn_castFNegVal(Value *V) {
603 if (BinaryOperator::isFNeg(V))
604 return BinaryOperator::getFNegArgument(V);
606 // Constants can be considered to be negated values if they can be folded.
607 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
608 return ConstantExpr::getFNeg(C);
610 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
611 if (C->getType()->getElementType()->isFloatingPoint())
612 return ConstantExpr::getFNeg(C);
617 static inline Value *dyn_castNotVal(Value *V) {
618 if (BinaryOperator::isNot(V))
619 return BinaryOperator::getNotArgument(V);
621 // Constants can be considered to be not'ed values...
622 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
623 return ConstantInt::get(C->getType(), ~C->getValue());
627 // dyn_castFoldableMul - If this value is a multiply that can be folded into
628 // other computations (because it has a constant operand), return the
629 // non-constant operand of the multiply, and set CST to point to the multiplier.
630 // Otherwise, return null.
632 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
633 if (V->hasOneUse() && V->getType()->isInteger())
634 if (Instruction *I = dyn_cast<Instruction>(V)) {
635 if (I->getOpcode() == Instruction::Mul)
636 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
637 return I->getOperand(0);
638 if (I->getOpcode() == Instruction::Shl)
639 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
640 // The multiplier is really 1 << CST.
641 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
642 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
643 CST = ConstantInt::get(V->getType()->getContext(),
644 APInt(BitWidth, 1).shl(CSTVal));
645 return I->getOperand(0);
651 /// AddOne - Add one to a ConstantInt
652 static Constant *AddOne(Constant *C) {
653 return ConstantExpr::getAdd(C,
654 ConstantInt::get(C->getType(), 1));
656 /// SubOne - Subtract one from a ConstantInt
657 static Constant *SubOne(ConstantInt *C) {
658 return ConstantExpr::getSub(C,
659 ConstantInt::get(C->getType(), 1));
661 /// MultiplyOverflows - True if the multiply can not be expressed in an int
663 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
664 uint32_t W = C1->getBitWidth();
665 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
674 APInt MulExt = LHSExt * RHSExt;
677 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
678 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
679 return MulExt.slt(Min) || MulExt.sgt(Max);
681 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
685 /// ShrinkDemandedConstant - Check to see if the specified operand of the
686 /// specified instruction is a constant integer. If so, check to see if there
687 /// are any bits set in the constant that are not demanded. If so, shrink the
688 /// constant and return true.
689 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
691 assert(I && "No instruction?");
692 assert(OpNo < I->getNumOperands() && "Operand index too large");
694 // If the operand is not a constant integer, nothing to do.
695 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
696 if (!OpC) return false;
698 // If there are no bits set that aren't demanded, nothing to do.
699 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
700 if ((~Demanded & OpC->getValue()) == 0)
703 // This instruction is producing bits that are not demanded. Shrink the RHS.
704 Demanded &= OpC->getValue();
705 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
709 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
710 // set of known zero and one bits, compute the maximum and minimum values that
711 // could have the specified known zero and known one bits, returning them in
713 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
714 const APInt& KnownOne,
715 APInt& Min, APInt& Max) {
716 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
717 KnownZero.getBitWidth() == Min.getBitWidth() &&
718 KnownZero.getBitWidth() == Max.getBitWidth() &&
719 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
720 APInt UnknownBits = ~(KnownZero|KnownOne);
722 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
723 // bit if it is unknown.
725 Max = KnownOne|UnknownBits;
727 if (UnknownBits.isNegative()) { // Sign bit is unknown
728 Min.set(Min.getBitWidth()-1);
729 Max.clear(Max.getBitWidth()-1);
733 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
734 // a set of known zero and one bits, compute the maximum and minimum values that
735 // could have the specified known zero and known one bits, returning them in
737 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
738 const APInt &KnownOne,
739 APInt &Min, APInt &Max) {
740 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
741 KnownZero.getBitWidth() == Min.getBitWidth() &&
742 KnownZero.getBitWidth() == Max.getBitWidth() &&
743 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
744 APInt UnknownBits = ~(KnownZero|KnownOne);
746 // The minimum value is when the unknown bits are all zeros.
748 // The maximum value is when the unknown bits are all ones.
749 Max = KnownOne|UnknownBits;
752 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
753 /// SimplifyDemandedBits knows about. See if the instruction has any
754 /// properties that allow us to simplify its operands.
755 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
756 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
757 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
758 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
760 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
761 KnownZero, KnownOne, 0);
762 if (V == 0) return false;
763 if (V == &Inst) return true;
764 ReplaceInstUsesWith(Inst, V);
768 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
769 /// specified instruction operand if possible, updating it in place. It returns
770 /// true if it made any change and false otherwise.
771 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
772 APInt &KnownZero, APInt &KnownOne,
774 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
775 KnownZero, KnownOne, Depth);
776 if (NewVal == 0) return false;
782 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
783 /// value based on the demanded bits. When this function is called, it is known
784 /// that only the bits set in DemandedMask of the result of V are ever used
785 /// downstream. Consequently, depending on the mask and V, it may be possible
786 /// to replace V with a constant or one of its operands. In such cases, this
787 /// function does the replacement and returns true. In all other cases, it
788 /// returns false after analyzing the expression and setting KnownOne and known
789 /// to be one in the expression. KnownZero contains all the bits that are known
790 /// to be zero in the expression. These are provided to potentially allow the
791 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
792 /// the expression. KnownOne and KnownZero always follow the invariant that
793 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
794 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
795 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
796 /// and KnownOne must all be the same.
798 /// This returns null if it did not change anything and it permits no
799 /// simplification. This returns V itself if it did some simplification of V's
800 /// operands based on the information about what bits are demanded. This returns
801 /// some other non-null value if it found out that V is equal to another value
802 /// in the context where the specified bits are demanded, but not for all users.
803 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
804 APInt &KnownZero, APInt &KnownOne,
806 assert(V != 0 && "Null pointer of Value???");
807 assert(Depth <= 6 && "Limit Search Depth");
808 uint32_t BitWidth = DemandedMask.getBitWidth();
809 const Type *VTy = V->getType();
810 assert((TD || !isa<PointerType>(VTy)) &&
811 "SimplifyDemandedBits needs to know bit widths!");
812 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
813 (!VTy->isIntOrIntVector() ||
814 VTy->getScalarSizeInBits() == BitWidth) &&
815 KnownZero.getBitWidth() == BitWidth &&
816 KnownOne.getBitWidth() == BitWidth &&
817 "Value *V, DemandedMask, KnownZero and KnownOne "
818 "must have same BitWidth");
819 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
820 // We know all of the bits for a constant!
821 KnownOne = CI->getValue() & DemandedMask;
822 KnownZero = ~KnownOne & DemandedMask;
825 if (isa<ConstantPointerNull>(V)) {
826 // We know all of the bits for a constant!
828 KnownZero = DemandedMask;
834 if (DemandedMask == 0) { // Not demanding any bits from V.
835 if (isa<UndefValue>(V))
837 return UndefValue::get(VTy);
840 if (Depth == 6) // Limit search depth.
843 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
844 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
846 Instruction *I = dyn_cast<Instruction>(V);
848 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
849 return 0; // Only analyze instructions.
852 // If there are multiple uses of this value and we aren't at the root, then
853 // we can't do any simplifications of the operands, because DemandedMask
854 // only reflects the bits demanded by *one* of the users.
855 if (Depth != 0 && !I->hasOneUse()) {
856 // Despite the fact that we can't simplify this instruction in all User's
857 // context, we can at least compute the knownzero/knownone bits, and we can
858 // do simplifications that apply to *just* the one user if we know that
859 // this instruction has a simpler value in that context.
860 if (I->getOpcode() == Instruction::And) {
861 // If either the LHS or the RHS are Zero, the result is zero.
862 ComputeMaskedBits(I->getOperand(1), DemandedMask,
863 RHSKnownZero, RHSKnownOne, Depth+1);
864 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
865 LHSKnownZero, LHSKnownOne, Depth+1);
867 // If all of the demanded bits are known 1 on one side, return the other.
868 // These bits cannot contribute to the result of the 'and' in this
870 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
871 (DemandedMask & ~LHSKnownZero))
872 return I->getOperand(0);
873 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
874 (DemandedMask & ~RHSKnownZero))
875 return I->getOperand(1);
877 // If all of the demanded bits in the inputs are known zeros, return zero.
878 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
879 return Constant::getNullValue(VTy);
881 } else if (I->getOpcode() == Instruction::Or) {
882 // We can simplify (X|Y) -> X or Y in the user's context if we know that
883 // only bits from X or Y are demanded.
885 // If either the LHS or the RHS are One, the result is One.
886 ComputeMaskedBits(I->getOperand(1), DemandedMask,
887 RHSKnownZero, RHSKnownOne, Depth+1);
888 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
889 LHSKnownZero, LHSKnownOne, Depth+1);
891 // If all of the demanded bits are known zero on one side, return the
892 // other. These bits cannot contribute to the result of the 'or' in this
894 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
895 (DemandedMask & ~LHSKnownOne))
896 return I->getOperand(0);
897 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
898 (DemandedMask & ~RHSKnownOne))
899 return I->getOperand(1);
901 // If all of the potentially set bits on one side are known to be set on
902 // the other side, just use the 'other' side.
903 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
904 (DemandedMask & (~RHSKnownZero)))
905 return I->getOperand(0);
906 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
907 (DemandedMask & (~LHSKnownZero)))
908 return I->getOperand(1);
911 // Compute the KnownZero/KnownOne bits to simplify things downstream.
912 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
916 // If this is the root being simplified, allow it to have multiple uses,
917 // just set the DemandedMask to all bits so that we can try to simplify the
918 // operands. This allows visitTruncInst (for example) to simplify the
919 // operand of a trunc without duplicating all the logic below.
920 if (Depth == 0 && !V->hasOneUse())
921 DemandedMask = APInt::getAllOnesValue(BitWidth);
923 switch (I->getOpcode()) {
925 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
927 case Instruction::And:
928 // If either the LHS or the RHS are Zero, the result is zero.
929 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
930 RHSKnownZero, RHSKnownOne, Depth+1) ||
931 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
932 LHSKnownZero, LHSKnownOne, Depth+1))
934 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
935 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
937 // If all of the demanded bits are known 1 on one side, return the other.
938 // These bits cannot contribute to the result of the 'and'.
939 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
940 (DemandedMask & ~LHSKnownZero))
941 return I->getOperand(0);
942 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
943 (DemandedMask & ~RHSKnownZero))
944 return I->getOperand(1);
946 // If all of the demanded bits in the inputs are known zeros, return zero.
947 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
948 return Constant::getNullValue(VTy);
950 // If the RHS is a constant, see if we can simplify it.
951 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
954 // Output known-1 bits are only known if set in both the LHS & RHS.
955 RHSKnownOne &= LHSKnownOne;
956 // Output known-0 are known to be clear if zero in either the LHS | RHS.
957 RHSKnownZero |= LHSKnownZero;
959 case Instruction::Or:
960 // If either the LHS or the RHS are One, the result is One.
961 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
962 RHSKnownZero, RHSKnownOne, Depth+1) ||
963 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
964 LHSKnownZero, LHSKnownOne, Depth+1))
966 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
967 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
969 // If all of the demanded bits are known zero on one side, return the other.
970 // These bits cannot contribute to the result of the 'or'.
971 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
972 (DemandedMask & ~LHSKnownOne))
973 return I->getOperand(0);
974 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
975 (DemandedMask & ~RHSKnownOne))
976 return I->getOperand(1);
978 // If all of the potentially set bits on one side are known to be set on
979 // the other side, just use the 'other' side.
980 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
981 (DemandedMask & (~RHSKnownZero)))
982 return I->getOperand(0);
983 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
984 (DemandedMask & (~LHSKnownZero)))
985 return I->getOperand(1);
987 // If the RHS is a constant, see if we can simplify it.
988 if (ShrinkDemandedConstant(I, 1, DemandedMask))
991 // Output known-0 bits are only known if clear in both the LHS & RHS.
992 RHSKnownZero &= LHSKnownZero;
993 // Output known-1 are known to be set if set in either the LHS | RHS.
994 RHSKnownOne |= LHSKnownOne;
996 case Instruction::Xor: {
997 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
998 RHSKnownZero, RHSKnownOne, Depth+1) ||
999 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1000 LHSKnownZero, LHSKnownOne, Depth+1))
1002 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1003 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
1005 // If all of the demanded bits are known zero on one side, return the other.
1006 // These bits cannot contribute to the result of the 'xor'.
1007 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1008 return I->getOperand(0);
1009 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1010 return I->getOperand(1);
1012 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1013 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1014 (RHSKnownOne & LHSKnownOne);
1015 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1016 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1017 (RHSKnownOne & LHSKnownZero);
1019 // If all of the demanded bits are known to be zero on one side or the
1020 // other, turn this into an *inclusive* or.
1021 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1022 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1024 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1026 return InsertNewInstBefore(Or, *I);
1029 // If all of the demanded bits on one side are known, and all of the set
1030 // bits on that side are also known to be set on the other side, turn this
1031 // into an AND, as we know the bits will be cleared.
1032 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1033 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1035 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1036 Constant *AndC = Constant::getIntegerValue(VTy,
1037 ~RHSKnownOne & DemandedMask);
1039 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1040 return InsertNewInstBefore(And, *I);
1044 // If the RHS is a constant, see if we can simplify it.
1045 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1046 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1049 RHSKnownZero = KnownZeroOut;
1050 RHSKnownOne = KnownOneOut;
1053 case Instruction::Select:
1054 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1055 RHSKnownZero, RHSKnownOne, Depth+1) ||
1056 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1057 LHSKnownZero, LHSKnownOne, Depth+1))
1059 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1060 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
1062 // If the operands are constants, see if we can simplify them.
1063 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1064 ShrinkDemandedConstant(I, 2, DemandedMask))
1067 // Only known if known in both the LHS and RHS.
1068 RHSKnownOne &= LHSKnownOne;
1069 RHSKnownZero &= LHSKnownZero;
1071 case Instruction::Trunc: {
1072 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1073 DemandedMask.zext(truncBf);
1074 RHSKnownZero.zext(truncBf);
1075 RHSKnownOne.zext(truncBf);
1076 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1077 RHSKnownZero, RHSKnownOne, Depth+1))
1079 DemandedMask.trunc(BitWidth);
1080 RHSKnownZero.trunc(BitWidth);
1081 RHSKnownOne.trunc(BitWidth);
1082 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1085 case Instruction::BitCast:
1086 if (!I->getOperand(0)->getType()->isIntOrIntVector())
1087 return false; // vector->int or fp->int?
1089 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1090 if (const VectorType *SrcVTy =
1091 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1092 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1093 // Don't touch a bitcast between vectors of different element counts.
1096 // Don't touch a scalar-to-vector bitcast.
1098 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1099 // Don't touch a vector-to-scalar bitcast.
1102 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1103 RHSKnownZero, RHSKnownOne, Depth+1))
1105 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1107 case Instruction::ZExt: {
1108 // Compute the bits in the result that are not present in the input.
1109 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1111 DemandedMask.trunc(SrcBitWidth);
1112 RHSKnownZero.trunc(SrcBitWidth);
1113 RHSKnownOne.trunc(SrcBitWidth);
1114 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1115 RHSKnownZero, RHSKnownOne, Depth+1))
1117 DemandedMask.zext(BitWidth);
1118 RHSKnownZero.zext(BitWidth);
1119 RHSKnownOne.zext(BitWidth);
1120 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1121 // The top bits are known to be zero.
1122 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1125 case Instruction::SExt: {
1126 // Compute the bits in the result that are not present in the input.
1127 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1129 APInt InputDemandedBits = DemandedMask &
1130 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1132 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1133 // If any of the sign extended bits are demanded, we know that the sign
1135 if ((NewBits & DemandedMask) != 0)
1136 InputDemandedBits.set(SrcBitWidth-1);
1138 InputDemandedBits.trunc(SrcBitWidth);
1139 RHSKnownZero.trunc(SrcBitWidth);
1140 RHSKnownOne.trunc(SrcBitWidth);
1141 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1142 RHSKnownZero, RHSKnownOne, Depth+1))
1144 InputDemandedBits.zext(BitWidth);
1145 RHSKnownZero.zext(BitWidth);
1146 RHSKnownOne.zext(BitWidth);
1147 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1149 // If the sign bit of the input is known set or clear, then we know the
1150 // top bits of the result.
1152 // If the input sign bit is known zero, or if the NewBits are not demanded
1153 // convert this into a zero extension.
1154 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1155 // Convert to ZExt cast
1156 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1157 return InsertNewInstBefore(NewCast, *I);
1158 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1159 RHSKnownOne |= NewBits;
1163 case Instruction::Add: {
1164 // Figure out what the input bits are. If the top bits of the and result
1165 // are not demanded, then the add doesn't demand them from its input
1167 unsigned NLZ = DemandedMask.countLeadingZeros();
1169 // If there is a constant on the RHS, there are a variety of xformations
1171 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1172 // If null, this should be simplified elsewhere. Some of the xforms here
1173 // won't work if the RHS is zero.
1177 // If the top bit of the output is demanded, demand everything from the
1178 // input. Otherwise, we demand all the input bits except NLZ top bits.
1179 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1181 // Find information about known zero/one bits in the input.
1182 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
1183 LHSKnownZero, LHSKnownOne, Depth+1))
1186 // If the RHS of the add has bits set that can't affect the input, reduce
1188 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1191 // Avoid excess work.
1192 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1195 // Turn it into OR if input bits are zero.
1196 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1198 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1200 return InsertNewInstBefore(Or, *I);
1203 // We can say something about the output known-zero and known-one bits,
1204 // depending on potential carries from the input constant and the
1205 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1206 // bits set and the RHS constant is 0x01001, then we know we have a known
1207 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1209 // To compute this, we first compute the potential carry bits. These are
1210 // the bits which may be modified. I'm not aware of a better way to do
1212 const APInt &RHSVal = RHS->getValue();
1213 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1215 // Now that we know which bits have carries, compute the known-1/0 sets.
1217 // Bits are known one if they are known zero in one operand and one in the
1218 // other, and there is no input carry.
1219 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1220 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1222 // Bits are known zero if they are known zero in both operands and there
1223 // is no input carry.
1224 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1226 // If the high-bits of this ADD are not demanded, then it does not demand
1227 // the high bits of its LHS or RHS.
1228 if (DemandedMask[BitWidth-1] == 0) {
1229 // Right fill the mask of bits for this ADD to demand the most
1230 // significant bit and all those below it.
1231 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1232 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1233 LHSKnownZero, LHSKnownOne, Depth+1) ||
1234 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1235 LHSKnownZero, LHSKnownOne, Depth+1))
1241 case Instruction::Sub:
1242 // If the high-bits of this SUB are not demanded, then it does not demand
1243 // the high bits of its LHS or RHS.
1244 if (DemandedMask[BitWidth-1] == 0) {
1245 // Right fill the mask of bits for this SUB to demand the most
1246 // significant bit and all those below it.
1247 uint32_t NLZ = DemandedMask.countLeadingZeros();
1248 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1249 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1250 LHSKnownZero, LHSKnownOne, Depth+1) ||
1251 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1252 LHSKnownZero, LHSKnownOne, Depth+1))
1255 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1256 // the known zeros and ones.
1257 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1259 case Instruction::Shl:
1260 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1261 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1262 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1263 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1264 RHSKnownZero, RHSKnownOne, Depth+1))
1266 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1267 RHSKnownZero <<= ShiftAmt;
1268 RHSKnownOne <<= ShiftAmt;
1269 // low bits known zero.
1271 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1274 case Instruction::LShr:
1275 // For a logical shift right
1276 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1277 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1279 // Unsigned shift right.
1280 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1281 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1282 RHSKnownZero, RHSKnownOne, Depth+1))
1284 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1285 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1286 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1288 // Compute the new bits that are at the top now.
1289 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1290 RHSKnownZero |= HighBits; // high bits known zero.
1294 case Instruction::AShr:
1295 // If this is an arithmetic shift right and only the low-bit is set, we can
1296 // always convert this into a logical shr, even if the shift amount is
1297 // variable. The low bit of the shift cannot be an input sign bit unless
1298 // the shift amount is >= the size of the datatype, which is undefined.
1299 if (DemandedMask == 1) {
1300 // Perform the logical shift right.
1301 Instruction *NewVal = BinaryOperator::CreateLShr(
1302 I->getOperand(0), I->getOperand(1), I->getName());
1303 return InsertNewInstBefore(NewVal, *I);
1306 // If the sign bit is the only bit demanded by this ashr, then there is no
1307 // need to do it, the shift doesn't change the high bit.
1308 if (DemandedMask.isSignBit())
1309 return I->getOperand(0);
1311 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1312 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1314 // Signed shift right.
1315 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1316 // If any of the "high bits" are demanded, we should set the sign bit as
1318 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1319 DemandedMaskIn.set(BitWidth-1);
1320 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1321 RHSKnownZero, RHSKnownOne, Depth+1))
1323 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1324 // Compute the new bits that are at the top now.
1325 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1326 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1327 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1329 // Handle the sign bits.
1330 APInt SignBit(APInt::getSignBit(BitWidth));
1331 // Adjust to where it is now in the mask.
1332 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1334 // If the input sign bit is known to be zero, or if none of the top bits
1335 // are demanded, turn this into an unsigned shift right.
1336 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
1337 (HighBits & ~DemandedMask) == HighBits) {
1338 // Perform the logical shift right.
1339 Instruction *NewVal = BinaryOperator::CreateLShr(
1340 I->getOperand(0), SA, I->getName());
1341 return InsertNewInstBefore(NewVal, *I);
1342 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1343 RHSKnownOne |= HighBits;
1347 case Instruction::SRem:
1348 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1349 APInt RA = Rem->getValue().abs();
1350 if (RA.isPowerOf2()) {
1351 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
1352 return I->getOperand(0);
1354 APInt LowBits = RA - 1;
1355 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1356 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1357 LHSKnownZero, LHSKnownOne, Depth+1))
1360 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1361 LHSKnownZero |= ~LowBits;
1363 KnownZero |= LHSKnownZero & DemandedMask;
1365 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
1369 case Instruction::URem: {
1370 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1371 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1372 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1373 KnownZero2, KnownOne2, Depth+1) ||
1374 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1375 KnownZero2, KnownOne2, Depth+1))
1378 unsigned Leaders = KnownZero2.countLeadingOnes();
1379 Leaders = std::max(Leaders,
1380 KnownZero2.countLeadingOnes());
1381 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1384 case Instruction::Call:
1385 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1386 switch (II->getIntrinsicID()) {
1388 case Intrinsic::bswap: {
1389 // If the only bits demanded come from one byte of the bswap result,
1390 // just shift the input byte into position to eliminate the bswap.
1391 unsigned NLZ = DemandedMask.countLeadingZeros();
1392 unsigned NTZ = DemandedMask.countTrailingZeros();
1394 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1395 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1396 // have 14 leading zeros, round to 8.
1399 // If we need exactly one byte, we can do this transformation.
1400 if (BitWidth-NLZ-NTZ == 8) {
1401 unsigned ResultBit = NTZ;
1402 unsigned InputBit = BitWidth-NTZ-8;
1404 // Replace this with either a left or right shift to get the byte into
1406 Instruction *NewVal;
1407 if (InputBit > ResultBit)
1408 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1409 ConstantInt::get(I->getType(), InputBit-ResultBit));
1411 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1412 ConstantInt::get(I->getType(), ResultBit-InputBit));
1413 NewVal->takeName(I);
1414 return InsertNewInstBefore(NewVal, *I);
1417 // TODO: Could compute known zero/one bits based on the input.
1422 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1426 // If the client is only demanding bits that we know, return the known
1428 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1429 return Constant::getIntegerValue(VTy, RHSKnownOne);
1434 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1435 /// any number of elements. DemandedElts contains the set of elements that are
1436 /// actually used by the caller. This method analyzes which elements of the
1437 /// operand are undef and returns that information in UndefElts.
1439 /// If the information about demanded elements can be used to simplify the
1440 /// operation, the operation is simplified, then the resultant value is
1441 /// returned. This returns null if no change was made.
1442 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1445 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1446 APInt EltMask(APInt::getAllOnesValue(VWidth));
1447 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1449 if (isa<UndefValue>(V)) {
1450 // If the entire vector is undefined, just return this info.
1451 UndefElts = EltMask;
1453 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1454 UndefElts = EltMask;
1455 return UndefValue::get(V->getType());
1459 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1460 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1461 Constant *Undef = UndefValue::get(EltTy);
1463 std::vector<Constant*> Elts;
1464 for (unsigned i = 0; i != VWidth; ++i)
1465 if (!DemandedElts[i]) { // If not demanded, set to undef.
1466 Elts.push_back(Undef);
1468 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1469 Elts.push_back(Undef);
1471 } else { // Otherwise, defined.
1472 Elts.push_back(CP->getOperand(i));
1475 // If we changed the constant, return it.
1476 Constant *NewCP = ConstantVector::get(Elts);
1477 return NewCP != CP ? NewCP : 0;
1478 } else if (isa<ConstantAggregateZero>(V)) {
1479 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1482 // Check if this is identity. If so, return 0 since we are not simplifying
1484 if (DemandedElts == ((1ULL << VWidth) -1))
1487 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1488 Constant *Zero = Constant::getNullValue(EltTy);
1489 Constant *Undef = UndefValue::get(EltTy);
1490 std::vector<Constant*> Elts;
1491 for (unsigned i = 0; i != VWidth; ++i) {
1492 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1493 Elts.push_back(Elt);
1495 UndefElts = DemandedElts ^ EltMask;
1496 return ConstantVector::get(Elts);
1499 // Limit search depth.
1503 // If multiple users are using the root value, procede with
1504 // simplification conservatively assuming that all elements
1506 if (!V->hasOneUse()) {
1507 // Quit if we find multiple users of a non-root value though.
1508 // They'll be handled when it's their turn to be visited by
1509 // the main instcombine process.
1511 // TODO: Just compute the UndefElts information recursively.
1514 // Conservatively assume that all elements are needed.
1515 DemandedElts = EltMask;
1518 Instruction *I = dyn_cast<Instruction>(V);
1519 if (!I) return 0; // Only analyze instructions.
1521 bool MadeChange = false;
1522 APInt UndefElts2(VWidth, 0);
1524 switch (I->getOpcode()) {
1527 case Instruction::InsertElement: {
1528 // If this is a variable index, we don't know which element it overwrites.
1529 // demand exactly the same input as we produce.
1530 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1532 // Note that we can't propagate undef elt info, because we don't know
1533 // which elt is getting updated.
1534 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1535 UndefElts2, Depth+1);
1536 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1540 // If this is inserting an element that isn't demanded, remove this
1542 unsigned IdxNo = Idx->getZExtValue();
1543 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1545 return I->getOperand(0);
1548 // Otherwise, the element inserted overwrites whatever was there, so the
1549 // input demanded set is simpler than the output set.
1550 APInt DemandedElts2 = DemandedElts;
1551 DemandedElts2.clear(IdxNo);
1552 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1553 UndefElts, Depth+1);
1554 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1556 // The inserted element is defined.
1557 UndefElts.clear(IdxNo);
1560 case Instruction::ShuffleVector: {
1561 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1562 uint64_t LHSVWidth =
1563 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1564 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1565 for (unsigned i = 0; i < VWidth; i++) {
1566 if (DemandedElts[i]) {
1567 unsigned MaskVal = Shuffle->getMaskValue(i);
1568 if (MaskVal != -1u) {
1569 assert(MaskVal < LHSVWidth * 2 &&
1570 "shufflevector mask index out of range!");
1571 if (MaskVal < LHSVWidth)
1572 LeftDemanded.set(MaskVal);
1574 RightDemanded.set(MaskVal - LHSVWidth);
1579 APInt UndefElts4(LHSVWidth, 0);
1580 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1581 UndefElts4, Depth+1);
1582 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1584 APInt UndefElts3(LHSVWidth, 0);
1585 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1586 UndefElts3, Depth+1);
1587 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1589 bool NewUndefElts = false;
1590 for (unsigned i = 0; i < VWidth; i++) {
1591 unsigned MaskVal = Shuffle->getMaskValue(i);
1592 if (MaskVal == -1u) {
1594 } else if (MaskVal < LHSVWidth) {
1595 if (UndefElts4[MaskVal]) {
1596 NewUndefElts = true;
1600 if (UndefElts3[MaskVal - LHSVWidth]) {
1601 NewUndefElts = true;
1608 // Add additional discovered undefs.
1609 std::vector<Constant*> Elts;
1610 for (unsigned i = 0; i < VWidth; ++i) {
1612 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1614 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1615 Shuffle->getMaskValue(i)));
1617 I->setOperand(2, ConstantVector::get(Elts));
1622 case Instruction::BitCast: {
1623 // Vector->vector casts only.
1624 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1626 unsigned InVWidth = VTy->getNumElements();
1627 APInt InputDemandedElts(InVWidth, 0);
1630 if (VWidth == InVWidth) {
1631 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1632 // elements as are demanded of us.
1634 InputDemandedElts = DemandedElts;
1635 } else if (VWidth > InVWidth) {
1639 // If there are more elements in the result than there are in the source,
1640 // then an input element is live if any of the corresponding output
1641 // elements are live.
1642 Ratio = VWidth/InVWidth;
1643 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1644 if (DemandedElts[OutIdx])
1645 InputDemandedElts.set(OutIdx/Ratio);
1651 // If there are more elements in the source than there are in the result,
1652 // then an input element is live if the corresponding output element is
1654 Ratio = InVWidth/VWidth;
1655 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1656 if (DemandedElts[InIdx/Ratio])
1657 InputDemandedElts.set(InIdx);
1660 // div/rem demand all inputs, because they don't want divide by zero.
1661 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1662 UndefElts2, Depth+1);
1664 I->setOperand(0, TmpV);
1668 UndefElts = UndefElts2;
1669 if (VWidth > InVWidth) {
1670 llvm_unreachable("Unimp");
1671 // If there are more elements in the result than there are in the source,
1672 // then an output element is undef if the corresponding input element is
1674 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1675 if (UndefElts2[OutIdx/Ratio])
1676 UndefElts.set(OutIdx);
1677 } else if (VWidth < InVWidth) {
1678 llvm_unreachable("Unimp");
1679 // If there are more elements in the source than there are in the result,
1680 // then a result element is undef if all of the corresponding input
1681 // elements are undef.
1682 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1683 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1684 if (!UndefElts2[InIdx]) // Not undef?
1685 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
1689 case Instruction::And:
1690 case Instruction::Or:
1691 case Instruction::Xor:
1692 case Instruction::Add:
1693 case Instruction::Sub:
1694 case Instruction::Mul:
1695 // div/rem demand all inputs, because they don't want divide by zero.
1696 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1697 UndefElts, Depth+1);
1698 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1699 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1700 UndefElts2, Depth+1);
1701 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1703 // Output elements are undefined if both are undefined. Consider things
1704 // like undef&0. The result is known zero, not undef.
1705 UndefElts &= UndefElts2;
1708 case Instruction::Call: {
1709 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1711 switch (II->getIntrinsicID()) {
1714 // Binary vector operations that work column-wise. A dest element is a
1715 // function of the corresponding input elements from the two inputs.
1716 case Intrinsic::x86_sse_sub_ss:
1717 case Intrinsic::x86_sse_mul_ss:
1718 case Intrinsic::x86_sse_min_ss:
1719 case Intrinsic::x86_sse_max_ss:
1720 case Intrinsic::x86_sse2_sub_sd:
1721 case Intrinsic::x86_sse2_mul_sd:
1722 case Intrinsic::x86_sse2_min_sd:
1723 case Intrinsic::x86_sse2_max_sd:
1724 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1725 UndefElts, Depth+1);
1726 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1727 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1728 UndefElts2, Depth+1);
1729 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1731 // If only the low elt is demanded and this is a scalarizable intrinsic,
1732 // scalarize it now.
1733 if (DemandedElts == 1) {
1734 switch (II->getIntrinsicID()) {
1736 case Intrinsic::x86_sse_sub_ss:
1737 case Intrinsic::x86_sse_mul_ss:
1738 case Intrinsic::x86_sse2_sub_sd:
1739 case Intrinsic::x86_sse2_mul_sd:
1740 // TODO: Lower MIN/MAX/ABS/etc
1741 Value *LHS = II->getOperand(1);
1742 Value *RHS = II->getOperand(2);
1743 // Extract the element as scalars.
1744 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
1745 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1746 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1747 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1749 switch (II->getIntrinsicID()) {
1750 default: llvm_unreachable("Case stmts out of sync!");
1751 case Intrinsic::x86_sse_sub_ss:
1752 case Intrinsic::x86_sse2_sub_sd:
1753 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1754 II->getName()), *II);
1756 case Intrinsic::x86_sse_mul_ss:
1757 case Intrinsic::x86_sse2_mul_sd:
1758 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1759 II->getName()), *II);
1764 InsertElementInst::Create(
1765 UndefValue::get(II->getType()), TmpV,
1766 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1767 InsertNewInstBefore(New, *II);
1772 // Output elements are undefined if both are undefined. Consider things
1773 // like undef&0. The result is known zero, not undef.
1774 UndefElts &= UndefElts2;
1780 return MadeChange ? I : 0;
1784 /// AssociativeOpt - Perform an optimization on an associative operator. This
1785 /// function is designed to check a chain of associative operators for a
1786 /// potential to apply a certain optimization. Since the optimization may be
1787 /// applicable if the expression was reassociated, this checks the chain, then
1788 /// reassociates the expression as necessary to expose the optimization
1789 /// opportunity. This makes use of a special Functor, which must define
1790 /// 'shouldApply' and 'apply' methods.
1792 template<typename Functor>
1793 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1794 unsigned Opcode = Root.getOpcode();
1795 Value *LHS = Root.getOperand(0);
1797 // Quick check, see if the immediate LHS matches...
1798 if (F.shouldApply(LHS))
1799 return F.apply(Root);
1801 // Otherwise, if the LHS is not of the same opcode as the root, return.
1802 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1803 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1804 // Should we apply this transform to the RHS?
1805 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1807 // If not to the RHS, check to see if we should apply to the LHS...
1808 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1809 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1813 // If the functor wants to apply the optimization to the RHS of LHSI,
1814 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1816 // Now all of the instructions are in the current basic block, go ahead
1817 // and perform the reassociation.
1818 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1820 // First move the selected RHS to the LHS of the root...
1821 Root.setOperand(0, LHSI->getOperand(1));
1823 // Make what used to be the LHS of the root be the user of the root...
1824 Value *ExtraOperand = TmpLHSI->getOperand(1);
1825 if (&Root == TmpLHSI) {
1826 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1829 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1830 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1831 BasicBlock::iterator ARI = &Root; ++ARI;
1832 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
1835 // Now propagate the ExtraOperand down the chain of instructions until we
1837 while (TmpLHSI != LHSI) {
1838 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1839 // Move the instruction to immediately before the chain we are
1840 // constructing to avoid breaking dominance properties.
1841 NextLHSI->moveBefore(ARI);
1844 Value *NextOp = NextLHSI->getOperand(1);
1845 NextLHSI->setOperand(1, ExtraOperand);
1847 ExtraOperand = NextOp;
1850 // Now that the instructions are reassociated, have the functor perform
1851 // the transformation...
1852 return F.apply(Root);
1855 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1862 // AddRHS - Implements: X + X --> X << 1
1865 explicit AddRHS(Value *rhs) : RHS(rhs) {}
1866 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1867 Instruction *apply(BinaryOperator &Add) const {
1868 return BinaryOperator::CreateShl(Add.getOperand(0),
1869 ConstantInt::get(Add.getType(), 1));
1873 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1875 struct AddMaskingAnd {
1877 explicit AddMaskingAnd(Constant *c) : C2(c) {}
1878 bool shouldApply(Value *LHS) const {
1880 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1881 ConstantExpr::getAnd(C1, C2)->isNullValue();
1883 Instruction *apply(BinaryOperator &Add) const {
1884 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1890 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1892 if (CastInst *CI = dyn_cast<CastInst>(&I))
1893 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
1895 // Figure out if the constant is the left or the right argument.
1896 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1897 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1899 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1901 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1902 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1905 Value *Op0 = SO, *Op1 = ConstOperand;
1907 std::swap(Op0, Op1);
1909 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1910 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1911 SO->getName()+".op");
1912 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1913 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1914 SO->getName()+".cmp");
1915 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1916 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1917 SO->getName()+".cmp");
1918 llvm_unreachable("Unknown binary instruction type!");
1921 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1922 // constant as the other operand, try to fold the binary operator into the
1923 // select arguments. This also works for Cast instructions, which obviously do
1924 // not have a second operand.
1925 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1927 // Don't modify shared select instructions
1928 if (!SI->hasOneUse()) return 0;
1929 Value *TV = SI->getOperand(1);
1930 Value *FV = SI->getOperand(2);
1932 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1933 // Bool selects with constant operands can be folded to logical ops.
1934 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
1936 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1937 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1939 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1946 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
1947 /// has a PHI node as operand #0, see if we can fold the instruction into the
1948 /// PHI (which is only possible if all operands to the PHI are constants).
1950 /// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
1951 /// that would normally be unprofitable because they strongly encourage jump
1953 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
1954 bool AllowAggressive) {
1955 AllowAggressive = false;
1956 PHINode *PN = cast<PHINode>(I.getOperand(0));
1957 unsigned NumPHIValues = PN->getNumIncomingValues();
1958 if (NumPHIValues == 0 ||
1959 // We normally only transform phis with a single use, unless we're trying
1960 // hard to make jump threading happen.
1961 (!PN->hasOneUse() && !AllowAggressive))
1965 // Check to see if all of the operands of the PHI are simple constants
1966 // (constantint/constantfp/undef). If there is one non-constant value,
1967 // remember the BB it is in. If there is more than one or if *it* is a PHI,
1968 // bail out. We don't do arbitrary constant expressions here because moving
1969 // their computation can be expensive without a cost model.
1970 BasicBlock *NonConstBB = 0;
1971 for (unsigned i = 0; i != NumPHIValues; ++i)
1972 if (!isa<Constant>(PN->getIncomingValue(i)) ||
1973 isa<ConstantExpr>(PN->getIncomingValue(i))) {
1974 if (NonConstBB) return 0; // More than one non-const value.
1975 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1976 NonConstBB = PN->getIncomingBlock(i);
1978 // If the incoming non-constant value is in I's block, we have an infinite
1980 if (NonConstBB == I.getParent())
1984 // If there is exactly one non-constant value, we can insert a copy of the
1985 // operation in that block. However, if this is a critical edge, we would be
1986 // inserting the computation one some other paths (e.g. inside a loop). Only
1987 // do this if the pred block is unconditionally branching into the phi block.
1988 if (NonConstBB != 0 && !AllowAggressive) {
1989 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1990 if (!BI || !BI->isUnconditional()) return 0;
1993 // Okay, we can do the transformation: create the new PHI node.
1994 PHINode *NewPN = PHINode::Create(I.getType(), "");
1995 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1996 InsertNewInstBefore(NewPN, *PN);
1997 NewPN->takeName(PN);
1999 // Next, add all of the operands to the PHI.
2000 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2001 // We only currently try to fold the condition of a select when it is a phi,
2002 // not the true/false values.
2003 Value *TrueV = SI->getTrueValue();
2004 Value *FalseV = SI->getFalseValue();
2005 for (unsigned i = 0; i != NumPHIValues; ++i) {
2006 BasicBlock *ThisBB = PN->getIncomingBlock(i);
2007 Value *TrueVInPred = TrueV->DoPHITranslation(I.getParent(), ThisBB);
2008 Value *FalseVInPred = FalseV->DoPHITranslation(I.getParent(), ThisBB);
2010 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2011 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
2013 assert(PN->getIncomingBlock(i) == NonConstBB);
2014 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2016 "phitmp", NonConstBB->getTerminator());
2017 Worklist.Add(cast<Instruction>(InV));
2019 NewPN->addIncoming(InV, ThisBB);
2021 } else if (I.getNumOperands() == 2) {
2022 Constant *C = cast<Constant>(I.getOperand(1));
2023 for (unsigned i = 0; i != NumPHIValues; ++i) {
2025 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2026 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2027 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2029 InV = ConstantExpr::get(I.getOpcode(), InC, C);
2031 assert(PN->getIncomingBlock(i) == NonConstBB);
2032 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2033 InV = BinaryOperator::Create(BO->getOpcode(),
2034 PN->getIncomingValue(i), C, "phitmp",
2035 NonConstBB->getTerminator());
2036 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2037 InV = CmpInst::Create(CI->getOpcode(),
2039 PN->getIncomingValue(i), C, "phitmp",
2040 NonConstBB->getTerminator());
2042 llvm_unreachable("Unknown binop!");
2044 Worklist.Add(cast<Instruction>(InV));
2046 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2049 CastInst *CI = cast<CastInst>(&I);
2050 const Type *RetTy = CI->getType();
2051 for (unsigned i = 0; i != NumPHIValues; ++i) {
2053 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2054 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2056 assert(PN->getIncomingBlock(i) == NonConstBB);
2057 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
2058 I.getType(), "phitmp",
2059 NonConstBB->getTerminator());
2060 Worklist.Add(cast<Instruction>(InV));
2062 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2065 return ReplaceInstUsesWith(I, NewPN);
2069 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2070 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2071 /// This basically requires proving that the add in the original type would not
2072 /// overflow to change the sign bit or have a carry out.
2073 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2074 // There are different heuristics we can use for this. Here are some simple
2077 // Add has the property that adding any two 2's complement numbers can only
2078 // have one carry bit which can change a sign. As such, if LHS and RHS each
2079 // have at least two sign bits, we know that the addition of the two values will
2080 // sign extend fine.
2081 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2085 // If one of the operands only has one non-zero bit, and if the other operand
2086 // has a known-zero bit in a more significant place than it (not including the
2087 // sign bit) the ripple may go up to and fill the zero, but won't change the
2088 // sign. For example, (X & ~4) + 1.
2096 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2097 bool Changed = SimplifyCommutative(I);
2098 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2100 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2101 // X + undef -> undef
2102 if (isa<UndefValue>(RHS))
2103 return ReplaceInstUsesWith(I, RHS);
2106 if (RHSC->isNullValue())
2107 return ReplaceInstUsesWith(I, LHS);
2109 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2110 // X + (signbit) --> X ^ signbit
2111 const APInt& Val = CI->getValue();
2112 uint32_t BitWidth = Val.getBitWidth();
2113 if (Val == APInt::getSignBit(BitWidth))
2114 return BinaryOperator::CreateXor(LHS, RHS);
2116 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2117 // (X & 254)+1 -> (X&254)|1
2118 if (SimplifyDemandedInstructionBits(I))
2121 // zext(bool) + C -> bool ? C + 1 : C
2122 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2123 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2124 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2127 if (isa<PHINode>(LHS))
2128 if (Instruction *NV = FoldOpIntoPhi(I))
2131 ConstantInt *XorRHS = 0;
2133 if (isa<ConstantInt>(RHSC) &&
2134 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2135 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2136 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2138 uint32_t Size = TySizeBits / 2;
2139 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2140 APInt CFF80Val(-C0080Val);
2142 if (TySizeBits > Size) {
2143 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2144 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2145 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2146 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2147 // This is a sign extend if the top bits are known zero.
2148 if (!MaskedValueIsZero(XorLHS,
2149 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2150 Size = 0; // Not a sign ext, but can't be any others either.
2155 C0080Val = APIntOps::lshr(C0080Val, Size);
2156 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2157 } while (Size >= 1);
2159 // FIXME: This shouldn't be necessary. When the backends can handle types
2160 // with funny bit widths then this switch statement should be removed. It
2161 // is just here to get the size of the "middle" type back up to something
2162 // that the back ends can handle.
2163 const Type *MiddleType = 0;
2166 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2167 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2168 case 8: MiddleType = Type::getInt8Ty(*Context); break;
2171 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
2172 return new SExtInst(NewTrunc, I.getType(), I.getName());
2177 if (I.getType() == Type::getInt1Ty(*Context))
2178 return BinaryOperator::CreateXor(LHS, RHS);
2181 if (I.getType()->isInteger()) {
2182 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2185 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2186 if (RHSI->getOpcode() == Instruction::Sub)
2187 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2188 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2190 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2191 if (LHSI->getOpcode() == Instruction::Sub)
2192 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2193 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2198 // -A + -B --> -(A + B)
2199 if (Value *LHSV = dyn_castNegVal(LHS)) {
2200 if (LHS->getType()->isIntOrIntVector()) {
2201 if (Value *RHSV = dyn_castNegVal(RHS)) {
2202 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
2203 return BinaryOperator::CreateNeg(NewAdd);
2207 return BinaryOperator::CreateSub(RHS, LHSV);
2211 if (!isa<Constant>(RHS))
2212 if (Value *V = dyn_castNegVal(RHS))
2213 return BinaryOperator::CreateSub(LHS, V);
2217 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2218 if (X == RHS) // X*C + X --> X * (C+1)
2219 return BinaryOperator::CreateMul(RHS, AddOne(C2));
2221 // X*C1 + X*C2 --> X * (C1+C2)
2223 if (X == dyn_castFoldableMul(RHS, C1))
2224 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2227 // X + X*C --> X * (C+1)
2228 if (dyn_castFoldableMul(RHS, C2) == LHS)
2229 return BinaryOperator::CreateMul(LHS, AddOne(C2));
2231 // X + ~X --> -1 since ~X = -X-1
2232 if (dyn_castNotVal(LHS) == RHS ||
2233 dyn_castNotVal(RHS) == LHS)
2234 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2237 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2238 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2239 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2242 // A+B --> A|B iff A and B have no bits set in common.
2243 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2244 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2245 APInt LHSKnownOne(IT->getBitWidth(), 0);
2246 APInt LHSKnownZero(IT->getBitWidth(), 0);
2247 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2248 if (LHSKnownZero != 0) {
2249 APInt RHSKnownOne(IT->getBitWidth(), 0);
2250 APInt RHSKnownZero(IT->getBitWidth(), 0);
2251 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2253 // No bits in common -> bitwise or.
2254 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2255 return BinaryOperator::CreateOr(LHS, RHS);
2259 // W*X + Y*Z --> W * (X+Z) iff W == Y
2260 if (I.getType()->isIntOrIntVector()) {
2261 Value *W, *X, *Y, *Z;
2262 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2263 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2267 } else if (Y == X) {
2269 } else if (X == Z) {
2276 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
2277 return BinaryOperator::CreateMul(W, NewAdd);
2282 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2284 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2285 return BinaryOperator::CreateSub(SubOne(CRHS), X);
2287 // (X & FF00) + xx00 -> (X+xx00) & FF00
2288 if (LHS->hasOneUse() &&
2289 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2290 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2291 if (Anded == CRHS) {
2292 // See if all bits from the first bit set in the Add RHS up are included
2293 // in the mask. First, get the rightmost bit.
2294 const APInt& AddRHSV = CRHS->getValue();
2296 // Form a mask of all bits from the lowest bit added through the top.
2297 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2299 // See if the and mask includes all of these bits.
2300 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2302 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2303 // Okay, the xform is safe. Insert the new add pronto.
2304 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
2305 return BinaryOperator::CreateAnd(NewAdd, C2);
2310 // Try to fold constant add into select arguments.
2311 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2312 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2316 // add (select X 0 (sub n A)) A --> select X A n
2318 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2321 SI = dyn_cast<SelectInst>(RHS);
2324 if (SI && SI->hasOneUse()) {
2325 Value *TV = SI->getTrueValue();
2326 Value *FV = SI->getFalseValue();
2329 // Can we fold the add into the argument of the select?
2330 // We check both true and false select arguments for a matching subtract.
2331 if (match(FV, m_Zero()) &&
2332 match(TV, m_Sub(m_Value(N), m_Specific(A))))
2333 // Fold the add into the true select value.
2334 return SelectInst::Create(SI->getCondition(), N, A);
2335 if (match(TV, m_Zero()) &&
2336 match(FV, m_Sub(m_Value(N), m_Specific(A))))
2337 // Fold the add into the false select value.
2338 return SelectInst::Create(SI->getCondition(), A, N);
2342 // Check for (add (sext x), y), see if we can merge this into an
2343 // integer add followed by a sext.
2344 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2345 // (add (sext x), cst) --> (sext (add x, cst'))
2346 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2348 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2349 if (LHSConv->hasOneUse() &&
2350 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2351 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2352 // Insert the new, smaller add.
2353 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2355 return new SExtInst(NewAdd, I.getType());
2359 // (add (sext x), (sext y)) --> (sext (add int x, y))
2360 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2361 // Only do this if x/y have the same type, if at last one of them has a
2362 // single use (so we don't increase the number of sexts), and if the
2363 // integer add will not overflow.
2364 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2365 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2366 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2367 RHSConv->getOperand(0))) {
2368 // Insert the new integer add.
2369 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2370 RHSConv->getOperand(0), "addconv");
2371 return new SExtInst(NewAdd, I.getType());
2376 return Changed ? &I : 0;
2379 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2380 bool Changed = SimplifyCommutative(I);
2381 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2383 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2385 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2386 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2387 (I.getType())->getValueAPF()))
2388 return ReplaceInstUsesWith(I, LHS);
2391 if (isa<PHINode>(LHS))
2392 if (Instruction *NV = FoldOpIntoPhi(I))
2397 // -A + -B --> -(A + B)
2398 if (Value *LHSV = dyn_castFNegVal(LHS))
2399 return BinaryOperator::CreateFSub(RHS, LHSV);
2402 if (!isa<Constant>(RHS))
2403 if (Value *V = dyn_castFNegVal(RHS))
2404 return BinaryOperator::CreateFSub(LHS, V);
2406 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2407 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2408 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2409 return ReplaceInstUsesWith(I, LHS);
2411 // Check for (add double (sitofp x), y), see if we can merge this into an
2412 // integer add followed by a promotion.
2413 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2414 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2415 // ... if the constant fits in the integer value. This is useful for things
2416 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2417 // requires a constant pool load, and generally allows the add to be better
2419 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2421 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2422 if (LHSConv->hasOneUse() &&
2423 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2424 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2425 // Insert the new integer add.
2426 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2428 return new SIToFPInst(NewAdd, I.getType());
2432 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2433 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2434 // Only do this if x/y have the same type, if at last one of them has a
2435 // single use (so we don't increase the number of int->fp conversions),
2436 // and if the integer add will not overflow.
2437 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2438 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2439 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2440 RHSConv->getOperand(0))) {
2441 // Insert the new integer add.
2442 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2443 RHSConv->getOperand(0), "addconv");
2444 return new SIToFPInst(NewAdd, I.getType());
2449 return Changed ? &I : 0;
2452 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2453 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2455 if (Op0 == Op1) // sub X, X -> 0
2456 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2458 // If this is a 'B = x-(-A)', change to B = x+A...
2459 if (Value *V = dyn_castNegVal(Op1))
2460 return BinaryOperator::CreateAdd(Op0, V);
2462 if (isa<UndefValue>(Op0))
2463 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2464 if (isa<UndefValue>(Op1))
2465 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2467 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2468 // Replace (-1 - A) with (~A)...
2469 if (C->isAllOnesValue())
2470 return BinaryOperator::CreateNot(Op1);
2472 // C - ~X == X + (1+C)
2474 if (match(Op1, m_Not(m_Value(X))))
2475 return BinaryOperator::CreateAdd(X, AddOne(C));
2477 // -(X >>u 31) -> (X >>s 31)
2478 // -(X >>s 31) -> (X >>u 31)
2480 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2481 if (SI->getOpcode() == Instruction::LShr) {
2482 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2483 // Check to see if we are shifting out everything but the sign bit.
2484 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2485 SI->getType()->getPrimitiveSizeInBits()-1) {
2486 // Ok, the transformation is safe. Insert AShr.
2487 return BinaryOperator::Create(Instruction::AShr,
2488 SI->getOperand(0), CU, SI->getName());
2492 else if (SI->getOpcode() == Instruction::AShr) {
2493 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2494 // Check to see if we are shifting out everything but the sign bit.
2495 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2496 SI->getType()->getPrimitiveSizeInBits()-1) {
2497 // Ok, the transformation is safe. Insert LShr.
2498 return BinaryOperator::CreateLShr(
2499 SI->getOperand(0), CU, SI->getName());
2506 // Try to fold constant sub into select arguments.
2507 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2508 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2511 // C - zext(bool) -> bool ? C - 1 : C
2512 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2513 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2514 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2517 if (I.getType() == Type::getInt1Ty(*Context))
2518 return BinaryOperator::CreateXor(Op0, Op1);
2520 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2521 if (Op1I->getOpcode() == Instruction::Add) {
2522 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2523 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2525 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2526 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2528 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2529 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2530 // C1-(X+C2) --> (C1-C2)-X
2531 return BinaryOperator::CreateSub(
2532 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2536 if (Op1I->hasOneUse()) {
2537 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2538 // is not used by anyone else...
2540 if (Op1I->getOpcode() == Instruction::Sub) {
2541 // Swap the two operands of the subexpr...
2542 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2543 Op1I->setOperand(0, IIOp1);
2544 Op1I->setOperand(1, IIOp0);
2546 // Create the new top level add instruction...
2547 return BinaryOperator::CreateAdd(Op0, Op1);
2550 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2552 if (Op1I->getOpcode() == Instruction::And &&
2553 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2554 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2556 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
2557 return BinaryOperator::CreateAnd(Op0, NewNot);
2560 // 0 - (X sdiv C) -> (X sdiv -C)
2561 if (Op1I->getOpcode() == Instruction::SDiv)
2562 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2564 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2565 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2566 ConstantExpr::getNeg(DivRHS));
2568 // X - X*C --> X * (1-C)
2569 ConstantInt *C2 = 0;
2570 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2572 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2574 return BinaryOperator::CreateMul(Op0, CP1);
2579 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2580 if (Op0I->getOpcode() == Instruction::Add) {
2581 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2582 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2583 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2584 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2585 } else if (Op0I->getOpcode() == Instruction::Sub) {
2586 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2587 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2593 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2594 if (X == Op1) // X*C - X --> X * (C-1)
2595 return BinaryOperator::CreateMul(Op1, SubOne(C1));
2597 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2598 if (X == dyn_castFoldableMul(Op1, C2))
2599 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2604 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2605 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2607 // If this is a 'B = x-(-A)', change to B = x+A...
2608 if (Value *V = dyn_castFNegVal(Op1))
2609 return BinaryOperator::CreateFAdd(Op0, V);
2611 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2612 if (Op1I->getOpcode() == Instruction::FAdd) {
2613 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2614 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2616 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2617 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2625 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2626 /// comparison only checks the sign bit. If it only checks the sign bit, set
2627 /// TrueIfSigned if the result of the comparison is true when the input value is
2629 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2630 bool &TrueIfSigned) {
2632 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2633 TrueIfSigned = true;
2634 return RHS->isZero();
2635 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2636 TrueIfSigned = true;
2637 return RHS->isAllOnesValue();
2638 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2639 TrueIfSigned = false;
2640 return RHS->isAllOnesValue();
2641 case ICmpInst::ICMP_UGT:
2642 // True if LHS u> RHS and RHS == high-bit-mask - 1
2643 TrueIfSigned = true;
2644 return RHS->getValue() ==
2645 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2646 case ICmpInst::ICMP_UGE:
2647 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2648 TrueIfSigned = true;
2649 return RHS->getValue().isSignBit();
2655 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2656 bool Changed = SimplifyCommutative(I);
2657 Value *Op0 = I.getOperand(0);
2659 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2660 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2662 // Simplify mul instructions with a constant RHS...
2663 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2664 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2666 // ((X << C1)*C2) == (X * (C2 << C1))
2667 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2668 if (SI->getOpcode() == Instruction::Shl)
2669 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2670 return BinaryOperator::CreateMul(SI->getOperand(0),
2671 ConstantExpr::getShl(CI, ShOp));
2674 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2675 if (CI->equalsInt(1)) // X * 1 == X
2676 return ReplaceInstUsesWith(I, Op0);
2677 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2678 return BinaryOperator::CreateNeg(Op0, I.getName());
2680 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2681 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2682 return BinaryOperator::CreateShl(Op0,
2683 ConstantInt::get(Op0->getType(), Val.logBase2()));
2685 } else if (isa<VectorType>(Op1->getType())) {
2686 if (Op1->isNullValue())
2687 return ReplaceInstUsesWith(I, Op1);
2689 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2690 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2691 return BinaryOperator::CreateNeg(Op0, I.getName());
2693 // As above, vector X*splat(1.0) -> X in all defined cases.
2694 if (Constant *Splat = Op1V->getSplatValue()) {
2695 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2696 if (CI->equalsInt(1))
2697 return ReplaceInstUsesWith(I, Op0);
2702 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2703 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2704 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2705 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2706 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1, "tmp");
2707 Value *C1C2 = Builder->CreateMul(Op1, Op0I->getOperand(1));
2708 return BinaryOperator::CreateAdd(Add, C1C2);
2712 // Try to fold constant mul into select arguments.
2713 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2714 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2717 if (isa<PHINode>(Op0))
2718 if (Instruction *NV = FoldOpIntoPhi(I))
2722 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2723 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2724 return BinaryOperator::CreateMul(Op0v, Op1v);
2726 // (X / Y) * Y = X - (X % Y)
2727 // (X / Y) * -Y = (X % Y) - X
2729 Value *Op1 = I.getOperand(1);
2730 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2732 (BO->getOpcode() != Instruction::UDiv &&
2733 BO->getOpcode() != Instruction::SDiv)) {
2735 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2737 Value *Neg = dyn_castNegVal(Op1);
2738 if (BO && BO->hasOneUse() &&
2739 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2740 (BO->getOpcode() == Instruction::UDiv ||
2741 BO->getOpcode() == Instruction::SDiv)) {
2742 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2744 // If the division is exact, X % Y is zero.
2745 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2746 if (SDiv->isExact()) {
2748 return ReplaceInstUsesWith(I, Op0BO);
2750 return BinaryOperator::CreateNeg(Op0BO);
2754 if (BO->getOpcode() == Instruction::UDiv)
2755 Rem = Builder->CreateURem(Op0BO, Op1BO);
2757 Rem = Builder->CreateSRem(Op0BO, Op1BO);
2761 return BinaryOperator::CreateSub(Op0BO, Rem);
2762 return BinaryOperator::CreateSub(Rem, Op0BO);
2766 if (I.getType() == Type::getInt1Ty(*Context))
2767 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2769 // If one of the operands of the multiply is a cast from a boolean value, then
2770 // we know the bool is either zero or one, so this is a 'masking' multiply.
2771 // See if we can simplify things based on how the boolean was originally
2773 CastInst *BoolCast = 0;
2774 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2775 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2778 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2779 if (CI->getOperand(0)->getType() == Type::getInt1Ty(*Context))
2782 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2783 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2784 const Type *SCOpTy = SCIOp0->getType();
2787 // If the icmp is true iff the sign bit of X is set, then convert this
2788 // multiply into a shift/and combination.
2789 if (isa<ConstantInt>(SCIOp1) &&
2790 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2792 // Shift the X value right to turn it into "all signbits".
2793 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2794 SCOpTy->getPrimitiveSizeInBits()-1);
2795 Value *V = Builder->CreateAShr(SCIOp0, Amt,
2796 BoolCast->getOperand(0)->getName()+".mask");
2798 // If the multiply type is not the same as the source type, sign extend
2799 // or truncate to the multiply type.
2800 if (I.getType() != V->getType())
2801 V = Builder->CreateIntCast(V, I.getType(), true);
2803 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2804 return BinaryOperator::CreateAnd(V, OtherOp);
2809 return Changed ? &I : 0;
2812 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2813 bool Changed = SimplifyCommutative(I);
2814 Value *Op0 = I.getOperand(0);
2816 // Simplify mul instructions with a constant RHS...
2817 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2818 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2819 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2820 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2821 if (Op1F->isExactlyValue(1.0))
2822 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2823 } else if (isa<VectorType>(Op1->getType())) {
2824 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2825 // As above, vector X*splat(1.0) -> X in all defined cases.
2826 if (Constant *Splat = Op1V->getSplatValue()) {
2827 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2828 if (F->isExactlyValue(1.0))
2829 return ReplaceInstUsesWith(I, Op0);
2834 // Try to fold constant mul into select arguments.
2835 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2836 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2839 if (isa<PHINode>(Op0))
2840 if (Instruction *NV = FoldOpIntoPhi(I))
2844 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2845 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1)))
2846 return BinaryOperator::CreateFMul(Op0v, Op1v);
2848 return Changed ? &I : 0;
2851 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2853 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2854 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2856 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2857 int NonNullOperand = -1;
2858 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2859 if (ST->isNullValue())
2861 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2862 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2863 if (ST->isNullValue())
2866 if (NonNullOperand == -1)
2869 Value *SelectCond = SI->getOperand(0);
2871 // Change the div/rem to use 'Y' instead of the select.
2872 I.setOperand(1, SI->getOperand(NonNullOperand));
2874 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2875 // problem. However, the select, or the condition of the select may have
2876 // multiple uses. Based on our knowledge that the operand must be non-zero,
2877 // propagate the known value for the select into other uses of it, and
2878 // propagate a known value of the condition into its other users.
2880 // If the select and condition only have a single use, don't bother with this,
2882 if (SI->use_empty() && SelectCond->hasOneUse())
2885 // Scan the current block backward, looking for other uses of SI.
2886 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2888 while (BBI != BBFront) {
2890 // If we found a call to a function, we can't assume it will return, so
2891 // information from below it cannot be propagated above it.
2892 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2895 // Replace uses of the select or its condition with the known values.
2896 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2899 *I = SI->getOperand(NonNullOperand);
2901 } else if (*I == SelectCond) {
2902 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2903 ConstantInt::getFalse(*Context);
2908 // If we past the instruction, quit looking for it.
2911 if (&*BBI == SelectCond)
2914 // If we ran out of things to eliminate, break out of the loop.
2915 if (SelectCond == 0 && SI == 0)
2923 /// This function implements the transforms on div instructions that work
2924 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2925 /// used by the visitors to those instructions.
2926 /// @brief Transforms common to all three div instructions
2927 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2928 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2930 // undef / X -> 0 for integer.
2931 // undef / X -> undef for FP (the undef could be a snan).
2932 if (isa<UndefValue>(Op0)) {
2933 if (Op0->getType()->isFPOrFPVector())
2934 return ReplaceInstUsesWith(I, Op0);
2935 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2938 // X / undef -> undef
2939 if (isa<UndefValue>(Op1))
2940 return ReplaceInstUsesWith(I, Op1);
2945 /// This function implements the transforms common to both integer division
2946 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2947 /// division instructions.
2948 /// @brief Common integer divide transforms
2949 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2950 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2952 // (sdiv X, X) --> 1 (udiv X, X) --> 1
2954 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2955 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
2956 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2957 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2960 Constant *CI = ConstantInt::get(I.getType(), 1);
2961 return ReplaceInstUsesWith(I, CI);
2964 if (Instruction *Common = commonDivTransforms(I))
2967 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2968 // This does not apply for fdiv.
2969 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2972 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2974 if (RHS->equalsInt(1))
2975 return ReplaceInstUsesWith(I, Op0);
2977 // (X / C1) / C2 -> X / (C1*C2)
2978 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2979 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2980 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2981 if (MultiplyOverflows(RHS, LHSRHS,
2982 I.getOpcode()==Instruction::SDiv))
2983 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2985 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2986 ConstantExpr::getMul(RHS, LHSRHS));
2989 if (!RHS->isZero()) { // avoid X udiv 0
2990 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2991 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2993 if (isa<PHINode>(Op0))
2994 if (Instruction *NV = FoldOpIntoPhi(I))
2999 // 0 / X == 0, we don't need to preserve faults!
3000 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3001 if (LHS->equalsInt(0))
3002 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3004 // It can't be division by zero, hence it must be division by one.
3005 if (I.getType() == Type::getInt1Ty(*Context))
3006 return ReplaceInstUsesWith(I, Op0);
3008 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3009 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3012 return ReplaceInstUsesWith(I, Op0);
3018 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3019 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3021 // Handle the integer div common cases
3022 if (Instruction *Common = commonIDivTransforms(I))
3025 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3026 // X udiv C^2 -> X >> C
3027 // Check to see if this is an unsigned division with an exact power of 2,
3028 // if so, convert to a right shift.
3029 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
3030 return BinaryOperator::CreateLShr(Op0,
3031 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3033 // X udiv C, where C >= signbit
3034 if (C->getValue().isNegative()) {
3035 Value *IC = Builder->CreateICmpULT( Op0, C);
3036 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3037 ConstantInt::get(I.getType(), 1));
3041 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3042 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3043 if (RHSI->getOpcode() == Instruction::Shl &&
3044 isa<ConstantInt>(RHSI->getOperand(0))) {
3045 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3046 if (C1.isPowerOf2()) {
3047 Value *N = RHSI->getOperand(1);
3048 const Type *NTy = N->getType();
3049 if (uint32_t C2 = C1.logBase2())
3050 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
3051 return BinaryOperator::CreateLShr(Op0, N);
3056 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3057 // where C1&C2 are powers of two.
3058 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3059 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3060 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3061 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3062 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3063 // Compute the shift amounts
3064 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3065 // Construct the "on true" case of the select
3066 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3067 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
3069 // Construct the "on false" case of the select
3070 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
3071 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
3073 // construct the select instruction and return it.
3074 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3080 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3081 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3083 // Handle the integer div common cases
3084 if (Instruction *Common = commonIDivTransforms(I))
3087 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3089 if (RHS->isAllOnesValue())
3090 return BinaryOperator::CreateNeg(Op0);
3092 // sdiv X, C --> ashr X, log2(C)
3093 if (cast<SDivOperator>(&I)->isExact() &&
3094 RHS->getValue().isNonNegative() &&
3095 RHS->getValue().isPowerOf2()) {
3096 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3097 RHS->getValue().exactLogBase2());
3098 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3101 // -X/C --> X/-C provided the negation doesn't overflow.
3102 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3103 if (isa<Constant>(Sub->getOperand(0)) &&
3104 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3105 Sub->hasNoSignedWrap())
3106 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3107 ConstantExpr::getNeg(RHS));
3110 // If the sign bits of both operands are zero (i.e. we can prove they are
3111 // unsigned inputs), turn this into a udiv.
3112 if (I.getType()->isInteger()) {
3113 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3114 if (MaskedValueIsZero(Op0, Mask)) {
3115 if (MaskedValueIsZero(Op1, Mask)) {
3116 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3117 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3119 ConstantInt *ShiftedInt;
3120 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3121 ShiftedInt->getValue().isPowerOf2()) {
3122 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3123 // Safe because the only negative value (1 << Y) can take on is
3124 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3125 // the sign bit set.
3126 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3134 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3135 return commonDivTransforms(I);
3138 /// This function implements the transforms on rem instructions that work
3139 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3140 /// is used by the visitors to those instructions.
3141 /// @brief Transforms common to all three rem instructions
3142 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3143 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3145 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3146 if (I.getType()->isFPOrFPVector())
3147 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
3148 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3150 if (isa<UndefValue>(Op1))
3151 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3153 // Handle cases involving: rem X, (select Cond, Y, Z)
3154 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3160 /// This function implements the transforms common to both integer remainder
3161 /// instructions (urem and srem). It is called by the visitors to those integer
3162 /// remainder instructions.
3163 /// @brief Common integer remainder transforms
3164 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3165 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3167 if (Instruction *common = commonRemTransforms(I))
3170 // 0 % X == 0 for integer, we don't need to preserve faults!
3171 if (Constant *LHS = dyn_cast<Constant>(Op0))
3172 if (LHS->isNullValue())
3173 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3175 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3176 // X % 0 == undef, we don't need to preserve faults!
3177 if (RHS->equalsInt(0))
3178 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3180 if (RHS->equalsInt(1)) // X % 1 == 0
3181 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3183 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3184 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3185 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3187 } else if (isa<PHINode>(Op0I)) {
3188 if (Instruction *NV = FoldOpIntoPhi(I))
3192 // See if we can fold away this rem instruction.
3193 if (SimplifyDemandedInstructionBits(I))
3201 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3202 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3204 if (Instruction *common = commonIRemTransforms(I))
3207 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3208 // X urem C^2 -> X and C
3209 // Check to see if this is an unsigned remainder with an exact power of 2,
3210 // if so, convert to a bitwise and.
3211 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3212 if (C->getValue().isPowerOf2())
3213 return BinaryOperator::CreateAnd(Op0, SubOne(C));
3216 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3217 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3218 if (RHSI->getOpcode() == Instruction::Shl &&
3219 isa<ConstantInt>(RHSI->getOperand(0))) {
3220 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3221 Constant *N1 = Constant::getAllOnesValue(I.getType());
3222 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
3223 return BinaryOperator::CreateAnd(Op0, Add);
3228 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3229 // where C1&C2 are powers of two.
3230 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3231 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3232 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3233 // STO == 0 and SFO == 0 handled above.
3234 if ((STO->getValue().isPowerOf2()) &&
3235 (SFO->getValue().isPowerOf2())) {
3236 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3237 SI->getName()+".t");
3238 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3239 SI->getName()+".f");
3240 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3248 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3249 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3251 // Handle the integer rem common cases
3252 if (Instruction *Common = commonIRemTransforms(I))
3255 if (Value *RHSNeg = dyn_castNegVal(Op1))
3256 if (!isa<Constant>(RHSNeg) ||
3257 (isa<ConstantInt>(RHSNeg) &&
3258 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3260 Worklist.AddValue(I.getOperand(1));
3261 I.setOperand(1, RHSNeg);
3265 // If the sign bits of both operands are zero (i.e. we can prove they are
3266 // unsigned inputs), turn this into a urem.
3267 if (I.getType()->isInteger()) {
3268 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3269 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3270 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3271 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3275 // If it's a constant vector, flip any negative values positive.
3276 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3277 unsigned VWidth = RHSV->getNumOperands();
3279 bool hasNegative = false;
3280 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3281 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3282 if (RHS->getValue().isNegative())
3286 std::vector<Constant *> Elts(VWidth);
3287 for (unsigned i = 0; i != VWidth; ++i) {
3288 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3289 if (RHS->getValue().isNegative())
3290 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3296 Constant *NewRHSV = ConstantVector::get(Elts);
3297 if (NewRHSV != RHSV) {
3298 Worklist.AddValue(I.getOperand(1));
3299 I.setOperand(1, NewRHSV);
3308 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3309 return commonRemTransforms(I);
3312 // isOneBitSet - Return true if there is exactly one bit set in the specified
3314 static bool isOneBitSet(const ConstantInt *CI) {
3315 return CI->getValue().isPowerOf2();
3318 // isHighOnes - Return true if the constant is of the form 1+0+.
3319 // This is the same as lowones(~X).
3320 static bool isHighOnes(const ConstantInt *CI) {
3321 return (~CI->getValue() + 1).isPowerOf2();
3324 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3325 /// are carefully arranged to allow folding of expressions such as:
3327 /// (A < B) | (A > B) --> (A != B)
3329 /// Note that this is only valid if the first and second predicates have the
3330 /// same sign. Is illegal to do: (A u< B) | (A s> B)
3332 /// Three bits are used to represent the condition, as follows:
3337 /// <=> Value Definition
3338 /// 000 0 Always false
3345 /// 111 7 Always true
3347 static unsigned getICmpCode(const ICmpInst *ICI) {
3348 switch (ICI->getPredicate()) {
3350 case ICmpInst::ICMP_UGT: return 1; // 001
3351 case ICmpInst::ICMP_SGT: return 1; // 001
3352 case ICmpInst::ICMP_EQ: return 2; // 010
3353 case ICmpInst::ICMP_UGE: return 3; // 011
3354 case ICmpInst::ICMP_SGE: return 3; // 011
3355 case ICmpInst::ICMP_ULT: return 4; // 100
3356 case ICmpInst::ICMP_SLT: return 4; // 100
3357 case ICmpInst::ICMP_NE: return 5; // 101
3358 case ICmpInst::ICMP_ULE: return 6; // 110
3359 case ICmpInst::ICMP_SLE: return 6; // 110
3362 llvm_unreachable("Invalid ICmp predicate!");
3367 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3368 /// predicate into a three bit mask. It also returns whether it is an ordered
3369 /// predicate by reference.
3370 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3373 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3374 case FCmpInst::FCMP_UNO: return 0; // 000
3375 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3376 case FCmpInst::FCMP_UGT: return 1; // 001
3377 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3378 case FCmpInst::FCMP_UEQ: return 2; // 010
3379 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3380 case FCmpInst::FCMP_UGE: return 3; // 011
3381 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3382 case FCmpInst::FCMP_ULT: return 4; // 100
3383 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3384 case FCmpInst::FCMP_UNE: return 5; // 101
3385 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3386 case FCmpInst::FCMP_ULE: return 6; // 110
3389 // Not expecting FCMP_FALSE and FCMP_TRUE;
3390 llvm_unreachable("Unexpected FCmp predicate!");
3395 /// getICmpValue - This is the complement of getICmpCode, which turns an
3396 /// opcode and two operands into either a constant true or false, or a brand
3397 /// new ICmp instruction. The sign is passed in to determine which kind
3398 /// of predicate to use in the new icmp instruction.
3399 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3400 LLVMContext *Context) {
3402 default: llvm_unreachable("Illegal ICmp code!");
3403 case 0: return ConstantInt::getFalse(*Context);
3406 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3408 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3409 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3412 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3414 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3417 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3419 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3420 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3423 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3425 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3426 case 7: return ConstantInt::getTrue(*Context);
3430 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3431 /// opcode and two operands into either a FCmp instruction. isordered is passed
3432 /// in to determine which kind of predicate to use in the new fcmp instruction.
3433 static Value *getFCmpValue(bool isordered, unsigned code,
3434 Value *LHS, Value *RHS, LLVMContext *Context) {
3436 default: llvm_unreachable("Illegal FCmp code!");
3439 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3441 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3444 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3446 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3449 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3451 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3454 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3456 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3459 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3461 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3464 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3466 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3469 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3471 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3472 case 7: return ConstantInt::getTrue(*Context);
3476 /// PredicatesFoldable - Return true if both predicates match sign or if at
3477 /// least one of them is an equality comparison (which is signless).
3478 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3479 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3480 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3481 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3485 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3486 struct FoldICmpLogical {
3489 ICmpInst::Predicate pred;
3490 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3491 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3492 pred(ICI->getPredicate()) {}
3493 bool shouldApply(Value *V) const {
3494 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3495 if (PredicatesFoldable(pred, ICI->getPredicate()))
3496 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3497 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3500 Instruction *apply(Instruction &Log) const {
3501 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3502 if (ICI->getOperand(0) != LHS) {
3503 assert(ICI->getOperand(1) == LHS);
3504 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3507 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3508 unsigned LHSCode = getICmpCode(ICI);
3509 unsigned RHSCode = getICmpCode(RHSICI);
3511 switch (Log.getOpcode()) {
3512 case Instruction::And: Code = LHSCode & RHSCode; break;
3513 case Instruction::Or: Code = LHSCode | RHSCode; break;
3514 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3515 default: llvm_unreachable("Illegal logical opcode!"); return 0;
3518 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3519 ICmpInst::isSignedPredicate(ICI->getPredicate());
3521 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3522 if (Instruction *I = dyn_cast<Instruction>(RV))
3524 // Otherwise, it's a constant boolean value...
3525 return IC.ReplaceInstUsesWith(Log, RV);
3528 } // end anonymous namespace
3530 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3531 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3532 // guaranteed to be a binary operator.
3533 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3535 ConstantInt *AndRHS,
3536 BinaryOperator &TheAnd) {
3537 Value *X = Op->getOperand(0);
3538 Constant *Together = 0;
3540 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3542 switch (Op->getOpcode()) {
3543 case Instruction::Xor:
3544 if (Op->hasOneUse()) {
3545 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3546 Value *And = Builder->CreateAnd(X, AndRHS);
3548 return BinaryOperator::CreateXor(And, Together);
3551 case Instruction::Or:
3552 if (Together == AndRHS) // (X | C) & C --> C
3553 return ReplaceInstUsesWith(TheAnd, AndRHS);
3555 if (Op->hasOneUse() && Together != OpRHS) {
3556 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3557 Value *Or = Builder->CreateOr(X, Together);
3559 return BinaryOperator::CreateAnd(Or, AndRHS);
3562 case Instruction::Add:
3563 if (Op->hasOneUse()) {
3564 // Adding a one to a single bit bit-field should be turned into an XOR
3565 // of the bit. First thing to check is to see if this AND is with a
3566 // single bit constant.
3567 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3569 // If there is only one bit set...
3570 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3571 // Ok, at this point, we know that we are masking the result of the
3572 // ADD down to exactly one bit. If the constant we are adding has
3573 // no bits set below this bit, then we can eliminate the ADD.
3574 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3576 // Check to see if any bits below the one bit set in AndRHSV are set.
3577 if ((AddRHS & (AndRHSV-1)) == 0) {
3578 // If not, the only thing that can effect the output of the AND is
3579 // the bit specified by AndRHSV. If that bit is set, the effect of
3580 // the XOR is to toggle the bit. If it is clear, then the ADD has
3582 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3583 TheAnd.setOperand(0, X);
3586 // Pull the XOR out of the AND.
3587 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
3588 NewAnd->takeName(Op);
3589 return BinaryOperator::CreateXor(NewAnd, AndRHS);
3596 case Instruction::Shl: {
3597 // We know that the AND will not produce any of the bits shifted in, so if
3598 // the anded constant includes them, clear them now!
3600 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3601 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3602 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3603 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3605 if (CI->getValue() == ShlMask) {
3606 // Masking out bits that the shift already masks
3607 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3608 } else if (CI != AndRHS) { // Reducing bits set in and.
3609 TheAnd.setOperand(1, CI);
3614 case Instruction::LShr:
3616 // We know that the AND will not produce any of the bits shifted in, so if
3617 // the anded constant includes them, clear them now! This only applies to
3618 // unsigned shifts, because a signed shr may bring in set bits!
3620 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3621 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3622 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3623 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3625 if (CI->getValue() == ShrMask) {
3626 // Masking out bits that the shift already masks.
3627 return ReplaceInstUsesWith(TheAnd, Op);
3628 } else if (CI != AndRHS) {
3629 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3634 case Instruction::AShr:
3636 // See if this is shifting in some sign extension, then masking it out
3638 if (Op->hasOneUse()) {
3639 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3640 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3641 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3642 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3643 if (C == AndRHS) { // Masking out bits shifted in.
3644 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3645 // Make the argument unsigned.
3646 Value *ShVal = Op->getOperand(0);
3647 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
3648 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3657 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3658 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3659 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3660 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3661 /// insert new instructions.
3662 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3663 bool isSigned, bool Inside,
3665 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3666 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3667 "Lo is not <= Hi in range emission code!");
3670 if (Lo == Hi) // Trivially false.
3671 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3673 // V >= Min && V < Hi --> V < Hi
3674 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3675 ICmpInst::Predicate pred = (isSigned ?
3676 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3677 return new ICmpInst(pred, V, Hi);
3680 // Emit V-Lo <u Hi-Lo
3681 Constant *NegLo = ConstantExpr::getNeg(Lo);
3682 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3683 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3684 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3687 if (Lo == Hi) // Trivially true.
3688 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3690 // V < Min || V >= Hi -> V > Hi-1
3691 Hi = SubOne(cast<ConstantInt>(Hi));
3692 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3693 ICmpInst::Predicate pred = (isSigned ?
3694 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3695 return new ICmpInst(pred, V, Hi);
3698 // Emit V-Lo >u Hi-1-Lo
3699 // Note that Hi has already had one subtracted from it, above.
3700 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3701 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3702 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3703 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3706 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3707 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3708 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3709 // not, since all 1s are not contiguous.
3710 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3711 const APInt& V = Val->getValue();
3712 uint32_t BitWidth = Val->getType()->getBitWidth();
3713 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3715 // look for the first zero bit after the run of ones
3716 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3717 // look for the first non-zero bit
3718 ME = V.getActiveBits();
3722 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3723 /// where isSub determines whether the operator is a sub. If we can fold one of
3724 /// the following xforms:
3726 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3727 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3728 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3730 /// return (A +/- B).
3732 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3733 ConstantInt *Mask, bool isSub,
3735 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3736 if (!LHSI || LHSI->getNumOperands() != 2 ||
3737 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3739 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3741 switch (LHSI->getOpcode()) {
3743 case Instruction::And:
3744 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3745 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3746 if ((Mask->getValue().countLeadingZeros() +
3747 Mask->getValue().countPopulation()) ==
3748 Mask->getValue().getBitWidth())
3751 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3752 // part, we don't need any explicit masks to take them out of A. If that
3753 // is all N is, ignore it.
3754 uint32_t MB = 0, ME = 0;
3755 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3756 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3757 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3758 if (MaskedValueIsZero(RHS, Mask))
3763 case Instruction::Or:
3764 case Instruction::Xor:
3765 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3766 if ((Mask->getValue().countLeadingZeros() +
3767 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3768 && ConstantExpr::getAnd(N, Mask)->isNullValue())
3774 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3775 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
3778 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3779 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3780 ICmpInst *LHS, ICmpInst *RHS) {
3782 ConstantInt *LHSCst, *RHSCst;
3783 ICmpInst::Predicate LHSCC, RHSCC;
3785 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3786 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3787 m_ConstantInt(LHSCst))) ||
3788 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3789 m_ConstantInt(RHSCst))))
3792 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3793 // where C is a power of 2
3794 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3795 LHSCst->getValue().isPowerOf2()) {
3796 Value *NewOr = Builder->CreateOr(Val, Val2);
3797 return new ICmpInst(LHSCC, NewOr, LHSCst);
3800 // From here on, we only handle:
3801 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3802 if (Val != Val2) return 0;
3804 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3805 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3806 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3807 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3808 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3811 // We can't fold (ugt x, C) & (sgt x, C2).
3812 if (!PredicatesFoldable(LHSCC, RHSCC))
3815 // Ensure that the larger constant is on the RHS.
3817 if (ICmpInst::isSignedPredicate(LHSCC) ||
3818 (ICmpInst::isEquality(LHSCC) &&
3819 ICmpInst::isSignedPredicate(RHSCC)))
3820 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3822 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3825 std::swap(LHS, RHS);
3826 std::swap(LHSCst, RHSCst);
3827 std::swap(LHSCC, RHSCC);
3830 // At this point, we know we have have two icmp instructions
3831 // comparing a value against two constants and and'ing the result
3832 // together. Because of the above check, we know that we only have
3833 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3834 // (from the FoldICmpLogical check above), that the two constants
3835 // are not equal and that the larger constant is on the RHS
3836 assert(LHSCst != RHSCst && "Compares not folded above?");
3839 default: llvm_unreachable("Unknown integer condition code!");
3840 case ICmpInst::ICMP_EQ:
3842 default: llvm_unreachable("Unknown integer condition code!");
3843 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3844 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3845 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3846 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3847 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3848 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3849 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3850 return ReplaceInstUsesWith(I, LHS);
3852 case ICmpInst::ICMP_NE:
3854 default: llvm_unreachable("Unknown integer condition code!");
3855 case ICmpInst::ICMP_ULT:
3856 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3857 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3858 break; // (X != 13 & X u< 15) -> no change
3859 case ICmpInst::ICMP_SLT:
3860 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3861 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3862 break; // (X != 13 & X s< 15) -> no change
3863 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3864 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3865 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3866 return ReplaceInstUsesWith(I, RHS);
3867 case ICmpInst::ICMP_NE:
3868 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3869 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3870 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
3871 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3872 ConstantInt::get(Add->getType(), 1));
3874 break; // (X != 13 & X != 15) -> no change
3877 case ICmpInst::ICMP_ULT:
3879 default: llvm_unreachable("Unknown integer condition code!");
3880 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3881 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3882 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3883 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3885 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3886 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3887 return ReplaceInstUsesWith(I, LHS);
3888 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3892 case ICmpInst::ICMP_SLT:
3894 default: llvm_unreachable("Unknown integer condition code!");
3895 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3896 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3897 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3898 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3900 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3901 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3902 return ReplaceInstUsesWith(I, LHS);
3903 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3907 case ICmpInst::ICMP_UGT:
3909 default: llvm_unreachable("Unknown integer condition code!");
3910 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3911 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3912 return ReplaceInstUsesWith(I, RHS);
3913 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3915 case ICmpInst::ICMP_NE:
3916 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3917 return new ICmpInst(LHSCC, Val, RHSCst);
3918 break; // (X u> 13 & X != 15) -> no change
3919 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
3920 return InsertRangeTest(Val, AddOne(LHSCst),
3921 RHSCst, false, true, I);
3922 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3926 case ICmpInst::ICMP_SGT:
3928 default: llvm_unreachable("Unknown integer condition code!");
3929 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3930 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3931 return ReplaceInstUsesWith(I, RHS);
3932 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3934 case ICmpInst::ICMP_NE:
3935 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3936 return new ICmpInst(LHSCC, Val, RHSCst);
3937 break; // (X s> 13 & X != 15) -> no change
3938 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
3939 return InsertRangeTest(Val, AddOne(LHSCst),
3940 RHSCst, true, true, I);
3941 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3950 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
3953 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3954 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
3955 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3956 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3957 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3958 // If either of the constants are nans, then the whole thing returns
3960 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
3961 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3962 return new FCmpInst(FCmpInst::FCMP_ORD,
3963 LHS->getOperand(0), RHS->getOperand(0));
3966 // Handle vector zeros. This occurs because the canonical form of
3967 // "fcmp ord x,x" is "fcmp ord x, 0".
3968 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
3969 isa<ConstantAggregateZero>(RHS->getOperand(1)))
3970 return new FCmpInst(FCmpInst::FCMP_ORD,
3971 LHS->getOperand(0), RHS->getOperand(0));
3975 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
3976 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
3977 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
3980 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
3981 // Swap RHS operands to match LHS.
3982 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
3983 std::swap(Op1LHS, Op1RHS);
3986 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
3987 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
3989 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
3991 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
3992 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3993 if (Op0CC == FCmpInst::FCMP_TRUE)
3994 return ReplaceInstUsesWith(I, RHS);
3995 if (Op1CC == FCmpInst::FCMP_TRUE)
3996 return ReplaceInstUsesWith(I, LHS);
4000 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4001 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4003 std::swap(LHS, RHS);
4004 std::swap(Op0Pred, Op1Pred);
4005 std::swap(Op0Ordered, Op1Ordered);
4008 // uno && ueq -> uno && (uno || eq) -> ueq
4009 // ord && olt -> ord && (ord && lt) -> olt
4010 if (Op0Ordered == Op1Ordered)
4011 return ReplaceInstUsesWith(I, RHS);
4013 // uno && oeq -> uno && (ord && eq) -> false
4014 // uno && ord -> false
4016 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4017 // ord && ueq -> ord && (uno || eq) -> oeq
4018 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4019 Op0LHS, Op0RHS, Context));
4027 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4028 bool Changed = SimplifyCommutative(I);
4029 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4031 if (isa<UndefValue>(Op1)) // X & undef -> 0
4032 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4036 return ReplaceInstUsesWith(I, Op1);
4038 // See if we can simplify any instructions used by the instruction whose sole
4039 // purpose is to compute bits we don't care about.
4040 if (SimplifyDemandedInstructionBits(I))
4042 if (isa<VectorType>(I.getType())) {
4043 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4044 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
4045 return ReplaceInstUsesWith(I, I.getOperand(0));
4046 } else if (isa<ConstantAggregateZero>(Op1)) {
4047 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
4051 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4052 const APInt& AndRHSMask = AndRHS->getValue();
4053 APInt NotAndRHS(~AndRHSMask);
4055 // Optimize a variety of ((val OP C1) & C2) combinations...
4056 if (isa<BinaryOperator>(Op0)) {
4057 Instruction *Op0I = cast<Instruction>(Op0);
4058 Value *Op0LHS = Op0I->getOperand(0);
4059 Value *Op0RHS = Op0I->getOperand(1);
4060 switch (Op0I->getOpcode()) {
4061 case Instruction::Xor:
4062 case Instruction::Or:
4063 // If the mask is only needed on one incoming arm, push it up.
4064 if (Op0I->hasOneUse()) {
4065 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4066 // Not masking anything out for the LHS, move to RHS.
4067 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4068 Op0RHS->getName()+".masked");
4069 return BinaryOperator::Create(
4070 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4072 if (!isa<Constant>(Op0RHS) &&
4073 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4074 // Not masking anything out for the RHS, move to LHS.
4075 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4076 Op0LHS->getName()+".masked");
4077 return BinaryOperator::Create(
4078 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4083 case Instruction::Add:
4084 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4085 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4086 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4087 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4088 return BinaryOperator::CreateAnd(V, AndRHS);
4089 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4090 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
4093 case Instruction::Sub:
4094 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4095 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4096 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4097 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4098 return BinaryOperator::CreateAnd(V, AndRHS);
4100 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4101 // has 1's for all bits that the subtraction with A might affect.
4102 if (Op0I->hasOneUse()) {
4103 uint32_t BitWidth = AndRHSMask.getBitWidth();
4104 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4105 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4107 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4108 if (!(A && A->isZero()) && // avoid infinite recursion.
4109 MaskedValueIsZero(Op0LHS, Mask)) {
4110 Value *NewNeg = Builder->CreateNeg(Op0RHS);
4111 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4116 case Instruction::Shl:
4117 case Instruction::LShr:
4118 // (1 << x) & 1 --> zext(x == 0)
4119 // (1 >> x) & 1 --> zext(x == 0)
4120 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4122 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
4123 return new ZExtInst(NewICmp, I.getType());
4128 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4129 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4131 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4132 // If this is an integer truncation or change from signed-to-unsigned, and
4133 // if the source is an and/or with immediate, transform it. This
4134 // frequently occurs for bitfield accesses.
4135 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4136 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4137 CastOp->getNumOperands() == 2)
4138 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4139 if (CastOp->getOpcode() == Instruction::And) {
4140 // Change: and (cast (and X, C1) to T), C2
4141 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4142 // This will fold the two constants together, which may allow
4143 // other simplifications.
4144 Value *NewCast = Builder->CreateTruncOrBitCast(
4145 CastOp->getOperand(0), I.getType(),
4146 CastOp->getName()+".shrunk");
4147 // trunc_or_bitcast(C1)&C2
4148 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4149 C3 = ConstantExpr::getAnd(C3, AndRHS);
4150 return BinaryOperator::CreateAnd(NewCast, C3);
4151 } else if (CastOp->getOpcode() == Instruction::Or) {
4152 // Change: and (cast (or X, C1) to T), C2
4153 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4154 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4155 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4157 return ReplaceInstUsesWith(I, AndRHS);
4163 // Try to fold constant and into select arguments.
4164 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4165 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4167 if (isa<PHINode>(Op0))
4168 if (Instruction *NV = FoldOpIntoPhi(I))
4172 Value *Op0NotVal = dyn_castNotVal(Op0);
4173 Value *Op1NotVal = dyn_castNotVal(Op1);
4175 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4176 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4178 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4179 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4180 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4181 I.getName()+".demorgan");
4182 return BinaryOperator::CreateNot(Or);
4186 Value *A = 0, *B = 0, *C = 0, *D = 0;
4187 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4188 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4189 return ReplaceInstUsesWith(I, Op1);
4191 // (A|B) & ~(A&B) -> A^B
4192 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4193 if ((A == C && B == D) || (A == D && B == C))
4194 return BinaryOperator::CreateXor(A, B);
4198 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4199 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4200 return ReplaceInstUsesWith(I, Op0);
4202 // ~(A&B) & (A|B) -> A^B
4203 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4204 if ((A == C && B == D) || (A == D && B == C))
4205 return BinaryOperator::CreateXor(A, B);
4209 if (Op0->hasOneUse() &&
4210 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4211 if (A == Op1) { // (A^B)&A -> A&(A^B)
4212 I.swapOperands(); // Simplify below
4213 std::swap(Op0, Op1);
4214 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4215 cast<BinaryOperator>(Op0)->swapOperands();
4216 I.swapOperands(); // Simplify below
4217 std::swap(Op0, Op1);
4221 if (Op1->hasOneUse() &&
4222 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4223 if (B == Op0) { // B&(A^B) -> B&(B^A)
4224 cast<BinaryOperator>(Op1)->swapOperands();
4227 if (A == Op0) // A&(A^B) -> A & ~B
4228 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
4231 // (A&((~A)|B)) -> A&B
4232 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4233 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4234 return BinaryOperator::CreateAnd(A, Op1);
4235 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4236 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4237 return BinaryOperator::CreateAnd(A, Op0);
4240 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4241 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4242 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4245 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4246 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4250 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4251 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4252 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4253 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4254 const Type *SrcTy = Op0C->getOperand(0)->getType();
4255 if (SrcTy == Op1C->getOperand(0)->getType() &&
4256 SrcTy->isIntOrIntVector() &&
4257 // Only do this if the casts both really cause code to be generated.
4258 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4260 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4262 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4263 Op1C->getOperand(0), I.getName());
4264 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4268 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4269 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4270 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4271 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4272 SI0->getOperand(1) == SI1->getOperand(1) &&
4273 (SI0->hasOneUse() || SI1->hasOneUse())) {
4275 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4277 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4278 SI1->getOperand(1));
4282 // If and'ing two fcmp, try combine them into one.
4283 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4284 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4285 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4289 return Changed ? &I : 0;
4292 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4293 /// capable of providing pieces of a bswap. The subexpression provides pieces
4294 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4295 /// the expression came from the corresponding "byte swapped" byte in some other
4296 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4297 /// we know that the expression deposits the low byte of %X into the high byte
4298 /// of the bswap result and that all other bytes are zero. This expression is
4299 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4302 /// This function returns true if the match was unsuccessful and false if so.
4303 /// On entry to the function the "OverallLeftShift" is a signed integer value
4304 /// indicating the number of bytes that the subexpression is later shifted. For
4305 /// example, if the expression is later right shifted by 16 bits, the
4306 /// OverallLeftShift value would be -2 on entry. This is used to specify which
4307 /// byte of ByteValues is actually being set.
4309 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4310 /// byte is masked to zero by a user. For example, in (X & 255), X will be
4311 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4312 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
4313 /// always in the local (OverallLeftShift) coordinate space.
4315 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4316 SmallVector<Value*, 8> &ByteValues) {
4317 if (Instruction *I = dyn_cast<Instruction>(V)) {
4318 // If this is an or instruction, it may be an inner node of the bswap.
4319 if (I->getOpcode() == Instruction::Or) {
4320 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4322 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4326 // If this is a logical shift by a constant multiple of 8, recurse with
4327 // OverallLeftShift and ByteMask adjusted.
4328 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4330 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4331 // Ensure the shift amount is defined and of a byte value.
4332 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4335 unsigned ByteShift = ShAmt >> 3;
4336 if (I->getOpcode() == Instruction::Shl) {
4337 // X << 2 -> collect(X, +2)
4338 OverallLeftShift += ByteShift;
4339 ByteMask >>= ByteShift;
4341 // X >>u 2 -> collect(X, -2)
4342 OverallLeftShift -= ByteShift;
4343 ByteMask <<= ByteShift;
4344 ByteMask &= (~0U >> (32-ByteValues.size()));
4347 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4348 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4350 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4354 // If this is a logical 'and' with a mask that clears bytes, clear the
4355 // corresponding bytes in ByteMask.
4356 if (I->getOpcode() == Instruction::And &&
4357 isa<ConstantInt>(I->getOperand(1))) {
4358 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4359 unsigned NumBytes = ByteValues.size();
4360 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4361 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4363 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4364 // If this byte is masked out by a later operation, we don't care what
4366 if ((ByteMask & (1 << i)) == 0)
4369 // If the AndMask is all zeros for this byte, clear the bit.
4370 APInt MaskB = AndMask & Byte;
4372 ByteMask &= ~(1U << i);
4376 // If the AndMask is not all ones for this byte, it's not a bytezap.
4380 // Otherwise, this byte is kept.
4383 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4388 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4389 // the input value to the bswap. Some observations: 1) if more than one byte
4390 // is demanded from this input, then it could not be successfully assembled
4391 // into a byteswap. At least one of the two bytes would not be aligned with
4392 // their ultimate destination.
4393 if (!isPowerOf2_32(ByteMask)) return true;
4394 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4396 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4397 // is demanded, it needs to go into byte 0 of the result. This means that the
4398 // byte needs to be shifted until it lands in the right byte bucket. The
4399 // shift amount depends on the position: if the byte is coming from the high
4400 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4401 // low part, it must be shifted left.
4402 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4403 if (InputByteNo < ByteValues.size()/2) {
4404 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4407 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4411 // If the destination byte value is already defined, the values are or'd
4412 // together, which isn't a bswap (unless it's an or of the same bits).
4413 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4415 ByteValues[DestByteNo] = V;
4419 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4420 /// If so, insert the new bswap intrinsic and return it.
4421 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4422 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4423 if (!ITy || ITy->getBitWidth() % 16 ||
4424 // ByteMask only allows up to 32-byte values.
4425 ITy->getBitWidth() > 32*8)
4426 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4428 /// ByteValues - For each byte of the result, we keep track of which value
4429 /// defines each byte.
4430 SmallVector<Value*, 8> ByteValues;
4431 ByteValues.resize(ITy->getBitWidth()/8);
4433 // Try to find all the pieces corresponding to the bswap.
4434 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4435 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4438 // Check to see if all of the bytes come from the same value.
4439 Value *V = ByteValues[0];
4440 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4442 // Check to make sure that all of the bytes come from the same value.
4443 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4444 if (ByteValues[i] != V)
4446 const Type *Tys[] = { ITy };
4447 Module *M = I.getParent()->getParent()->getParent();
4448 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4449 return CallInst::Create(F, V);
4452 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4453 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4454 /// we can simplify this expression to "cond ? C : D or B".
4455 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4457 LLVMContext *Context) {
4458 // If A is not a select of -1/0, this cannot match.
4460 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4463 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4464 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4465 return SelectInst::Create(Cond, C, B);
4466 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4467 return SelectInst::Create(Cond, C, B);
4468 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4469 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4470 return SelectInst::Create(Cond, C, D);
4471 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4472 return SelectInst::Create(Cond, C, D);
4476 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4477 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4478 ICmpInst *LHS, ICmpInst *RHS) {
4480 ConstantInt *LHSCst, *RHSCst;
4481 ICmpInst::Predicate LHSCC, RHSCC;
4483 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4484 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4485 m_ConstantInt(LHSCst))) ||
4486 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4487 m_ConstantInt(RHSCst))))
4490 // From here on, we only handle:
4491 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4492 if (Val != Val2) return 0;
4494 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4495 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4496 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4497 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4498 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4501 // We can't fold (ugt x, C) | (sgt x, C2).
4502 if (!PredicatesFoldable(LHSCC, RHSCC))
4505 // Ensure that the larger constant is on the RHS.
4507 if (ICmpInst::isSignedPredicate(LHSCC) ||
4508 (ICmpInst::isEquality(LHSCC) &&
4509 ICmpInst::isSignedPredicate(RHSCC)))
4510 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4512 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4515 std::swap(LHS, RHS);
4516 std::swap(LHSCst, RHSCst);
4517 std::swap(LHSCC, RHSCC);
4520 // At this point, we know we have have two icmp instructions
4521 // comparing a value against two constants and or'ing the result
4522 // together. Because of the above check, we know that we only have
4523 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4524 // FoldICmpLogical check above), that the two constants are not
4526 assert(LHSCst != RHSCst && "Compares not folded above?");
4529 default: llvm_unreachable("Unknown integer condition code!");
4530 case ICmpInst::ICMP_EQ:
4532 default: llvm_unreachable("Unknown integer condition code!");
4533 case ICmpInst::ICMP_EQ:
4534 if (LHSCst == SubOne(RHSCst)) {
4535 // (X == 13 | X == 14) -> X-13 <u 2
4536 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4537 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4538 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4539 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4541 break; // (X == 13 | X == 15) -> no change
4542 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4543 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4545 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4546 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4547 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4548 return ReplaceInstUsesWith(I, RHS);
4551 case ICmpInst::ICMP_NE:
4553 default: llvm_unreachable("Unknown integer condition code!");
4554 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4555 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4556 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4557 return ReplaceInstUsesWith(I, LHS);
4558 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4559 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4560 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4561 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4564 case ICmpInst::ICMP_ULT:
4566 default: llvm_unreachable("Unknown integer condition code!");
4567 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4569 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4570 // If RHSCst is [us]MAXINT, it is always false. Not handling
4571 // this can cause overflow.
4572 if (RHSCst->isMaxValue(false))
4573 return ReplaceInstUsesWith(I, LHS);
4574 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4576 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4578 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4579 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4580 return ReplaceInstUsesWith(I, RHS);
4581 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4585 case ICmpInst::ICMP_SLT:
4587 default: llvm_unreachable("Unknown integer condition code!");
4588 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4590 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4591 // If RHSCst is [us]MAXINT, it is always false. Not handling
4592 // this can cause overflow.
4593 if (RHSCst->isMaxValue(true))
4594 return ReplaceInstUsesWith(I, LHS);
4595 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4597 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4599 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4600 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4601 return ReplaceInstUsesWith(I, RHS);
4602 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4606 case ICmpInst::ICMP_UGT:
4608 default: llvm_unreachable("Unknown integer condition code!");
4609 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4610 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4611 return ReplaceInstUsesWith(I, LHS);
4612 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4614 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4615 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4616 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4617 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4621 case ICmpInst::ICMP_SGT:
4623 default: llvm_unreachable("Unknown integer condition code!");
4624 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4625 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4626 return ReplaceInstUsesWith(I, LHS);
4627 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4629 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4630 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4631 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4632 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4640 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4642 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4643 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4644 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4645 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4646 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4647 // If either of the constants are nans, then the whole thing returns
4649 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4650 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4652 // Otherwise, no need to compare the two constants, compare the
4654 return new FCmpInst(FCmpInst::FCMP_UNO,
4655 LHS->getOperand(0), RHS->getOperand(0));
4658 // Handle vector zeros. This occurs because the canonical form of
4659 // "fcmp uno x,x" is "fcmp uno x, 0".
4660 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4661 isa<ConstantAggregateZero>(RHS->getOperand(1)))
4662 return new FCmpInst(FCmpInst::FCMP_UNO,
4663 LHS->getOperand(0), RHS->getOperand(0));
4668 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4669 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4670 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4672 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4673 // Swap RHS operands to match LHS.
4674 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4675 std::swap(Op1LHS, Op1RHS);
4677 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4678 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4680 return new FCmpInst((FCmpInst::Predicate)Op0CC,
4682 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4683 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4684 if (Op0CC == FCmpInst::FCMP_FALSE)
4685 return ReplaceInstUsesWith(I, RHS);
4686 if (Op1CC == FCmpInst::FCMP_FALSE)
4687 return ReplaceInstUsesWith(I, LHS);
4690 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4691 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4692 if (Op0Ordered == Op1Ordered) {
4693 // If both are ordered or unordered, return a new fcmp with
4694 // or'ed predicates.
4695 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4696 Op0LHS, Op0RHS, Context);
4697 if (Instruction *I = dyn_cast<Instruction>(RV))
4699 // Otherwise, it's a constant boolean value...
4700 return ReplaceInstUsesWith(I, RV);
4706 /// FoldOrWithConstants - This helper function folds:
4708 /// ((A | B) & C1) | (B & C2)
4714 /// when the XOR of the two constants is "all ones" (-1).
4715 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4716 Value *A, Value *B, Value *C) {
4717 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4721 ConstantInt *CI2 = 0;
4722 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4724 APInt Xor = CI1->getValue() ^ CI2->getValue();
4725 if (!Xor.isAllOnesValue()) return 0;
4727 if (V1 == A || V1 == B) {
4728 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
4729 return BinaryOperator::CreateOr(NewOp, V1);
4735 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4736 bool Changed = SimplifyCommutative(I);
4737 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4739 if (isa<UndefValue>(Op1)) // X | undef -> -1
4740 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4744 return ReplaceInstUsesWith(I, Op0);
4746 // See if we can simplify any instructions used by the instruction whose sole
4747 // purpose is to compute bits we don't care about.
4748 if (SimplifyDemandedInstructionBits(I))
4750 if (isa<VectorType>(I.getType())) {
4751 if (isa<ConstantAggregateZero>(Op1)) {
4752 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4753 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4754 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4755 return ReplaceInstUsesWith(I, I.getOperand(1));
4760 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4761 ConstantInt *C1 = 0; Value *X = 0;
4762 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4763 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
4765 Value *Or = Builder->CreateOr(X, RHS);
4767 return BinaryOperator::CreateAnd(Or,
4768 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4771 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4772 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
4774 Value *Or = Builder->CreateOr(X, RHS);
4776 return BinaryOperator::CreateXor(Or,
4777 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4780 // Try to fold constant and into select arguments.
4781 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4782 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4784 if (isa<PHINode>(Op0))
4785 if (Instruction *NV = FoldOpIntoPhi(I))
4789 Value *A = 0, *B = 0;
4790 ConstantInt *C1 = 0, *C2 = 0;
4792 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4793 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4794 return ReplaceInstUsesWith(I, Op1);
4795 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4796 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4797 return ReplaceInstUsesWith(I, Op0);
4799 // (A | B) | C and A | (B | C) -> bswap if possible.
4800 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4801 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4802 match(Op1, m_Or(m_Value(), m_Value())) ||
4803 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4804 match(Op1, m_Shift(m_Value(), m_Value())))) {
4805 if (Instruction *BSwap = MatchBSwap(I))
4809 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4810 if (Op0->hasOneUse() &&
4811 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4812 MaskedValueIsZero(Op1, C1->getValue())) {
4813 Value *NOr = Builder->CreateOr(A, Op1);
4815 return BinaryOperator::CreateXor(NOr, C1);
4818 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4819 if (Op1->hasOneUse() &&
4820 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4821 MaskedValueIsZero(Op0, C1->getValue())) {
4822 Value *NOr = Builder->CreateOr(A, Op0);
4824 return BinaryOperator::CreateXor(NOr, C1);
4828 Value *C = 0, *D = 0;
4829 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4830 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4831 Value *V1 = 0, *V2 = 0, *V3 = 0;
4832 C1 = dyn_cast<ConstantInt>(C);
4833 C2 = dyn_cast<ConstantInt>(D);
4834 if (C1 && C2) { // (A & C1)|(B & C2)
4835 // If we have: ((V + N) & C1) | (V & C2)
4836 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4837 // replace with V+N.
4838 if (C1->getValue() == ~C2->getValue()) {
4839 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4840 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4841 // Add commutes, try both ways.
4842 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4843 return ReplaceInstUsesWith(I, A);
4844 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4845 return ReplaceInstUsesWith(I, A);
4847 // Or commutes, try both ways.
4848 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4849 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4850 // Add commutes, try both ways.
4851 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4852 return ReplaceInstUsesWith(I, B);
4853 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4854 return ReplaceInstUsesWith(I, B);
4857 V1 = 0; V2 = 0; V3 = 0;
4860 // Check to see if we have any common things being and'ed. If so, find the
4861 // terms for V1 & (V2|V3).
4862 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4863 if (A == B) // (A & C)|(A & D) == A & (C|D)
4864 V1 = A, V2 = C, V3 = D;
4865 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4866 V1 = A, V2 = B, V3 = C;
4867 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4868 V1 = C, V2 = A, V3 = D;
4869 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4870 V1 = C, V2 = A, V3 = B;
4873 Value *Or = Builder->CreateOr(V2, V3, "tmp");
4874 return BinaryOperator::CreateAnd(V1, Or);
4878 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
4879 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4881 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4883 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4885 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4888 // ((A&~B)|(~A&B)) -> A^B
4889 if ((match(C, m_Not(m_Specific(D))) &&
4890 match(B, m_Not(m_Specific(A)))))
4891 return BinaryOperator::CreateXor(A, D);
4892 // ((~B&A)|(~A&B)) -> A^B
4893 if ((match(A, m_Not(m_Specific(D))) &&
4894 match(B, m_Not(m_Specific(C)))))
4895 return BinaryOperator::CreateXor(C, D);
4896 // ((A&~B)|(B&~A)) -> A^B
4897 if ((match(C, m_Not(m_Specific(B))) &&
4898 match(D, m_Not(m_Specific(A)))))
4899 return BinaryOperator::CreateXor(A, B);
4900 // ((~B&A)|(B&~A)) -> A^B
4901 if ((match(A, m_Not(m_Specific(B))) &&
4902 match(D, m_Not(m_Specific(C)))))
4903 return BinaryOperator::CreateXor(C, B);
4906 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4907 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4908 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4909 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4910 SI0->getOperand(1) == SI1->getOperand(1) &&
4911 (SI0->hasOneUse() || SI1->hasOneUse())) {
4912 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4914 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4915 SI1->getOperand(1));
4919 // ((A|B)&1)|(B&-2) -> (A&1) | B
4920 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4921 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4922 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4923 if (Ret) return Ret;
4925 // (B&-2)|((A|B)&1) -> (A&1) | B
4926 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4927 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4928 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4929 if (Ret) return Ret;
4932 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4933 if (A == Op1) // ~A | A == -1
4934 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4938 // Note, A is still live here!
4939 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4941 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4943 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4944 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4945 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
4946 return BinaryOperator::CreateNot(And);
4950 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4951 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4952 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4955 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4956 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4960 // fold (or (cast A), (cast B)) -> (cast (or A, B))
4961 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4962 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4963 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4964 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4965 !isa<ICmpInst>(Op1C->getOperand(0))) {
4966 const Type *SrcTy = Op0C->getOperand(0)->getType();
4967 if (SrcTy == Op1C->getOperand(0)->getType() &&
4968 SrcTy->isIntOrIntVector() &&
4969 // Only do this if the casts both really cause code to be
4971 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4973 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4975 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
4976 Op1C->getOperand(0), I.getName());
4977 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4984 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4985 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4986 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4987 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
4991 return Changed ? &I : 0;
4996 // XorSelf - Implements: X ^ X --> 0
4999 XorSelf(Value *rhs) : RHS(rhs) {}
5000 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5001 Instruction *apply(BinaryOperator &Xor) const {
5008 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5009 bool Changed = SimplifyCommutative(I);
5010 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5012 if (isa<UndefValue>(Op1)) {
5013 if (isa<UndefValue>(Op0))
5014 // Handle undef ^ undef -> 0 special case. This is a common
5016 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5017 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
5020 // xor X, X = 0, even if X is nested in a sequence of Xor's.
5021 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5022 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5023 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5026 // See if we can simplify any instructions used by the instruction whose sole
5027 // purpose is to compute bits we don't care about.
5028 if (SimplifyDemandedInstructionBits(I))
5030 if (isa<VectorType>(I.getType()))
5031 if (isa<ConstantAggregateZero>(Op1))
5032 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
5034 // Is this a ~ operation?
5035 if (Value *NotOp = dyn_castNotVal(&I)) {
5036 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5037 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5038 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5039 if (Op0I->getOpcode() == Instruction::And ||
5040 Op0I->getOpcode() == Instruction::Or) {
5041 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
5042 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5044 Builder->CreateNot(Op0I->getOperand(1),
5045 Op0I->getOperand(1)->getName()+".not");
5046 if (Op0I->getOpcode() == Instruction::And)
5047 return BinaryOperator::CreateOr(Op0NotVal, NotY);
5048 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5055 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5056 if (RHS == ConstantInt::getTrue(*Context) && Op0->hasOneUse()) {
5057 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5058 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5059 return new ICmpInst(ICI->getInversePredicate(),
5060 ICI->getOperand(0), ICI->getOperand(1));
5062 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5063 return new FCmpInst(FCI->getInversePredicate(),
5064 FCI->getOperand(0), FCI->getOperand(1));
5067 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5068 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5069 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5070 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5071 Instruction::CastOps Opcode = Op0C->getOpcode();
5072 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5073 (RHS == ConstantExpr::getCast(Opcode,
5074 ConstantInt::getTrue(*Context),
5075 Op0C->getDestTy()))) {
5076 CI->setPredicate(CI->getInversePredicate());
5077 return CastInst::Create(Opcode, CI, Op0C->getType());
5083 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5084 // ~(c-X) == X-c-1 == X+(-c-1)
5085 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5086 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5087 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5088 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5089 ConstantInt::get(I.getType(), 1));
5090 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5093 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5094 if (Op0I->getOpcode() == Instruction::Add) {
5095 // ~(X-c) --> (-c-1)-X
5096 if (RHS->isAllOnesValue()) {
5097 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5098 return BinaryOperator::CreateSub(
5099 ConstantExpr::getSub(NegOp0CI,
5100 ConstantInt::get(I.getType(), 1)),
5101 Op0I->getOperand(0));
5102 } else if (RHS->getValue().isSignBit()) {
5103 // (X + C) ^ signbit -> (X + C + signbit)
5104 Constant *C = ConstantInt::get(*Context,
5105 RHS->getValue() + Op0CI->getValue());
5106 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5109 } else if (Op0I->getOpcode() == Instruction::Or) {
5110 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5111 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5112 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5113 // Anything in both C1 and C2 is known to be zero, remove it from
5115 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5116 NewRHS = ConstantExpr::getAnd(NewRHS,
5117 ConstantExpr::getNot(CommonBits));
5119 I.setOperand(0, Op0I->getOperand(0));
5120 I.setOperand(1, NewRHS);
5127 // Try to fold constant and into select arguments.
5128 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5129 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5131 if (isa<PHINode>(Op0))
5132 if (Instruction *NV = FoldOpIntoPhi(I))
5136 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
5138 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5140 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
5142 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5145 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5148 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5149 if (A == Op0) { // B^(B|A) == (A|B)^B
5150 Op1I->swapOperands();
5152 std::swap(Op0, Op1);
5153 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5154 I.swapOperands(); // Simplified below.
5155 std::swap(Op0, Op1);
5157 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5158 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5159 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5160 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
5161 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
5163 if (A == Op0) { // A^(A&B) -> A^(B&A)
5164 Op1I->swapOperands();
5167 if (B == Op0) { // A^(B&A) -> (B&A)^A
5168 I.swapOperands(); // Simplified below.
5169 std::swap(Op0, Op1);
5174 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5177 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5178 Op0I->hasOneUse()) {
5179 if (A == Op1) // (B|A)^B == (A|B)^B
5181 if (B == Op1) // (A|B)^B == A & ~B
5182 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
5183 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5184 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5185 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5186 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
5187 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5189 if (A == Op1) // (A&B)^A -> (B&A)^A
5191 if (B == Op1 && // (B&A)^A == ~B & A
5192 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5193 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
5198 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5199 if (Op0I && Op1I && Op0I->isShift() &&
5200 Op0I->getOpcode() == Op1I->getOpcode() &&
5201 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5202 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5204 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5206 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
5207 Op1I->getOperand(1));
5211 Value *A, *B, *C, *D;
5212 // (A & B)^(A | B) -> A ^ B
5213 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5214 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5215 if ((A == C && B == D) || (A == D && B == C))
5216 return BinaryOperator::CreateXor(A, B);
5218 // (A | B)^(A & B) -> A ^ B
5219 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5220 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5221 if ((A == C && B == D) || (A == D && B == C))
5222 return BinaryOperator::CreateXor(A, B);
5226 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5227 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5228 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5229 // (X & Y)^(X & Y) -> (Y^Z) & X
5230 Value *X = 0, *Y = 0, *Z = 0;
5232 X = A, Y = B, Z = D;
5234 X = A, Y = B, Z = C;
5236 X = B, Y = A, Z = D;
5238 X = B, Y = A, Z = C;
5241 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
5242 return BinaryOperator::CreateAnd(NewOp, X);
5247 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5248 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5249 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5252 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5253 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5254 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5255 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5256 const Type *SrcTy = Op0C->getOperand(0)->getType();
5257 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5258 // Only do this if the casts both really cause code to be generated.
5259 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5261 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5263 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5264 Op1C->getOperand(0), I.getName());
5265 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5270 return Changed ? &I : 0;
5273 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5274 LLVMContext *Context) {
5275 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5278 static bool HasAddOverflow(ConstantInt *Result,
5279 ConstantInt *In1, ConstantInt *In2,
5282 if (In2->getValue().isNegative())
5283 return Result->getValue().sgt(In1->getValue());
5285 return Result->getValue().slt(In1->getValue());
5287 return Result->getValue().ult(In1->getValue());
5290 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5291 /// overflowed for this type.
5292 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5293 Constant *In2, LLVMContext *Context,
5294 bool IsSigned = false) {
5295 Result = ConstantExpr::getAdd(In1, In2);
5297 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5298 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5299 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5300 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5301 ExtractElement(In1, Idx, Context),
5302 ExtractElement(In2, Idx, Context),
5309 return HasAddOverflow(cast<ConstantInt>(Result),
5310 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5314 static bool HasSubOverflow(ConstantInt *Result,
5315 ConstantInt *In1, ConstantInt *In2,
5318 if (In2->getValue().isNegative())
5319 return Result->getValue().slt(In1->getValue());
5321 return Result->getValue().sgt(In1->getValue());
5323 return Result->getValue().ugt(In1->getValue());
5326 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5327 /// overflowed for this type.
5328 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5329 Constant *In2, LLVMContext *Context,
5330 bool IsSigned = false) {
5331 Result = ConstantExpr::getSub(In1, In2);
5333 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5334 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5335 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5336 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5337 ExtractElement(In1, Idx, Context),
5338 ExtractElement(In2, Idx, Context),
5345 return HasSubOverflow(cast<ConstantInt>(Result),
5346 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5350 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5351 /// code necessary to compute the offset from the base pointer (without adding
5352 /// in the base pointer). Return the result as a signed integer of intptr size.
5353 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5354 TargetData &TD = *IC.getTargetData();
5355 gep_type_iterator GTI = gep_type_begin(GEP);
5356 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
5357 Value *Result = Constant::getNullValue(IntPtrTy);
5359 // Build a mask for high order bits.
5360 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5361 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5363 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5366 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5367 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5368 if (OpC->isZero()) continue;
5370 // Handle a struct index, which adds its field offset to the pointer.
5371 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5372 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5374 Result = IC.Builder->CreateAdd(Result,
5375 ConstantInt::get(IntPtrTy, Size),
5376 GEP->getName()+".offs");
5380 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5382 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5383 Scale = ConstantExpr::getMul(OC, Scale);
5384 // Emit an add instruction.
5385 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
5388 // Convert to correct type.
5389 if (Op->getType() != IntPtrTy)
5390 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
5392 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5393 // We'll let instcombine(mul) convert this to a shl if possible.
5394 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
5397 // Emit an add instruction.
5398 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
5404 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5405 /// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5406 /// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5407 /// be complex, and scales are involved. The above expression would also be
5408 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5409 /// This later form is less amenable to optimization though, and we are allowed
5410 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5412 /// If we can't emit an optimized form for this expression, this returns null.
5414 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5416 TargetData &TD = *IC.getTargetData();
5417 gep_type_iterator GTI = gep_type_begin(GEP);
5419 // Check to see if this gep only has a single variable index. If so, and if
5420 // any constant indices are a multiple of its scale, then we can compute this
5421 // in terms of the scale of the variable index. For example, if the GEP
5422 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5423 // because the expression will cross zero at the same point.
5424 unsigned i, e = GEP->getNumOperands();
5426 for (i = 1; i != e; ++i, ++GTI) {
5427 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5428 // Compute the aggregate offset of constant indices.
5429 if (CI->isZero()) continue;
5431 // Handle a struct index, which adds its field offset to the pointer.
5432 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5433 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5435 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5436 Offset += Size*CI->getSExtValue();
5439 // Found our variable index.
5444 // If there are no variable indices, we must have a constant offset, just
5445 // evaluate it the general way.
5446 if (i == e) return 0;
5448 Value *VariableIdx = GEP->getOperand(i);
5449 // Determine the scale factor of the variable element. For example, this is
5450 // 4 if the variable index is into an array of i32.
5451 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5453 // Verify that there are no other variable indices. If so, emit the hard way.
5454 for (++i, ++GTI; i != e; ++i, ++GTI) {
5455 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5458 // Compute the aggregate offset of constant indices.
5459 if (CI->isZero()) continue;
5461 // Handle a struct index, which adds its field offset to the pointer.
5462 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5463 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5465 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5466 Offset += Size*CI->getSExtValue();
5470 // Okay, we know we have a single variable index, which must be a
5471 // pointer/array/vector index. If there is no offset, life is simple, return
5473 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5475 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5476 // we don't need to bother extending: the extension won't affect where the
5477 // computation crosses zero.
5478 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5479 VariableIdx = new TruncInst(VariableIdx,
5480 TD.getIntPtrType(VariableIdx->getContext()),
5481 VariableIdx->getName(), &I);
5485 // Otherwise, there is an index. The computation we will do will be modulo
5486 // the pointer size, so get it.
5487 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5489 Offset &= PtrSizeMask;
5490 VariableScale &= PtrSizeMask;
5492 // To do this transformation, any constant index must be a multiple of the
5493 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5494 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5495 // multiple of the variable scale.
5496 int64_t NewOffs = Offset / (int64_t)VariableScale;
5497 if (Offset != NewOffs*(int64_t)VariableScale)
5500 // Okay, we can do this evaluation. Start by converting the index to intptr.
5501 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
5502 if (VariableIdx->getType() != IntPtrTy)
5503 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5505 VariableIdx->getName(), &I);
5506 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5507 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5511 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5512 /// else. At this point we know that the GEP is on the LHS of the comparison.
5513 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5514 ICmpInst::Predicate Cond,
5516 // Look through bitcasts.
5517 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5518 RHS = BCI->getOperand(0);
5520 Value *PtrBase = GEPLHS->getOperand(0);
5521 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5522 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
5523 // This transformation (ignoring the base and scales) is valid because we
5524 // know pointers can't overflow since the gep is inbounds. See if we can
5525 // output an optimized form.
5526 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5528 // If not, synthesize the offset the hard way.
5530 Offset = EmitGEPOffset(GEPLHS, I, *this);
5531 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5532 Constant::getNullValue(Offset->getType()));
5533 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5534 // If the base pointers are different, but the indices are the same, just
5535 // compare the base pointer.
5536 if (PtrBase != GEPRHS->getOperand(0)) {
5537 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5538 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5539 GEPRHS->getOperand(0)->getType();
5541 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5542 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5543 IndicesTheSame = false;
5547 // If all indices are the same, just compare the base pointers.
5549 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5550 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5552 // Otherwise, the base pointers are different and the indices are
5553 // different, bail out.
5557 // If one of the GEPs has all zero indices, recurse.
5558 bool AllZeros = true;
5559 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5560 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5561 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5566 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5567 ICmpInst::getSwappedPredicate(Cond), I);
5569 // If the other GEP has all zero indices, recurse.
5571 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5572 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5573 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5578 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5580 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5581 // If the GEPs only differ by one index, compare it.
5582 unsigned NumDifferences = 0; // Keep track of # differences.
5583 unsigned DiffOperand = 0; // The operand that differs.
5584 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5585 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5586 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5587 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5588 // Irreconcilable differences.
5592 if (NumDifferences++) break;
5597 if (NumDifferences == 0) // SAME GEP?
5598 return ReplaceInstUsesWith(I, // No comparison is needed here.
5599 ConstantInt::get(Type::getInt1Ty(*Context),
5600 ICmpInst::isTrueWhenEqual(Cond)));
5602 else if (NumDifferences == 1) {
5603 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5604 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5605 // Make sure we do a signed comparison here.
5606 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5610 // Only lower this if the icmp is the only user of the GEP or if we expect
5611 // the result to fold to a constant!
5613 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5614 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5615 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5616 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5617 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5618 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5624 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5626 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5629 if (!isa<ConstantFP>(RHSC)) return 0;
5630 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5632 // Get the width of the mantissa. We don't want to hack on conversions that
5633 // might lose information from the integer, e.g. "i64 -> float"
5634 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5635 if (MantissaWidth == -1) return 0; // Unknown.
5637 // Check to see that the input is converted from an integer type that is small
5638 // enough that preserves all bits. TODO: check here for "known" sign bits.
5639 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5640 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5642 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5643 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5647 // If the conversion would lose info, don't hack on this.
5648 if ((int)InputSize > MantissaWidth)
5651 // Otherwise, we can potentially simplify the comparison. We know that it
5652 // will always come through as an integer value and we know the constant is
5653 // not a NAN (it would have been previously simplified).
5654 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5656 ICmpInst::Predicate Pred;
5657 switch (I.getPredicate()) {
5658 default: llvm_unreachable("Unexpected predicate!");
5659 case FCmpInst::FCMP_UEQ:
5660 case FCmpInst::FCMP_OEQ:
5661 Pred = ICmpInst::ICMP_EQ;
5663 case FCmpInst::FCMP_UGT:
5664 case FCmpInst::FCMP_OGT:
5665 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5667 case FCmpInst::FCMP_UGE:
5668 case FCmpInst::FCMP_OGE:
5669 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5671 case FCmpInst::FCMP_ULT:
5672 case FCmpInst::FCMP_OLT:
5673 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5675 case FCmpInst::FCMP_ULE:
5676 case FCmpInst::FCMP_OLE:
5677 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5679 case FCmpInst::FCMP_UNE:
5680 case FCmpInst::FCMP_ONE:
5681 Pred = ICmpInst::ICMP_NE;
5683 case FCmpInst::FCMP_ORD:
5684 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5685 case FCmpInst::FCMP_UNO:
5686 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5689 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5691 // Now we know that the APFloat is a normal number, zero or inf.
5693 // See if the FP constant is too large for the integer. For example,
5694 // comparing an i8 to 300.0.
5695 unsigned IntWidth = IntTy->getScalarSizeInBits();
5698 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5699 // and large values.
5700 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5701 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5702 APFloat::rmNearestTiesToEven);
5703 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5704 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5705 Pred == ICmpInst::ICMP_SLE)
5706 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5707 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5710 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5711 // +INF and large values.
5712 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5713 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5714 APFloat::rmNearestTiesToEven);
5715 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5716 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5717 Pred == ICmpInst::ICMP_ULE)
5718 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5719 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5724 // See if the RHS value is < SignedMin.
5725 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5726 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5727 APFloat::rmNearestTiesToEven);
5728 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5729 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5730 Pred == ICmpInst::ICMP_SGE)
5731 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5732 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5736 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5737 // [0, UMAX], but it may still be fractional. See if it is fractional by
5738 // casting the FP value to the integer value and back, checking for equality.
5739 // Don't do this for zero, because -0.0 is not fractional.
5740 Constant *RHSInt = LHSUnsigned
5741 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5742 : ConstantExpr::getFPToSI(RHSC, IntTy);
5743 if (!RHS.isZero()) {
5744 bool Equal = LHSUnsigned
5745 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5746 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5748 // If we had a comparison against a fractional value, we have to adjust
5749 // the compare predicate and sometimes the value. RHSC is rounded towards
5750 // zero at this point.
5752 default: llvm_unreachable("Unexpected integer comparison!");
5753 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5754 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5755 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5756 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5757 case ICmpInst::ICMP_ULE:
5758 // (float)int <= 4.4 --> int <= 4
5759 // (float)int <= -4.4 --> false
5760 if (RHS.isNegative())
5761 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5763 case ICmpInst::ICMP_SLE:
5764 // (float)int <= 4.4 --> int <= 4
5765 // (float)int <= -4.4 --> int < -4
5766 if (RHS.isNegative())
5767 Pred = ICmpInst::ICMP_SLT;
5769 case ICmpInst::ICMP_ULT:
5770 // (float)int < -4.4 --> false
5771 // (float)int < 4.4 --> int <= 4
5772 if (RHS.isNegative())
5773 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5774 Pred = ICmpInst::ICMP_ULE;
5776 case ICmpInst::ICMP_SLT:
5777 // (float)int < -4.4 --> int < -4
5778 // (float)int < 4.4 --> int <= 4
5779 if (!RHS.isNegative())
5780 Pred = ICmpInst::ICMP_SLE;
5782 case ICmpInst::ICMP_UGT:
5783 // (float)int > 4.4 --> int > 4
5784 // (float)int > -4.4 --> true
5785 if (RHS.isNegative())
5786 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5788 case ICmpInst::ICMP_SGT:
5789 // (float)int > 4.4 --> int > 4
5790 // (float)int > -4.4 --> int >= -4
5791 if (RHS.isNegative())
5792 Pred = ICmpInst::ICMP_SGE;
5794 case ICmpInst::ICMP_UGE:
5795 // (float)int >= -4.4 --> true
5796 // (float)int >= 4.4 --> int > 4
5797 if (!RHS.isNegative())
5798 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5799 Pred = ICmpInst::ICMP_UGT;
5801 case ICmpInst::ICMP_SGE:
5802 // (float)int >= -4.4 --> int >= -4
5803 // (float)int >= 4.4 --> int > 4
5804 if (!RHS.isNegative())
5805 Pred = ICmpInst::ICMP_SGT;
5811 // Lower this FP comparison into an appropriate integer version of the
5813 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5816 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5817 bool Changed = SimplifyCompare(I);
5818 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5820 // Fold trivial predicates.
5821 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5822 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
5823 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5824 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
5826 // Simplify 'fcmp pred X, X'
5828 switch (I.getPredicate()) {
5829 default: llvm_unreachable("Unknown predicate!");
5830 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5831 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5832 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5833 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
5834 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5835 case FCmpInst::FCMP_OLT: // True if ordered and less than
5836 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5837 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
5839 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5840 case FCmpInst::FCMP_ULT: // True if unordered or less than
5841 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5842 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5843 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5844 I.setPredicate(FCmpInst::FCMP_UNO);
5845 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5848 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5849 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5850 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5851 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5852 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5853 I.setPredicate(FCmpInst::FCMP_ORD);
5854 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5859 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5860 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
5862 // Handle fcmp with constant RHS
5863 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5864 // If the constant is a nan, see if we can fold the comparison based on it.
5865 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5866 if (CFP->getValueAPF().isNaN()) {
5867 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5868 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5869 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5870 "Comparison must be either ordered or unordered!");
5871 // True if unordered.
5872 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5876 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5877 switch (LHSI->getOpcode()) {
5878 case Instruction::PHI:
5879 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5880 // block. If in the same block, we're encouraging jump threading. If
5881 // not, we are just pessimizing the code by making an i1 phi.
5882 if (LHSI->getParent() == I.getParent())
5883 if (Instruction *NV = FoldOpIntoPhi(I, true))
5886 case Instruction::SIToFP:
5887 case Instruction::UIToFP:
5888 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5891 case Instruction::Select:
5892 // If either operand of the select is a constant, we can fold the
5893 // comparison into the select arms, which will cause one to be
5894 // constant folded and the select turned into a bitwise or.
5895 Value *Op1 = 0, *Op2 = 0;
5896 if (LHSI->hasOneUse()) {
5897 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5898 // Fold the known value into the constant operand.
5899 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5900 // Insert a new FCmp of the other select operand.
5901 Op2 = Builder->CreateFCmp(I.getPredicate(),
5902 LHSI->getOperand(2), RHSC, I.getName());
5903 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5904 // Fold the known value into the constant operand.
5905 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5906 // Insert a new FCmp of the other select operand.
5907 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5913 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5918 return Changed ? &I : 0;
5921 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5922 bool Changed = SimplifyCompare(I);
5923 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5924 const Type *Ty = Op0->getType();
5928 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
5929 I.isTrueWhenEqual()));
5931 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5932 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
5934 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5935 // addresses never equal each other! We already know that Op0 != Op1.
5936 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) || isMalloc(Op0) ||
5937 isa<ConstantPointerNull>(Op0)) &&
5938 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) || isMalloc(Op1) ||
5939 isa<ConstantPointerNull>(Op1)))
5940 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
5941 !I.isTrueWhenEqual()));
5943 // icmp's with boolean values can always be turned into bitwise operations
5944 if (Ty == Type::getInt1Ty(*Context)) {
5945 switch (I.getPredicate()) {
5946 default: llvm_unreachable("Invalid icmp instruction!");
5947 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
5948 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
5949 return BinaryOperator::CreateNot(Xor);
5951 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
5952 return BinaryOperator::CreateXor(Op0, Op1);
5954 case ICmpInst::ICMP_UGT:
5955 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
5957 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
5958 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
5959 return BinaryOperator::CreateAnd(Not, Op1);
5961 case ICmpInst::ICMP_SGT:
5962 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
5964 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5965 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
5966 return BinaryOperator::CreateAnd(Not, Op0);
5968 case ICmpInst::ICMP_UGE:
5969 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5971 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
5972 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
5973 return BinaryOperator::CreateOr(Not, Op1);
5975 case ICmpInst::ICMP_SGE:
5976 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5978 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5979 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
5980 return BinaryOperator::CreateOr(Not, Op0);
5985 unsigned BitWidth = 0;
5987 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
5988 else if (Ty->isIntOrIntVector())
5989 BitWidth = Ty->getScalarSizeInBits();
5991 bool isSignBit = false;
5993 // See if we are doing a comparison with a constant.
5994 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
5995 Value *A = 0, *B = 0;
5997 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5998 if (I.isEquality() && CI->isNullValue() &&
5999 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6000 // (icmp cond A B) if cond is equality
6001 return new ICmpInst(I.getPredicate(), A, B);
6004 // If we have an icmp le or icmp ge instruction, turn it into the
6005 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6006 // them being folded in the code below.
6007 switch (I.getPredicate()) {
6009 case ICmpInst::ICMP_ULE:
6010 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
6011 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6012 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
6014 case ICmpInst::ICMP_SLE:
6015 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
6016 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6017 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6019 case ICmpInst::ICMP_UGE:
6020 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
6021 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6022 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
6024 case ICmpInst::ICMP_SGE:
6025 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
6026 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6027 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6031 // If this comparison is a normal comparison, it demands all
6032 // bits, if it is a sign bit comparison, it only demands the sign bit.
6034 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6037 // See if we can fold the comparison based on range information we can get
6038 // by checking whether bits are known to be zero or one in the input.
6039 if (BitWidth != 0) {
6040 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6041 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6043 if (SimplifyDemandedBits(I.getOperandUse(0),
6044 isSignBit ? APInt::getSignBit(BitWidth)
6045 : APInt::getAllOnesValue(BitWidth),
6046 Op0KnownZero, Op0KnownOne, 0))
6048 if (SimplifyDemandedBits(I.getOperandUse(1),
6049 APInt::getAllOnesValue(BitWidth),
6050 Op1KnownZero, Op1KnownOne, 0))
6053 // Given the known and unknown bits, compute a range that the LHS could be
6054 // in. Compute the Min, Max and RHS values based on the known bits. For the
6055 // EQ and NE we use unsigned values.
6056 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6057 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6058 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6059 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6061 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6064 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6066 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6070 // If Min and Max are known to be the same, then SimplifyDemandedBits
6071 // figured out that the LHS is a constant. Just constant fold this now so
6072 // that code below can assume that Min != Max.
6073 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6074 return new ICmpInst(I.getPredicate(),
6075 ConstantInt::get(*Context, Op0Min), Op1);
6076 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6077 return new ICmpInst(I.getPredicate(), Op0,
6078 ConstantInt::get(*Context, Op1Min));
6080 // Based on the range information we know about the LHS, see if we can
6081 // simplify this comparison. For example, (x&4) < 8 is always true.
6082 switch (I.getPredicate()) {
6083 default: llvm_unreachable("Unknown icmp opcode!");
6084 case ICmpInst::ICMP_EQ:
6085 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6086 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6088 case ICmpInst::ICMP_NE:
6089 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6090 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6092 case ICmpInst::ICMP_ULT:
6093 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
6094 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6095 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
6096 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6097 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
6098 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6099 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6100 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
6101 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6104 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6105 if (CI->isMinValue(true))
6106 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6107 Constant::getAllOnesValue(Op0->getType()));
6110 case ICmpInst::ICMP_UGT:
6111 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
6112 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6113 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
6114 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6116 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
6117 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6118 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6119 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
6120 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6123 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6124 if (CI->isMaxValue(true))
6125 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6126 Constant::getNullValue(Op0->getType()));
6129 case ICmpInst::ICMP_SLT:
6130 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
6131 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6132 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
6133 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6134 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
6135 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6136 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6137 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
6138 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6142 case ICmpInst::ICMP_SGT:
6143 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
6144 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6145 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
6146 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6148 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
6149 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6150 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6151 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
6152 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6156 case ICmpInst::ICMP_SGE:
6157 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6158 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
6159 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6160 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
6161 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6163 case ICmpInst::ICMP_SLE:
6164 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6165 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
6166 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6167 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
6168 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6170 case ICmpInst::ICMP_UGE:
6171 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6172 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
6173 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6174 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
6175 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6177 case ICmpInst::ICMP_ULE:
6178 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6179 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
6180 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6181 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
6182 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6186 // Turn a signed comparison into an unsigned one if both operands
6187 // are known to have the same sign.
6188 if (I.isSignedPredicate() &&
6189 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6190 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6191 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6194 // Test if the ICmpInst instruction is used exclusively by a select as
6195 // part of a minimum or maximum operation. If so, refrain from doing
6196 // any other folding. This helps out other analyses which understand
6197 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6198 // and CodeGen. And in this case, at least one of the comparison
6199 // operands has at least one user besides the compare (the select),
6200 // which would often largely negate the benefit of folding anyway.
6202 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6203 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6204 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6207 // See if we are doing a comparison between a constant and an instruction that
6208 // can be folded into the comparison.
6209 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6210 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6211 // instruction, see if that instruction also has constants so that the
6212 // instruction can be folded into the icmp
6213 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6214 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6218 // Handle icmp with constant (but not simple integer constant) RHS
6219 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6220 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6221 switch (LHSI->getOpcode()) {
6222 case Instruction::GetElementPtr:
6223 if (RHSC->isNullValue()) {
6224 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6225 bool isAllZeros = true;
6226 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6227 if (!isa<Constant>(LHSI->getOperand(i)) ||
6228 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6233 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6234 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6238 case Instruction::PHI:
6239 // Only fold icmp into the PHI if the phi and icmp are in the same
6240 // block. If in the same block, we're encouraging jump threading. If
6241 // not, we are just pessimizing the code by making an i1 phi.
6242 if (LHSI->getParent() == I.getParent())
6243 if (Instruction *NV = FoldOpIntoPhi(I, true))
6246 case Instruction::Select: {
6247 // If either operand of the select is a constant, we can fold the
6248 // comparison into the select arms, which will cause one to be
6249 // constant folded and the select turned into a bitwise or.
6250 Value *Op1 = 0, *Op2 = 0;
6251 if (LHSI->hasOneUse()) {
6252 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6253 // Fold the known value into the constant operand.
6254 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6255 // Insert a new ICmp of the other select operand.
6256 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6258 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6259 // Fold the known value into the constant operand.
6260 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6261 // Insert a new ICmp of the other select operand.
6262 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6268 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6271 case Instruction::Malloc:
6272 // If we have (malloc != null), and if the malloc has a single use, we
6273 // can assume it is successful and remove the malloc.
6274 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6276 return ReplaceInstUsesWith(I,
6277 ConstantInt::get(Type::getInt1Ty(*Context),
6278 !I.isTrueWhenEqual()));
6281 case Instruction::Call:
6282 // If we have (malloc != null), and if the malloc has a single use, we
6283 // can assume it is successful and remove the malloc.
6284 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6285 isa<ConstantPointerNull>(RHSC)) {
6287 return ReplaceInstUsesWith(I,
6288 ConstantInt::get(Type::getInt1Ty(*Context),
6289 !I.isTrueWhenEqual()));
6295 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6296 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6297 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6299 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6300 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6301 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6304 // Test to see if the operands of the icmp are casted versions of other
6305 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6307 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6308 if (isa<PointerType>(Op0->getType()) &&
6309 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6310 // We keep moving the cast from the left operand over to the right
6311 // operand, where it can often be eliminated completely.
6312 Op0 = CI->getOperand(0);
6314 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6315 // so eliminate it as well.
6316 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6317 Op1 = CI2->getOperand(0);
6319 // If Op1 is a constant, we can fold the cast into the constant.
6320 if (Op0->getType() != Op1->getType()) {
6321 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6322 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6324 // Otherwise, cast the RHS right before the icmp
6325 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6328 return new ICmpInst(I.getPredicate(), Op0, Op1);
6332 if (isa<CastInst>(Op0)) {
6333 // Handle the special case of: icmp (cast bool to X), <cst>
6334 // This comes up when you have code like
6337 // For generality, we handle any zero-extension of any operand comparison
6338 // with a constant or another cast from the same type.
6339 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6340 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6344 // See if it's the same type of instruction on the left and right.
6345 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6346 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6347 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6348 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6349 switch (Op0I->getOpcode()) {
6351 case Instruction::Add:
6352 case Instruction::Sub:
6353 case Instruction::Xor:
6354 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
6355 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6356 Op1I->getOperand(0));
6357 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6358 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6359 if (CI->getValue().isSignBit()) {
6360 ICmpInst::Predicate Pred = I.isSignedPredicate()
6361 ? I.getUnsignedPredicate()
6362 : I.getSignedPredicate();
6363 return new ICmpInst(Pred, Op0I->getOperand(0),
6364 Op1I->getOperand(0));
6367 if (CI->getValue().isMaxSignedValue()) {
6368 ICmpInst::Predicate Pred = I.isSignedPredicate()
6369 ? I.getUnsignedPredicate()
6370 : I.getSignedPredicate();
6371 Pred = I.getSwappedPredicate(Pred);
6372 return new ICmpInst(Pred, Op0I->getOperand(0),
6373 Op1I->getOperand(0));
6377 case Instruction::Mul:
6378 if (!I.isEquality())
6381 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6382 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6383 // Mask = -1 >> count-trailing-zeros(Cst).
6384 if (!CI->isZero() && !CI->isOne()) {
6385 const APInt &AP = CI->getValue();
6386 ConstantInt *Mask = ConstantInt::get(*Context,
6387 APInt::getLowBitsSet(AP.getBitWidth(),
6389 AP.countTrailingZeros()));
6390 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6391 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6392 return new ICmpInst(I.getPredicate(), And1, And2);
6401 // ~x < ~y --> y < x
6403 if (match(Op0, m_Not(m_Value(A))) &&
6404 match(Op1, m_Not(m_Value(B))))
6405 return new ICmpInst(I.getPredicate(), B, A);
6408 if (I.isEquality()) {
6409 Value *A, *B, *C, *D;
6411 // -x == -y --> x == y
6412 if (match(Op0, m_Neg(m_Value(A))) &&
6413 match(Op1, m_Neg(m_Value(B))))
6414 return new ICmpInst(I.getPredicate(), A, B);
6416 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6417 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6418 Value *OtherVal = A == Op1 ? B : A;
6419 return new ICmpInst(I.getPredicate(), OtherVal,
6420 Constant::getNullValue(A->getType()));
6423 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6424 // A^c1 == C^c2 --> A == C^(c1^c2)
6425 ConstantInt *C1, *C2;
6426 if (match(B, m_ConstantInt(C1)) &&
6427 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6429 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6430 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6431 return new ICmpInst(I.getPredicate(), A, Xor);
6434 // A^B == A^D -> B == D
6435 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6436 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6437 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6438 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6442 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6443 (A == Op0 || B == Op0)) {
6444 // A == (A^B) -> B == 0
6445 Value *OtherVal = A == Op0 ? B : A;
6446 return new ICmpInst(I.getPredicate(), OtherVal,
6447 Constant::getNullValue(A->getType()));
6450 // (A-B) == A -> B == 0
6451 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6452 return new ICmpInst(I.getPredicate(), B,
6453 Constant::getNullValue(B->getType()));
6455 // A == (A-B) -> B == 0
6456 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6457 return new ICmpInst(I.getPredicate(), B,
6458 Constant::getNullValue(B->getType()));
6460 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6461 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6462 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6463 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6464 Value *X = 0, *Y = 0, *Z = 0;
6467 X = B; Y = D; Z = A;
6468 } else if (A == D) {
6469 X = B; Y = C; Z = A;
6470 } else if (B == C) {
6471 X = A; Y = D; Z = B;
6472 } else if (B == D) {
6473 X = A; Y = C; Z = B;
6476 if (X) { // Build (X^Y) & Z
6477 Op1 = Builder->CreateXor(X, Y, "tmp");
6478 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6479 I.setOperand(0, Op1);
6480 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6485 return Changed ? &I : 0;
6489 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6490 /// and CmpRHS are both known to be integer constants.
6491 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6492 ConstantInt *DivRHS) {
6493 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6494 const APInt &CmpRHSV = CmpRHS->getValue();
6496 // FIXME: If the operand types don't match the type of the divide
6497 // then don't attempt this transform. The code below doesn't have the
6498 // logic to deal with a signed divide and an unsigned compare (and
6499 // vice versa). This is because (x /s C1) <s C2 produces different
6500 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6501 // (x /u C1) <u C2. Simply casting the operands and result won't
6502 // work. :( The if statement below tests that condition and bails
6504 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6505 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6507 if (DivRHS->isZero())
6508 return 0; // The ProdOV computation fails on divide by zero.
6509 if (DivIsSigned && DivRHS->isAllOnesValue())
6510 return 0; // The overflow computation also screws up here
6511 if (DivRHS->isOne())
6512 return 0; // Not worth bothering, and eliminates some funny cases
6515 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6516 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6517 // C2 (CI). By solving for X we can turn this into a range check
6518 // instead of computing a divide.
6519 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6521 // Determine if the product overflows by seeing if the product is
6522 // not equal to the divide. Make sure we do the same kind of divide
6523 // as in the LHS instruction that we're folding.
6524 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6525 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6527 // Get the ICmp opcode
6528 ICmpInst::Predicate Pred = ICI.getPredicate();
6530 // Figure out the interval that is being checked. For example, a comparison
6531 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6532 // Compute this interval based on the constants involved and the signedness of
6533 // the compare/divide. This computes a half-open interval, keeping track of
6534 // whether either value in the interval overflows. After analysis each
6535 // overflow variable is set to 0 if it's corresponding bound variable is valid
6536 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6537 int LoOverflow = 0, HiOverflow = 0;
6538 Constant *LoBound = 0, *HiBound = 0;
6540 if (!DivIsSigned) { // udiv
6541 // e.g. X/5 op 3 --> [15, 20)
6543 HiOverflow = LoOverflow = ProdOV;
6545 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6546 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6547 if (CmpRHSV == 0) { // (X / pos) op 0
6548 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
6549 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6551 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
6552 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6553 HiOverflow = LoOverflow = ProdOV;
6555 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6556 } else { // (X / pos) op neg
6557 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
6558 HiBound = AddOne(Prod);
6559 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6561 ConstantInt* DivNeg =
6562 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6563 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6567 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6568 if (CmpRHSV == 0) { // (X / neg) op 0
6569 // e.g. X/-5 op 0 --> [-4, 5)
6570 LoBound = AddOne(DivRHS);
6571 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6572 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6573 HiOverflow = 1; // [INTMIN+1, overflow)
6574 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6576 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
6577 // e.g. X/-5 op 3 --> [-19, -14)
6578 HiBound = AddOne(Prod);
6579 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6581 LoOverflow = AddWithOverflow(LoBound, HiBound,
6582 DivRHS, Context, true) ? -1 : 0;
6583 } else { // (X / neg) op neg
6584 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6585 LoOverflow = HiOverflow = ProdOV;
6587 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6590 // Dividing by a negative swaps the condition. LT <-> GT
6591 Pred = ICmpInst::getSwappedPredicate(Pred);
6594 Value *X = DivI->getOperand(0);
6596 default: llvm_unreachable("Unhandled icmp opcode!");
6597 case ICmpInst::ICMP_EQ:
6598 if (LoOverflow && HiOverflow)
6599 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6600 else if (HiOverflow)
6601 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6602 ICmpInst::ICMP_UGE, X, LoBound);
6603 else if (LoOverflow)
6604 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6605 ICmpInst::ICMP_ULT, X, HiBound);
6607 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6608 case ICmpInst::ICMP_NE:
6609 if (LoOverflow && HiOverflow)
6610 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6611 else if (HiOverflow)
6612 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6613 ICmpInst::ICMP_ULT, X, LoBound);
6614 else if (LoOverflow)
6615 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6616 ICmpInst::ICMP_UGE, X, HiBound);
6618 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6619 case ICmpInst::ICMP_ULT:
6620 case ICmpInst::ICMP_SLT:
6621 if (LoOverflow == +1) // Low bound is greater than input range.
6622 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6623 if (LoOverflow == -1) // Low bound is less than input range.
6624 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6625 return new ICmpInst(Pred, X, LoBound);
6626 case ICmpInst::ICMP_UGT:
6627 case ICmpInst::ICMP_SGT:
6628 if (HiOverflow == +1) // High bound greater than input range.
6629 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6630 else if (HiOverflow == -1) // High bound less than input range.
6631 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6632 if (Pred == ICmpInst::ICMP_UGT)
6633 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6635 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6640 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6642 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6645 const APInt &RHSV = RHS->getValue();
6647 switch (LHSI->getOpcode()) {
6648 case Instruction::Trunc:
6649 if (ICI.isEquality() && LHSI->hasOneUse()) {
6650 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6651 // of the high bits truncated out of x are known.
6652 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6653 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6654 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6655 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6656 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6658 // If all the high bits are known, we can do this xform.
6659 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6660 // Pull in the high bits from known-ones set.
6661 APInt NewRHS(RHS->getValue());
6662 NewRHS.zext(SrcBits);
6664 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6665 ConstantInt::get(*Context, NewRHS));
6670 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6671 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6672 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6674 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6675 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6676 Value *CompareVal = LHSI->getOperand(0);
6678 // If the sign bit of the XorCST is not set, there is no change to
6679 // the operation, just stop using the Xor.
6680 if (!XorCST->getValue().isNegative()) {
6681 ICI.setOperand(0, CompareVal);
6686 // Was the old condition true if the operand is positive?
6687 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6689 // If so, the new one isn't.
6690 isTrueIfPositive ^= true;
6692 if (isTrueIfPositive)
6693 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6696 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6700 if (LHSI->hasOneUse()) {
6701 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6702 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6703 const APInt &SignBit = XorCST->getValue();
6704 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6705 ? ICI.getUnsignedPredicate()
6706 : ICI.getSignedPredicate();
6707 return new ICmpInst(Pred, LHSI->getOperand(0),
6708 ConstantInt::get(*Context, RHSV ^ SignBit));
6711 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6712 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6713 const APInt &NotSignBit = XorCST->getValue();
6714 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6715 ? ICI.getUnsignedPredicate()
6716 : ICI.getSignedPredicate();
6717 Pred = ICI.getSwappedPredicate(Pred);
6718 return new ICmpInst(Pred, LHSI->getOperand(0),
6719 ConstantInt::get(*Context, RHSV ^ NotSignBit));
6724 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6725 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6726 LHSI->getOperand(0)->hasOneUse()) {
6727 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6729 // If the LHS is an AND of a truncating cast, we can widen the
6730 // and/compare to be the input width without changing the value
6731 // produced, eliminating a cast.
6732 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6733 // We can do this transformation if either the AND constant does not
6734 // have its sign bit set or if it is an equality comparison.
6735 // Extending a relational comparison when we're checking the sign
6736 // bit would not work.
6737 if (Cast->hasOneUse() &&
6738 (ICI.isEquality() ||
6739 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6741 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6742 APInt NewCST = AndCST->getValue();
6743 NewCST.zext(BitWidth);
6745 NewCI.zext(BitWidth);
6747 Builder->CreateAnd(Cast->getOperand(0),
6748 ConstantInt::get(*Context, NewCST), LHSI->getName());
6749 return new ICmpInst(ICI.getPredicate(), NewAnd,
6750 ConstantInt::get(*Context, NewCI));
6754 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6755 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6756 // happens a LOT in code produced by the C front-end, for bitfield
6758 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6759 if (Shift && !Shift->isShift())
6763 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6764 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6765 const Type *AndTy = AndCST->getType(); // Type of the and.
6767 // We can fold this as long as we can't shift unknown bits
6768 // into the mask. This can only happen with signed shift
6769 // rights, as they sign-extend.
6771 bool CanFold = Shift->isLogicalShift();
6773 // To test for the bad case of the signed shr, see if any
6774 // of the bits shifted in could be tested after the mask.
6775 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6776 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6778 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6779 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6780 AndCST->getValue()) == 0)
6786 if (Shift->getOpcode() == Instruction::Shl)
6787 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6789 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6791 // Check to see if we are shifting out any of the bits being
6793 if (ConstantExpr::get(Shift->getOpcode(),
6794 NewCst, ShAmt) != RHS) {
6795 // If we shifted bits out, the fold is not going to work out.
6796 // As a special case, check to see if this means that the
6797 // result is always true or false now.
6798 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6799 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6800 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6801 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6803 ICI.setOperand(1, NewCst);
6804 Constant *NewAndCST;
6805 if (Shift->getOpcode() == Instruction::Shl)
6806 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6808 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6809 LHSI->setOperand(1, NewAndCST);
6810 LHSI->setOperand(0, Shift->getOperand(0));
6811 Worklist.Add(Shift); // Shift is dead.
6817 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6818 // preferable because it allows the C<<Y expression to be hoisted out
6819 // of a loop if Y is invariant and X is not.
6820 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6821 ICI.isEquality() && !Shift->isArithmeticShift() &&
6822 !isa<Constant>(Shift->getOperand(0))) {
6825 if (Shift->getOpcode() == Instruction::LShr) {
6826 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
6828 // Insert a logical shift.
6829 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
6832 // Compute X & (C << Y).
6834 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6836 ICI.setOperand(0, NewAnd);
6842 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6843 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6846 uint32_t TypeBits = RHSV.getBitWidth();
6848 // Check that the shift amount is in range. If not, don't perform
6849 // undefined shifts. When the shift is visited it will be
6851 if (ShAmt->uge(TypeBits))
6854 if (ICI.isEquality()) {
6855 // If we are comparing against bits always shifted out, the
6856 // comparison cannot succeed.
6858 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6860 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6861 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6862 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6863 return ReplaceInstUsesWith(ICI, Cst);
6866 if (LHSI->hasOneUse()) {
6867 // Otherwise strength reduce the shift into an and.
6868 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6870 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
6871 TypeBits-ShAmtVal));
6874 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
6875 return new ICmpInst(ICI.getPredicate(), And,
6876 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6880 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6881 bool TrueIfSigned = false;
6882 if (LHSI->hasOneUse() &&
6883 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6884 // (X << 31) <s 0 --> (X&1) != 0
6885 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6886 (TypeBits-ShAmt->getZExtValue()-1));
6888 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
6889 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6890 And, Constant::getNullValue(And->getType()));
6895 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6896 case Instruction::AShr: {
6897 // Only handle equality comparisons of shift-by-constant.
6898 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6899 if (!ShAmt || !ICI.isEquality()) break;
6901 // Check that the shift amount is in range. If not, don't perform
6902 // undefined shifts. When the shift is visited it will be
6904 uint32_t TypeBits = RHSV.getBitWidth();
6905 if (ShAmt->uge(TypeBits))
6908 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6910 // If we are comparing against bits always shifted out, the
6911 // comparison cannot succeed.
6912 APInt Comp = RHSV << ShAmtVal;
6913 if (LHSI->getOpcode() == Instruction::LShr)
6914 Comp = Comp.lshr(ShAmtVal);
6916 Comp = Comp.ashr(ShAmtVal);
6918 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6919 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6920 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6921 return ReplaceInstUsesWith(ICI, Cst);
6924 // Otherwise, check to see if the bits shifted out are known to be zero.
6925 // If so, we can compare against the unshifted value:
6926 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
6927 if (LHSI->hasOneUse() &&
6928 MaskedValueIsZero(LHSI->getOperand(0),
6929 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6930 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6931 ConstantExpr::getShl(RHS, ShAmt));
6934 if (LHSI->hasOneUse()) {
6935 // Otherwise strength reduce the shift into an and.
6936 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6937 Constant *Mask = ConstantInt::get(*Context, Val);
6939 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
6940 Mask, LHSI->getName()+".mask");
6941 return new ICmpInst(ICI.getPredicate(), And,
6942 ConstantExpr::getShl(RHS, ShAmt));
6947 case Instruction::SDiv:
6948 case Instruction::UDiv:
6949 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6950 // Fold this div into the comparison, producing a range check.
6951 // Determine, based on the divide type, what the range is being
6952 // checked. If there is an overflow on the low or high side, remember
6953 // it, otherwise compute the range [low, hi) bounding the new value.
6954 // See: InsertRangeTest above for the kinds of replacements possible.
6955 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6956 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6961 case Instruction::Add:
6962 // Fold: icmp pred (add, X, C1), C2
6964 if (!ICI.isEquality()) {
6965 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6967 const APInt &LHSV = LHSC->getValue();
6969 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6972 if (ICI.isSignedPredicate()) {
6973 if (CR.getLower().isSignBit()) {
6974 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6975 ConstantInt::get(*Context, CR.getUpper()));
6976 } else if (CR.getUpper().isSignBit()) {
6977 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6978 ConstantInt::get(*Context, CR.getLower()));
6981 if (CR.getLower().isMinValue()) {
6982 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6983 ConstantInt::get(*Context, CR.getUpper()));
6984 } else if (CR.getUpper().isMinValue()) {
6985 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6986 ConstantInt::get(*Context, CR.getLower()));
6993 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6994 if (ICI.isEquality()) {
6995 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6997 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6998 // the second operand is a constant, simplify a bit.
6999 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7000 switch (BO->getOpcode()) {
7001 case Instruction::SRem:
7002 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7003 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7004 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7005 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7007 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7009 return new ICmpInst(ICI.getPredicate(), NewRem,
7010 Constant::getNullValue(BO->getType()));
7014 case Instruction::Add:
7015 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7016 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7017 if (BO->hasOneUse())
7018 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7019 ConstantExpr::getSub(RHS, BOp1C));
7020 } else if (RHSV == 0) {
7021 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7022 // efficiently invertible, or if the add has just this one use.
7023 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7025 if (Value *NegVal = dyn_castNegVal(BOp1))
7026 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7027 else if (Value *NegVal = dyn_castNegVal(BOp0))
7028 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7029 else if (BO->hasOneUse()) {
7030 Value *Neg = Builder->CreateNeg(BOp1);
7032 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7036 case Instruction::Xor:
7037 // For the xor case, we can xor two constants together, eliminating
7038 // the explicit xor.
7039 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7040 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7041 ConstantExpr::getXor(RHS, BOC));
7044 case Instruction::Sub:
7045 // Replace (([sub|xor] A, B) != 0) with (A != B)
7047 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7051 case Instruction::Or:
7052 // If bits are being or'd in that are not present in the constant we
7053 // are comparing against, then the comparison could never succeed!
7054 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7055 Constant *NotCI = ConstantExpr::getNot(RHS);
7056 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7057 return ReplaceInstUsesWith(ICI,
7058 ConstantInt::get(Type::getInt1Ty(*Context),
7063 case Instruction::And:
7064 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7065 // If bits are being compared against that are and'd out, then the
7066 // comparison can never succeed!
7067 if ((RHSV & ~BOC->getValue()) != 0)
7068 return ReplaceInstUsesWith(ICI,
7069 ConstantInt::get(Type::getInt1Ty(*Context),
7072 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7073 if (RHS == BOC && RHSV.isPowerOf2())
7074 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7075 ICmpInst::ICMP_NE, LHSI,
7076 Constant::getNullValue(RHS->getType()));
7078 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7079 if (BOC->getValue().isSignBit()) {
7080 Value *X = BO->getOperand(0);
7081 Constant *Zero = Constant::getNullValue(X->getType());
7082 ICmpInst::Predicate pred = isICMP_NE ?
7083 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7084 return new ICmpInst(pred, X, Zero);
7087 // ((X & ~7) == 0) --> X < 8
7088 if (RHSV == 0 && isHighOnes(BOC)) {
7089 Value *X = BO->getOperand(0);
7090 Constant *NegX = ConstantExpr::getNeg(BOC);
7091 ICmpInst::Predicate pred = isICMP_NE ?
7092 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7093 return new ICmpInst(pred, X, NegX);
7098 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7099 // Handle icmp {eq|ne} <intrinsic>, intcst.
7100 if (II->getIntrinsicID() == Intrinsic::bswap) {
7102 ICI.setOperand(0, II->getOperand(1));
7103 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7111 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7112 /// We only handle extending casts so far.
7114 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7115 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7116 Value *LHSCIOp = LHSCI->getOperand(0);
7117 const Type *SrcTy = LHSCIOp->getType();
7118 const Type *DestTy = LHSCI->getType();
7121 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7122 // integer type is the same size as the pointer type.
7123 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7124 TD->getPointerSizeInBits() ==
7125 cast<IntegerType>(DestTy)->getBitWidth()) {
7127 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7128 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7129 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7130 RHSOp = RHSC->getOperand(0);
7131 // If the pointer types don't match, insert a bitcast.
7132 if (LHSCIOp->getType() != RHSOp->getType())
7133 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7137 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7140 // The code below only handles extension cast instructions, so far.
7142 if (LHSCI->getOpcode() != Instruction::ZExt &&
7143 LHSCI->getOpcode() != Instruction::SExt)
7146 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7147 bool isSignedCmp = ICI.isSignedPredicate();
7149 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7150 // Not an extension from the same type?
7151 RHSCIOp = CI->getOperand(0);
7152 if (RHSCIOp->getType() != LHSCIOp->getType())
7155 // If the signedness of the two casts doesn't agree (i.e. one is a sext
7156 // and the other is a zext), then we can't handle this.
7157 if (CI->getOpcode() != LHSCI->getOpcode())
7160 // Deal with equality cases early.
7161 if (ICI.isEquality())
7162 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7164 // A signed comparison of sign extended values simplifies into a
7165 // signed comparison.
7166 if (isSignedCmp && isSignedExt)
7167 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7169 // The other three cases all fold into an unsigned comparison.
7170 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7173 // If we aren't dealing with a constant on the RHS, exit early
7174 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7178 // Compute the constant that would happen if we truncated to SrcTy then
7179 // reextended to DestTy.
7180 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7181 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7184 // If the re-extended constant didn't change...
7186 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7187 // For example, we might have:
7188 // %A = sext i16 %X to i32
7189 // %B = icmp ugt i32 %A, 1330
7190 // It is incorrect to transform this into
7191 // %B = icmp ugt i16 %X, 1330
7192 // because %A may have negative value.
7194 // However, we allow this when the compare is EQ/NE, because they are
7196 if (isSignedExt == isSignedCmp || ICI.isEquality())
7197 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7201 // The re-extended constant changed so the constant cannot be represented
7202 // in the shorter type. Consequently, we cannot emit a simple comparison.
7204 // First, handle some easy cases. We know the result cannot be equal at this
7205 // point so handle the ICI.isEquality() cases
7206 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7207 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7208 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7209 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7211 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7212 // should have been folded away previously and not enter in here.
7215 // We're performing a signed comparison.
7216 if (cast<ConstantInt>(CI)->getValue().isNegative())
7217 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
7219 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
7221 // We're performing an unsigned comparison.
7223 // We're performing an unsigned comp with a sign extended value.
7224 // This is true if the input is >= 0. [aka >s -1]
7225 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7226 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7228 // Unsigned extend & unsigned compare -> always true.
7229 Result = ConstantInt::getTrue(*Context);
7233 // Finally, return the value computed.
7234 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7235 ICI.getPredicate() == ICmpInst::ICMP_SLT)
7236 return ReplaceInstUsesWith(ICI, Result);
7238 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7239 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7240 "ICmp should be folded!");
7241 if (Constant *CI = dyn_cast<Constant>(Result))
7242 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7243 return BinaryOperator::CreateNot(Result);
7246 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7247 return commonShiftTransforms(I);
7250 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7251 return commonShiftTransforms(I);
7254 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7255 if (Instruction *R = commonShiftTransforms(I))
7258 Value *Op0 = I.getOperand(0);
7260 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7261 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7262 if (CSI->isAllOnesValue())
7263 return ReplaceInstUsesWith(I, CSI);
7265 // See if we can turn a signed shr into an unsigned shr.
7266 if (MaskedValueIsZero(Op0,
7267 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7268 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7270 // Arithmetic shifting an all-sign-bit value is a no-op.
7271 unsigned NumSignBits = ComputeNumSignBits(Op0);
7272 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7273 return ReplaceInstUsesWith(I, Op0);
7278 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7279 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7280 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7282 // shl X, 0 == X and shr X, 0 == X
7283 // shl 0, X == 0 and shr 0, X == 0
7284 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7285 Op0 == Constant::getNullValue(Op0->getType()))
7286 return ReplaceInstUsesWith(I, Op0);
7288 if (isa<UndefValue>(Op0)) {
7289 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7290 return ReplaceInstUsesWith(I, Op0);
7291 else // undef << X -> 0, undef >>u X -> 0
7292 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7294 if (isa<UndefValue>(Op1)) {
7295 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7296 return ReplaceInstUsesWith(I, Op0);
7297 else // X << undef, X >>u undef -> 0
7298 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7301 // See if we can fold away this shift.
7302 if (SimplifyDemandedInstructionBits(I))
7305 // Try to fold constant and into select arguments.
7306 if (isa<Constant>(Op0))
7307 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7308 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7311 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7312 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7317 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7318 BinaryOperator &I) {
7319 bool isLeftShift = I.getOpcode() == Instruction::Shl;
7321 // See if we can simplify any instructions used by the instruction whose sole
7322 // purpose is to compute bits we don't care about.
7323 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7325 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7328 if (Op1->uge(TypeBits)) {
7329 if (I.getOpcode() != Instruction::AShr)
7330 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7332 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7337 // ((X*C1) << C2) == (X * (C1 << C2))
7338 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7339 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7340 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7341 return BinaryOperator::CreateMul(BO->getOperand(0),
7342 ConstantExpr::getShl(BOOp, Op1));
7344 // Try to fold constant and into select arguments.
7345 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7346 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7348 if (isa<PHINode>(Op0))
7349 if (Instruction *NV = FoldOpIntoPhi(I))
7352 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7353 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7354 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7355 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7356 // place. Don't try to do this transformation in this case. Also, we
7357 // require that the input operand is a shift-by-constant so that we have
7358 // confidence that the shifts will get folded together. We could do this
7359 // xform in more cases, but it is unlikely to be profitable.
7360 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7361 isa<ConstantInt>(TrOp->getOperand(1))) {
7362 // Okay, we'll do this xform. Make the shift of shift.
7363 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7364 // (shift2 (shift1 & 0x00FF), c2)
7365 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7367 // For logical shifts, the truncation has the effect of making the high
7368 // part of the register be zeros. Emulate this by inserting an AND to
7369 // clear the top bits as needed. This 'and' will usually be zapped by
7370 // other xforms later if dead.
7371 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7372 unsigned DstSize = TI->getType()->getScalarSizeInBits();
7373 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7375 // The mask we constructed says what the trunc would do if occurring
7376 // between the shifts. We want to know the effect *after* the second
7377 // shift. We know that it is a logical shift by a constant, so adjust the
7378 // mask as appropriate.
7379 if (I.getOpcode() == Instruction::Shl)
7380 MaskV <<= Op1->getZExtValue();
7382 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7383 MaskV = MaskV.lshr(Op1->getZExtValue());
7387 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7390 // Return the value truncated to the interesting size.
7391 return new TruncInst(And, I.getType());
7395 if (Op0->hasOneUse()) {
7396 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7397 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7400 switch (Op0BO->getOpcode()) {
7402 case Instruction::Add:
7403 case Instruction::And:
7404 case Instruction::Or:
7405 case Instruction::Xor: {
7406 // These operators commute.
7407 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7408 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7409 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7410 m_Specific(Op1)))) {
7411 Value *YS = // (Y << C)
7412 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7414 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7415 Op0BO->getOperand(1)->getName());
7416 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7417 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7418 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7421 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7422 Value *Op0BOOp1 = Op0BO->getOperand(1);
7423 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7425 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7426 m_ConstantInt(CC))) &&
7427 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7428 Value *YS = // (Y << C)
7429 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7432 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7433 V1->getName()+".mask");
7434 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7439 case Instruction::Sub: {
7440 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7441 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7442 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7443 m_Specific(Op1)))) {
7444 Value *YS = // (Y << C)
7445 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7447 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7448 Op0BO->getOperand(0)->getName());
7449 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7450 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7451 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7454 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7455 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7456 match(Op0BO->getOperand(0),
7457 m_And(m_Shr(m_Value(V1), m_Value(V2)),
7458 m_ConstantInt(CC))) && V2 == Op1 &&
7459 cast<BinaryOperator>(Op0BO->getOperand(0))
7460 ->getOperand(0)->hasOneUse()) {
7461 Value *YS = // (Y << C)
7462 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7464 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7465 V1->getName()+".mask");
7467 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7475 // If the operand is an bitwise operator with a constant RHS, and the
7476 // shift is the only use, we can pull it out of the shift.
7477 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7478 bool isValid = true; // Valid only for And, Or, Xor
7479 bool highBitSet = false; // Transform if high bit of constant set?
7481 switch (Op0BO->getOpcode()) {
7482 default: isValid = false; break; // Do not perform transform!
7483 case Instruction::Add:
7484 isValid = isLeftShift;
7486 case Instruction::Or:
7487 case Instruction::Xor:
7490 case Instruction::And:
7495 // If this is a signed shift right, and the high bit is modified
7496 // by the logical operation, do not perform the transformation.
7497 // The highBitSet boolean indicates the value of the high bit of
7498 // the constant which would cause it to be modified for this
7501 if (isValid && I.getOpcode() == Instruction::AShr)
7502 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7505 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7508 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
7509 NewShift->takeName(Op0BO);
7511 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7518 // Find out if this is a shift of a shift by a constant.
7519 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7520 if (ShiftOp && !ShiftOp->isShift())
7523 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7524 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7525 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7526 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7527 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7528 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7529 Value *X = ShiftOp->getOperand(0);
7531 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
7533 const IntegerType *Ty = cast<IntegerType>(I.getType());
7535 // Check for (X << c1) << c2 and (X >> c1) >> c2
7536 if (I.getOpcode() == ShiftOp->getOpcode()) {
7537 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7539 if (AmtSum >= TypeBits) {
7540 if (I.getOpcode() != Instruction::AShr)
7541 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7542 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7545 return BinaryOperator::Create(I.getOpcode(), X,
7546 ConstantInt::get(Ty, AmtSum));
7549 if (ShiftOp->getOpcode() == Instruction::LShr &&
7550 I.getOpcode() == Instruction::AShr) {
7551 if (AmtSum >= TypeBits)
7552 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7554 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
7555 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7558 if (ShiftOp->getOpcode() == Instruction::AShr &&
7559 I.getOpcode() == Instruction::LShr) {
7560 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7561 if (AmtSum >= TypeBits)
7562 AmtSum = TypeBits-1;
7564 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7566 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7567 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7570 // Okay, if we get here, one shift must be left, and the other shift must be
7571 // right. See if the amounts are equal.
7572 if (ShiftAmt1 == ShiftAmt2) {
7573 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7574 if (I.getOpcode() == Instruction::Shl) {
7575 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7576 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7578 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7579 if (I.getOpcode() == Instruction::LShr) {
7580 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7581 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7583 // We can simplify ((X << C) >>s C) into a trunc + sext.
7584 // NOTE: we could do this for any C, but that would make 'unusual' integer
7585 // types. For now, just stick to ones well-supported by the code
7587 const Type *SExtType = 0;
7588 switch (Ty->getBitWidth() - ShiftAmt1) {
7595 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7600 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
7601 // Otherwise, we can't handle it yet.
7602 } else if (ShiftAmt1 < ShiftAmt2) {
7603 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7605 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7606 if (I.getOpcode() == Instruction::Shl) {
7607 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7608 ShiftOp->getOpcode() == Instruction::AShr);
7609 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7611 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7612 return BinaryOperator::CreateAnd(Shift,
7613 ConstantInt::get(*Context, Mask));
7616 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7617 if (I.getOpcode() == Instruction::LShr) {
7618 assert(ShiftOp->getOpcode() == Instruction::Shl);
7619 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7621 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7622 return BinaryOperator::CreateAnd(Shift,
7623 ConstantInt::get(*Context, Mask));
7626 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7628 assert(ShiftAmt2 < ShiftAmt1);
7629 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7631 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7632 if (I.getOpcode() == Instruction::Shl) {
7633 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7634 ShiftOp->getOpcode() == Instruction::AShr);
7635 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7636 ConstantInt::get(Ty, ShiftDiff));
7638 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7639 return BinaryOperator::CreateAnd(Shift,
7640 ConstantInt::get(*Context, Mask));
7643 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7644 if (I.getOpcode() == Instruction::LShr) {
7645 assert(ShiftOp->getOpcode() == Instruction::Shl);
7646 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7648 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7649 return BinaryOperator::CreateAnd(Shift,
7650 ConstantInt::get(*Context, Mask));
7653 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7660 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7661 /// expression. If so, decompose it, returning some value X, such that Val is
7664 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7665 int &Offset, LLVMContext *Context) {
7666 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7667 "Unexpected allocation size type!");
7668 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7669 Offset = CI->getZExtValue();
7671 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7672 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7673 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7674 if (I->getOpcode() == Instruction::Shl) {
7675 // This is a value scaled by '1 << the shift amt'.
7676 Scale = 1U << RHS->getZExtValue();
7678 return I->getOperand(0);
7679 } else if (I->getOpcode() == Instruction::Mul) {
7680 // This value is scaled by 'RHS'.
7681 Scale = RHS->getZExtValue();
7683 return I->getOperand(0);
7684 } else if (I->getOpcode() == Instruction::Add) {
7685 // We have X+C. Check to see if we really have (X*C2)+C1,
7686 // where C1 is divisible by C2.
7689 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7691 Offset += RHS->getZExtValue();
7698 // Otherwise, we can't look past this.
7705 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7706 /// try to eliminate the cast by moving the type information into the alloc.
7707 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7708 AllocationInst &AI) {
7709 const PointerType *PTy = cast<PointerType>(CI.getType());
7711 BuilderTy AllocaBuilder(*Builder);
7712 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7714 // Remove any uses of AI that are dead.
7715 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7717 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7718 Instruction *User = cast<Instruction>(*UI++);
7719 if (isInstructionTriviallyDead(User)) {
7720 while (UI != E && *UI == User)
7721 ++UI; // If this instruction uses AI more than once, don't break UI.
7724 DEBUG(errs() << "IC: DCE: " << *User << '\n');
7725 EraseInstFromFunction(*User);
7729 // This requires TargetData to get the alloca alignment and size information.
7732 // Get the type really allocated and the type casted to.
7733 const Type *AllocElTy = AI.getAllocatedType();
7734 const Type *CastElTy = PTy->getElementType();
7735 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7737 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7738 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7739 if (CastElTyAlign < AllocElTyAlign) return 0;
7741 // If the allocation has multiple uses, only promote it if we are strictly
7742 // increasing the alignment of the resultant allocation. If we keep it the
7743 // same, we open the door to infinite loops of various kinds. (A reference
7744 // from a dbg.declare doesn't count as a use for this purpose.)
7745 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7746 CastElTyAlign == AllocElTyAlign) return 0;
7748 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7749 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7750 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7752 // See if we can satisfy the modulus by pulling a scale out of the array
7754 unsigned ArraySizeScale;
7756 Value *NumElements = // See if the array size is a decomposable linear expr.
7757 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7758 ArrayOffset, Context);
7760 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7762 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7763 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7765 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7770 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7771 // Insert before the alloca, not before the cast.
7772 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
7775 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7776 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7777 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
7780 AllocationInst *New;
7781 if (isa<MallocInst>(AI))
7782 New = AllocaBuilder.CreateMalloc(CastElTy, Amt);
7784 New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7785 New->setAlignment(AI.getAlignment());
7788 // If the allocation has one real use plus a dbg.declare, just remove the
7790 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7791 EraseInstFromFunction(*DI);
7793 // If the allocation has multiple real uses, insert a cast and change all
7794 // things that used it to use the new cast. This will also hack on CI, but it
7796 else if (!AI.hasOneUse()) {
7797 // New is the allocation instruction, pointer typed. AI is the original
7798 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7799 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
7800 AI.replaceAllUsesWith(NewCast);
7802 return ReplaceInstUsesWith(CI, New);
7805 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7806 /// and return it as type Ty without inserting any new casts and without
7807 /// changing the computed value. This is used by code that tries to decide
7808 /// whether promoting or shrinking integer operations to wider or smaller types
7809 /// will allow us to eliminate a truncate or extend.
7811 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7812 /// extension operation if Ty is larger.
7814 /// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7815 /// should return true if trunc(V) can be computed by computing V in the smaller
7816 /// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7817 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7818 /// efficiently truncated.
7820 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7821 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7822 /// the final result.
7823 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7825 int &NumCastsRemoved){
7826 // We can always evaluate constants in another type.
7827 if (isa<Constant>(V))
7830 Instruction *I = dyn_cast<Instruction>(V);
7831 if (!I) return false;
7833 const Type *OrigTy = V->getType();
7835 // If this is an extension or truncate, we can often eliminate it.
7836 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7837 // If this is a cast from the destination type, we can trivially eliminate
7838 // it, and this will remove a cast overall.
7839 if (I->getOperand(0)->getType() == Ty) {
7840 // If the first operand is itself a cast, and is eliminable, do not count
7841 // this as an eliminable cast. We would prefer to eliminate those two
7843 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7849 // We can't extend or shrink something that has multiple uses: doing so would
7850 // require duplicating the instruction in general, which isn't profitable.
7851 if (!I->hasOneUse()) return false;
7853 unsigned Opc = I->getOpcode();
7855 case Instruction::Add:
7856 case Instruction::Sub:
7857 case Instruction::Mul:
7858 case Instruction::And:
7859 case Instruction::Or:
7860 case Instruction::Xor:
7861 // These operators can all arbitrarily be extended or truncated.
7862 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7864 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7867 case Instruction::UDiv:
7868 case Instruction::URem: {
7869 // UDiv and URem can be truncated if all the truncated bits are zero.
7870 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7871 uint32_t BitWidth = Ty->getScalarSizeInBits();
7872 if (BitWidth < OrigBitWidth) {
7873 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7874 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7875 MaskedValueIsZero(I->getOperand(1), Mask)) {
7876 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7878 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7884 case Instruction::Shl:
7885 // If we are truncating the result of this SHL, and if it's a shift of a
7886 // constant amount, we can always perform a SHL in a smaller type.
7887 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7888 uint32_t BitWidth = Ty->getScalarSizeInBits();
7889 if (BitWidth < OrigTy->getScalarSizeInBits() &&
7890 CI->getLimitedValue(BitWidth) < BitWidth)
7891 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7895 case Instruction::LShr:
7896 // If this is a truncate of a logical shr, we can truncate it to a smaller
7897 // lshr iff we know that the bits we would otherwise be shifting in are
7899 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7900 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7901 uint32_t BitWidth = Ty->getScalarSizeInBits();
7902 if (BitWidth < OrigBitWidth &&
7903 MaskedValueIsZero(I->getOperand(0),
7904 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7905 CI->getLimitedValue(BitWidth) < BitWidth) {
7906 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7911 case Instruction::ZExt:
7912 case Instruction::SExt:
7913 case Instruction::Trunc:
7914 // If this is the same kind of case as our original (e.g. zext+zext), we
7915 // can safely replace it. Note that replacing it does not reduce the number
7916 // of casts in the input.
7920 // sext (zext ty1), ty2 -> zext ty2
7921 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7924 case Instruction::Select: {
7925 SelectInst *SI = cast<SelectInst>(I);
7926 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7928 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7931 case Instruction::PHI: {
7932 // We can change a phi if we can change all operands.
7933 PHINode *PN = cast<PHINode>(I);
7934 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7935 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7941 // TODO: Can handle more cases here.
7948 /// EvaluateInDifferentType - Given an expression that
7949 /// CanEvaluateInDifferentType returns true for, actually insert the code to
7950 /// evaluate the expression.
7951 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7953 if (Constant *C = dyn_cast<Constant>(V))
7954 return ConstantExpr::getIntegerCast(C, Ty,
7955 isSigned /*Sext or ZExt*/);
7957 // Otherwise, it must be an instruction.
7958 Instruction *I = cast<Instruction>(V);
7959 Instruction *Res = 0;
7960 unsigned Opc = I->getOpcode();
7962 case Instruction::Add:
7963 case Instruction::Sub:
7964 case Instruction::Mul:
7965 case Instruction::And:
7966 case Instruction::Or:
7967 case Instruction::Xor:
7968 case Instruction::AShr:
7969 case Instruction::LShr:
7970 case Instruction::Shl:
7971 case Instruction::UDiv:
7972 case Instruction::URem: {
7973 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7974 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7975 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
7978 case Instruction::Trunc:
7979 case Instruction::ZExt:
7980 case Instruction::SExt:
7981 // If the source type of the cast is the type we're trying for then we can
7982 // just return the source. There's no need to insert it because it is not
7984 if (I->getOperand(0)->getType() == Ty)
7985 return I->getOperand(0);
7987 // Otherwise, must be the same type of cast, so just reinsert a new one.
7988 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
7991 case Instruction::Select: {
7992 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7993 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7994 Res = SelectInst::Create(I->getOperand(0), True, False);
7997 case Instruction::PHI: {
7998 PHINode *OPN = cast<PHINode>(I);
7999 PHINode *NPN = PHINode::Create(Ty);
8000 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8001 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8002 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8008 // TODO: Can handle more cases here.
8009 llvm_unreachable("Unreachable!");
8014 return InsertNewInstBefore(Res, *I);
8017 /// @brief Implement the transforms common to all CastInst visitors.
8018 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8019 Value *Src = CI.getOperand(0);
8021 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8022 // eliminate it now.
8023 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8024 if (Instruction::CastOps opc =
8025 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8026 // The first cast (CSrc) is eliminable so we need to fix up or replace
8027 // the second cast (CI). CSrc will then have a good chance of being dead.
8028 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8032 // If we are casting a select then fold the cast into the select
8033 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8034 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8037 // If we are casting a PHI then fold the cast into the PHI
8038 if (isa<PHINode>(Src))
8039 if (Instruction *NV = FoldOpIntoPhi(CI))
8045 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8046 /// or not there is a sequence of GEP indices into the type that will land us at
8047 /// the specified offset. If so, fill them into NewIndices and return the
8048 /// resultant element type, otherwise return null.
8049 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8050 SmallVectorImpl<Value*> &NewIndices,
8051 const TargetData *TD,
8052 LLVMContext *Context) {
8054 if (!Ty->isSized()) return 0;
8056 // Start with the index over the outer type. Note that the type size
8057 // might be zero (even if the offset isn't zero) if the indexed type
8058 // is something like [0 x {int, int}]
8059 const Type *IntPtrTy = TD->getIntPtrType(*Context);
8060 int64_t FirstIdx = 0;
8061 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8062 FirstIdx = Offset/TySize;
8063 Offset -= FirstIdx*TySize;
8065 // Handle hosts where % returns negative instead of values [0..TySize).
8069 assert(Offset >= 0);
8071 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8074 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8076 // Index into the types. If we fail, set OrigBase to null.
8078 // Indexing into tail padding between struct/array elements.
8079 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8082 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8083 const StructLayout *SL = TD->getStructLayout(STy);
8084 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8085 "Offset must stay within the indexed type");
8087 unsigned Elt = SL->getElementContainingOffset(Offset);
8088 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8090 Offset -= SL->getElementOffset(Elt);
8091 Ty = STy->getElementType(Elt);
8092 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8093 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8094 assert(EltSize && "Cannot index into a zero-sized array");
8095 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8097 Ty = AT->getElementType();
8099 // Otherwise, we can't index into the middle of this atomic type, bail.
8107 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8108 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8109 Value *Src = CI.getOperand(0);
8111 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8112 // If casting the result of a getelementptr instruction with no offset, turn
8113 // this into a cast of the original pointer!
8114 if (GEP->hasAllZeroIndices()) {
8115 // Changing the cast operand is usually not a good idea but it is safe
8116 // here because the pointer operand is being replaced with another
8117 // pointer operand so the opcode doesn't need to change.
8119 CI.setOperand(0, GEP->getOperand(0));
8123 // If the GEP has a single use, and the base pointer is a bitcast, and the
8124 // GEP computes a constant offset, see if we can convert these three
8125 // instructions into fewer. This typically happens with unions and other
8126 // non-type-safe code.
8127 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8128 if (GEP->hasAllConstantIndices()) {
8129 // We are guaranteed to get a constant from EmitGEPOffset.
8130 ConstantInt *OffsetV =
8131 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8132 int64_t Offset = OffsetV->getSExtValue();
8134 // Get the base pointer input of the bitcast, and the type it points to.
8135 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8136 const Type *GEPIdxTy =
8137 cast<PointerType>(OrigBase->getType())->getElementType();
8138 SmallVector<Value*, 8> NewIndices;
8139 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8140 // If we were able to index down into an element, create the GEP
8141 // and bitcast the result. This eliminates one bitcast, potentially
8143 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8144 Builder->CreateInBoundsGEP(OrigBase,
8145 NewIndices.begin(), NewIndices.end()) :
8146 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
8147 NGEP->takeName(GEP);
8149 if (isa<BitCastInst>(CI))
8150 return new BitCastInst(NGEP, CI.getType());
8151 assert(isa<PtrToIntInst>(CI));
8152 return new PtrToIntInst(NGEP, CI.getType());
8158 return commonCastTransforms(CI);
8161 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8162 /// type like i42. We don't want to introduce operations on random non-legal
8163 /// integer types where they don't already exist in the code. In the future,
8164 /// we should consider making this based off target-data, so that 32-bit targets
8165 /// won't get i64 operations etc.
8166 static bool isSafeIntegerType(const Type *Ty) {
8167 switch (Ty->getPrimitiveSizeInBits()) {
8178 /// commonIntCastTransforms - This function implements the common transforms
8179 /// for trunc, zext, and sext.
8180 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8181 if (Instruction *Result = commonCastTransforms(CI))
8184 Value *Src = CI.getOperand(0);
8185 const Type *SrcTy = Src->getType();
8186 const Type *DestTy = CI.getType();
8187 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8188 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8190 // See if we can simplify any instructions used by the LHS whose sole
8191 // purpose is to compute bits we don't care about.
8192 if (SimplifyDemandedInstructionBits(CI))
8195 // If the source isn't an instruction or has more than one use then we
8196 // can't do anything more.
8197 Instruction *SrcI = dyn_cast<Instruction>(Src);
8198 if (!SrcI || !Src->hasOneUse())
8201 // Attempt to propagate the cast into the instruction for int->int casts.
8202 int NumCastsRemoved = 0;
8203 // Only do this if the dest type is a simple type, don't convert the
8204 // expression tree to something weird like i93 unless the source is also
8206 if ((isSafeIntegerType(DestTy->getScalarType()) ||
8207 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8208 CanEvaluateInDifferentType(SrcI, DestTy,
8209 CI.getOpcode(), NumCastsRemoved)) {
8210 // If this cast is a truncate, evaluting in a different type always
8211 // eliminates the cast, so it is always a win. If this is a zero-extension,
8212 // we need to do an AND to maintain the clear top-part of the computation,
8213 // so we require that the input have eliminated at least one cast. If this
8214 // is a sign extension, we insert two new casts (to do the extension) so we
8215 // require that two casts have been eliminated.
8216 bool DoXForm = false;
8217 bool JustReplace = false;
8218 switch (CI.getOpcode()) {
8220 // All the others use floating point so we shouldn't actually
8221 // get here because of the check above.
8222 llvm_unreachable("Unknown cast type");
8223 case Instruction::Trunc:
8226 case Instruction::ZExt: {
8227 DoXForm = NumCastsRemoved >= 1;
8228 if (!DoXForm && 0) {
8229 // If it's unnecessary to issue an AND to clear the high bits, it's
8230 // always profitable to do this xform.
8231 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8232 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8233 if (MaskedValueIsZero(TryRes, Mask))
8234 return ReplaceInstUsesWith(CI, TryRes);
8236 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8237 if (TryI->use_empty())
8238 EraseInstFromFunction(*TryI);
8242 case Instruction::SExt: {
8243 DoXForm = NumCastsRemoved >= 2;
8244 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8245 // If we do not have to emit the truncate + sext pair, then it's always
8246 // profitable to do this xform.
8248 // It's not safe to eliminate the trunc + sext pair if one of the
8249 // eliminated cast is a truncate. e.g.
8250 // t2 = trunc i32 t1 to i16
8251 // t3 = sext i16 t2 to i32
8254 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8255 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8256 if (NumSignBits > (DestBitSize - SrcBitSize))
8257 return ReplaceInstUsesWith(CI, TryRes);
8259 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8260 if (TryI->use_empty())
8261 EraseInstFromFunction(*TryI);
8268 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8269 " to avoid cast: " << CI);
8270 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8271 CI.getOpcode() == Instruction::SExt);
8273 // Just replace this cast with the result.
8274 return ReplaceInstUsesWith(CI, Res);
8276 assert(Res->getType() == DestTy);
8277 switch (CI.getOpcode()) {
8278 default: llvm_unreachable("Unknown cast type!");
8279 case Instruction::Trunc:
8280 // Just replace this cast with the result.
8281 return ReplaceInstUsesWith(CI, Res);
8282 case Instruction::ZExt: {
8283 assert(SrcBitSize < DestBitSize && "Not a zext?");
8285 // If the high bits are already zero, just replace this cast with the
8287 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8288 if (MaskedValueIsZero(Res, Mask))
8289 return ReplaceInstUsesWith(CI, Res);
8291 // We need to emit an AND to clear the high bits.
8292 Constant *C = ConstantInt::get(*Context,
8293 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8294 return BinaryOperator::CreateAnd(Res, C);
8296 case Instruction::SExt: {
8297 // If the high bits are already filled with sign bit, just replace this
8298 // cast with the result.
8299 unsigned NumSignBits = ComputeNumSignBits(Res);
8300 if (NumSignBits > (DestBitSize - SrcBitSize))
8301 return ReplaceInstUsesWith(CI, Res);
8303 // We need to emit a cast to truncate, then a cast to sext.
8304 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8310 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8311 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8313 switch (SrcI->getOpcode()) {
8314 case Instruction::Add:
8315 case Instruction::Mul:
8316 case Instruction::And:
8317 case Instruction::Or:
8318 case Instruction::Xor:
8319 // If we are discarding information, rewrite.
8320 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8321 // Don't insert two casts unless at least one can be eliminated.
8322 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8323 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8324 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8325 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8326 return BinaryOperator::Create(
8327 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8331 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8332 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8333 SrcI->getOpcode() == Instruction::Xor &&
8334 Op1 == ConstantInt::getTrue(*Context) &&
8335 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8336 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8337 return BinaryOperator::CreateXor(New,
8338 ConstantInt::get(CI.getType(), 1));
8342 case Instruction::Shl: {
8343 // Canonicalize trunc inside shl, if we can.
8344 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8345 if (CI && DestBitSize < SrcBitSize &&
8346 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8347 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8348 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8349 return BinaryOperator::CreateShl(Op0c, Op1c);
8357 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8358 if (Instruction *Result = commonIntCastTransforms(CI))
8361 Value *Src = CI.getOperand(0);
8362 const Type *Ty = CI.getType();
8363 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8364 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8366 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8367 if (DestBitWidth == 1) {
8368 Constant *One = ConstantInt::get(Src->getType(), 1);
8369 Src = Builder->CreateAnd(Src, One, "tmp");
8370 Value *Zero = Constant::getNullValue(Src->getType());
8371 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8374 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8375 ConstantInt *ShAmtV = 0;
8377 if (Src->hasOneUse() &&
8378 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8379 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8381 // Get a mask for the bits shifting in.
8382 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8383 if (MaskedValueIsZero(ShiftOp, Mask)) {
8384 if (ShAmt >= DestBitWidth) // All zeros.
8385 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8387 // Okay, we can shrink this. Truncate the input, then return a new
8389 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8390 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8391 return BinaryOperator::CreateLShr(V1, V2);
8398 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8399 /// in order to eliminate the icmp.
8400 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8402 // If we are just checking for a icmp eq of a single bit and zext'ing it
8403 // to an integer, then shift the bit to the appropriate place and then
8404 // cast to integer to avoid the comparison.
8405 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8406 const APInt &Op1CV = Op1C->getValue();
8408 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8409 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8410 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8411 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8412 if (!DoXform) return ICI;
8414 Value *In = ICI->getOperand(0);
8415 Value *Sh = ConstantInt::get(In->getType(),
8416 In->getType()->getScalarSizeInBits()-1);
8417 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8418 if (In->getType() != CI.getType())
8419 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8421 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8422 Constant *One = ConstantInt::get(In->getType(), 1);
8423 In = Builder->CreateXor(In, One, In->getName()+".not");
8426 return ReplaceInstUsesWith(CI, In);
8431 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8432 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8433 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8434 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8435 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8436 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8437 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8438 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8439 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8440 // This only works for EQ and NE
8441 ICI->isEquality()) {
8442 // If Op1C some other power of two, convert:
8443 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8444 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8445 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8446 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8448 APInt KnownZeroMask(~KnownZero);
8449 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8450 if (!DoXform) return ICI;
8452 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8453 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8454 // (X&4) == 2 --> false
8455 // (X&4) != 2 --> true
8456 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8457 Res = ConstantExpr::getZExt(Res, CI.getType());
8458 return ReplaceInstUsesWith(CI, Res);
8461 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8462 Value *In = ICI->getOperand(0);
8464 // Perform a logical shr by shiftamt.
8465 // Insert the shift to put the result in the low bit.
8466 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8467 In->getName()+".lobit");
8470 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8471 Constant *One = ConstantInt::get(In->getType(), 1);
8472 In = Builder->CreateXor(In, One, "tmp");
8475 if (CI.getType() == In->getType())
8476 return ReplaceInstUsesWith(CI, In);
8478 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8486 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8487 // If one of the common conversion will work ..
8488 if (Instruction *Result = commonIntCastTransforms(CI))
8491 Value *Src = CI.getOperand(0);
8493 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8494 // types and if the sizes are just right we can convert this into a logical
8495 // 'and' which will be much cheaper than the pair of casts.
8496 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8497 // Get the sizes of the types involved. We know that the intermediate type
8498 // will be smaller than A or C, but don't know the relation between A and C.
8499 Value *A = CSrc->getOperand(0);
8500 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8501 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8502 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8503 // If we're actually extending zero bits, then if
8504 // SrcSize < DstSize: zext(a & mask)
8505 // SrcSize == DstSize: a & mask
8506 // SrcSize > DstSize: trunc(a) & mask
8507 if (SrcSize < DstSize) {
8508 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8509 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8510 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
8511 return new ZExtInst(And, CI.getType());
8514 if (SrcSize == DstSize) {
8515 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8516 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8519 if (SrcSize > DstSize) {
8520 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
8521 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8522 return BinaryOperator::CreateAnd(Trunc,
8523 ConstantInt::get(Trunc->getType(),
8528 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8529 return transformZExtICmp(ICI, CI);
8531 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8532 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8533 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8534 // of the (zext icmp) will be transformed.
8535 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8536 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8537 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8538 (transformZExtICmp(LHS, CI, false) ||
8539 transformZExtICmp(RHS, CI, false))) {
8540 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8541 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
8542 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8546 // zext(trunc(t) & C) -> (t & zext(C)).
8547 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8548 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8549 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8550 Value *TI0 = TI->getOperand(0);
8551 if (TI0->getType() == CI.getType())
8553 BinaryOperator::CreateAnd(TI0,
8554 ConstantExpr::getZExt(C, CI.getType()));
8557 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8558 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8559 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8560 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8561 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8562 And->getOperand(1) == C)
8563 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8564 Value *TI0 = TI->getOperand(0);
8565 if (TI0->getType() == CI.getType()) {
8566 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8567 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
8568 return BinaryOperator::CreateXor(NewAnd, ZC);
8575 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8576 if (Instruction *I = commonIntCastTransforms(CI))
8579 Value *Src = CI.getOperand(0);
8581 // Canonicalize sign-extend from i1 to a select.
8582 if (Src->getType() == Type::getInt1Ty(*Context))
8583 return SelectInst::Create(Src,
8584 Constant::getAllOnesValue(CI.getType()),
8585 Constant::getNullValue(CI.getType()));
8587 // See if the value being truncated is already sign extended. If so, just
8588 // eliminate the trunc/sext pair.
8589 if (Operator::getOpcode(Src) == Instruction::Trunc) {
8590 Value *Op = cast<User>(Src)->getOperand(0);
8591 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8592 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8593 unsigned DestBits = CI.getType()->getScalarSizeInBits();
8594 unsigned NumSignBits = ComputeNumSignBits(Op);
8596 if (OpBits == DestBits) {
8597 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8598 // bits, it is already ready.
8599 if (NumSignBits > DestBits-MidBits)
8600 return ReplaceInstUsesWith(CI, Op);
8601 } else if (OpBits < DestBits) {
8602 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8603 // bits, just sext from i32.
8604 if (NumSignBits > OpBits-MidBits)
8605 return new SExtInst(Op, CI.getType(), "tmp");
8607 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8608 // bits, just truncate to i32.
8609 if (NumSignBits > OpBits-MidBits)
8610 return new TruncInst(Op, CI.getType(), "tmp");
8614 // If the input is a shl/ashr pair of a same constant, then this is a sign
8615 // extension from a smaller value. If we could trust arbitrary bitwidth
8616 // integers, we could turn this into a truncate to the smaller bit and then
8617 // use a sext for the whole extension. Since we don't, look deeper and check
8618 // for a truncate. If the source and dest are the same type, eliminate the
8619 // trunc and extend and just do shifts. For example, turn:
8620 // %a = trunc i32 %i to i8
8621 // %b = shl i8 %a, 6
8622 // %c = ashr i8 %b, 6
8623 // %d = sext i8 %c to i32
8625 // %a = shl i32 %i, 30
8626 // %d = ashr i32 %a, 30
8628 ConstantInt *BA = 0, *CA = 0;
8629 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8630 m_ConstantInt(CA))) &&
8631 BA == CA && isa<TruncInst>(A)) {
8632 Value *I = cast<TruncInst>(A)->getOperand(0);
8633 if (I->getType() == CI.getType()) {
8634 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8635 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8636 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8637 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8638 I = Builder->CreateShl(I, ShAmtV, CI.getName());
8639 return BinaryOperator::CreateAShr(I, ShAmtV);
8646 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8647 /// in the specified FP type without changing its value.
8648 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8649 LLVMContext *Context) {
8651 APFloat F = CFP->getValueAPF();
8652 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8654 return ConstantFP::get(*Context, F);
8658 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8659 /// through it until we get the source value.
8660 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8661 if (Instruction *I = dyn_cast<Instruction>(V))
8662 if (I->getOpcode() == Instruction::FPExt)
8663 return LookThroughFPExtensions(I->getOperand(0), Context);
8665 // If this value is a constant, return the constant in the smallest FP type
8666 // that can accurately represent it. This allows us to turn
8667 // (float)((double)X+2.0) into x+2.0f.
8668 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8669 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8670 return V; // No constant folding of this.
8671 // See if the value can be truncated to float and then reextended.
8672 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8674 if (CFP->getType() == Type::getDoubleTy(*Context))
8675 return V; // Won't shrink.
8676 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8678 // Don't try to shrink to various long double types.
8684 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8685 if (Instruction *I = commonCastTransforms(CI))
8688 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8689 // smaller than the destination type, we can eliminate the truncate by doing
8690 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
8691 // many builtins (sqrt, etc).
8692 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8693 if (OpI && OpI->hasOneUse()) {
8694 switch (OpI->getOpcode()) {
8696 case Instruction::FAdd:
8697 case Instruction::FSub:
8698 case Instruction::FMul:
8699 case Instruction::FDiv:
8700 case Instruction::FRem:
8701 const Type *SrcTy = OpI->getType();
8702 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8703 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8704 if (LHSTrunc->getType() != SrcTy &&
8705 RHSTrunc->getType() != SrcTy) {
8706 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8707 // If the source types were both smaller than the destination type of
8708 // the cast, do this xform.
8709 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8710 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8711 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8712 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
8713 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8722 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8723 return commonCastTransforms(CI);
8726 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8727 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8729 return commonCastTransforms(FI);
8731 // fptoui(uitofp(X)) --> X
8732 // fptoui(sitofp(X)) --> X
8733 // This is safe if the intermediate type has enough bits in its mantissa to
8734 // accurately represent all values of X. For example, do not do this with
8735 // i64->float->i64. This is also safe for sitofp case, because any negative
8736 // 'X' value would cause an undefined result for the fptoui.
8737 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8738 OpI->getOperand(0)->getType() == FI.getType() &&
8739 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8740 OpI->getType()->getFPMantissaWidth())
8741 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8743 return commonCastTransforms(FI);
8746 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8747 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8749 return commonCastTransforms(FI);
8751 // fptosi(sitofp(X)) --> X
8752 // fptosi(uitofp(X)) --> X
8753 // This is safe if the intermediate type has enough bits in its mantissa to
8754 // accurately represent all values of X. For example, do not do this with
8755 // i64->float->i64. This is also safe for sitofp case, because any negative
8756 // 'X' value would cause an undefined result for the fptoui.
8757 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8758 OpI->getOperand(0)->getType() == FI.getType() &&
8759 (int)FI.getType()->getScalarSizeInBits() <=
8760 OpI->getType()->getFPMantissaWidth())
8761 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8763 return commonCastTransforms(FI);
8766 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8767 return commonCastTransforms(CI);
8770 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8771 return commonCastTransforms(CI);
8774 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8775 // If the destination integer type is smaller than the intptr_t type for
8776 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8777 // trunc to be exposed to other transforms. Don't do this for extending
8778 // ptrtoint's, because we don't know if the target sign or zero extends its
8781 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8782 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8783 TD->getIntPtrType(CI.getContext()),
8785 return new TruncInst(P, CI.getType());
8788 return commonPointerCastTransforms(CI);
8791 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8792 // If the source integer type is larger than the intptr_t type for
8793 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8794 // allows the trunc to be exposed to other transforms. Don't do this for
8795 // extending inttoptr's, because we don't know if the target sign or zero
8796 // extends to pointers.
8797 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
8798 TD->getPointerSizeInBits()) {
8799 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8800 TD->getIntPtrType(CI.getContext()), "tmp");
8801 return new IntToPtrInst(P, CI.getType());
8804 if (Instruction *I = commonCastTransforms(CI))
8810 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8811 // If the operands are integer typed then apply the integer transforms,
8812 // otherwise just apply the common ones.
8813 Value *Src = CI.getOperand(0);
8814 const Type *SrcTy = Src->getType();
8815 const Type *DestTy = CI.getType();
8817 if (isa<PointerType>(SrcTy)) {
8818 if (Instruction *I = commonPointerCastTransforms(CI))
8821 if (Instruction *Result = commonCastTransforms(CI))
8826 // Get rid of casts from one type to the same type. These are useless and can
8827 // be replaced by the operand.
8828 if (DestTy == Src->getType())
8829 return ReplaceInstUsesWith(CI, Src);
8831 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8832 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8833 const Type *DstElTy = DstPTy->getElementType();
8834 const Type *SrcElTy = SrcPTy->getElementType();
8836 // If the address spaces don't match, don't eliminate the bitcast, which is
8837 // required for changing types.
8838 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8841 // If we are casting a alloca to a pointer to a type of the same
8842 // size, rewrite the allocation instruction to allocate the "right" type.
8843 // There is no need to modify malloc calls because it is their bitcast that
8844 // needs to be cleaned up.
8845 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8846 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8849 // If the source and destination are pointers, and this cast is equivalent
8850 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8851 // This can enhance SROA and other transforms that want type-safe pointers.
8852 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8853 unsigned NumZeros = 0;
8854 while (SrcElTy != DstElTy &&
8855 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8856 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8857 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8861 // If we found a path from the src to dest, create the getelementptr now.
8862 if (SrcElTy == DstElTy) {
8863 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8864 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8865 ((Instruction*) NULL));
8869 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8870 if (DestVTy->getNumElements() == 1) {
8871 if (!isa<VectorType>(SrcTy)) {
8872 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
8873 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
8874 Constant::getNullValue(Type::getInt32Ty(*Context)));
8876 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8880 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8881 if (SrcVTy->getNumElements() == 1) {
8882 if (!isa<VectorType>(DestTy)) {
8884 Builder->CreateExtractElement(Src,
8885 Constant::getNullValue(Type::getInt32Ty(*Context)));
8886 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8891 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8892 if (SVI->hasOneUse()) {
8893 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8894 // a bitconvert to a vector with the same # elts.
8895 if (isa<VectorType>(DestTy) &&
8896 cast<VectorType>(DestTy)->getNumElements() ==
8897 SVI->getType()->getNumElements() &&
8898 SVI->getType()->getNumElements() ==
8899 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8901 // If either of the operands is a cast from CI.getType(), then
8902 // evaluating the shuffle in the casted destination's type will allow
8903 // us to eliminate at least one cast.
8904 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8905 Tmp->getOperand(0)->getType() == DestTy) ||
8906 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8907 Tmp->getOperand(0)->getType() == DestTy)) {
8908 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8909 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
8910 // Return a new shuffle vector. Use the same element ID's, as we
8911 // know the vector types match #elts.
8912 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8920 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8922 /// %D = select %cond, %C, %A
8924 /// %C = select %cond, %B, 0
8927 /// Assuming that the specified instruction is an operand to the select, return
8928 /// a bitmask indicating which operands of this instruction are foldable if they
8929 /// equal the other incoming value of the select.
8931 static unsigned GetSelectFoldableOperands(Instruction *I) {
8932 switch (I->getOpcode()) {
8933 case Instruction::Add:
8934 case Instruction::Mul:
8935 case Instruction::And:
8936 case Instruction::Or:
8937 case Instruction::Xor:
8938 return 3; // Can fold through either operand.
8939 case Instruction::Sub: // Can only fold on the amount subtracted.
8940 case Instruction::Shl: // Can only fold on the shift amount.
8941 case Instruction::LShr:
8942 case Instruction::AShr:
8945 return 0; // Cannot fold
8949 /// GetSelectFoldableConstant - For the same transformation as the previous
8950 /// function, return the identity constant that goes into the select.
8951 static Constant *GetSelectFoldableConstant(Instruction *I,
8952 LLVMContext *Context) {
8953 switch (I->getOpcode()) {
8954 default: llvm_unreachable("This cannot happen!");
8955 case Instruction::Add:
8956 case Instruction::Sub:
8957 case Instruction::Or:
8958 case Instruction::Xor:
8959 case Instruction::Shl:
8960 case Instruction::LShr:
8961 case Instruction::AShr:
8962 return Constant::getNullValue(I->getType());
8963 case Instruction::And:
8964 return Constant::getAllOnesValue(I->getType());
8965 case Instruction::Mul:
8966 return ConstantInt::get(I->getType(), 1);
8970 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8971 /// have the same opcode and only one use each. Try to simplify this.
8972 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8974 if (TI->getNumOperands() == 1) {
8975 // If this is a non-volatile load or a cast from the same type,
8978 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8981 return 0; // unknown unary op.
8984 // Fold this by inserting a select from the input values.
8985 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8986 FI->getOperand(0), SI.getName()+".v");
8987 InsertNewInstBefore(NewSI, SI);
8988 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
8992 // Only handle binary operators here.
8993 if (!isa<BinaryOperator>(TI))
8996 // Figure out if the operations have any operands in common.
8997 Value *MatchOp, *OtherOpT, *OtherOpF;
8999 if (TI->getOperand(0) == FI->getOperand(0)) {
9000 MatchOp = TI->getOperand(0);
9001 OtherOpT = TI->getOperand(1);
9002 OtherOpF = FI->getOperand(1);
9003 MatchIsOpZero = true;
9004 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9005 MatchOp = TI->getOperand(1);
9006 OtherOpT = TI->getOperand(0);
9007 OtherOpF = FI->getOperand(0);
9008 MatchIsOpZero = false;
9009 } else if (!TI->isCommutative()) {
9011 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9012 MatchOp = TI->getOperand(0);
9013 OtherOpT = TI->getOperand(1);
9014 OtherOpF = FI->getOperand(0);
9015 MatchIsOpZero = true;
9016 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9017 MatchOp = TI->getOperand(1);
9018 OtherOpT = TI->getOperand(0);
9019 OtherOpF = FI->getOperand(1);
9020 MatchIsOpZero = true;
9025 // If we reach here, they do have operations in common.
9026 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9027 OtherOpF, SI.getName()+".v");
9028 InsertNewInstBefore(NewSI, SI);
9030 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9032 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9034 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9036 llvm_unreachable("Shouldn't get here");
9040 static bool isSelect01(Constant *C1, Constant *C2) {
9041 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9044 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9047 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9050 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9051 /// facilitate further optimization.
9052 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9054 // See the comment above GetSelectFoldableOperands for a description of the
9055 // transformation we are doing here.
9056 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9057 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9058 !isa<Constant>(FalseVal)) {
9059 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9060 unsigned OpToFold = 0;
9061 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9063 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9068 Constant *C = GetSelectFoldableConstant(TVI, Context);
9069 Value *OOp = TVI->getOperand(2-OpToFold);
9070 // Avoid creating select between 2 constants unless it's selecting
9072 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9073 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9074 InsertNewInstBefore(NewSel, SI);
9075 NewSel->takeName(TVI);
9076 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9077 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9078 llvm_unreachable("Unknown instruction!!");
9085 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9086 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9087 !isa<Constant>(TrueVal)) {
9088 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9089 unsigned OpToFold = 0;
9090 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9092 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9097 Constant *C = GetSelectFoldableConstant(FVI, Context);
9098 Value *OOp = FVI->getOperand(2-OpToFold);
9099 // Avoid creating select between 2 constants unless it's selecting
9101 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9102 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9103 InsertNewInstBefore(NewSel, SI);
9104 NewSel->takeName(FVI);
9105 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9106 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9107 llvm_unreachable("Unknown instruction!!");
9117 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9118 /// ICmpInst as its first operand.
9120 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9122 bool Changed = false;
9123 ICmpInst::Predicate Pred = ICI->getPredicate();
9124 Value *CmpLHS = ICI->getOperand(0);
9125 Value *CmpRHS = ICI->getOperand(1);
9126 Value *TrueVal = SI.getTrueValue();
9127 Value *FalseVal = SI.getFalseValue();
9129 // Check cases where the comparison is with a constant that
9130 // can be adjusted to fit the min/max idiom. We may edit ICI in
9131 // place here, so make sure the select is the only user.
9132 if (ICI->hasOneUse())
9133 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9136 case ICmpInst::ICMP_ULT:
9137 case ICmpInst::ICMP_SLT: {
9138 // X < MIN ? T : F --> F
9139 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9140 return ReplaceInstUsesWith(SI, FalseVal);
9141 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
9142 Constant *AdjustedRHS = SubOne(CI);
9143 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9144 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9145 Pred = ICmpInst::getSwappedPredicate(Pred);
9146 CmpRHS = AdjustedRHS;
9147 std::swap(FalseVal, TrueVal);
9148 ICI->setPredicate(Pred);
9149 ICI->setOperand(1, CmpRHS);
9150 SI.setOperand(1, TrueVal);
9151 SI.setOperand(2, FalseVal);
9156 case ICmpInst::ICMP_UGT:
9157 case ICmpInst::ICMP_SGT: {
9158 // X > MAX ? T : F --> F
9159 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9160 return ReplaceInstUsesWith(SI, FalseVal);
9161 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
9162 Constant *AdjustedRHS = AddOne(CI);
9163 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9164 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9165 Pred = ICmpInst::getSwappedPredicate(Pred);
9166 CmpRHS = AdjustedRHS;
9167 std::swap(FalseVal, TrueVal);
9168 ICI->setPredicate(Pred);
9169 ICI->setOperand(1, CmpRHS);
9170 SI.setOperand(1, TrueVal);
9171 SI.setOperand(2, FalseVal);
9178 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9179 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
9180 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9181 if (match(TrueVal, m_ConstantInt<-1>()) &&
9182 match(FalseVal, m_ConstantInt<0>()))
9183 Pred = ICI->getPredicate();
9184 else if (match(TrueVal, m_ConstantInt<0>()) &&
9185 match(FalseVal, m_ConstantInt<-1>()))
9186 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9188 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9189 // If we are just checking for a icmp eq of a single bit and zext'ing it
9190 // to an integer, then shift the bit to the appropriate place and then
9191 // cast to integer to avoid the comparison.
9192 const APInt &Op1CV = CI->getValue();
9194 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9195 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9196 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9197 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9198 Value *In = ICI->getOperand(0);
9199 Value *Sh = ConstantInt::get(In->getType(),
9200 In->getType()->getScalarSizeInBits()-1);
9201 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9202 In->getName()+".lobit"),
9204 if (In->getType() != SI.getType())
9205 In = CastInst::CreateIntegerCast(In, SI.getType(),
9206 true/*SExt*/, "tmp", ICI);
9208 if (Pred == ICmpInst::ICMP_SGT)
9209 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9210 In->getName()+".not"), *ICI);
9212 return ReplaceInstUsesWith(SI, In);
9217 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9218 // Transform (X == Y) ? X : Y -> Y
9219 if (Pred == ICmpInst::ICMP_EQ)
9220 return ReplaceInstUsesWith(SI, FalseVal);
9221 // Transform (X != Y) ? X : Y -> X
9222 if (Pred == ICmpInst::ICMP_NE)
9223 return ReplaceInstUsesWith(SI, TrueVal);
9224 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9226 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9227 // Transform (X == Y) ? Y : X -> X
9228 if (Pred == ICmpInst::ICMP_EQ)
9229 return ReplaceInstUsesWith(SI, FalseVal);
9230 // Transform (X != Y) ? Y : X -> Y
9231 if (Pred == ICmpInst::ICMP_NE)
9232 return ReplaceInstUsesWith(SI, TrueVal);
9233 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9236 /// NOTE: if we wanted to, this is where to detect integer ABS
9238 return Changed ? &SI : 0;
9241 /// isDefinedInBB - Return true if the value is an instruction defined in the
9242 /// specified basicblock.
9243 static bool isDefinedInBB(const Value *V, const BasicBlock *BB) {
9244 const Instruction *I = dyn_cast<Instruction>(V);
9245 return I != 0 && I->getParent() == BB;
9249 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9250 Value *CondVal = SI.getCondition();
9251 Value *TrueVal = SI.getTrueValue();
9252 Value *FalseVal = SI.getFalseValue();
9254 // select true, X, Y -> X
9255 // select false, X, Y -> Y
9256 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9257 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9259 // select C, X, X -> X
9260 if (TrueVal == FalseVal)
9261 return ReplaceInstUsesWith(SI, TrueVal);
9263 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9264 return ReplaceInstUsesWith(SI, FalseVal);
9265 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9266 return ReplaceInstUsesWith(SI, TrueVal);
9267 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9268 if (isa<Constant>(TrueVal))
9269 return ReplaceInstUsesWith(SI, TrueVal);
9271 return ReplaceInstUsesWith(SI, FalseVal);
9274 if (SI.getType() == Type::getInt1Ty(*Context)) {
9275 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9276 if (C->getZExtValue()) {
9277 // Change: A = select B, true, C --> A = or B, C
9278 return BinaryOperator::CreateOr(CondVal, FalseVal);
9280 // Change: A = select B, false, C --> A = and !B, C
9282 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9283 "not."+CondVal->getName()), SI);
9284 return BinaryOperator::CreateAnd(NotCond, FalseVal);
9286 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9287 if (C->getZExtValue() == false) {
9288 // Change: A = select B, C, false --> A = and B, C
9289 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9291 // Change: A = select B, C, true --> A = or !B, C
9293 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9294 "not."+CondVal->getName()), SI);
9295 return BinaryOperator::CreateOr(NotCond, TrueVal);
9299 // select a, b, a -> a&b
9300 // select a, a, b -> a|b
9301 if (CondVal == TrueVal)
9302 return BinaryOperator::CreateOr(CondVal, FalseVal);
9303 else if (CondVal == FalseVal)
9304 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9307 // Selecting between two integer constants?
9308 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9309 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9310 // select C, 1, 0 -> zext C to int
9311 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9312 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9313 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9314 // select C, 0, 1 -> zext !C to int
9316 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9317 "not."+CondVal->getName()), SI);
9318 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9321 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9322 // If one of the constants is zero (we know they can't both be) and we
9323 // have an icmp instruction with zero, and we have an 'and' with the
9324 // non-constant value, eliminate this whole mess. This corresponds to
9325 // cases like this: ((X & 27) ? 27 : 0)
9326 if (TrueValC->isZero() || FalseValC->isZero())
9327 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9328 cast<Constant>(IC->getOperand(1))->isNullValue())
9329 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9330 if (ICA->getOpcode() == Instruction::And &&
9331 isa<ConstantInt>(ICA->getOperand(1)) &&
9332 (ICA->getOperand(1) == TrueValC ||
9333 ICA->getOperand(1) == FalseValC) &&
9334 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9335 // Okay, now we know that everything is set up, we just don't
9336 // know whether we have a icmp_ne or icmp_eq and whether the
9337 // true or false val is the zero.
9338 bool ShouldNotVal = !TrueValC->isZero();
9339 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9342 V = InsertNewInstBefore(BinaryOperator::Create(
9343 Instruction::Xor, V, ICA->getOperand(1)), SI);
9344 return ReplaceInstUsesWith(SI, V);
9349 // See if we are selecting two values based on a comparison of the two values.
9350 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9351 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9352 // Transform (X == Y) ? X : Y -> Y
9353 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9354 // This is not safe in general for floating point:
9355 // consider X== -0, Y== +0.
9356 // It becomes safe if either operand is a nonzero constant.
9357 ConstantFP *CFPt, *CFPf;
9358 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9359 !CFPt->getValueAPF().isZero()) ||
9360 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9361 !CFPf->getValueAPF().isZero()))
9362 return ReplaceInstUsesWith(SI, FalseVal);
9364 // Transform (X != Y) ? X : Y -> X
9365 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9366 return ReplaceInstUsesWith(SI, TrueVal);
9367 // NOTE: if we wanted to, this is where to detect MIN/MAX
9369 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9370 // Transform (X == Y) ? Y : X -> X
9371 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9372 // This is not safe in general for floating point:
9373 // consider X== -0, Y== +0.
9374 // It becomes safe if either operand is a nonzero constant.
9375 ConstantFP *CFPt, *CFPf;
9376 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9377 !CFPt->getValueAPF().isZero()) ||
9378 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9379 !CFPf->getValueAPF().isZero()))
9380 return ReplaceInstUsesWith(SI, FalseVal);
9382 // Transform (X != Y) ? Y : X -> Y
9383 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9384 return ReplaceInstUsesWith(SI, TrueVal);
9385 // NOTE: if we wanted to, this is where to detect MIN/MAX
9387 // NOTE: if we wanted to, this is where to detect ABS
9390 // See if we are selecting two values based on a comparison of the two values.
9391 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9392 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9395 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9396 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9397 if (TI->hasOneUse() && FI->hasOneUse()) {
9398 Instruction *AddOp = 0, *SubOp = 0;
9400 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9401 if (TI->getOpcode() == FI->getOpcode())
9402 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9405 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9406 // even legal for FP.
9407 if ((TI->getOpcode() == Instruction::Sub &&
9408 FI->getOpcode() == Instruction::Add) ||
9409 (TI->getOpcode() == Instruction::FSub &&
9410 FI->getOpcode() == Instruction::FAdd)) {
9411 AddOp = FI; SubOp = TI;
9412 } else if ((FI->getOpcode() == Instruction::Sub &&
9413 TI->getOpcode() == Instruction::Add) ||
9414 (FI->getOpcode() == Instruction::FSub &&
9415 TI->getOpcode() == Instruction::FAdd)) {
9416 AddOp = TI; SubOp = FI;
9420 Value *OtherAddOp = 0;
9421 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9422 OtherAddOp = AddOp->getOperand(1);
9423 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9424 OtherAddOp = AddOp->getOperand(0);
9428 // So at this point we know we have (Y -> OtherAddOp):
9429 // select C, (add X, Y), (sub X, Z)
9430 Value *NegVal; // Compute -Z
9431 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9432 NegVal = ConstantExpr::getNeg(C);
9434 NegVal = InsertNewInstBefore(
9435 BinaryOperator::CreateNeg(SubOp->getOperand(1),
9439 Value *NewTrueOp = OtherAddOp;
9440 Value *NewFalseOp = NegVal;
9442 std::swap(NewTrueOp, NewFalseOp);
9443 Instruction *NewSel =
9444 SelectInst::Create(CondVal, NewTrueOp,
9445 NewFalseOp, SI.getName() + ".p");
9447 NewSel = InsertNewInstBefore(NewSel, SI);
9448 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9453 // See if we can fold the select into one of our operands.
9454 if (SI.getType()->isInteger()) {
9455 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9460 // See if we can fold the select into a phi node. The true/false values have
9461 // to be live in the predecessor blocks. If they are instructions in SI's
9462 // block, we can't map to the predecessor.
9463 if (isa<PHINode>(SI.getCondition()) &&
9464 (!isDefinedInBB(SI.getTrueValue(), SI.getParent()) ||
9465 isa<PHINode>(SI.getTrueValue())) &&
9466 (!isDefinedInBB(SI.getFalseValue(), SI.getParent()) ||
9467 isa<PHINode>(SI.getFalseValue())))
9468 if (Instruction *NV = FoldOpIntoPhi(SI))
9471 if (BinaryOperator::isNot(CondVal)) {
9472 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9473 SI.setOperand(1, FalseVal);
9474 SI.setOperand(2, TrueVal);
9481 /// EnforceKnownAlignment - If the specified pointer points to an object that
9482 /// we control, modify the object's alignment to PrefAlign. This isn't
9483 /// often possible though. If alignment is important, a more reliable approach
9484 /// is to simply align all global variables and allocation instructions to
9485 /// their preferred alignment from the beginning.
9487 static unsigned EnforceKnownAlignment(Value *V,
9488 unsigned Align, unsigned PrefAlign) {
9490 User *U = dyn_cast<User>(V);
9491 if (!U) return Align;
9493 switch (Operator::getOpcode(U)) {
9495 case Instruction::BitCast:
9496 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9497 case Instruction::GetElementPtr: {
9498 // If all indexes are zero, it is just the alignment of the base pointer.
9499 bool AllZeroOperands = true;
9500 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9501 if (!isa<Constant>(*i) ||
9502 !cast<Constant>(*i)->isNullValue()) {
9503 AllZeroOperands = false;
9507 if (AllZeroOperands) {
9508 // Treat this like a bitcast.
9509 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9515 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9516 // If there is a large requested alignment and we can, bump up the alignment
9518 if (!GV->isDeclaration()) {
9519 if (GV->getAlignment() >= PrefAlign)
9520 Align = GV->getAlignment();
9522 GV->setAlignment(PrefAlign);
9526 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9527 // If there is a requested alignment and if this is an alloca, round up.
9528 if (AI->getAlignment() >= PrefAlign)
9529 Align = AI->getAlignment();
9531 AI->setAlignment(PrefAlign);
9539 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9540 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9541 /// and it is more than the alignment of the ultimate object, see if we can
9542 /// increase the alignment of the ultimate object, making this check succeed.
9543 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9544 unsigned PrefAlign) {
9545 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9546 sizeof(PrefAlign) * CHAR_BIT;
9547 APInt Mask = APInt::getAllOnesValue(BitWidth);
9548 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9549 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9550 unsigned TrailZ = KnownZero.countTrailingOnes();
9551 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9553 if (PrefAlign > Align)
9554 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9556 // We don't need to make any adjustment.
9560 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9561 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9562 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9563 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9564 unsigned CopyAlign = MI->getAlignment();
9566 if (CopyAlign < MinAlign) {
9567 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9572 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9574 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9575 if (MemOpLength == 0) return 0;
9577 // Source and destination pointer types are always "i8*" for intrinsic. See
9578 // if the size is something we can handle with a single primitive load/store.
9579 // A single load+store correctly handles overlapping memory in the memmove
9581 unsigned Size = MemOpLength->getZExtValue();
9582 if (Size == 0) return MI; // Delete this mem transfer.
9584 if (Size > 8 || (Size&(Size-1)))
9585 return 0; // If not 1/2/4/8 bytes, exit.
9587 // Use an integer load+store unless we can find something better.
9589 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9591 // Memcpy forces the use of i8* for the source and destination. That means
9592 // that if you're using memcpy to move one double around, you'll get a cast
9593 // from double* to i8*. We'd much rather use a double load+store rather than
9594 // an i64 load+store, here because this improves the odds that the source or
9595 // dest address will be promotable. See if we can find a better type than the
9596 // integer datatype.
9597 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9598 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9599 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9600 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9601 // down through these levels if so.
9602 while (!SrcETy->isSingleValueType()) {
9603 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9604 if (STy->getNumElements() == 1)
9605 SrcETy = STy->getElementType(0);
9608 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9609 if (ATy->getNumElements() == 1)
9610 SrcETy = ATy->getElementType();
9617 if (SrcETy->isSingleValueType())
9618 NewPtrTy = PointerType::getUnqual(SrcETy);
9623 // If the memcpy/memmove provides better alignment info than we can
9625 SrcAlign = std::max(SrcAlign, CopyAlign);
9626 DstAlign = std::max(DstAlign, CopyAlign);
9628 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9629 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
9630 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9631 InsertNewInstBefore(L, *MI);
9632 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9634 // Set the size of the copy to 0, it will be deleted on the next iteration.
9635 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9639 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9640 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9641 if (MI->getAlignment() < Alignment) {
9642 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9647 // Extract the length and alignment and fill if they are constant.
9648 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9649 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9650 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9652 uint64_t Len = LenC->getZExtValue();
9653 Alignment = MI->getAlignment();
9655 // If the length is zero, this is a no-op
9656 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9658 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9659 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9660 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
9662 Value *Dest = MI->getDest();
9663 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
9665 // Alignment 0 is identity for alignment 1 for memset, but not store.
9666 if (Alignment == 0) Alignment = 1;
9668 // Extract the fill value and store.
9669 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9670 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9671 Dest, false, Alignment), *MI);
9673 // Set the size of the copy to 0, it will be deleted on the next iteration.
9674 MI->setLength(Constant::getNullValue(LenC->getType()));
9682 /// visitCallInst - CallInst simplification. This mostly only handles folding
9683 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9684 /// the heavy lifting.
9686 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9687 // If the caller function is nounwind, mark the call as nounwind, even if the
9689 if (CI.getParent()->getParent()->doesNotThrow() &&
9690 !CI.doesNotThrow()) {
9691 CI.setDoesNotThrow();
9695 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9696 if (!II) return visitCallSite(&CI);
9698 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9700 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9701 bool Changed = false;
9703 // memmove/cpy/set of zero bytes is a noop.
9704 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9705 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9707 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9708 if (CI->getZExtValue() == 1) {
9709 // Replace the instruction with just byte operations. We would
9710 // transform other cases to loads/stores, but we don't know if
9711 // alignment is sufficient.
9715 // If we have a memmove and the source operation is a constant global,
9716 // then the source and dest pointers can't alias, so we can change this
9717 // into a call to memcpy.
9718 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9719 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9720 if (GVSrc->isConstant()) {
9721 Module *M = CI.getParent()->getParent()->getParent();
9722 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9724 Tys[0] = CI.getOperand(3)->getType();
9726 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9730 // memmove(x,x,size) -> noop.
9731 if (MMI->getSource() == MMI->getDest())
9732 return EraseInstFromFunction(CI);
9735 // If we can determine a pointer alignment that is bigger than currently
9736 // set, update the alignment.
9737 if (isa<MemTransferInst>(MI)) {
9738 if (Instruction *I = SimplifyMemTransfer(MI))
9740 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9741 if (Instruction *I = SimplifyMemSet(MSI))
9745 if (Changed) return II;
9748 switch (II->getIntrinsicID()) {
9750 case Intrinsic::bswap:
9751 // bswap(bswap(x)) -> x
9752 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9753 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9754 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9756 case Intrinsic::ppc_altivec_lvx:
9757 case Intrinsic::ppc_altivec_lvxl:
9758 case Intrinsic::x86_sse_loadu_ps:
9759 case Intrinsic::x86_sse2_loadu_pd:
9760 case Intrinsic::x86_sse2_loadu_dq:
9761 // Turn PPC lvx -> load if the pointer is known aligned.
9762 // Turn X86 loadups -> load if the pointer is known aligned.
9763 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9764 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9765 PointerType::getUnqual(II->getType()));
9766 return new LoadInst(Ptr);
9769 case Intrinsic::ppc_altivec_stvx:
9770 case Intrinsic::ppc_altivec_stvxl:
9771 // Turn stvx -> store if the pointer is known aligned.
9772 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9773 const Type *OpPtrTy =
9774 PointerType::getUnqual(II->getOperand(1)->getType());
9775 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
9776 return new StoreInst(II->getOperand(1), Ptr);
9779 case Intrinsic::x86_sse_storeu_ps:
9780 case Intrinsic::x86_sse2_storeu_pd:
9781 case Intrinsic::x86_sse2_storeu_dq:
9782 // Turn X86 storeu -> store if the pointer is known aligned.
9783 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9784 const Type *OpPtrTy =
9785 PointerType::getUnqual(II->getOperand(2)->getType());
9786 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
9787 return new StoreInst(II->getOperand(2), Ptr);
9791 case Intrinsic::x86_sse_cvttss2si: {
9792 // These intrinsics only demands the 0th element of its input vector. If
9793 // we can simplify the input based on that, do so now.
9795 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9796 APInt DemandedElts(VWidth, 1);
9797 APInt UndefElts(VWidth, 0);
9798 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9800 II->setOperand(1, V);
9806 case Intrinsic::ppc_altivec_vperm:
9807 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9808 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9809 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9811 // Check that all of the elements are integer constants or undefs.
9812 bool AllEltsOk = true;
9813 for (unsigned i = 0; i != 16; ++i) {
9814 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9815 !isa<UndefValue>(Mask->getOperand(i))) {
9822 // Cast the input vectors to byte vectors.
9823 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9824 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
9825 Value *Result = UndefValue::get(Op0->getType());
9827 // Only extract each element once.
9828 Value *ExtractedElts[32];
9829 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9831 for (unsigned i = 0; i != 16; ++i) {
9832 if (isa<UndefValue>(Mask->getOperand(i)))
9834 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9835 Idx &= 31; // Match the hardware behavior.
9837 if (ExtractedElts[Idx] == 0) {
9838 ExtractedElts[Idx] =
9839 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9840 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9844 // Insert this value into the result vector.
9845 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9846 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9849 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9854 case Intrinsic::stackrestore: {
9855 // If the save is right next to the restore, remove the restore. This can
9856 // happen when variable allocas are DCE'd.
9857 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9858 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9859 BasicBlock::iterator BI = SS;
9861 return EraseInstFromFunction(CI);
9865 // Scan down this block to see if there is another stack restore in the
9866 // same block without an intervening call/alloca.
9867 BasicBlock::iterator BI = II;
9868 TerminatorInst *TI = II->getParent()->getTerminator();
9869 bool CannotRemove = false;
9870 for (++BI; &*BI != TI; ++BI) {
9871 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
9872 CannotRemove = true;
9875 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9876 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9877 // If there is a stackrestore below this one, remove this one.
9878 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9879 return EraseInstFromFunction(CI);
9880 // Otherwise, ignore the intrinsic.
9882 // If we found a non-intrinsic call, we can't remove the stack
9884 CannotRemove = true;
9890 // If the stack restore is in a return/unwind block and if there are no
9891 // allocas or calls between the restore and the return, nuke the restore.
9892 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9893 return EraseInstFromFunction(CI);
9898 return visitCallSite(II);
9901 // InvokeInst simplification
9903 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9904 return visitCallSite(&II);
9907 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
9908 /// passed through the varargs area, we can eliminate the use of the cast.
9909 static bool isSafeToEliminateVarargsCast(const CallSite CS,
9910 const CastInst * const CI,
9911 const TargetData * const TD,
9913 if (!CI->isLosslessCast())
9916 // The size of ByVal arguments is derived from the type, so we
9917 // can't change to a type with a different size. If the size were
9918 // passed explicitly we could avoid this check.
9919 if (!CS.paramHasAttr(ix, Attribute::ByVal))
9923 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9924 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9925 if (!SrcTy->isSized() || !DstTy->isSized())
9927 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
9932 // visitCallSite - Improvements for call and invoke instructions.
9934 Instruction *InstCombiner::visitCallSite(CallSite CS) {
9935 bool Changed = false;
9937 // If the callee is a constexpr cast of a function, attempt to move the cast
9938 // to the arguments of the call/invoke.
9939 if (transformConstExprCastCall(CS)) return 0;
9941 Value *Callee = CS.getCalledValue();
9943 if (Function *CalleeF = dyn_cast<Function>(Callee))
9944 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9945 Instruction *OldCall = CS.getInstruction();
9946 // If the call and callee calling conventions don't match, this call must
9947 // be unreachable, as the call is undefined.
9948 new StoreInst(ConstantInt::getTrue(*Context),
9949 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
9951 if (!OldCall->use_empty())
9952 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9953 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9954 return EraseInstFromFunction(*OldCall);
9958 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9959 // This instruction is not reachable, just remove it. We insert a store to
9960 // undef so that we know that this code is not reachable, despite the fact
9961 // that we can't modify the CFG here.
9962 new StoreInst(ConstantInt::getTrue(*Context),
9963 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))),
9964 CS.getInstruction());
9966 if (!CS.getInstruction()->use_empty())
9967 CS.getInstruction()->
9968 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9970 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9971 // Don't break the CFG, insert a dummy cond branch.
9972 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9973 ConstantInt::getTrue(*Context), II);
9975 return EraseInstFromFunction(*CS.getInstruction());
9978 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9979 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9980 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9981 return transformCallThroughTrampoline(CS);
9983 const PointerType *PTy = cast<PointerType>(Callee->getType());
9984 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9985 if (FTy->isVarArg()) {
9986 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
9987 // See if we can optimize any arguments passed through the varargs area of
9989 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
9990 E = CS.arg_end(); I != E; ++I, ++ix) {
9991 CastInst *CI = dyn_cast<CastInst>(*I);
9992 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9993 *I = CI->getOperand(0);
9999 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10000 // Inline asm calls cannot throw - mark them 'nounwind'.
10001 CS.setDoesNotThrow();
10005 return Changed ? CS.getInstruction() : 0;
10008 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10009 // attempt to move the cast to the arguments of the call/invoke.
10011 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10012 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10013 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10014 if (CE->getOpcode() != Instruction::BitCast ||
10015 !isa<Function>(CE->getOperand(0)))
10017 Function *Callee = cast<Function>(CE->getOperand(0));
10018 Instruction *Caller = CS.getInstruction();
10019 const AttrListPtr &CallerPAL = CS.getAttributes();
10021 // Okay, this is a cast from a function to a different type. Unless doing so
10022 // would cause a type conversion of one of our arguments, change this call to
10023 // be a direct call with arguments casted to the appropriate types.
10025 const FunctionType *FT = Callee->getFunctionType();
10026 const Type *OldRetTy = Caller->getType();
10027 const Type *NewRetTy = FT->getReturnType();
10029 if (isa<StructType>(NewRetTy))
10030 return false; // TODO: Handle multiple return values.
10032 // Check to see if we are changing the return type...
10033 if (OldRetTy != NewRetTy) {
10034 if (Callee->isDeclaration() &&
10035 // Conversion is ok if changing from one pointer type to another or from
10036 // a pointer to an integer of the same size.
10037 !((isa<PointerType>(OldRetTy) || !TD ||
10038 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10039 (isa<PointerType>(NewRetTy) || !TD ||
10040 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10041 return false; // Cannot transform this return value.
10043 if (!Caller->use_empty() &&
10044 // void -> non-void is handled specially
10045 NewRetTy != Type::getVoidTy(*Context) && !CastInst::isCastable(NewRetTy, OldRetTy))
10046 return false; // Cannot transform this return value.
10048 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10049 Attributes RAttrs = CallerPAL.getRetAttributes();
10050 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10051 return false; // Attribute not compatible with transformed value.
10054 // If the callsite is an invoke instruction, and the return value is used by
10055 // a PHI node in a successor, we cannot change the return type of the call
10056 // because there is no place to put the cast instruction (without breaking
10057 // the critical edge). Bail out in this case.
10058 if (!Caller->use_empty())
10059 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10060 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10062 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10063 if (PN->getParent() == II->getNormalDest() ||
10064 PN->getParent() == II->getUnwindDest())
10068 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10069 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10071 CallSite::arg_iterator AI = CS.arg_begin();
10072 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10073 const Type *ParamTy = FT->getParamType(i);
10074 const Type *ActTy = (*AI)->getType();
10076 if (!CastInst::isCastable(ActTy, ParamTy))
10077 return false; // Cannot transform this parameter value.
10079 if (CallerPAL.getParamAttributes(i + 1)
10080 & Attribute::typeIncompatible(ParamTy))
10081 return false; // Attribute not compatible with transformed value.
10083 // Converting from one pointer type to another or between a pointer and an
10084 // integer of the same size is safe even if we do not have a body.
10085 bool isConvertible = ActTy == ParamTy ||
10086 (TD && ((isa<PointerType>(ParamTy) ||
10087 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10088 (isa<PointerType>(ActTy) ||
10089 ActTy == TD->getIntPtrType(Caller->getContext()))));
10090 if (Callee->isDeclaration() && !isConvertible) return false;
10093 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10094 Callee->isDeclaration())
10095 return false; // Do not delete arguments unless we have a function body.
10097 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10098 !CallerPAL.isEmpty())
10099 // In this case we have more arguments than the new function type, but we
10100 // won't be dropping them. Check that these extra arguments have attributes
10101 // that are compatible with being a vararg call argument.
10102 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10103 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10105 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10106 if (PAttrs & Attribute::VarArgsIncompatible)
10110 // Okay, we decided that this is a safe thing to do: go ahead and start
10111 // inserting cast instructions as necessary...
10112 std::vector<Value*> Args;
10113 Args.reserve(NumActualArgs);
10114 SmallVector<AttributeWithIndex, 8> attrVec;
10115 attrVec.reserve(NumCommonArgs);
10117 // Get any return attributes.
10118 Attributes RAttrs = CallerPAL.getRetAttributes();
10120 // If the return value is not being used, the type may not be compatible
10121 // with the existing attributes. Wipe out any problematic attributes.
10122 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10124 // Add the new return attributes.
10126 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10128 AI = CS.arg_begin();
10129 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10130 const Type *ParamTy = FT->getParamType(i);
10131 if ((*AI)->getType() == ParamTy) {
10132 Args.push_back(*AI);
10134 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10135 false, ParamTy, false);
10136 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10139 // Add any parameter attributes.
10140 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10141 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10144 // If the function takes more arguments than the call was taking, add them
10146 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10147 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10149 // If we are removing arguments to the function, emit an obnoxious warning.
10150 if (FT->getNumParams() < NumActualArgs) {
10151 if (!FT->isVarArg()) {
10152 errs() << "WARNING: While resolving call to function '"
10153 << Callee->getName() << "' arguments were dropped!\n";
10155 // Add all of the arguments in their promoted form to the arg list.
10156 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10157 const Type *PTy = getPromotedType((*AI)->getType());
10158 if (PTy != (*AI)->getType()) {
10159 // Must promote to pass through va_arg area!
10160 Instruction::CastOps opcode =
10161 CastInst::getCastOpcode(*AI, false, PTy, false);
10162 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10164 Args.push_back(*AI);
10167 // Add any parameter attributes.
10168 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10169 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10174 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10175 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10177 if (NewRetTy == Type::getVoidTy(*Context))
10178 Caller->setName(""); // Void type should not have a name.
10180 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10184 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10185 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10186 Args.begin(), Args.end(),
10187 Caller->getName(), Caller);
10188 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10189 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10191 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10192 Caller->getName(), Caller);
10193 CallInst *CI = cast<CallInst>(Caller);
10194 if (CI->isTailCall())
10195 cast<CallInst>(NC)->setTailCall();
10196 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10197 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10200 // Insert a cast of the return type as necessary.
10202 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10203 if (NV->getType() != Type::getVoidTy(*Context)) {
10204 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
10206 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10208 // If this is an invoke instruction, we should insert it after the first
10209 // non-phi, instruction in the normal successor block.
10210 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10211 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10212 InsertNewInstBefore(NC, *I);
10214 // Otherwise, it's a call, just insert cast right after the call instr
10215 InsertNewInstBefore(NC, *Caller);
10217 Worklist.AddUsersToWorkList(*Caller);
10219 NV = UndefValue::get(Caller->getType());
10224 if (!Caller->use_empty())
10225 Caller->replaceAllUsesWith(NV);
10227 EraseInstFromFunction(*Caller);
10231 // transformCallThroughTrampoline - Turn a call to a function created by the
10232 // init_trampoline intrinsic into a direct call to the underlying function.
10234 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10235 Value *Callee = CS.getCalledValue();
10236 const PointerType *PTy = cast<PointerType>(Callee->getType());
10237 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10238 const AttrListPtr &Attrs = CS.getAttributes();
10240 // If the call already has the 'nest' attribute somewhere then give up -
10241 // otherwise 'nest' would occur twice after splicing in the chain.
10242 if (Attrs.hasAttrSomewhere(Attribute::Nest))
10245 IntrinsicInst *Tramp =
10246 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10248 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10249 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10250 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10252 const AttrListPtr &NestAttrs = NestF->getAttributes();
10253 if (!NestAttrs.isEmpty()) {
10254 unsigned NestIdx = 1;
10255 const Type *NestTy = 0;
10256 Attributes NestAttr = Attribute::None;
10258 // Look for a parameter marked with the 'nest' attribute.
10259 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10260 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10261 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10262 // Record the parameter type and any other attributes.
10264 NestAttr = NestAttrs.getParamAttributes(NestIdx);
10269 Instruction *Caller = CS.getInstruction();
10270 std::vector<Value*> NewArgs;
10271 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10273 SmallVector<AttributeWithIndex, 8> NewAttrs;
10274 NewAttrs.reserve(Attrs.getNumSlots() + 1);
10276 // Insert the nest argument into the call argument list, which may
10277 // mean appending it. Likewise for attributes.
10279 // Add any result attributes.
10280 if (Attributes Attr = Attrs.getRetAttributes())
10281 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10285 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10287 if (Idx == NestIdx) {
10288 // Add the chain argument and attributes.
10289 Value *NestVal = Tramp->getOperand(3);
10290 if (NestVal->getType() != NestTy)
10291 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10292 NewArgs.push_back(NestVal);
10293 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10299 // Add the original argument and attributes.
10300 NewArgs.push_back(*I);
10301 if (Attributes Attr = Attrs.getParamAttributes(Idx))
10303 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10309 // Add any function attributes.
10310 if (Attributes Attr = Attrs.getFnAttributes())
10311 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10313 // The trampoline may have been bitcast to a bogus type (FTy).
10314 // Handle this by synthesizing a new function type, equal to FTy
10315 // with the chain parameter inserted.
10317 std::vector<const Type*> NewTypes;
10318 NewTypes.reserve(FTy->getNumParams()+1);
10320 // Insert the chain's type into the list of parameter types, which may
10321 // mean appending it.
10324 FunctionType::param_iterator I = FTy->param_begin(),
10325 E = FTy->param_end();
10328 if (Idx == NestIdx)
10329 // Add the chain's type.
10330 NewTypes.push_back(NestTy);
10335 // Add the original type.
10336 NewTypes.push_back(*I);
10342 // Replace the trampoline call with a direct call. Let the generic
10343 // code sort out any function type mismatches.
10344 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
10346 Constant *NewCallee =
10347 NestF->getType() == PointerType::getUnqual(NewFTy) ?
10348 NestF : ConstantExpr::getBitCast(NestF,
10349 PointerType::getUnqual(NewFTy));
10350 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10353 Instruction *NewCaller;
10354 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10355 NewCaller = InvokeInst::Create(NewCallee,
10356 II->getNormalDest(), II->getUnwindDest(),
10357 NewArgs.begin(), NewArgs.end(),
10358 Caller->getName(), Caller);
10359 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10360 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10362 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10363 Caller->getName(), Caller);
10364 if (cast<CallInst>(Caller)->isTailCall())
10365 cast<CallInst>(NewCaller)->setTailCall();
10366 cast<CallInst>(NewCaller)->
10367 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10368 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10370 if (Caller->getType() != Type::getVoidTy(*Context) && !Caller->use_empty())
10371 Caller->replaceAllUsesWith(NewCaller);
10372 Caller->eraseFromParent();
10373 Worklist.Remove(Caller);
10378 // Replace the trampoline call with a direct call. Since there is no 'nest'
10379 // parameter, there is no need to adjust the argument list. Let the generic
10380 // code sort out any function type mismatches.
10381 Constant *NewCallee =
10382 NestF->getType() == PTy ? NestF :
10383 ConstantExpr::getBitCast(NestF, PTy);
10384 CS.setCalledFunction(NewCallee);
10385 return CS.getInstruction();
10388 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10389 /// and if a/b/c and the add's all have a single use, turn this into a phi
10390 /// and a single binop.
10391 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10392 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10393 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10394 unsigned Opc = FirstInst->getOpcode();
10395 Value *LHSVal = FirstInst->getOperand(0);
10396 Value *RHSVal = FirstInst->getOperand(1);
10398 const Type *LHSType = LHSVal->getType();
10399 const Type *RHSType = RHSVal->getType();
10401 // Scan to see if all operands are the same opcode, and all have one use.
10402 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10403 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10404 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10405 // Verify type of the LHS matches so we don't fold cmp's of different
10406 // types or GEP's with different index types.
10407 I->getOperand(0)->getType() != LHSType ||
10408 I->getOperand(1)->getType() != RHSType)
10411 // If they are CmpInst instructions, check their predicates
10412 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10413 if (cast<CmpInst>(I)->getPredicate() !=
10414 cast<CmpInst>(FirstInst)->getPredicate())
10417 // Keep track of which operand needs a phi node.
10418 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10419 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10422 // If both LHS and RHS would need a PHI, don't do this transformation,
10423 // because it would increase the number of PHIs entering the block,
10424 // which leads to higher register pressure. This is especially
10425 // bad when the PHIs are in the header of a loop.
10426 if (!LHSVal && !RHSVal)
10429 // Otherwise, this is safe to transform!
10431 Value *InLHS = FirstInst->getOperand(0);
10432 Value *InRHS = FirstInst->getOperand(1);
10433 PHINode *NewLHS = 0, *NewRHS = 0;
10435 NewLHS = PHINode::Create(LHSType,
10436 FirstInst->getOperand(0)->getName() + ".pn");
10437 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10438 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10439 InsertNewInstBefore(NewLHS, PN);
10444 NewRHS = PHINode::Create(RHSType,
10445 FirstInst->getOperand(1)->getName() + ".pn");
10446 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10447 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10448 InsertNewInstBefore(NewRHS, PN);
10452 // Add all operands to the new PHIs.
10453 if (NewLHS || NewRHS) {
10454 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10455 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10457 Value *NewInLHS = InInst->getOperand(0);
10458 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10461 Value *NewInRHS = InInst->getOperand(1);
10462 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10467 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10468 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10469 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10470 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10474 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10475 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10477 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10478 FirstInst->op_end());
10479 // This is true if all GEP bases are allocas and if all indices into them are
10481 bool AllBasePointersAreAllocas = true;
10483 // We don't want to replace this phi if the replacement would require
10484 // more than one phi, which leads to higher register pressure. This is
10485 // especially bad when the PHIs are in the header of a loop.
10486 bool NeededPhi = false;
10488 // Scan to see if all operands are the same opcode, and all have one use.
10489 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10490 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10491 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10492 GEP->getNumOperands() != FirstInst->getNumOperands())
10495 // Keep track of whether or not all GEPs are of alloca pointers.
10496 if (AllBasePointersAreAllocas &&
10497 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10498 !GEP->hasAllConstantIndices()))
10499 AllBasePointersAreAllocas = false;
10501 // Compare the operand lists.
10502 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10503 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10506 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10507 // if one of the PHIs has a constant for the index. The index may be
10508 // substantially cheaper to compute for the constants, so making it a
10509 // variable index could pessimize the path. This also handles the case
10510 // for struct indices, which must always be constant.
10511 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10512 isa<ConstantInt>(GEP->getOperand(op)))
10515 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10518 // If we already needed a PHI for an earlier operand, and another operand
10519 // also requires a PHI, we'd be introducing more PHIs than we're
10520 // eliminating, which increases register pressure on entry to the PHI's
10525 FixedOperands[op] = 0; // Needs a PHI.
10530 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10531 // bother doing this transformation. At best, this will just save a bit of
10532 // offset calculation, but all the predecessors will have to materialize the
10533 // stack address into a register anyway. We'd actually rather *clone* the
10534 // load up into the predecessors so that we have a load of a gep of an alloca,
10535 // which can usually all be folded into the load.
10536 if (AllBasePointersAreAllocas)
10539 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10540 // that is variable.
10541 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10543 bool HasAnyPHIs = false;
10544 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10545 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10546 Value *FirstOp = FirstInst->getOperand(i);
10547 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10548 FirstOp->getName()+".pn");
10549 InsertNewInstBefore(NewPN, PN);
10551 NewPN->reserveOperandSpace(e);
10552 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10553 OperandPhis[i] = NewPN;
10554 FixedOperands[i] = NewPN;
10559 // Add all operands to the new PHIs.
10561 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10562 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10563 BasicBlock *InBB = PN.getIncomingBlock(i);
10565 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10566 if (PHINode *OpPhi = OperandPhis[op])
10567 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10571 Value *Base = FixedOperands[0];
10572 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10573 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10574 FixedOperands.end()) :
10575 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10576 FixedOperands.end());
10580 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10581 /// sink the load out of the block that defines it. This means that it must be
10582 /// obvious the value of the load is not changed from the point of the load to
10583 /// the end of the block it is in.
10585 /// Finally, it is safe, but not profitable, to sink a load targetting a
10586 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
10588 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10589 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10591 for (++BBI; BBI != E; ++BBI)
10592 if (BBI->mayWriteToMemory())
10595 // Check for non-address taken alloca. If not address-taken already, it isn't
10596 // profitable to do this xform.
10597 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10598 bool isAddressTaken = false;
10599 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10601 if (isa<LoadInst>(UI)) continue;
10602 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10603 // If storing TO the alloca, then the address isn't taken.
10604 if (SI->getOperand(1) == AI) continue;
10606 isAddressTaken = true;
10610 if (!isAddressTaken && AI->isStaticAlloca())
10614 // If this load is a load from a GEP with a constant offset from an alloca,
10615 // then we don't want to sink it. In its present form, it will be
10616 // load [constant stack offset]. Sinking it will cause us to have to
10617 // materialize the stack addresses in each predecessor in a register only to
10618 // do a shared load from register in the successor.
10619 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10620 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10621 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10628 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10629 // operator and they all are only used by the PHI, PHI together their
10630 // inputs, and do the operation once, to the result of the PHI.
10631 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10632 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10634 // Scan the instruction, looking for input operations that can be folded away.
10635 // If all input operands to the phi are the same instruction (e.g. a cast from
10636 // the same type or "+42") we can pull the operation through the PHI, reducing
10637 // code size and simplifying code.
10638 Constant *ConstantOp = 0;
10639 const Type *CastSrcTy = 0;
10640 bool isVolatile = false;
10641 if (isa<CastInst>(FirstInst)) {
10642 CastSrcTy = FirstInst->getOperand(0)->getType();
10643 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10644 // Can fold binop, compare or shift here if the RHS is a constant,
10645 // otherwise call FoldPHIArgBinOpIntoPHI.
10646 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10647 if (ConstantOp == 0)
10648 return FoldPHIArgBinOpIntoPHI(PN);
10649 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10650 isVolatile = LI->isVolatile();
10651 // We can't sink the load if the loaded value could be modified between the
10652 // load and the PHI.
10653 if (LI->getParent() != PN.getIncomingBlock(0) ||
10654 !isSafeAndProfitableToSinkLoad(LI))
10657 // If the PHI is of volatile loads and the load block has multiple
10658 // successors, sinking it would remove a load of the volatile value from
10659 // the path through the other successor.
10661 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10664 } else if (isa<GetElementPtrInst>(FirstInst)) {
10665 return FoldPHIArgGEPIntoPHI(PN);
10667 return 0; // Cannot fold this operation.
10670 // Check to see if all arguments are the same operation.
10671 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10672 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10673 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10674 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10677 if (I->getOperand(0)->getType() != CastSrcTy)
10678 return 0; // Cast operation must match.
10679 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10680 // We can't sink the load if the loaded value could be modified between
10681 // the load and the PHI.
10682 if (LI->isVolatile() != isVolatile ||
10683 LI->getParent() != PN.getIncomingBlock(i) ||
10684 !isSafeAndProfitableToSinkLoad(LI))
10687 // If the PHI is of volatile loads and the load block has multiple
10688 // successors, sinking it would remove a load of the volatile value from
10689 // the path through the other successor.
10691 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10694 } else if (I->getOperand(1) != ConstantOp) {
10699 // Okay, they are all the same operation. Create a new PHI node of the
10700 // correct type, and PHI together all of the LHS's of the instructions.
10701 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10702 PN.getName()+".in");
10703 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10705 Value *InVal = FirstInst->getOperand(0);
10706 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10708 // Add all operands to the new PHI.
10709 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10710 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10711 if (NewInVal != InVal)
10713 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10718 // The new PHI unions all of the same values together. This is really
10719 // common, so we handle it intelligently here for compile-time speed.
10723 InsertNewInstBefore(NewPN, PN);
10727 // Insert and return the new operation.
10728 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10729 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10730 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10731 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10732 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10733 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10734 PhiVal, ConstantOp);
10735 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10737 // If this was a volatile load that we are merging, make sure to loop through
10738 // and mark all the input loads as non-volatile. If we don't do this, we will
10739 // insert a new volatile load and the old ones will not be deletable.
10741 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10742 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10744 return new LoadInst(PhiVal, "", isVolatile);
10747 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10749 static bool DeadPHICycle(PHINode *PN,
10750 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10751 if (PN->use_empty()) return true;
10752 if (!PN->hasOneUse()) return false;
10754 // Remember this node, and if we find the cycle, return.
10755 if (!PotentiallyDeadPHIs.insert(PN))
10758 // Don't scan crazily complex things.
10759 if (PotentiallyDeadPHIs.size() == 16)
10762 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10763 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10768 /// PHIsEqualValue - Return true if this phi node is always equal to
10769 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10770 /// z = some value; x = phi (y, z); y = phi (x, z)
10771 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10772 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10773 // See if we already saw this PHI node.
10774 if (!ValueEqualPHIs.insert(PN))
10777 // Don't scan crazily complex things.
10778 if (ValueEqualPHIs.size() == 16)
10781 // Scan the operands to see if they are either phi nodes or are equal to
10783 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10784 Value *Op = PN->getIncomingValue(i);
10785 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10786 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10788 } else if (Op != NonPhiInVal)
10796 // PHINode simplification
10798 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10799 // If LCSSA is around, don't mess with Phi nodes
10800 if (MustPreserveLCSSA) return 0;
10802 if (Value *V = PN.hasConstantValue())
10803 return ReplaceInstUsesWith(PN, V);
10805 // If all PHI operands are the same operation, pull them through the PHI,
10806 // reducing code size.
10807 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10808 isa<Instruction>(PN.getIncomingValue(1)) &&
10809 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10810 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10811 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10812 // than themselves more than once.
10813 PN.getIncomingValue(0)->hasOneUse())
10814 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10817 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10818 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10819 // PHI)... break the cycle.
10820 if (PN.hasOneUse()) {
10821 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10822 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10823 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10824 PotentiallyDeadPHIs.insert(&PN);
10825 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10826 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10829 // If this phi has a single use, and if that use just computes a value for
10830 // the next iteration of a loop, delete the phi. This occurs with unused
10831 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10832 // common case here is good because the only other things that catch this
10833 // are induction variable analysis (sometimes) and ADCE, which is only run
10835 if (PHIUser->hasOneUse() &&
10836 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10837 PHIUser->use_back() == &PN) {
10838 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10842 // We sometimes end up with phi cycles that non-obviously end up being the
10843 // same value, for example:
10844 // z = some value; x = phi (y, z); y = phi (x, z)
10845 // where the phi nodes don't necessarily need to be in the same block. Do a
10846 // quick check to see if the PHI node only contains a single non-phi value, if
10847 // so, scan to see if the phi cycle is actually equal to that value.
10849 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10850 // Scan for the first non-phi operand.
10851 while (InValNo != NumOperandVals &&
10852 isa<PHINode>(PN.getIncomingValue(InValNo)))
10855 if (InValNo != NumOperandVals) {
10856 Value *NonPhiInVal = PN.getOperand(InValNo);
10858 // Scan the rest of the operands to see if there are any conflicts, if so
10859 // there is no need to recursively scan other phis.
10860 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10861 Value *OpVal = PN.getIncomingValue(InValNo);
10862 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10866 // If we scanned over all operands, then we have one unique value plus
10867 // phi values. Scan PHI nodes to see if they all merge in each other or
10869 if (InValNo == NumOperandVals) {
10870 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10871 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10872 return ReplaceInstUsesWith(PN, NonPhiInVal);
10879 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10880 Value *PtrOp = GEP.getOperand(0);
10881 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
10882 if (GEP.getNumOperands() == 1)
10883 return ReplaceInstUsesWith(GEP, PtrOp);
10885 if (isa<UndefValue>(GEP.getOperand(0)))
10886 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10888 bool HasZeroPointerIndex = false;
10889 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10890 HasZeroPointerIndex = C->isNullValue();
10892 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10893 return ReplaceInstUsesWith(GEP, PtrOp);
10895 // Eliminate unneeded casts for indices.
10897 bool MadeChange = false;
10898 unsigned PtrSize = TD->getPointerSizeInBits();
10900 gep_type_iterator GTI = gep_type_begin(GEP);
10901 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
10902 I != E; ++I, ++GTI) {
10903 if (!isa<SequentialType>(*GTI)) continue;
10905 // If we are using a wider index than needed for this platform, shrink it
10906 // to what we need. If narrower, sign-extend it to what we need. This
10907 // explicit cast can make subsequent optimizations more obvious.
10908 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
10909 if (OpBits == PtrSize)
10912 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
10915 if (MadeChange) return &GEP;
10918 // Combine Indices - If the source pointer to this getelementptr instruction
10919 // is a getelementptr instruction, combine the indices of the two
10920 // getelementptr instructions into a single instruction.
10922 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
10923 // Note that if our source is a gep chain itself that we wait for that
10924 // chain to be resolved before we perform this transformation. This
10925 // avoids us creating a TON of code in some cases.
10927 if (GetElementPtrInst *SrcGEP =
10928 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
10929 if (SrcGEP->getNumOperands() == 2)
10930 return 0; // Wait until our source is folded to completion.
10932 SmallVector<Value*, 8> Indices;
10934 // Find out whether the last index in the source GEP is a sequential idx.
10935 bool EndsWithSequential = false;
10936 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
10938 EndsWithSequential = !isa<StructType>(*I);
10940 // Can we combine the two pointer arithmetics offsets?
10941 if (EndsWithSequential) {
10942 // Replace: gep (gep %P, long B), long A, ...
10943 // With: T = long A+B; gep %P, T, ...
10946 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
10947 Value *GO1 = GEP.getOperand(1);
10948 if (SO1 == Constant::getNullValue(SO1->getType())) {
10950 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10953 // If they aren't the same type, then the input hasn't been processed
10954 // by the loop above yet (which canonicalizes sequential index types to
10955 // intptr_t). Just avoid transforming this until the input has been
10957 if (SO1->getType() != GO1->getType())
10959 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
10962 // Update the GEP in place if possible.
10963 if (Src->getNumOperands() == 2) {
10964 GEP.setOperand(0, Src->getOperand(0));
10965 GEP.setOperand(1, Sum);
10968 Indices.append(Src->op_begin()+1, Src->op_end()-1);
10969 Indices.push_back(Sum);
10970 Indices.append(GEP.op_begin()+2, GEP.op_end());
10971 } else if (isa<Constant>(*GEP.idx_begin()) &&
10972 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10973 Src->getNumOperands() != 1) {
10974 // Otherwise we can do the fold if the first index of the GEP is a zero
10975 Indices.append(Src->op_begin()+1, Src->op_end());
10976 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
10979 if (!Indices.empty())
10980 return (cast<GEPOperator>(&GEP)->isInBounds() &&
10981 Src->isInBounds()) ?
10982 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
10983 Indices.end(), GEP.getName()) :
10984 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
10985 Indices.end(), GEP.getName());
10988 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
10989 if (Value *X = getBitCastOperand(PtrOp)) {
10990 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
10992 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
10993 // want to change the gep until the bitcasts are eliminated.
10994 if (getBitCastOperand(X)) {
10995 Worklist.AddValue(PtrOp);
10999 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11000 // into : GEP [10 x i8]* X, i32 0, ...
11002 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11003 // into : GEP i8* X, ...
11005 // This occurs when the program declares an array extern like "int X[];"
11006 if (HasZeroPointerIndex) {
11007 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11008 const PointerType *XTy = cast<PointerType>(X->getType());
11009 if (const ArrayType *CATy =
11010 dyn_cast<ArrayType>(CPTy->getElementType())) {
11011 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11012 if (CATy->getElementType() == XTy->getElementType()) {
11013 // -> GEP i8* X, ...
11014 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11015 return cast<GEPOperator>(&GEP)->isInBounds() ?
11016 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11018 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11022 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
11023 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11024 if (CATy->getElementType() == XATy->getElementType()) {
11025 // -> GEP [10 x i8]* X, i32 0, ...
11026 // At this point, we know that the cast source type is a pointer
11027 // to an array of the same type as the destination pointer
11028 // array. Because the array type is never stepped over (there
11029 // is a leading zero) we can fold the cast into this GEP.
11030 GEP.setOperand(0, X);
11035 } else if (GEP.getNumOperands() == 2) {
11036 // Transform things like:
11037 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11038 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11039 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11040 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11041 if (TD && isa<ArrayType>(SrcElTy) &&
11042 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11043 TD->getTypeAllocSize(ResElTy)) {
11045 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11046 Idx[1] = GEP.getOperand(1);
11047 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11048 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11049 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11050 // V and GEP are both pointer types --> BitCast
11051 return new BitCastInst(NewGEP, GEP.getType());
11054 // Transform things like:
11055 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11056 // (where tmp = 8*tmp2) into:
11057 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11059 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
11060 uint64_t ArrayEltSize =
11061 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11063 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11064 // allow either a mul, shift, or constant here.
11066 ConstantInt *Scale = 0;
11067 if (ArrayEltSize == 1) {
11068 NewIdx = GEP.getOperand(1);
11069 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11070 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11071 NewIdx = ConstantInt::get(CI->getType(), 1);
11073 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11074 if (Inst->getOpcode() == Instruction::Shl &&
11075 isa<ConstantInt>(Inst->getOperand(1))) {
11076 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11077 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11078 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11080 NewIdx = Inst->getOperand(0);
11081 } else if (Inst->getOpcode() == Instruction::Mul &&
11082 isa<ConstantInt>(Inst->getOperand(1))) {
11083 Scale = cast<ConstantInt>(Inst->getOperand(1));
11084 NewIdx = Inst->getOperand(0);
11088 // If the index will be to exactly the right offset with the scale taken
11089 // out, perform the transformation. Note, we don't know whether Scale is
11090 // signed or not. We'll use unsigned version of division/modulo
11091 // operation after making sure Scale doesn't have the sign bit set.
11092 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11093 Scale->getZExtValue() % ArrayEltSize == 0) {
11094 Scale = ConstantInt::get(Scale->getType(),
11095 Scale->getZExtValue() / ArrayEltSize);
11096 if (Scale->getZExtValue() != 1) {
11097 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11099 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
11102 // Insert the new GEP instruction.
11104 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11106 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11107 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11108 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11109 // The NewGEP must be pointer typed, so must the old one -> BitCast
11110 return new BitCastInst(NewGEP, GEP.getType());
11116 /// See if we can simplify:
11117 /// X = bitcast A* to B*
11118 /// Y = gep X, <...constant indices...>
11119 /// into a gep of the original struct. This is important for SROA and alias
11120 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
11121 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11123 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11124 // Determine how much the GEP moves the pointer. We are guaranteed to get
11125 // a constant back from EmitGEPOffset.
11126 ConstantInt *OffsetV =
11127 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11128 int64_t Offset = OffsetV->getSExtValue();
11130 // If this GEP instruction doesn't move the pointer, just replace the GEP
11131 // with a bitcast of the real input to the dest type.
11133 // If the bitcast is of an allocation, and the allocation will be
11134 // converted to match the type of the cast, don't touch this.
11135 if (isa<AllocationInst>(BCI->getOperand(0)) ||
11136 isMalloc(BCI->getOperand(0))) {
11137 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11138 if (Instruction *I = visitBitCast(*BCI)) {
11141 BCI->getParent()->getInstList().insert(BCI, I);
11142 ReplaceInstUsesWith(*BCI, I);
11147 return new BitCastInst(BCI->getOperand(0), GEP.getType());
11150 // Otherwise, if the offset is non-zero, we need to find out if there is a
11151 // field at Offset in 'A's type. If so, we can pull the cast through the
11153 SmallVector<Value*, 8> NewIndices;
11155 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11156 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11157 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11158 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11159 NewIndices.end()) :
11160 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11163 if (NGEP->getType() == GEP.getType())
11164 return ReplaceInstUsesWith(GEP, NGEP);
11165 NGEP->takeName(&GEP);
11166 return new BitCastInst(NGEP, GEP.getType());
11174 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11175 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11176 if (AI.isArrayAllocation()) { // Check C != 1
11177 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11178 const Type *NewTy =
11179 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11180 AllocationInst *New = 0;
11182 // Create and insert the replacement instruction...
11183 if (isa<MallocInst>(AI))
11184 New = Builder->CreateMalloc(NewTy, 0, AI.getName());
11186 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11187 New = Builder->CreateAlloca(NewTy, 0, AI.getName());
11189 New->setAlignment(AI.getAlignment());
11191 // Scan to the end of the allocation instructions, to skip over a block of
11192 // allocas if possible...also skip interleaved debug info
11194 BasicBlock::iterator It = New;
11195 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11197 // Now that I is pointing to the first non-allocation-inst in the block,
11198 // insert our getelementptr instruction...
11200 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11204 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11205 New->getName()+".sub", It);
11207 // Now make everything use the getelementptr instead of the original
11209 return ReplaceInstUsesWith(AI, V);
11210 } else if (isa<UndefValue>(AI.getArraySize())) {
11211 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11215 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11216 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11217 // Note that we only do this for alloca's, because malloc should allocate
11218 // and return a unique pointer, even for a zero byte allocation.
11219 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11220 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11222 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11223 if (AI.getAlignment() == 0)
11224 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11230 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11231 Value *Op = FI.getOperand(0);
11233 // free undef -> unreachable.
11234 if (isa<UndefValue>(Op)) {
11235 // Insert a new store to null because we cannot modify the CFG here.
11236 new StoreInst(ConstantInt::getTrue(*Context),
11237 UndefValue::get(PointerType::getUnqual(Type::getInt1Ty(*Context))), &FI);
11238 return EraseInstFromFunction(FI);
11241 // If we have 'free null' delete the instruction. This can happen in stl code
11242 // when lots of inlining happens.
11243 if (isa<ConstantPointerNull>(Op))
11244 return EraseInstFromFunction(FI);
11246 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11247 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11248 FI.setOperand(0, CI->getOperand(0));
11252 // Change free (gep X, 0,0,0,0) into free(X)
11253 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11254 if (GEPI->hasAllZeroIndices()) {
11255 Worklist.Add(GEPI);
11256 FI.setOperand(0, GEPI->getOperand(0));
11261 // Change free(malloc) into nothing, if the malloc has a single use.
11262 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11263 if (MI->hasOneUse()) {
11264 EraseInstFromFunction(FI);
11265 return EraseInstFromFunction(*MI);
11267 if (isMalloc(Op)) {
11268 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11269 if (Op->hasOneUse() && CI->hasOneUse()) {
11270 EraseInstFromFunction(FI);
11271 EraseInstFromFunction(*CI);
11272 return EraseInstFromFunction(*cast<Instruction>(Op));
11275 // Op is a call to malloc
11276 if (Op->hasOneUse()) {
11277 EraseInstFromFunction(FI);
11278 return EraseInstFromFunction(*cast<Instruction>(Op));
11287 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11288 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11289 const TargetData *TD) {
11290 User *CI = cast<User>(LI.getOperand(0));
11291 Value *CastOp = CI->getOperand(0);
11292 LLVMContext *Context = IC.getContext();
11295 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11296 // Instead of loading constant c string, use corresponding integer value
11297 // directly if string length is small enough.
11299 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11300 unsigned len = Str.length();
11301 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11302 unsigned numBits = Ty->getPrimitiveSizeInBits();
11303 // Replace LI with immediate integer store.
11304 if ((numBits >> 3) == len + 1) {
11305 APInt StrVal(numBits, 0);
11306 APInt SingleChar(numBits, 0);
11307 if (TD->isLittleEndian()) {
11308 for (signed i = len-1; i >= 0; i--) {
11309 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11310 StrVal = (StrVal << 8) | SingleChar;
11313 for (unsigned i = 0; i < len; i++) {
11314 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11315 StrVal = (StrVal << 8) | SingleChar;
11317 // Append NULL at the end.
11319 StrVal = (StrVal << 8) | SingleChar;
11321 Value *NL = ConstantInt::get(*Context, StrVal);
11322 return IC.ReplaceInstUsesWith(LI, NL);
11328 const PointerType *DestTy = cast<PointerType>(CI->getType());
11329 const Type *DestPTy = DestTy->getElementType();
11330 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11332 // If the address spaces don't match, don't eliminate the cast.
11333 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11336 const Type *SrcPTy = SrcTy->getElementType();
11338 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11339 isa<VectorType>(DestPTy)) {
11340 // If the source is an array, the code below will not succeed. Check to
11341 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11343 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11344 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11345 if (ASrcTy->getNumElements() != 0) {
11347 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::getInt32Ty(*Context));
11348 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11349 SrcTy = cast<PointerType>(CastOp->getType());
11350 SrcPTy = SrcTy->getElementType();
11353 if (IC.getTargetData() &&
11354 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
11355 isa<VectorType>(SrcPTy)) &&
11356 // Do not allow turning this into a load of an integer, which is then
11357 // casted to a pointer, this pessimizes pointer analysis a lot.
11358 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11359 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11360 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11362 // Okay, we are casting from one integer or pointer type to another of
11363 // the same size. Instead of casting the pointer before the load, cast
11364 // the result of the loaded value.
11366 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
11367 // Now cast the result of the load.
11368 return new BitCastInst(NewLoad, LI.getType());
11375 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11376 Value *Op = LI.getOperand(0);
11378 // Attempt to improve the alignment.
11380 unsigned KnownAlign =
11381 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11383 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11384 LI.getAlignment()))
11385 LI.setAlignment(KnownAlign);
11388 // load (cast X) --> cast (load X) iff safe.
11389 if (isa<CastInst>(Op))
11390 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11393 // None of the following transforms are legal for volatile loads.
11394 if (LI.isVolatile()) return 0;
11396 // Do really simple store-to-load forwarding and load CSE, to catch cases
11397 // where there are several consequtive memory accesses to the same location,
11398 // separated by a few arithmetic operations.
11399 BasicBlock::iterator BBI = &LI;
11400 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11401 return ReplaceInstUsesWith(LI, AvailableVal);
11403 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11404 const Value *GEPI0 = GEPI->getOperand(0);
11405 // TODO: Consider a target hook for valid address spaces for this xform.
11406 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
11407 // Insert a new store to null instruction before the load to indicate
11408 // that this code is not reachable. We do this instead of inserting
11409 // an unreachable instruction directly because we cannot modify the
11411 new StoreInst(UndefValue::get(LI.getType()),
11412 Constant::getNullValue(Op->getType()), &LI);
11413 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11417 if (Constant *C = dyn_cast<Constant>(Op)) {
11418 // load null/undef -> undef
11419 // TODO: Consider a target hook for valid address spaces for this xform.
11420 if (isa<UndefValue>(C) ||
11421 (C->isNullValue() && LI.getPointerAddressSpace() == 0)) {
11422 // Insert a new store to null instruction before the load to indicate that
11423 // this code is not reachable. We do this instead of inserting an
11424 // unreachable instruction directly because we cannot modify the CFG.
11425 new StoreInst(UndefValue::get(LI.getType()),
11426 Constant::getNullValue(Op->getType()), &LI);
11427 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11430 // Instcombine load (constant global) into the value loaded.
11431 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11432 if (GV->isConstant() && GV->hasDefinitiveInitializer())
11433 return ReplaceInstUsesWith(LI, GV->getInitializer());
11435 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11436 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11437 if (CE->getOpcode() == Instruction::GetElementPtr) {
11438 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11439 if (GV->isConstant() && GV->hasDefinitiveInitializer())
11441 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
11443 return ReplaceInstUsesWith(LI, V);
11444 if (CE->getOperand(0)->isNullValue()) {
11445 // Insert a new store to null instruction before the load to indicate
11446 // that this code is not reachable. We do this instead of inserting
11447 // an unreachable instruction directly because we cannot modify the
11449 new StoreInst(UndefValue::get(LI.getType()),
11450 Constant::getNullValue(Op->getType()), &LI);
11451 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11454 } else if (CE->isCast()) {
11455 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11461 // If this load comes from anywhere in a constant global, and if the global
11462 // is all undef or zero, we know what it loads.
11463 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11464 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11465 if (GV->getInitializer()->isNullValue())
11466 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11467 else if (isa<UndefValue>(GV->getInitializer()))
11468 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11472 if (Op->hasOneUse()) {
11473 // Change select and PHI nodes to select values instead of addresses: this
11474 // helps alias analysis out a lot, allows many others simplifications, and
11475 // exposes redundancy in the code.
11477 // Note that we cannot do the transformation unless we know that the
11478 // introduced loads cannot trap! Something like this is valid as long as
11479 // the condition is always false: load (select bool %C, int* null, int* %G),
11480 // but it would not be valid if we transformed it to load from null
11481 // unconditionally.
11483 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11484 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11485 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11486 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11487 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11488 SI->getOperand(1)->getName()+".val");
11489 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11490 SI->getOperand(2)->getName()+".val");
11491 return SelectInst::Create(SI->getCondition(), V1, V2);
11494 // load (select (cond, null, P)) -> load P
11495 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11496 if (C->isNullValue()) {
11497 LI.setOperand(0, SI->getOperand(2));
11501 // load (select (cond, P, null)) -> load P
11502 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11503 if (C->isNullValue()) {
11504 LI.setOperand(0, SI->getOperand(1));
11512 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11513 /// when possible. This makes it generally easy to do alias analysis and/or
11514 /// SROA/mem2reg of the memory object.
11515 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11516 User *CI = cast<User>(SI.getOperand(1));
11517 Value *CastOp = CI->getOperand(0);
11519 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11520 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11521 if (SrcTy == 0) return 0;
11523 const Type *SrcPTy = SrcTy->getElementType();
11525 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11528 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11529 /// to its first element. This allows us to handle things like:
11530 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11531 /// on 32-bit hosts.
11532 SmallVector<Value*, 4> NewGEPIndices;
11534 // If the source is an array, the code below will not succeed. Check to
11535 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11537 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11538 // Index through pointer.
11539 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11540 NewGEPIndices.push_back(Zero);
11543 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11544 if (!STy->getNumElements()) /* Struct can be empty {} */
11546 NewGEPIndices.push_back(Zero);
11547 SrcPTy = STy->getElementType(0);
11548 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11549 NewGEPIndices.push_back(Zero);
11550 SrcPTy = ATy->getElementType();
11556 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11559 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11562 // If the pointers point into different address spaces or if they point to
11563 // values with different sizes, we can't do the transformation.
11564 if (!IC.getTargetData() ||
11565 SrcTy->getAddressSpace() !=
11566 cast<PointerType>(CI->getType())->getAddressSpace() ||
11567 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11568 IC.getTargetData()->getTypeSizeInBits(DestPTy))
11571 // Okay, we are casting from one integer or pointer type to another of
11572 // the same size. Instead of casting the pointer before
11573 // the store, cast the value to be stored.
11575 Value *SIOp0 = SI.getOperand(0);
11576 Instruction::CastOps opcode = Instruction::BitCast;
11577 const Type* CastSrcTy = SIOp0->getType();
11578 const Type* CastDstTy = SrcPTy;
11579 if (isa<PointerType>(CastDstTy)) {
11580 if (CastSrcTy->isInteger())
11581 opcode = Instruction::IntToPtr;
11582 } else if (isa<IntegerType>(CastDstTy)) {
11583 if (isa<PointerType>(SIOp0->getType()))
11584 opcode = Instruction::PtrToInt;
11587 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11588 // emit a GEP to index into its first field.
11589 if (!NewGEPIndices.empty())
11590 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11591 NewGEPIndices.end());
11593 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11594 SIOp0->getName()+".c");
11595 return new StoreInst(NewCast, CastOp);
11598 /// equivalentAddressValues - Test if A and B will obviously have the same
11599 /// value. This includes recognizing that %t0 and %t1 will have the same
11600 /// value in code like this:
11601 /// %t0 = getelementptr \@a, 0, 3
11602 /// store i32 0, i32* %t0
11603 /// %t1 = getelementptr \@a, 0, 3
11604 /// %t2 = load i32* %t1
11606 static bool equivalentAddressValues(Value *A, Value *B) {
11607 // Test if the values are trivially equivalent.
11608 if (A == B) return true;
11610 // Test if the values come form identical arithmetic instructions.
11611 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11612 // its only used to compare two uses within the same basic block, which
11613 // means that they'll always either have the same value or one of them
11614 // will have an undefined value.
11615 if (isa<BinaryOperator>(A) ||
11616 isa<CastInst>(A) ||
11618 isa<GetElementPtrInst>(A))
11619 if (Instruction *BI = dyn_cast<Instruction>(B))
11620 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
11623 // Otherwise they may not be equivalent.
11627 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11628 // return the llvm.dbg.declare.
11629 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11630 if (!V->hasNUses(2))
11632 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11634 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11636 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11637 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11644 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11645 Value *Val = SI.getOperand(0);
11646 Value *Ptr = SI.getOperand(1);
11648 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11649 EraseInstFromFunction(SI);
11654 // If the RHS is an alloca with a single use, zapify the store, making the
11656 // If the RHS is an alloca with a two uses, the other one being a
11657 // llvm.dbg.declare, zapify the store and the declare, making the
11658 // alloca dead. We must do this to prevent declare's from affecting
11660 if (!SI.isVolatile()) {
11661 if (Ptr->hasOneUse()) {
11662 if (isa<AllocaInst>(Ptr)) {
11663 EraseInstFromFunction(SI);
11667 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11668 if (isa<AllocaInst>(GEP->getOperand(0))) {
11669 if (GEP->getOperand(0)->hasOneUse()) {
11670 EraseInstFromFunction(SI);
11674 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11675 EraseInstFromFunction(*DI);
11676 EraseInstFromFunction(SI);
11683 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11684 EraseInstFromFunction(*DI);
11685 EraseInstFromFunction(SI);
11691 // Attempt to improve the alignment.
11693 unsigned KnownAlign =
11694 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11696 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11697 SI.getAlignment()))
11698 SI.setAlignment(KnownAlign);
11701 // Do really simple DSE, to catch cases where there are several consecutive
11702 // stores to the same location, separated by a few arithmetic operations. This
11703 // situation often occurs with bitfield accesses.
11704 BasicBlock::iterator BBI = &SI;
11705 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11708 // Don't count debug info directives, lest they affect codegen,
11709 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11710 // It is necessary for correctness to skip those that feed into a
11711 // llvm.dbg.declare, as these are not present when debugging is off.
11712 if (isa<DbgInfoIntrinsic>(BBI) ||
11713 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11718 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11719 // Prev store isn't volatile, and stores to the same location?
11720 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11721 SI.getOperand(1))) {
11724 EraseInstFromFunction(*PrevSI);
11730 // If this is a load, we have to stop. However, if the loaded value is from
11731 // the pointer we're loading and is producing the pointer we're storing,
11732 // then *this* store is dead (X = load P; store X -> P).
11733 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11734 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11735 !SI.isVolatile()) {
11736 EraseInstFromFunction(SI);
11740 // Otherwise, this is a load from some other location. Stores before it
11741 // may not be dead.
11745 // Don't skip over loads or things that can modify memory.
11746 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11751 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11753 // store X, null -> turns into 'unreachable' in SimplifyCFG
11754 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
11755 if (!isa<UndefValue>(Val)) {
11756 SI.setOperand(0, UndefValue::get(Val->getType()));
11757 if (Instruction *U = dyn_cast<Instruction>(Val))
11758 Worklist.Add(U); // Dropped a use.
11761 return 0; // Do not modify these!
11764 // store undef, Ptr -> noop
11765 if (isa<UndefValue>(Val)) {
11766 EraseInstFromFunction(SI);
11771 // If the pointer destination is a cast, see if we can fold the cast into the
11773 if (isa<CastInst>(Ptr))
11774 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11776 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11778 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11782 // If this store is the last instruction in the basic block (possibly
11783 // excepting debug info instructions and the pointer bitcasts that feed
11784 // into them), and if the block ends with an unconditional branch, try
11785 // to move it to the successor block.
11789 } while (isa<DbgInfoIntrinsic>(BBI) ||
11790 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11791 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11792 if (BI->isUnconditional())
11793 if (SimplifyStoreAtEndOfBlock(SI))
11794 return 0; // xform done!
11799 /// SimplifyStoreAtEndOfBlock - Turn things like:
11800 /// if () { *P = v1; } else { *P = v2 }
11801 /// into a phi node with a store in the successor.
11803 /// Simplify things like:
11804 /// *P = v1; if () { *P = v2; }
11805 /// into a phi node with a store in the successor.
11807 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11808 BasicBlock *StoreBB = SI.getParent();
11810 // Check to see if the successor block has exactly two incoming edges. If
11811 // so, see if the other predecessor contains a store to the same location.
11812 // if so, insert a PHI node (if needed) and move the stores down.
11813 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11815 // Determine whether Dest has exactly two predecessors and, if so, compute
11816 // the other predecessor.
11817 pred_iterator PI = pred_begin(DestBB);
11818 BasicBlock *OtherBB = 0;
11819 if (*PI != StoreBB)
11822 if (PI == pred_end(DestBB))
11825 if (*PI != StoreBB) {
11830 if (++PI != pred_end(DestBB))
11833 // Bail out if all the relevant blocks aren't distinct (this can happen,
11834 // for example, if SI is in an infinite loop)
11835 if (StoreBB == DestBB || OtherBB == DestBB)
11838 // Verify that the other block ends in a branch and is not otherwise empty.
11839 BasicBlock::iterator BBI = OtherBB->getTerminator();
11840 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11841 if (!OtherBr || BBI == OtherBB->begin())
11844 // If the other block ends in an unconditional branch, check for the 'if then
11845 // else' case. there is an instruction before the branch.
11846 StoreInst *OtherStore = 0;
11847 if (OtherBr->isUnconditional()) {
11849 // Skip over debugging info.
11850 while (isa<DbgInfoIntrinsic>(BBI) ||
11851 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11852 if (BBI==OtherBB->begin())
11856 // If this isn't a store, or isn't a store to the same location, bail out.
11857 OtherStore = dyn_cast<StoreInst>(BBI);
11858 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11861 // Otherwise, the other block ended with a conditional branch. If one of the
11862 // destinations is StoreBB, then we have the if/then case.
11863 if (OtherBr->getSuccessor(0) != StoreBB &&
11864 OtherBr->getSuccessor(1) != StoreBB)
11867 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11868 // if/then triangle. See if there is a store to the same ptr as SI that
11869 // lives in OtherBB.
11871 // Check to see if we find the matching store.
11872 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11873 if (OtherStore->getOperand(1) != SI.getOperand(1))
11877 // If we find something that may be using or overwriting the stored
11878 // value, or if we run out of instructions, we can't do the xform.
11879 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11880 BBI == OtherBB->begin())
11884 // In order to eliminate the store in OtherBr, we have to
11885 // make sure nothing reads or overwrites the stored value in
11887 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11888 // FIXME: This should really be AA driven.
11889 if (I->mayReadFromMemory() || I->mayWriteToMemory())
11894 // Insert a PHI node now if we need it.
11895 Value *MergedVal = OtherStore->getOperand(0);
11896 if (MergedVal != SI.getOperand(0)) {
11897 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11898 PN->reserveOperandSpace(2);
11899 PN->addIncoming(SI.getOperand(0), SI.getParent());
11900 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11901 MergedVal = InsertNewInstBefore(PN, DestBB->front());
11904 // Advance to a place where it is safe to insert the new store and
11906 BBI = DestBB->getFirstNonPHI();
11907 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11908 OtherStore->isVolatile()), *BBI);
11910 // Nuke the old stores.
11911 EraseInstFromFunction(SI);
11912 EraseInstFromFunction(*OtherStore);
11918 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11919 // Change br (not X), label True, label False to: br X, label False, True
11921 BasicBlock *TrueDest;
11922 BasicBlock *FalseDest;
11923 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11924 !isa<Constant>(X)) {
11925 // Swap Destinations and condition...
11926 BI.setCondition(X);
11927 BI.setSuccessor(0, FalseDest);
11928 BI.setSuccessor(1, TrueDest);
11932 // Cannonicalize fcmp_one -> fcmp_oeq
11933 FCmpInst::Predicate FPred; Value *Y;
11934 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11935 TrueDest, FalseDest)) &&
11936 BI.getCondition()->hasOneUse())
11937 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11938 FPred == FCmpInst::FCMP_OGE) {
11939 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
11940 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
11942 // Swap Destinations and condition.
11943 BI.setSuccessor(0, FalseDest);
11944 BI.setSuccessor(1, TrueDest);
11945 Worklist.Add(Cond);
11949 // Cannonicalize icmp_ne -> icmp_eq
11950 ICmpInst::Predicate IPred;
11951 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11952 TrueDest, FalseDest)) &&
11953 BI.getCondition()->hasOneUse())
11954 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11955 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11956 IPred == ICmpInst::ICMP_SGE) {
11957 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
11958 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
11959 // Swap Destinations and condition.
11960 BI.setSuccessor(0, FalseDest);
11961 BI.setSuccessor(1, TrueDest);
11962 Worklist.Add(Cond);
11969 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11970 Value *Cond = SI.getCondition();
11971 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11972 if (I->getOpcode() == Instruction::Add)
11973 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11974 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11975 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11977 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11979 SI.setOperand(0, I->getOperand(0));
11987 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
11988 Value *Agg = EV.getAggregateOperand();
11990 if (!EV.hasIndices())
11991 return ReplaceInstUsesWith(EV, Agg);
11993 if (Constant *C = dyn_cast<Constant>(Agg)) {
11994 if (isa<UndefValue>(C))
11995 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11997 if (isa<ConstantAggregateZero>(C))
11998 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12000 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12001 // Extract the element indexed by the first index out of the constant
12002 Value *V = C->getOperand(*EV.idx_begin());
12003 if (EV.getNumIndices() > 1)
12004 // Extract the remaining indices out of the constant indexed by the
12006 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12008 return ReplaceInstUsesWith(EV, V);
12010 return 0; // Can't handle other constants
12012 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12013 // We're extracting from an insertvalue instruction, compare the indices
12014 const unsigned *exti, *exte, *insi, *inse;
12015 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12016 exte = EV.idx_end(), inse = IV->idx_end();
12017 exti != exte && insi != inse;
12019 if (*insi != *exti)
12020 // The insert and extract both reference distinctly different elements.
12021 // This means the extract is not influenced by the insert, and we can
12022 // replace the aggregate operand of the extract with the aggregate
12023 // operand of the insert. i.e., replace
12024 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12025 // %E = extractvalue { i32, { i32 } } %I, 0
12027 // %E = extractvalue { i32, { i32 } } %A, 0
12028 return ExtractValueInst::Create(IV->getAggregateOperand(),
12029 EV.idx_begin(), EV.idx_end());
12031 if (exti == exte && insi == inse)
12032 // Both iterators are at the end: Index lists are identical. Replace
12033 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12034 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12036 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12037 if (exti == exte) {
12038 // The extract list is a prefix of the insert list. i.e. replace
12039 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12040 // %E = extractvalue { i32, { i32 } } %I, 1
12042 // %X = extractvalue { i32, { i32 } } %A, 1
12043 // %E = insertvalue { i32 } %X, i32 42, 0
12044 // by switching the order of the insert and extract (though the
12045 // insertvalue should be left in, since it may have other uses).
12046 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12047 EV.idx_begin(), EV.idx_end());
12048 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12052 // The insert list is a prefix of the extract list
12053 // We can simply remove the common indices from the extract and make it
12054 // operate on the inserted value instead of the insertvalue result.
12056 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12057 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12059 // %E extractvalue { i32 } { i32 42 }, 0
12060 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12063 // Can't simplify extracts from other values. Note that nested extracts are
12064 // already simplified implicitely by the above (extract ( extract (insert) )
12065 // will be translated into extract ( insert ( extract ) ) first and then just
12066 // the value inserted, if appropriate).
12070 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12071 /// is to leave as a vector operation.
12072 static bool CheapToScalarize(Value *V, bool isConstant) {
12073 if (isa<ConstantAggregateZero>(V))
12075 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12076 if (isConstant) return true;
12077 // If all elts are the same, we can extract.
12078 Constant *Op0 = C->getOperand(0);
12079 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12080 if (C->getOperand(i) != Op0)
12084 Instruction *I = dyn_cast<Instruction>(V);
12085 if (!I) return false;
12087 // Insert element gets simplified to the inserted element or is deleted if
12088 // this is constant idx extract element and its a constant idx insertelt.
12089 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12090 isa<ConstantInt>(I->getOperand(2)))
12092 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12094 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12095 if (BO->hasOneUse() &&
12096 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12097 CheapToScalarize(BO->getOperand(1), isConstant)))
12099 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12100 if (CI->hasOneUse() &&
12101 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12102 CheapToScalarize(CI->getOperand(1), isConstant)))
12108 /// Read and decode a shufflevector mask.
12110 /// It turns undef elements into values that are larger than the number of
12111 /// elements in the input.
12112 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12113 unsigned NElts = SVI->getType()->getNumElements();
12114 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12115 return std::vector<unsigned>(NElts, 0);
12116 if (isa<UndefValue>(SVI->getOperand(2)))
12117 return std::vector<unsigned>(NElts, 2*NElts);
12119 std::vector<unsigned> Result;
12120 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12121 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12122 if (isa<UndefValue>(*i))
12123 Result.push_back(NElts*2); // undef -> 8
12125 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12129 /// FindScalarElement - Given a vector and an element number, see if the scalar
12130 /// value is already around as a register, for example if it were inserted then
12131 /// extracted from the vector.
12132 static Value *FindScalarElement(Value *V, unsigned EltNo,
12133 LLVMContext *Context) {
12134 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12135 const VectorType *PTy = cast<VectorType>(V->getType());
12136 unsigned Width = PTy->getNumElements();
12137 if (EltNo >= Width) // Out of range access.
12138 return UndefValue::get(PTy->getElementType());
12140 if (isa<UndefValue>(V))
12141 return UndefValue::get(PTy->getElementType());
12142 else if (isa<ConstantAggregateZero>(V))
12143 return Constant::getNullValue(PTy->getElementType());
12144 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12145 return CP->getOperand(EltNo);
12146 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12147 // If this is an insert to a variable element, we don't know what it is.
12148 if (!isa<ConstantInt>(III->getOperand(2)))
12150 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12152 // If this is an insert to the element we are looking for, return the
12154 if (EltNo == IIElt)
12155 return III->getOperand(1);
12157 // Otherwise, the insertelement doesn't modify the value, recurse on its
12159 return FindScalarElement(III->getOperand(0), EltNo, Context);
12160 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12161 unsigned LHSWidth =
12162 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12163 unsigned InEl = getShuffleMask(SVI)[EltNo];
12164 if (InEl < LHSWidth)
12165 return FindScalarElement(SVI->getOperand(0), InEl, Context);
12166 else if (InEl < LHSWidth*2)
12167 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12169 return UndefValue::get(PTy->getElementType());
12172 // Otherwise, we don't know.
12176 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12177 // If vector val is undef, replace extract with scalar undef.
12178 if (isa<UndefValue>(EI.getOperand(0)))
12179 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12181 // If vector val is constant 0, replace extract with scalar 0.
12182 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12183 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12185 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12186 // If vector val is constant with all elements the same, replace EI with
12187 // that element. When the elements are not identical, we cannot replace yet
12188 // (we do that below, but only when the index is constant).
12189 Constant *op0 = C->getOperand(0);
12190 for (unsigned i = 1; i != C->getNumOperands(); ++i)
12191 if (C->getOperand(i) != op0) {
12196 return ReplaceInstUsesWith(EI, op0);
12199 // If extracting a specified index from the vector, see if we can recursively
12200 // find a previously computed scalar that was inserted into the vector.
12201 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12202 unsigned IndexVal = IdxC->getZExtValue();
12203 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
12205 // If this is extracting an invalid index, turn this into undef, to avoid
12206 // crashing the code below.
12207 if (IndexVal >= VectorWidth)
12208 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12210 // This instruction only demands the single element from the input vector.
12211 // If the input vector has a single use, simplify it based on this use
12213 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12214 APInt UndefElts(VectorWidth, 0);
12215 APInt DemandedMask(VectorWidth, 1 << IndexVal);
12216 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12217 DemandedMask, UndefElts)) {
12218 EI.setOperand(0, V);
12223 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12224 return ReplaceInstUsesWith(EI, Elt);
12226 // If the this extractelement is directly using a bitcast from a vector of
12227 // the same number of elements, see if we can find the source element from
12228 // it. In this case, we will end up needing to bitcast the scalars.
12229 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12230 if (const VectorType *VT =
12231 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12232 if (VT->getNumElements() == VectorWidth)
12233 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12234 IndexVal, Context))
12235 return new BitCastInst(Elt, EI.getType());
12239 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12240 // Push extractelement into predecessor operation if legal and
12241 // profitable to do so
12242 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12243 if (I->hasOneUse() &&
12244 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12246 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12247 EI.getName()+".lhs");
12249 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12250 EI.getName()+".rhs");
12251 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12253 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12254 // Extracting the inserted element?
12255 if (IE->getOperand(2) == EI.getOperand(1))
12256 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12257 // If the inserted and extracted elements are constants, they must not
12258 // be the same value, extract from the pre-inserted value instead.
12259 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
12260 Worklist.AddValue(EI.getOperand(0));
12261 EI.setOperand(0, IE->getOperand(0));
12264 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12265 // If this is extracting an element from a shufflevector, figure out where
12266 // it came from and extract from the appropriate input element instead.
12267 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12268 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12270 unsigned LHSWidth =
12271 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12273 if (SrcIdx < LHSWidth)
12274 Src = SVI->getOperand(0);
12275 else if (SrcIdx < LHSWidth*2) {
12276 SrcIdx -= LHSWidth;
12277 Src = SVI->getOperand(1);
12279 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12281 return ExtractElementInst::Create(Src,
12282 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12286 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12291 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12292 /// elements from either LHS or RHS, return the shuffle mask and true.
12293 /// Otherwise, return false.
12294 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12295 std::vector<Constant*> &Mask,
12296 LLVMContext *Context) {
12297 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12298 "Invalid CollectSingleShuffleElements");
12299 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12301 if (isa<UndefValue>(V)) {
12302 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12304 } else if (V == LHS) {
12305 for (unsigned i = 0; i != NumElts; ++i)
12306 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12308 } else if (V == RHS) {
12309 for (unsigned i = 0; i != NumElts; ++i)
12310 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12312 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12313 // If this is an insert of an extract from some other vector, include it.
12314 Value *VecOp = IEI->getOperand(0);
12315 Value *ScalarOp = IEI->getOperand(1);
12316 Value *IdxOp = IEI->getOperand(2);
12318 if (!isa<ConstantInt>(IdxOp))
12320 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12322 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12323 // Okay, we can handle this if the vector we are insertinting into is
12324 // transitively ok.
12325 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12326 // If so, update the mask to reflect the inserted undef.
12327 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12330 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12331 if (isa<ConstantInt>(EI->getOperand(1)) &&
12332 EI->getOperand(0)->getType() == V->getType()) {
12333 unsigned ExtractedIdx =
12334 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12336 // This must be extracting from either LHS or RHS.
12337 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12338 // Okay, we can handle this if the vector we are insertinting into is
12339 // transitively ok.
12340 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12341 // If so, update the mask to reflect the inserted value.
12342 if (EI->getOperand(0) == LHS) {
12343 Mask[InsertedIdx % NumElts] =
12344 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12346 assert(EI->getOperand(0) == RHS);
12347 Mask[InsertedIdx % NumElts] =
12348 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12357 // TODO: Handle shufflevector here!
12362 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12363 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12364 /// that computes V and the LHS value of the shuffle.
12365 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12366 Value *&RHS, LLVMContext *Context) {
12367 assert(isa<VectorType>(V->getType()) &&
12368 (RHS == 0 || V->getType() == RHS->getType()) &&
12369 "Invalid shuffle!");
12370 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12372 if (isa<UndefValue>(V)) {
12373 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12375 } else if (isa<ConstantAggregateZero>(V)) {
12376 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12378 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12379 // If this is an insert of an extract from some other vector, include it.
12380 Value *VecOp = IEI->getOperand(0);
12381 Value *ScalarOp = IEI->getOperand(1);
12382 Value *IdxOp = IEI->getOperand(2);
12384 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12385 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12386 EI->getOperand(0)->getType() == V->getType()) {
12387 unsigned ExtractedIdx =
12388 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12389 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12391 // Either the extracted from or inserted into vector must be RHSVec,
12392 // otherwise we'd end up with a shuffle of three inputs.
12393 if (EI->getOperand(0) == RHS || RHS == 0) {
12394 RHS = EI->getOperand(0);
12395 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12396 Mask[InsertedIdx % NumElts] =
12397 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12401 if (VecOp == RHS) {
12402 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12404 // Everything but the extracted element is replaced with the RHS.
12405 for (unsigned i = 0; i != NumElts; ++i) {
12406 if (i != InsertedIdx)
12407 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12412 // If this insertelement is a chain that comes from exactly these two
12413 // vectors, return the vector and the effective shuffle.
12414 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12416 return EI->getOperand(0);
12421 // TODO: Handle shufflevector here!
12423 // Otherwise, can't do anything fancy. Return an identity vector.
12424 for (unsigned i = 0; i != NumElts; ++i)
12425 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12429 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12430 Value *VecOp = IE.getOperand(0);
12431 Value *ScalarOp = IE.getOperand(1);
12432 Value *IdxOp = IE.getOperand(2);
12434 // Inserting an undef or into an undefined place, remove this.
12435 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12436 ReplaceInstUsesWith(IE, VecOp);
12438 // If the inserted element was extracted from some other vector, and if the
12439 // indexes are constant, try to turn this into a shufflevector operation.
12440 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12441 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12442 EI->getOperand(0)->getType() == IE.getType()) {
12443 unsigned NumVectorElts = IE.getType()->getNumElements();
12444 unsigned ExtractedIdx =
12445 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12446 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12448 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12449 return ReplaceInstUsesWith(IE, VecOp);
12451 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12452 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12454 // If we are extracting a value from a vector, then inserting it right
12455 // back into the same place, just use the input vector.
12456 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12457 return ReplaceInstUsesWith(IE, VecOp);
12459 // We could theoretically do this for ANY input. However, doing so could
12460 // turn chains of insertelement instructions into a chain of shufflevector
12461 // instructions, and right now we do not merge shufflevectors. As such,
12462 // only do this in a situation where it is clear that there is benefit.
12463 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12464 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12465 // the values of VecOp, except then one read from EIOp0.
12466 // Build a new shuffle mask.
12467 std::vector<Constant*> Mask;
12468 if (isa<UndefValue>(VecOp))
12469 Mask.assign(NumVectorElts, UndefValue::get(Type::getInt32Ty(*Context)));
12471 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12472 Mask.assign(NumVectorElts, ConstantInt::get(Type::getInt32Ty(*Context),
12475 Mask[InsertedIdx] =
12476 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12477 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12478 ConstantVector::get(Mask));
12481 // If this insertelement isn't used by some other insertelement, turn it
12482 // (and any insertelements it points to), into one big shuffle.
12483 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12484 std::vector<Constant*> Mask;
12486 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12487 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12488 // We now have a shuffle of LHS, RHS, Mask.
12489 return new ShuffleVectorInst(LHS, RHS,
12490 ConstantVector::get(Mask));
12495 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12496 APInt UndefElts(VWidth, 0);
12497 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12498 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12505 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12506 Value *LHS = SVI.getOperand(0);
12507 Value *RHS = SVI.getOperand(1);
12508 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12510 bool MadeChange = false;
12512 // Undefined shuffle mask -> undefined value.
12513 if (isa<UndefValue>(SVI.getOperand(2)))
12514 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12516 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12518 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12521 APInt UndefElts(VWidth, 0);
12522 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12523 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12524 LHS = SVI.getOperand(0);
12525 RHS = SVI.getOperand(1);
12529 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12530 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12531 if (LHS == RHS || isa<UndefValue>(LHS)) {
12532 if (isa<UndefValue>(LHS) && LHS == RHS) {
12533 // shuffle(undef,undef,mask) -> undef.
12534 return ReplaceInstUsesWith(SVI, LHS);
12537 // Remap any references to RHS to use LHS.
12538 std::vector<Constant*> Elts;
12539 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12540 if (Mask[i] >= 2*e)
12541 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12543 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12544 (Mask[i] < e && isa<UndefValue>(LHS))) {
12545 Mask[i] = 2*e; // Turn into undef.
12546 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12548 Mask[i] = Mask[i] % e; // Force to LHS.
12549 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12553 SVI.setOperand(0, SVI.getOperand(1));
12554 SVI.setOperand(1, UndefValue::get(RHS->getType()));
12555 SVI.setOperand(2, ConstantVector::get(Elts));
12556 LHS = SVI.getOperand(0);
12557 RHS = SVI.getOperand(1);
12561 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12562 bool isLHSID = true, isRHSID = true;
12564 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12565 if (Mask[i] >= e*2) continue; // Ignore undef values.
12566 // Is this an identity shuffle of the LHS value?
12567 isLHSID &= (Mask[i] == i);
12569 // Is this an identity shuffle of the RHS value?
12570 isRHSID &= (Mask[i]-e == i);
12573 // Eliminate identity shuffles.
12574 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12575 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12577 // If the LHS is a shufflevector itself, see if we can combine it with this
12578 // one without producing an unusual shuffle. Here we are really conservative:
12579 // we are absolutely afraid of producing a shuffle mask not in the input
12580 // program, because the code gen may not be smart enough to turn a merged
12581 // shuffle into two specific shuffles: it may produce worse code. As such,
12582 // we only merge two shuffles if the result is one of the two input shuffle
12583 // masks. In this case, merging the shuffles just removes one instruction,
12584 // which we know is safe. This is good for things like turning:
12585 // (splat(splat)) -> splat.
12586 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12587 if (isa<UndefValue>(RHS)) {
12588 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12590 std::vector<unsigned> NewMask;
12591 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12592 if (Mask[i] >= 2*e)
12593 NewMask.push_back(2*e);
12595 NewMask.push_back(LHSMask[Mask[i]]);
12597 // If the result mask is equal to the src shuffle or this shuffle mask, do
12598 // the replacement.
12599 if (NewMask == LHSMask || NewMask == Mask) {
12600 unsigned LHSInNElts =
12601 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12602 std::vector<Constant*> Elts;
12603 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12604 if (NewMask[i] >= LHSInNElts*2) {
12605 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12607 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
12610 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12611 LHSSVI->getOperand(1),
12612 ConstantVector::get(Elts));
12617 return MadeChange ? &SVI : 0;
12623 /// TryToSinkInstruction - Try to move the specified instruction from its
12624 /// current block into the beginning of DestBlock, which can only happen if it's
12625 /// safe to move the instruction past all of the instructions between it and the
12626 /// end of its block.
12627 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12628 assert(I->hasOneUse() && "Invariants didn't hold!");
12630 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12631 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12634 // Do not sink alloca instructions out of the entry block.
12635 if (isa<AllocaInst>(I) && I->getParent() ==
12636 &DestBlock->getParent()->getEntryBlock())
12639 // We can only sink load instructions if there is nothing between the load and
12640 // the end of block that could change the value.
12641 if (I->mayReadFromMemory()) {
12642 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12644 if (Scan->mayWriteToMemory())
12648 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12650 CopyPrecedingStopPoint(I, InsertPos);
12651 I->moveBefore(InsertPos);
12657 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12658 /// all reachable code to the worklist.
12660 /// This has a couple of tricks to make the code faster and more powerful. In
12661 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12662 /// them to the worklist (this significantly speeds up instcombine on code where
12663 /// many instructions are dead or constant). Additionally, if we find a branch
12664 /// whose condition is a known constant, we only visit the reachable successors.
12666 static void AddReachableCodeToWorklist(BasicBlock *BB,
12667 SmallPtrSet<BasicBlock*, 64> &Visited,
12669 const TargetData *TD) {
12670 SmallVector<BasicBlock*, 256> Worklist;
12671 Worklist.push_back(BB);
12673 while (!Worklist.empty()) {
12674 BB = Worklist.back();
12675 Worklist.pop_back();
12677 // We have now visited this block! If we've already been here, ignore it.
12678 if (!Visited.insert(BB)) continue;
12680 DbgInfoIntrinsic *DBI_Prev = NULL;
12681 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12682 Instruction *Inst = BBI++;
12684 // DCE instruction if trivially dead.
12685 if (isInstructionTriviallyDead(Inst)) {
12687 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
12688 Inst->eraseFromParent();
12692 // ConstantProp instruction if trivially constant.
12693 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12694 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12696 Inst->replaceAllUsesWith(C);
12698 Inst->eraseFromParent();
12702 // If there are two consecutive llvm.dbg.stoppoint calls then
12703 // it is likely that the optimizer deleted code in between these
12705 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12708 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12709 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12710 IC.Worklist.Remove(DBI_Prev);
12711 DBI_Prev->eraseFromParent();
12713 DBI_Prev = DBI_Next;
12718 IC.Worklist.Add(Inst);
12721 // Recursively visit successors. If this is a branch or switch on a
12722 // constant, only visit the reachable successor.
12723 TerminatorInst *TI = BB->getTerminator();
12724 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12725 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12726 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12727 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12728 Worklist.push_back(ReachableBB);
12731 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12732 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12733 // See if this is an explicit destination.
12734 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12735 if (SI->getCaseValue(i) == Cond) {
12736 BasicBlock *ReachableBB = SI->getSuccessor(i);
12737 Worklist.push_back(ReachableBB);
12741 // Otherwise it is the default destination.
12742 Worklist.push_back(SI->getSuccessor(0));
12747 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12748 Worklist.push_back(TI->getSuccessor(i));
12752 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12753 MadeIRChange = false;
12754 TD = getAnalysisIfAvailable<TargetData>();
12756 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12757 << F.getNameStr() << "\n");
12760 // Do a depth-first traversal of the function, populate the worklist with
12761 // the reachable instructions. Ignore blocks that are not reachable. Keep
12762 // track of which blocks we visit.
12763 SmallPtrSet<BasicBlock*, 64> Visited;
12764 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12766 // Do a quick scan over the function. If we find any blocks that are
12767 // unreachable, remove any instructions inside of them. This prevents
12768 // the instcombine code from having to deal with some bad special cases.
12769 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12770 if (!Visited.count(BB)) {
12771 Instruction *Term = BB->getTerminator();
12772 while (Term != BB->begin()) { // Remove instrs bottom-up
12773 BasicBlock::iterator I = Term; --I;
12775 DEBUG(errs() << "IC: DCE: " << *I << '\n');
12776 // A debug intrinsic shouldn't force another iteration if we weren't
12777 // going to do one without it.
12778 if (!isa<DbgInfoIntrinsic>(I)) {
12780 MadeIRChange = true;
12782 if (!I->use_empty())
12783 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12784 I->eraseFromParent();
12789 while (!Worklist.isEmpty()) {
12790 Instruction *I = Worklist.RemoveOne();
12791 if (I == 0) continue; // skip null values.
12793 // Check to see if we can DCE the instruction.
12794 if (isInstructionTriviallyDead(I)) {
12795 DEBUG(errs() << "IC: DCE: " << *I << '\n');
12796 EraseInstFromFunction(*I);
12798 MadeIRChange = true;
12802 // Instruction isn't dead, see if we can constant propagate it.
12803 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12804 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
12806 // Add operands to the worklist.
12807 ReplaceInstUsesWith(*I, C);
12809 EraseInstFromFunction(*I);
12810 MadeIRChange = true;
12815 // See if we can constant fold its operands.
12816 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
12817 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
12818 if (Constant *NewC = ConstantFoldConstantExpression(CE,
12819 F.getContext(), TD))
12822 MadeIRChange = true;
12826 // See if we can trivially sink this instruction to a successor basic block.
12827 if (I->hasOneUse()) {
12828 BasicBlock *BB = I->getParent();
12829 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12830 if (UserParent != BB) {
12831 bool UserIsSuccessor = false;
12832 // See if the user is one of our successors.
12833 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12834 if (*SI == UserParent) {
12835 UserIsSuccessor = true;
12839 // If the user is one of our immediate successors, and if that successor
12840 // only has us as a predecessors (we'd have to split the critical edge
12841 // otherwise), we can keep going.
12842 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12843 next(pred_begin(UserParent)) == pred_end(UserParent))
12844 // Okay, the CFG is simple enough, try to sink this instruction.
12845 MadeIRChange |= TryToSinkInstruction(I, UserParent);
12849 // Now that we have an instruction, try combining it to simplify it.
12850 Builder->SetInsertPoint(I->getParent(), I);
12855 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
12857 if (Instruction *Result = visit(*I)) {
12859 // Should we replace the old instruction with a new one?
12861 DEBUG(errs() << "IC: Old = " << *I << '\n'
12862 << " New = " << *Result << '\n');
12864 // Everything uses the new instruction now.
12865 I->replaceAllUsesWith(Result);
12867 // Push the new instruction and any users onto the worklist.
12868 Worklist.Add(Result);
12869 Worklist.AddUsersToWorkList(*Result);
12871 // Move the name to the new instruction first.
12872 Result->takeName(I);
12874 // Insert the new instruction into the basic block...
12875 BasicBlock *InstParent = I->getParent();
12876 BasicBlock::iterator InsertPos = I;
12878 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12879 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12882 InstParent->getInstList().insert(InsertPos, Result);
12884 EraseInstFromFunction(*I);
12887 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12888 << " New = " << *I << '\n');
12891 // If the instruction was modified, it's possible that it is now dead.
12892 // if so, remove it.
12893 if (isInstructionTriviallyDead(I)) {
12894 EraseInstFromFunction(*I);
12897 Worklist.AddUsersToWorkList(*I);
12900 MadeIRChange = true;
12905 return MadeIRChange;
12909 bool InstCombiner::runOnFunction(Function &F) {
12910 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12911 Context = &F.getContext();
12914 /// Builder - This is an IRBuilder that automatically inserts new
12915 /// instructions into the worklist when they are created.
12916 IRBuilder<true, ConstantFolder, InstCombineIRInserter>
12917 TheBuilder(F.getContext(), ConstantFolder(F.getContext()),
12918 InstCombineIRInserter(Worklist));
12919 Builder = &TheBuilder;
12921 bool EverMadeChange = false;
12923 // Iterate while there is work to do.
12924 unsigned Iteration = 0;
12925 while (DoOneIteration(F, Iteration++))
12926 EverMadeChange = true;
12929 return EverMadeChange;
12932 FunctionPass *llvm::createInstructionCombiningPass() {
12933 return new InstCombiner();