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/TargetFolder.h"
60 #include "llvm/Support/raw_ostream.h"
61 #include "llvm/ADT/DenseMap.h"
62 #include "llvm/ADT/SmallVector.h"
63 #include "llvm/ADT/SmallPtrSet.h"
64 #include "llvm/ADT/Statistic.h"
65 #include "llvm/ADT/STLExtras.h"
69 using namespace llvm::PatternMatch;
71 STATISTIC(NumCombined , "Number of insts combined");
72 STATISTIC(NumConstProp, "Number of constant folds");
73 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
74 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
75 STATISTIC(NumSunkInst , "Number of instructions sunk");
78 /// InstCombineWorklist - This is the worklist management logic for
80 class InstCombineWorklist {
81 SmallVector<Instruction*, 256> Worklist;
82 DenseMap<Instruction*, unsigned> WorklistMap;
84 void operator=(const InstCombineWorklist&RHS); // DO NOT IMPLEMENT
85 InstCombineWorklist(const InstCombineWorklist&); // DO NOT IMPLEMENT
87 InstCombineWorklist() {}
89 bool isEmpty() const { return Worklist.empty(); }
91 /// Add - Add the specified instruction to the worklist if it isn't already
93 void Add(Instruction *I) {
94 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second) {
95 DEBUG(errs() << "IC: ADD: " << *I << '\n');
96 Worklist.push_back(I);
100 void AddValue(Value *V) {
101 if (Instruction *I = dyn_cast<Instruction>(V))
105 /// AddInitialGroup - Add the specified batch of stuff in reverse order.
106 /// which should only be done when the worklist is empty and when the group
107 /// has no duplicates.
108 void AddInitialGroup(Instruction *const *List, unsigned NumEntries) {
109 assert(Worklist.empty() && "Worklist must be empty to add initial group");
110 Worklist.reserve(NumEntries+16);
111 DEBUG(errs() << "IC: ADDING: " << NumEntries << " instrs to worklist\n");
112 for (; NumEntries; --NumEntries) {
113 Instruction *I = List[NumEntries-1];
114 WorklistMap.insert(std::make_pair(I, Worklist.size()));
115 Worklist.push_back(I);
119 // Remove - remove I from the worklist if it exists.
120 void Remove(Instruction *I) {
121 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
122 if (It == WorklistMap.end()) return; // Not in worklist.
124 // Don't bother moving everything down, just null out the slot.
125 Worklist[It->second] = 0;
127 WorklistMap.erase(It);
130 Instruction *RemoveOne() {
131 Instruction *I = Worklist.back();
133 WorklistMap.erase(I);
137 /// AddUsersToWorkList - When an instruction is simplified, add all users of
138 /// the instruction to the work lists because they might get more simplified
141 void AddUsersToWorkList(Instruction &I) {
142 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
144 Add(cast<Instruction>(*UI));
148 /// Zap - check that the worklist is empty and nuke the backing store for
149 /// the map if it is large.
151 assert(WorklistMap.empty() && "Worklist empty, but map not?");
153 // Do an explicit clear, this shrinks the map if needed.
157 } // end anonymous namespace.
161 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
162 /// just like the normal insertion helper, but also adds any new instructions
163 /// to the instcombine worklist.
164 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
165 InstCombineWorklist &Worklist;
167 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
169 void InsertHelper(Instruction *I, const Twine &Name,
170 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
171 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
175 } // end anonymous namespace
179 class InstCombiner : public FunctionPass,
180 public InstVisitor<InstCombiner, Instruction*> {
182 bool MustPreserveLCSSA;
185 /// Worklist - All of the instructions that need to be simplified.
186 InstCombineWorklist Worklist;
188 /// Builder - This is an IRBuilder that automatically inserts new
189 /// instructions into the worklist when they are created.
190 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
193 static char ID; // Pass identification, replacement for typeid
194 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
196 LLVMContext *Context;
197 LLVMContext *getContext() const { return Context; }
200 virtual bool runOnFunction(Function &F);
202 bool DoOneIteration(Function &F, unsigned ItNum);
204 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
205 AU.addPreservedID(LCSSAID);
206 AU.setPreservesCFG();
209 TargetData *getTargetData() const { return TD; }
211 // Visitation implementation - Implement instruction combining for different
212 // instruction types. The semantics are as follows:
214 // null - No change was made
215 // I - Change was made, I is still valid, I may be dead though
216 // otherwise - Change was made, replace I with returned instruction
218 Instruction *visitAdd(BinaryOperator &I);
219 Instruction *visitFAdd(BinaryOperator &I);
220 Instruction *visitSub(BinaryOperator &I);
221 Instruction *visitFSub(BinaryOperator &I);
222 Instruction *visitMul(BinaryOperator &I);
223 Instruction *visitFMul(BinaryOperator &I);
224 Instruction *visitURem(BinaryOperator &I);
225 Instruction *visitSRem(BinaryOperator &I);
226 Instruction *visitFRem(BinaryOperator &I);
227 bool SimplifyDivRemOfSelect(BinaryOperator &I);
228 Instruction *commonRemTransforms(BinaryOperator &I);
229 Instruction *commonIRemTransforms(BinaryOperator &I);
230 Instruction *commonDivTransforms(BinaryOperator &I);
231 Instruction *commonIDivTransforms(BinaryOperator &I);
232 Instruction *visitUDiv(BinaryOperator &I);
233 Instruction *visitSDiv(BinaryOperator &I);
234 Instruction *visitFDiv(BinaryOperator &I);
235 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
236 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
237 Instruction *visitAnd(BinaryOperator &I);
238 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
239 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
240 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
241 Value *A, Value *B, Value *C);
242 Instruction *visitOr (BinaryOperator &I);
243 Instruction *visitXor(BinaryOperator &I);
244 Instruction *visitShl(BinaryOperator &I);
245 Instruction *visitAShr(BinaryOperator &I);
246 Instruction *visitLShr(BinaryOperator &I);
247 Instruction *commonShiftTransforms(BinaryOperator &I);
248 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
250 Instruction *visitFCmpInst(FCmpInst &I);
251 Instruction *visitICmpInst(ICmpInst &I);
252 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
253 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
256 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
257 ConstantInt *DivRHS);
259 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
260 ICmpInst::Predicate Cond, Instruction &I);
261 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
263 Instruction *commonCastTransforms(CastInst &CI);
264 Instruction *commonIntCastTransforms(CastInst &CI);
265 Instruction *commonPointerCastTransforms(CastInst &CI);
266 Instruction *visitTrunc(TruncInst &CI);
267 Instruction *visitZExt(ZExtInst &CI);
268 Instruction *visitSExt(SExtInst &CI);
269 Instruction *visitFPTrunc(FPTruncInst &CI);
270 Instruction *visitFPExt(CastInst &CI);
271 Instruction *visitFPToUI(FPToUIInst &FI);
272 Instruction *visitFPToSI(FPToSIInst &FI);
273 Instruction *visitUIToFP(CastInst &CI);
274 Instruction *visitSIToFP(CastInst &CI);
275 Instruction *visitPtrToInt(PtrToIntInst &CI);
276 Instruction *visitIntToPtr(IntToPtrInst &CI);
277 Instruction *visitBitCast(BitCastInst &CI);
278 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
280 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
281 Instruction *visitSelectInst(SelectInst &SI);
282 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
283 Instruction *visitCallInst(CallInst &CI);
284 Instruction *visitInvokeInst(InvokeInst &II);
285 Instruction *visitPHINode(PHINode &PN);
286 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
287 Instruction *visitAllocaInst(AllocaInst &AI);
288 Instruction *visitFreeInst(FreeInst &FI);
289 Instruction *visitFree(Instruction &FI);
290 Instruction *visitLoadInst(LoadInst &LI);
291 Instruction *visitStoreInst(StoreInst &SI);
292 Instruction *visitBranchInst(BranchInst &BI);
293 Instruction *visitSwitchInst(SwitchInst &SI);
294 Instruction *visitInsertElementInst(InsertElementInst &IE);
295 Instruction *visitExtractElementInst(ExtractElementInst &EI);
296 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
297 Instruction *visitExtractValueInst(ExtractValueInst &EV);
299 // visitInstruction - Specify what to return for unhandled instructions...
300 Instruction *visitInstruction(Instruction &I) { return 0; }
303 Instruction *visitCallSite(CallSite CS);
304 bool transformConstExprCastCall(CallSite CS);
305 Instruction *transformCallThroughTrampoline(CallSite CS);
306 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
307 bool DoXform = true);
308 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
309 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
313 // InsertNewInstBefore - insert an instruction New before instruction Old
314 // in the program. Add the new instruction to the worklist.
316 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
317 assert(New && New->getParent() == 0 &&
318 "New instruction already inserted into a basic block!");
319 BasicBlock *BB = Old.getParent();
320 BB->getInstList().insert(&Old, New); // Insert inst
325 // ReplaceInstUsesWith - This method is to be used when an instruction is
326 // found to be dead, replacable with another preexisting expression. Here
327 // we add all uses of I to the worklist, replace all uses of I with the new
328 // value, then return I, so that the inst combiner will know that I was
331 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
332 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
334 // If we are replacing the instruction with itself, this must be in a
335 // segment of unreachable code, so just clobber the instruction.
337 V = UndefValue::get(I.getType());
339 I.replaceAllUsesWith(V);
343 // EraseInstFromFunction - When dealing with an instruction that has side
344 // effects or produces a void value, we can't rely on DCE to delete the
345 // instruction. Instead, visit methods should return the value returned by
347 Instruction *EraseInstFromFunction(Instruction &I) {
348 DEBUG(errs() << "IC: ERASE " << I << '\n');
350 assert(I.use_empty() && "Cannot erase instruction that is used!");
351 // Make sure that we reprocess all operands now that we reduced their
353 if (I.getNumOperands() < 8) {
354 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
355 if (Instruction *Op = dyn_cast<Instruction>(*i))
361 return 0; // Don't do anything with FI
364 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
365 APInt &KnownOne, unsigned Depth = 0) const {
366 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
369 bool MaskedValueIsZero(Value *V, const APInt &Mask,
370 unsigned Depth = 0) const {
371 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
373 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
374 return llvm::ComputeNumSignBits(Op, TD, Depth);
379 /// SimplifyCommutative - This performs a few simplifications for
380 /// commutative operators.
381 bool SimplifyCommutative(BinaryOperator &I);
383 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
384 /// most-complex to least-complex order.
385 bool SimplifyCompare(CmpInst &I);
387 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
388 /// based on the demanded bits.
389 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
390 APInt& KnownZero, APInt& KnownOne,
392 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
393 APInt& KnownZero, APInt& KnownOne,
396 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
397 /// SimplifyDemandedBits knows about. See if the instruction has any
398 /// properties that allow us to simplify its operands.
399 bool SimplifyDemandedInstructionBits(Instruction &Inst);
401 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
402 APInt& UndefElts, unsigned Depth = 0);
404 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
405 // which has a PHI node as operand #0, see if we can fold the instruction
406 // into the PHI (which is only possible if all operands to the PHI are
409 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
410 // that would normally be unprofitable because they strongly encourage jump
412 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
414 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
415 // operator and they all are only used by the PHI, PHI together their
416 // inputs, and do the operation once, to the result of the PHI.
417 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
418 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
419 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
422 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
423 ConstantInt *AndRHS, BinaryOperator &TheAnd);
425 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
426 bool isSub, Instruction &I);
427 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
428 bool isSigned, bool Inside, Instruction &IB);
429 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
430 Instruction *MatchBSwap(BinaryOperator &I);
431 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
432 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
433 Instruction *SimplifyMemSet(MemSetInst *MI);
436 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
438 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
439 unsigned CastOpc, int &NumCastsRemoved);
440 unsigned GetOrEnforceKnownAlignment(Value *V,
441 unsigned PrefAlign = 0);
444 } // end anonymous namespace
446 char InstCombiner::ID = 0;
447 static RegisterPass<InstCombiner>
448 X("instcombine", "Combine redundant instructions");
450 // getComplexity: Assign a complexity or rank value to LLVM Values...
451 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
452 static unsigned getComplexity(Value *V) {
453 if (isa<Instruction>(V)) {
454 if (BinaryOperator::isNeg(V) ||
455 BinaryOperator::isFNeg(V) ||
456 BinaryOperator::isNot(V))
460 if (isa<Argument>(V)) return 3;
461 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
464 // isOnlyUse - Return true if this instruction will be deleted if we stop using
466 static bool isOnlyUse(Value *V) {
467 return V->hasOneUse() || isa<Constant>(V);
470 // getPromotedType - Return the specified type promoted as it would be to pass
471 // though a va_arg area...
472 static const Type *getPromotedType(const Type *Ty) {
473 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
474 if (ITy->getBitWidth() < 32)
475 return Type::getInt32Ty(Ty->getContext());
480 /// getBitCastOperand - If the specified operand is a CastInst, a constant
481 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
482 /// operand value, otherwise return null.
483 static Value *getBitCastOperand(Value *V) {
484 if (Operator *O = dyn_cast<Operator>(V)) {
485 if (O->getOpcode() == Instruction::BitCast)
486 return O->getOperand(0);
487 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
488 if (GEP->hasAllZeroIndices())
489 return GEP->getPointerOperand();
494 /// This function is a wrapper around CastInst::isEliminableCastPair. It
495 /// simply extracts arguments and returns what that function returns.
496 static Instruction::CastOps
497 isEliminableCastPair(
498 const CastInst *CI, ///< The first cast instruction
499 unsigned opcode, ///< The opcode of the second cast instruction
500 const Type *DstTy, ///< The target type for the second cast instruction
501 TargetData *TD ///< The target data for pointer size
504 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
505 const Type *MidTy = CI->getType(); // B from above
507 // Get the opcodes of the two Cast instructions
508 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
509 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
511 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
513 TD ? TD->getIntPtrType(CI->getContext()) : 0);
515 // We don't want to form an inttoptr or ptrtoint that converts to an integer
516 // type that differs from the pointer size.
517 if ((Res == Instruction::IntToPtr &&
518 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
519 (Res == Instruction::PtrToInt &&
520 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
523 return Instruction::CastOps(Res);
526 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
527 /// in any code being generated. It does not require codegen if V is simple
528 /// enough or if the cast can be folded into other casts.
529 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
530 const Type *Ty, TargetData *TD) {
531 if (V->getType() == Ty || isa<Constant>(V)) return false;
533 // If this is another cast that can be eliminated, it isn't codegen either.
534 if (const CastInst *CI = dyn_cast<CastInst>(V))
535 if (isEliminableCastPair(CI, opcode, Ty, TD))
540 // SimplifyCommutative - This performs a few simplifications for commutative
543 // 1. Order operands such that they are listed from right (least complex) to
544 // left (most complex). This puts constants before unary operators before
547 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
548 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
550 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
551 bool Changed = false;
552 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
553 Changed = !I.swapOperands();
555 if (!I.isAssociative()) return Changed;
556 Instruction::BinaryOps Opcode = I.getOpcode();
557 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
558 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
559 if (isa<Constant>(I.getOperand(1))) {
560 Constant *Folded = ConstantExpr::get(I.getOpcode(),
561 cast<Constant>(I.getOperand(1)),
562 cast<Constant>(Op->getOperand(1)));
563 I.setOperand(0, Op->getOperand(0));
564 I.setOperand(1, Folded);
566 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
567 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
568 isOnlyUse(Op) && isOnlyUse(Op1)) {
569 Constant *C1 = cast<Constant>(Op->getOperand(1));
570 Constant *C2 = cast<Constant>(Op1->getOperand(1));
572 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
573 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
574 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
578 I.setOperand(0, New);
579 I.setOperand(1, Folded);
586 /// SimplifyCompare - For a CmpInst this function just orders the operands
587 /// so that theyare listed from right (least complex) to left (most complex).
588 /// This puts constants before unary operators before binary operators.
589 bool InstCombiner::SimplifyCompare(CmpInst &I) {
590 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
593 // Compare instructions are not associative so there's nothing else we can do.
597 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
598 // if the LHS is a constant zero (which is the 'negate' form).
600 static inline Value *dyn_castNegVal(Value *V) {
601 if (BinaryOperator::isNeg(V))
602 return BinaryOperator::getNegArgument(V);
604 // Constants can be considered to be negated values if they can be folded.
605 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
606 return ConstantExpr::getNeg(C);
608 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
609 if (C->getType()->getElementType()->isInteger())
610 return ConstantExpr::getNeg(C);
615 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
616 // instruction if the LHS is a constant negative zero (which is the 'negate'
619 static inline Value *dyn_castFNegVal(Value *V) {
620 if (BinaryOperator::isFNeg(V))
621 return BinaryOperator::getFNegArgument(V);
623 // Constants can be considered to be negated values if they can be folded.
624 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
625 return ConstantExpr::getFNeg(C);
627 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
628 if (C->getType()->getElementType()->isFloatingPoint())
629 return ConstantExpr::getFNeg(C);
634 /// isFreeToInvert - Return true if the specified value is free to invert (apply
635 /// ~ to). This happens in cases where the ~ can be eliminated.
636 static inline bool isFreeToInvert(Value *V) {
638 if (BinaryOperator::isNot(V))
641 // Constants can be considered to be not'ed values.
642 if (isa<ConstantInt>(V))
645 // Compares can be inverted if they have a single use.
646 if (CmpInst *CI = dyn_cast<CmpInst>(V))
647 return CI->hasOneUse();
652 static inline Value *dyn_castNotVal(Value *V) {
653 // If this is not(not(x)) don't return that this is a not: we want the two
654 // not's to be folded first.
655 if (BinaryOperator::isNot(V)) {
656 Value *Operand = BinaryOperator::getNotArgument(V);
657 if (!isFreeToInvert(Operand))
661 // Constants can be considered to be not'ed values...
662 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
663 return ConstantInt::get(C->getType(), ~C->getValue());
669 // dyn_castFoldableMul - If this value is a multiply that can be folded into
670 // other computations (because it has a constant operand), return the
671 // non-constant operand of the multiply, and set CST to point to the multiplier.
672 // Otherwise, return null.
674 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
675 if (V->hasOneUse() && V->getType()->isInteger())
676 if (Instruction *I = dyn_cast<Instruction>(V)) {
677 if (I->getOpcode() == Instruction::Mul)
678 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
679 return I->getOperand(0);
680 if (I->getOpcode() == Instruction::Shl)
681 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
682 // The multiplier is really 1 << CST.
683 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
684 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
685 CST = ConstantInt::get(V->getType()->getContext(),
686 APInt(BitWidth, 1).shl(CSTVal));
687 return I->getOperand(0);
693 /// AddOne - Add one to a ConstantInt
694 static Constant *AddOne(Constant *C) {
695 return ConstantExpr::getAdd(C,
696 ConstantInt::get(C->getType(), 1));
698 /// SubOne - Subtract one from a ConstantInt
699 static Constant *SubOne(ConstantInt *C) {
700 return ConstantExpr::getSub(C,
701 ConstantInt::get(C->getType(), 1));
703 /// MultiplyOverflows - True if the multiply can not be expressed in an int
705 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
706 uint32_t W = C1->getBitWidth();
707 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
716 APInt MulExt = LHSExt * RHSExt;
719 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
720 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
721 return MulExt.slt(Min) || MulExt.sgt(Max);
723 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
727 /// ShrinkDemandedConstant - Check to see if the specified operand of the
728 /// specified instruction is a constant integer. If so, check to see if there
729 /// are any bits set in the constant that are not demanded. If so, shrink the
730 /// constant and return true.
731 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
733 assert(I && "No instruction?");
734 assert(OpNo < I->getNumOperands() && "Operand index too large");
736 // If the operand is not a constant integer, nothing to do.
737 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
738 if (!OpC) return false;
740 // If there are no bits set that aren't demanded, nothing to do.
741 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
742 if ((~Demanded & OpC->getValue()) == 0)
745 // This instruction is producing bits that are not demanded. Shrink the RHS.
746 Demanded &= OpC->getValue();
747 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
751 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
752 // set of known zero and one bits, compute the maximum and minimum values that
753 // could have the specified known zero and known one bits, returning them in
755 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
756 const APInt& KnownOne,
757 APInt& Min, APInt& Max) {
758 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
759 KnownZero.getBitWidth() == Min.getBitWidth() &&
760 KnownZero.getBitWidth() == Max.getBitWidth() &&
761 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
762 APInt UnknownBits = ~(KnownZero|KnownOne);
764 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
765 // bit if it is unknown.
767 Max = KnownOne|UnknownBits;
769 if (UnknownBits.isNegative()) { // Sign bit is unknown
770 Min.set(Min.getBitWidth()-1);
771 Max.clear(Max.getBitWidth()-1);
775 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
776 // a set of known zero and one bits, compute the maximum and minimum values that
777 // could have the specified known zero and known one bits, returning them in
779 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
780 const APInt &KnownOne,
781 APInt &Min, APInt &Max) {
782 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
783 KnownZero.getBitWidth() == Min.getBitWidth() &&
784 KnownZero.getBitWidth() == Max.getBitWidth() &&
785 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
786 APInt UnknownBits = ~(KnownZero|KnownOne);
788 // The minimum value is when the unknown bits are all zeros.
790 // The maximum value is when the unknown bits are all ones.
791 Max = KnownOne|UnknownBits;
794 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
795 /// SimplifyDemandedBits knows about. See if the instruction has any
796 /// properties that allow us to simplify its operands.
797 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
798 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
799 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
800 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
802 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
803 KnownZero, KnownOne, 0);
804 if (V == 0) return false;
805 if (V == &Inst) return true;
806 ReplaceInstUsesWith(Inst, V);
810 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
811 /// specified instruction operand if possible, updating it in place. It returns
812 /// true if it made any change and false otherwise.
813 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
814 APInt &KnownZero, APInt &KnownOne,
816 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
817 KnownZero, KnownOne, Depth);
818 if (NewVal == 0) return false;
824 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
825 /// value based on the demanded bits. When this function is called, it is known
826 /// that only the bits set in DemandedMask of the result of V are ever used
827 /// downstream. Consequently, depending on the mask and V, it may be possible
828 /// to replace V with a constant or one of its operands. In such cases, this
829 /// function does the replacement and returns true. In all other cases, it
830 /// returns false after analyzing the expression and setting KnownOne and known
831 /// to be one in the expression. KnownZero contains all the bits that are known
832 /// to be zero in the expression. These are provided to potentially allow the
833 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
834 /// the expression. KnownOne and KnownZero always follow the invariant that
835 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
836 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
837 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
838 /// and KnownOne must all be the same.
840 /// This returns null if it did not change anything and it permits no
841 /// simplification. This returns V itself if it did some simplification of V's
842 /// operands based on the information about what bits are demanded. This returns
843 /// some other non-null value if it found out that V is equal to another value
844 /// in the context where the specified bits are demanded, but not for all users.
845 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
846 APInt &KnownZero, APInt &KnownOne,
848 assert(V != 0 && "Null pointer of Value???");
849 assert(Depth <= 6 && "Limit Search Depth");
850 uint32_t BitWidth = DemandedMask.getBitWidth();
851 const Type *VTy = V->getType();
852 assert((TD || !isa<PointerType>(VTy)) &&
853 "SimplifyDemandedBits needs to know bit widths!");
854 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
855 (!VTy->isIntOrIntVector() ||
856 VTy->getScalarSizeInBits() == BitWidth) &&
857 KnownZero.getBitWidth() == BitWidth &&
858 KnownOne.getBitWidth() == BitWidth &&
859 "Value *V, DemandedMask, KnownZero and KnownOne "
860 "must have same BitWidth");
861 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
862 // We know all of the bits for a constant!
863 KnownOne = CI->getValue() & DemandedMask;
864 KnownZero = ~KnownOne & DemandedMask;
867 if (isa<ConstantPointerNull>(V)) {
868 // We know all of the bits for a constant!
870 KnownZero = DemandedMask;
876 if (DemandedMask == 0) { // Not demanding any bits from V.
877 if (isa<UndefValue>(V))
879 return UndefValue::get(VTy);
882 if (Depth == 6) // Limit search depth.
885 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
886 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
888 Instruction *I = dyn_cast<Instruction>(V);
890 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
891 return 0; // Only analyze instructions.
894 // If there are multiple uses of this value and we aren't at the root, then
895 // we can't do any simplifications of the operands, because DemandedMask
896 // only reflects the bits demanded by *one* of the users.
897 if (Depth != 0 && !I->hasOneUse()) {
898 // Despite the fact that we can't simplify this instruction in all User's
899 // context, we can at least compute the knownzero/knownone bits, and we can
900 // do simplifications that apply to *just* the one user if we know that
901 // this instruction has a simpler value in that context.
902 if (I->getOpcode() == Instruction::And) {
903 // If either the LHS or the RHS are Zero, the result is zero.
904 ComputeMaskedBits(I->getOperand(1), DemandedMask,
905 RHSKnownZero, RHSKnownOne, Depth+1);
906 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
907 LHSKnownZero, LHSKnownOne, Depth+1);
909 // If all of the demanded bits are known 1 on one side, return the other.
910 // These bits cannot contribute to the result of the 'and' in this
912 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
913 (DemandedMask & ~LHSKnownZero))
914 return I->getOperand(0);
915 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
916 (DemandedMask & ~RHSKnownZero))
917 return I->getOperand(1);
919 // If all of the demanded bits in the inputs are known zeros, return zero.
920 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
921 return Constant::getNullValue(VTy);
923 } else if (I->getOpcode() == Instruction::Or) {
924 // We can simplify (X|Y) -> X or Y in the user's context if we know that
925 // only bits from X or Y are demanded.
927 // If either the LHS or the RHS are One, the result is One.
928 ComputeMaskedBits(I->getOperand(1), DemandedMask,
929 RHSKnownZero, RHSKnownOne, Depth+1);
930 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
931 LHSKnownZero, LHSKnownOne, Depth+1);
933 // If all of the demanded bits are known zero on one side, return the
934 // other. These bits cannot contribute to the result of the 'or' in this
936 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
937 (DemandedMask & ~LHSKnownOne))
938 return I->getOperand(0);
939 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
940 (DemandedMask & ~RHSKnownOne))
941 return I->getOperand(1);
943 // If all of the potentially set bits on one side are known to be set on
944 // the other side, just use the 'other' side.
945 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
946 (DemandedMask & (~RHSKnownZero)))
947 return I->getOperand(0);
948 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
949 (DemandedMask & (~LHSKnownZero)))
950 return I->getOperand(1);
953 // Compute the KnownZero/KnownOne bits to simplify things downstream.
954 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
958 // If this is the root being simplified, allow it to have multiple uses,
959 // just set the DemandedMask to all bits so that we can try to simplify the
960 // operands. This allows visitTruncInst (for example) to simplify the
961 // operand of a trunc without duplicating all the logic below.
962 if (Depth == 0 && !V->hasOneUse())
963 DemandedMask = APInt::getAllOnesValue(BitWidth);
965 switch (I->getOpcode()) {
967 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
969 case Instruction::And:
970 // If either the LHS or the RHS are Zero, the result is zero.
971 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
972 RHSKnownZero, RHSKnownOne, Depth+1) ||
973 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
974 LHSKnownZero, LHSKnownOne, Depth+1))
976 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
977 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
979 // If all of the demanded bits are known 1 on one side, return the other.
980 // These bits cannot contribute to the result of the 'and'.
981 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
982 (DemandedMask & ~LHSKnownZero))
983 return I->getOperand(0);
984 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
985 (DemandedMask & ~RHSKnownZero))
986 return I->getOperand(1);
988 // If all of the demanded bits in the inputs are known zeros, return zero.
989 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
990 return Constant::getNullValue(VTy);
992 // If the RHS is a constant, see if we can simplify it.
993 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
996 // Output known-1 bits are only known if set in both the LHS & RHS.
997 RHSKnownOne &= LHSKnownOne;
998 // Output known-0 are known to be clear if zero in either the LHS | RHS.
999 RHSKnownZero |= LHSKnownZero;
1001 case Instruction::Or:
1002 // If either the LHS or the RHS are One, the result is One.
1003 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1004 RHSKnownZero, RHSKnownOne, Depth+1) ||
1005 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
1006 LHSKnownZero, LHSKnownOne, Depth+1))
1008 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1009 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
1011 // If all of the demanded bits are known zero on one side, return the other.
1012 // These bits cannot contribute to the result of the 'or'.
1013 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1014 (DemandedMask & ~LHSKnownOne))
1015 return I->getOperand(0);
1016 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1017 (DemandedMask & ~RHSKnownOne))
1018 return I->getOperand(1);
1020 // If all of the potentially set bits on one side are known to be set on
1021 // the other side, just use the 'other' side.
1022 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1023 (DemandedMask & (~RHSKnownZero)))
1024 return I->getOperand(0);
1025 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1026 (DemandedMask & (~LHSKnownZero)))
1027 return I->getOperand(1);
1029 // If the RHS is a constant, see if we can simplify it.
1030 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1033 // Output known-0 bits are only known if clear in both the LHS & RHS.
1034 RHSKnownZero &= LHSKnownZero;
1035 // Output known-1 are known to be set if set in either the LHS | RHS.
1036 RHSKnownOne |= LHSKnownOne;
1038 case Instruction::Xor: {
1039 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1040 RHSKnownZero, RHSKnownOne, Depth+1) ||
1041 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1042 LHSKnownZero, LHSKnownOne, Depth+1))
1044 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1045 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
1047 // If all of the demanded bits are known zero on one side, return the other.
1048 // These bits cannot contribute to the result of the 'xor'.
1049 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1050 return I->getOperand(0);
1051 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1052 return I->getOperand(1);
1054 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1055 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1056 (RHSKnownOne & LHSKnownOne);
1057 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1058 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1059 (RHSKnownOne & LHSKnownZero);
1061 // If all of the demanded bits are known to be zero on one side or the
1062 // other, turn this into an *inclusive* or.
1063 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1064 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1066 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1068 return InsertNewInstBefore(Or, *I);
1071 // If all of the demanded bits on one side are known, and all of the set
1072 // bits on that side are also known to be set on the other side, turn this
1073 // into an AND, as we know the bits will be cleared.
1074 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1075 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1077 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1078 Constant *AndC = Constant::getIntegerValue(VTy,
1079 ~RHSKnownOne & DemandedMask);
1081 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1082 return InsertNewInstBefore(And, *I);
1086 // If the RHS is a constant, see if we can simplify it.
1087 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1088 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1091 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1092 // are flipping are known to be set, then the xor is just resetting those
1093 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1094 // simplifying both of them.
1095 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1096 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1097 isa<ConstantInt>(I->getOperand(1)) &&
1098 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1099 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1100 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1101 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1102 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1105 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1106 Instruction *NewAnd =
1107 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1108 InsertNewInstBefore(NewAnd, *I);
1111 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1112 Instruction *NewXor =
1113 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1114 return InsertNewInstBefore(NewXor, *I);
1118 RHSKnownZero = KnownZeroOut;
1119 RHSKnownOne = KnownOneOut;
1122 case Instruction::Select:
1123 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1124 RHSKnownZero, RHSKnownOne, Depth+1) ||
1125 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1126 LHSKnownZero, LHSKnownOne, Depth+1))
1128 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1129 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
1131 // If the operands are constants, see if we can simplify them.
1132 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1133 ShrinkDemandedConstant(I, 2, DemandedMask))
1136 // Only known if known in both the LHS and RHS.
1137 RHSKnownOne &= LHSKnownOne;
1138 RHSKnownZero &= LHSKnownZero;
1140 case Instruction::Trunc: {
1141 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1142 DemandedMask.zext(truncBf);
1143 RHSKnownZero.zext(truncBf);
1144 RHSKnownOne.zext(truncBf);
1145 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1146 RHSKnownZero, RHSKnownOne, Depth+1))
1148 DemandedMask.trunc(BitWidth);
1149 RHSKnownZero.trunc(BitWidth);
1150 RHSKnownOne.trunc(BitWidth);
1151 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1154 case Instruction::BitCast:
1155 if (!I->getOperand(0)->getType()->isIntOrIntVector())
1156 return false; // vector->int or fp->int?
1158 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1159 if (const VectorType *SrcVTy =
1160 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1161 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1162 // Don't touch a bitcast between vectors of different element counts.
1165 // Don't touch a scalar-to-vector bitcast.
1167 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1168 // Don't touch a vector-to-scalar bitcast.
1171 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1172 RHSKnownZero, RHSKnownOne, Depth+1))
1174 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1176 case Instruction::ZExt: {
1177 // Compute the bits in the result that are not present in the input.
1178 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1180 DemandedMask.trunc(SrcBitWidth);
1181 RHSKnownZero.trunc(SrcBitWidth);
1182 RHSKnownOne.trunc(SrcBitWidth);
1183 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1184 RHSKnownZero, RHSKnownOne, Depth+1))
1186 DemandedMask.zext(BitWidth);
1187 RHSKnownZero.zext(BitWidth);
1188 RHSKnownOne.zext(BitWidth);
1189 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1190 // The top bits are known to be zero.
1191 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1194 case Instruction::SExt: {
1195 // Compute the bits in the result that are not present in the input.
1196 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1198 APInt InputDemandedBits = DemandedMask &
1199 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1201 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1202 // If any of the sign extended bits are demanded, we know that the sign
1204 if ((NewBits & DemandedMask) != 0)
1205 InputDemandedBits.set(SrcBitWidth-1);
1207 InputDemandedBits.trunc(SrcBitWidth);
1208 RHSKnownZero.trunc(SrcBitWidth);
1209 RHSKnownOne.trunc(SrcBitWidth);
1210 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1211 RHSKnownZero, RHSKnownOne, Depth+1))
1213 InputDemandedBits.zext(BitWidth);
1214 RHSKnownZero.zext(BitWidth);
1215 RHSKnownOne.zext(BitWidth);
1216 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1218 // If the sign bit of the input is known set or clear, then we know the
1219 // top bits of the result.
1221 // If the input sign bit is known zero, or if the NewBits are not demanded
1222 // convert this into a zero extension.
1223 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1224 // Convert to ZExt cast
1225 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1226 return InsertNewInstBefore(NewCast, *I);
1227 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1228 RHSKnownOne |= NewBits;
1232 case Instruction::Add: {
1233 // Figure out what the input bits are. If the top bits of the and result
1234 // are not demanded, then the add doesn't demand them from its input
1236 unsigned NLZ = DemandedMask.countLeadingZeros();
1238 // If there is a constant on the RHS, there are a variety of xformations
1240 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1241 // If null, this should be simplified elsewhere. Some of the xforms here
1242 // won't work if the RHS is zero.
1246 // If the top bit of the output is demanded, demand everything from the
1247 // input. Otherwise, we demand all the input bits except NLZ top bits.
1248 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1250 // Find information about known zero/one bits in the input.
1251 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
1252 LHSKnownZero, LHSKnownOne, Depth+1))
1255 // If the RHS of the add has bits set that can't affect the input, reduce
1257 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1260 // Avoid excess work.
1261 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1264 // Turn it into OR if input bits are zero.
1265 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1267 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1269 return InsertNewInstBefore(Or, *I);
1272 // We can say something about the output known-zero and known-one bits,
1273 // depending on potential carries from the input constant and the
1274 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1275 // bits set and the RHS constant is 0x01001, then we know we have a known
1276 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1278 // To compute this, we first compute the potential carry bits. These are
1279 // the bits which may be modified. I'm not aware of a better way to do
1281 const APInt &RHSVal = RHS->getValue();
1282 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1284 // Now that we know which bits have carries, compute the known-1/0 sets.
1286 // Bits are known one if they are known zero in one operand and one in the
1287 // other, and there is no input carry.
1288 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1289 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1291 // Bits are known zero if they are known zero in both operands and there
1292 // is no input carry.
1293 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1295 // If the high-bits of this ADD are not demanded, then it does not demand
1296 // the high bits of its LHS or RHS.
1297 if (DemandedMask[BitWidth-1] == 0) {
1298 // Right fill the mask of bits for this ADD to demand the most
1299 // significant bit and all those below it.
1300 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1301 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1302 LHSKnownZero, LHSKnownOne, Depth+1) ||
1303 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1304 LHSKnownZero, LHSKnownOne, Depth+1))
1310 case Instruction::Sub:
1311 // If the high-bits of this SUB are not demanded, then it does not demand
1312 // the high bits of its LHS or RHS.
1313 if (DemandedMask[BitWidth-1] == 0) {
1314 // Right fill the mask of bits for this SUB to demand the most
1315 // significant bit and all those below it.
1316 uint32_t NLZ = DemandedMask.countLeadingZeros();
1317 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1318 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1319 LHSKnownZero, LHSKnownOne, Depth+1) ||
1320 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1321 LHSKnownZero, LHSKnownOne, Depth+1))
1324 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1325 // the known zeros and ones.
1326 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1328 case Instruction::Shl:
1329 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1330 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1331 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1332 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1333 RHSKnownZero, RHSKnownOne, Depth+1))
1335 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1336 RHSKnownZero <<= ShiftAmt;
1337 RHSKnownOne <<= ShiftAmt;
1338 // low bits known zero.
1340 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1343 case Instruction::LShr:
1344 // For a logical shift right
1345 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1346 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1348 // Unsigned shift right.
1349 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1350 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1351 RHSKnownZero, RHSKnownOne, Depth+1))
1353 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1354 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1355 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1357 // Compute the new bits that are at the top now.
1358 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1359 RHSKnownZero |= HighBits; // high bits known zero.
1363 case Instruction::AShr:
1364 // If this is an arithmetic shift right and only the low-bit is set, we can
1365 // always convert this into a logical shr, even if the shift amount is
1366 // variable. The low bit of the shift cannot be an input sign bit unless
1367 // the shift amount is >= the size of the datatype, which is undefined.
1368 if (DemandedMask == 1) {
1369 // Perform the logical shift right.
1370 Instruction *NewVal = BinaryOperator::CreateLShr(
1371 I->getOperand(0), I->getOperand(1), I->getName());
1372 return InsertNewInstBefore(NewVal, *I);
1375 // If the sign bit is the only bit demanded by this ashr, then there is no
1376 // need to do it, the shift doesn't change the high bit.
1377 if (DemandedMask.isSignBit())
1378 return I->getOperand(0);
1380 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1381 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1383 // Signed shift right.
1384 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1385 // If any of the "high bits" are demanded, we should set the sign bit as
1387 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1388 DemandedMaskIn.set(BitWidth-1);
1389 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1390 RHSKnownZero, RHSKnownOne, Depth+1))
1392 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1393 // Compute the new bits that are at the top now.
1394 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1395 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1396 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1398 // Handle the sign bits.
1399 APInt SignBit(APInt::getSignBit(BitWidth));
1400 // Adjust to where it is now in the mask.
1401 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1403 // If the input sign bit is known to be zero, or if none of the top bits
1404 // are demanded, turn this into an unsigned shift right.
1405 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
1406 (HighBits & ~DemandedMask) == HighBits) {
1407 // Perform the logical shift right.
1408 Instruction *NewVal = BinaryOperator::CreateLShr(
1409 I->getOperand(0), SA, I->getName());
1410 return InsertNewInstBefore(NewVal, *I);
1411 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1412 RHSKnownOne |= HighBits;
1416 case Instruction::SRem:
1417 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1418 APInt RA = Rem->getValue().abs();
1419 if (RA.isPowerOf2()) {
1420 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
1421 return I->getOperand(0);
1423 APInt LowBits = RA - 1;
1424 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1425 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1426 LHSKnownZero, LHSKnownOne, Depth+1))
1429 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1430 LHSKnownZero |= ~LowBits;
1432 KnownZero |= LHSKnownZero & DemandedMask;
1434 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
1438 case Instruction::URem: {
1439 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1440 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1441 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1442 KnownZero2, KnownOne2, Depth+1) ||
1443 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1444 KnownZero2, KnownOne2, Depth+1))
1447 unsigned Leaders = KnownZero2.countLeadingOnes();
1448 Leaders = std::max(Leaders,
1449 KnownZero2.countLeadingOnes());
1450 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1453 case Instruction::Call:
1454 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1455 switch (II->getIntrinsicID()) {
1457 case Intrinsic::bswap: {
1458 // If the only bits demanded come from one byte of the bswap result,
1459 // just shift the input byte into position to eliminate the bswap.
1460 unsigned NLZ = DemandedMask.countLeadingZeros();
1461 unsigned NTZ = DemandedMask.countTrailingZeros();
1463 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1464 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1465 // have 14 leading zeros, round to 8.
1468 // If we need exactly one byte, we can do this transformation.
1469 if (BitWidth-NLZ-NTZ == 8) {
1470 unsigned ResultBit = NTZ;
1471 unsigned InputBit = BitWidth-NTZ-8;
1473 // Replace this with either a left or right shift to get the byte into
1475 Instruction *NewVal;
1476 if (InputBit > ResultBit)
1477 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1478 ConstantInt::get(I->getType(), InputBit-ResultBit));
1480 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1481 ConstantInt::get(I->getType(), ResultBit-InputBit));
1482 NewVal->takeName(I);
1483 return InsertNewInstBefore(NewVal, *I);
1486 // TODO: Could compute known zero/one bits based on the input.
1491 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1495 // If the client is only demanding bits that we know, return the known
1497 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1498 return Constant::getIntegerValue(VTy, RHSKnownOne);
1503 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1504 /// any number of elements. DemandedElts contains the set of elements that are
1505 /// actually used by the caller. This method analyzes which elements of the
1506 /// operand are undef and returns that information in UndefElts.
1508 /// If the information about demanded elements can be used to simplify the
1509 /// operation, the operation is simplified, then the resultant value is
1510 /// returned. This returns null if no change was made.
1511 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1514 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1515 APInt EltMask(APInt::getAllOnesValue(VWidth));
1516 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1518 if (isa<UndefValue>(V)) {
1519 // If the entire vector is undefined, just return this info.
1520 UndefElts = EltMask;
1522 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1523 UndefElts = EltMask;
1524 return UndefValue::get(V->getType());
1528 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1529 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1530 Constant *Undef = UndefValue::get(EltTy);
1532 std::vector<Constant*> Elts;
1533 for (unsigned i = 0; i != VWidth; ++i)
1534 if (!DemandedElts[i]) { // If not demanded, set to undef.
1535 Elts.push_back(Undef);
1537 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1538 Elts.push_back(Undef);
1540 } else { // Otherwise, defined.
1541 Elts.push_back(CP->getOperand(i));
1544 // If we changed the constant, return it.
1545 Constant *NewCP = ConstantVector::get(Elts);
1546 return NewCP != CP ? NewCP : 0;
1547 } else if (isa<ConstantAggregateZero>(V)) {
1548 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1551 // Check if this is identity. If so, return 0 since we are not simplifying
1553 if (DemandedElts == ((1ULL << VWidth) -1))
1556 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1557 Constant *Zero = Constant::getNullValue(EltTy);
1558 Constant *Undef = UndefValue::get(EltTy);
1559 std::vector<Constant*> Elts;
1560 for (unsigned i = 0; i != VWidth; ++i) {
1561 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1562 Elts.push_back(Elt);
1564 UndefElts = DemandedElts ^ EltMask;
1565 return ConstantVector::get(Elts);
1568 // Limit search depth.
1572 // If multiple users are using the root value, procede with
1573 // simplification conservatively assuming that all elements
1575 if (!V->hasOneUse()) {
1576 // Quit if we find multiple users of a non-root value though.
1577 // They'll be handled when it's their turn to be visited by
1578 // the main instcombine process.
1580 // TODO: Just compute the UndefElts information recursively.
1583 // Conservatively assume that all elements are needed.
1584 DemandedElts = EltMask;
1587 Instruction *I = dyn_cast<Instruction>(V);
1588 if (!I) return 0; // Only analyze instructions.
1590 bool MadeChange = false;
1591 APInt UndefElts2(VWidth, 0);
1593 switch (I->getOpcode()) {
1596 case Instruction::InsertElement: {
1597 // If this is a variable index, we don't know which element it overwrites.
1598 // demand exactly the same input as we produce.
1599 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1601 // Note that we can't propagate undef elt info, because we don't know
1602 // which elt is getting updated.
1603 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1604 UndefElts2, Depth+1);
1605 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1609 // If this is inserting an element that isn't demanded, remove this
1611 unsigned IdxNo = Idx->getZExtValue();
1612 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1614 return I->getOperand(0);
1617 // Otherwise, the element inserted overwrites whatever was there, so the
1618 // input demanded set is simpler than the output set.
1619 APInt DemandedElts2 = DemandedElts;
1620 DemandedElts2.clear(IdxNo);
1621 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1622 UndefElts, Depth+1);
1623 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1625 // The inserted element is defined.
1626 UndefElts.clear(IdxNo);
1629 case Instruction::ShuffleVector: {
1630 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1631 uint64_t LHSVWidth =
1632 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1633 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1634 for (unsigned i = 0; i < VWidth; i++) {
1635 if (DemandedElts[i]) {
1636 unsigned MaskVal = Shuffle->getMaskValue(i);
1637 if (MaskVal != -1u) {
1638 assert(MaskVal < LHSVWidth * 2 &&
1639 "shufflevector mask index out of range!");
1640 if (MaskVal < LHSVWidth)
1641 LeftDemanded.set(MaskVal);
1643 RightDemanded.set(MaskVal - LHSVWidth);
1648 APInt UndefElts4(LHSVWidth, 0);
1649 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1650 UndefElts4, Depth+1);
1651 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1653 APInt UndefElts3(LHSVWidth, 0);
1654 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1655 UndefElts3, Depth+1);
1656 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1658 bool NewUndefElts = false;
1659 for (unsigned i = 0; i < VWidth; i++) {
1660 unsigned MaskVal = Shuffle->getMaskValue(i);
1661 if (MaskVal == -1u) {
1663 } else if (MaskVal < LHSVWidth) {
1664 if (UndefElts4[MaskVal]) {
1665 NewUndefElts = true;
1669 if (UndefElts3[MaskVal - LHSVWidth]) {
1670 NewUndefElts = true;
1677 // Add additional discovered undefs.
1678 std::vector<Constant*> Elts;
1679 for (unsigned i = 0; i < VWidth; ++i) {
1681 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
1683 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
1684 Shuffle->getMaskValue(i)));
1686 I->setOperand(2, ConstantVector::get(Elts));
1691 case Instruction::BitCast: {
1692 // Vector->vector casts only.
1693 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1695 unsigned InVWidth = VTy->getNumElements();
1696 APInt InputDemandedElts(InVWidth, 0);
1699 if (VWidth == InVWidth) {
1700 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1701 // elements as are demanded of us.
1703 InputDemandedElts = DemandedElts;
1704 } else if (VWidth > InVWidth) {
1708 // If there are more elements in the result than there are in the source,
1709 // then an input element is live if any of the corresponding output
1710 // elements are live.
1711 Ratio = VWidth/InVWidth;
1712 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1713 if (DemandedElts[OutIdx])
1714 InputDemandedElts.set(OutIdx/Ratio);
1720 // If there are more elements in the source than there are in the result,
1721 // then an input element is live if the corresponding output element is
1723 Ratio = InVWidth/VWidth;
1724 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1725 if (DemandedElts[InIdx/Ratio])
1726 InputDemandedElts.set(InIdx);
1729 // div/rem demand all inputs, because they don't want divide by zero.
1730 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1731 UndefElts2, Depth+1);
1733 I->setOperand(0, TmpV);
1737 UndefElts = UndefElts2;
1738 if (VWidth > InVWidth) {
1739 llvm_unreachable("Unimp");
1740 // If there are more elements in the result than there are in the source,
1741 // then an output element is undef if the corresponding input element is
1743 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1744 if (UndefElts2[OutIdx/Ratio])
1745 UndefElts.set(OutIdx);
1746 } else if (VWidth < InVWidth) {
1747 llvm_unreachable("Unimp");
1748 // If there are more elements in the source than there are in the result,
1749 // then a result element is undef if all of the corresponding input
1750 // elements are undef.
1751 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1752 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1753 if (!UndefElts2[InIdx]) // Not undef?
1754 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
1758 case Instruction::And:
1759 case Instruction::Or:
1760 case Instruction::Xor:
1761 case Instruction::Add:
1762 case Instruction::Sub:
1763 case Instruction::Mul:
1764 // div/rem demand all inputs, because they don't want divide by zero.
1765 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1766 UndefElts, Depth+1);
1767 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1768 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1769 UndefElts2, Depth+1);
1770 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
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;
1777 case Instruction::Call: {
1778 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1780 switch (II->getIntrinsicID()) {
1783 // Binary vector operations that work column-wise. A dest element is a
1784 // function of the corresponding input elements from the two inputs.
1785 case Intrinsic::x86_sse_sub_ss:
1786 case Intrinsic::x86_sse_mul_ss:
1787 case Intrinsic::x86_sse_min_ss:
1788 case Intrinsic::x86_sse_max_ss:
1789 case Intrinsic::x86_sse2_sub_sd:
1790 case Intrinsic::x86_sse2_mul_sd:
1791 case Intrinsic::x86_sse2_min_sd:
1792 case Intrinsic::x86_sse2_max_sd:
1793 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1794 UndefElts, Depth+1);
1795 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1796 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1797 UndefElts2, Depth+1);
1798 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1800 // If only the low elt is demanded and this is a scalarizable intrinsic,
1801 // scalarize it now.
1802 if (DemandedElts == 1) {
1803 switch (II->getIntrinsicID()) {
1805 case Intrinsic::x86_sse_sub_ss:
1806 case Intrinsic::x86_sse_mul_ss:
1807 case Intrinsic::x86_sse2_sub_sd:
1808 case Intrinsic::x86_sse2_mul_sd:
1809 // TODO: Lower MIN/MAX/ABS/etc
1810 Value *LHS = II->getOperand(1);
1811 Value *RHS = II->getOperand(2);
1812 // Extract the element as scalars.
1813 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
1814 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1815 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
1816 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
1818 switch (II->getIntrinsicID()) {
1819 default: llvm_unreachable("Case stmts out of sync!");
1820 case Intrinsic::x86_sse_sub_ss:
1821 case Intrinsic::x86_sse2_sub_sd:
1822 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1823 II->getName()), *II);
1825 case Intrinsic::x86_sse_mul_ss:
1826 case Intrinsic::x86_sse2_mul_sd:
1827 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1828 II->getName()), *II);
1833 InsertElementInst::Create(
1834 UndefValue::get(II->getType()), TmpV,
1835 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
1836 InsertNewInstBefore(New, *II);
1841 // Output elements are undefined if both are undefined. Consider things
1842 // like undef&0. The result is known zero, not undef.
1843 UndefElts &= UndefElts2;
1849 return MadeChange ? I : 0;
1853 /// AssociativeOpt - Perform an optimization on an associative operator. This
1854 /// function is designed to check a chain of associative operators for a
1855 /// potential to apply a certain optimization. Since the optimization may be
1856 /// applicable if the expression was reassociated, this checks the chain, then
1857 /// reassociates the expression as necessary to expose the optimization
1858 /// opportunity. This makes use of a special Functor, which must define
1859 /// 'shouldApply' and 'apply' methods.
1861 template<typename Functor>
1862 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1863 unsigned Opcode = Root.getOpcode();
1864 Value *LHS = Root.getOperand(0);
1866 // Quick check, see if the immediate LHS matches...
1867 if (F.shouldApply(LHS))
1868 return F.apply(Root);
1870 // Otherwise, if the LHS is not of the same opcode as the root, return.
1871 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1872 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1873 // Should we apply this transform to the RHS?
1874 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1876 // If not to the RHS, check to see if we should apply to the LHS...
1877 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1878 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1882 // If the functor wants to apply the optimization to the RHS of LHSI,
1883 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1885 // Now all of the instructions are in the current basic block, go ahead
1886 // and perform the reassociation.
1887 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1889 // First move the selected RHS to the LHS of the root...
1890 Root.setOperand(0, LHSI->getOperand(1));
1892 // Make what used to be the LHS of the root be the user of the root...
1893 Value *ExtraOperand = TmpLHSI->getOperand(1);
1894 if (&Root == TmpLHSI) {
1895 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1898 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1899 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1900 BasicBlock::iterator ARI = &Root; ++ARI;
1901 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
1904 // Now propagate the ExtraOperand down the chain of instructions until we
1906 while (TmpLHSI != LHSI) {
1907 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1908 // Move the instruction to immediately before the chain we are
1909 // constructing to avoid breaking dominance properties.
1910 NextLHSI->moveBefore(ARI);
1913 Value *NextOp = NextLHSI->getOperand(1);
1914 NextLHSI->setOperand(1, ExtraOperand);
1916 ExtraOperand = NextOp;
1919 // Now that the instructions are reassociated, have the functor perform
1920 // the transformation...
1921 return F.apply(Root);
1924 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1931 // AddRHS - Implements: X + X --> X << 1
1934 explicit AddRHS(Value *rhs) : RHS(rhs) {}
1935 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1936 Instruction *apply(BinaryOperator &Add) const {
1937 return BinaryOperator::CreateShl(Add.getOperand(0),
1938 ConstantInt::get(Add.getType(), 1));
1942 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1944 struct AddMaskingAnd {
1946 explicit AddMaskingAnd(Constant *c) : C2(c) {}
1947 bool shouldApply(Value *LHS) const {
1949 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1950 ConstantExpr::getAnd(C1, C2)->isNullValue();
1952 Instruction *apply(BinaryOperator &Add) const {
1953 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1959 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1961 if (CastInst *CI = dyn_cast<CastInst>(&I))
1962 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
1964 // Figure out if the constant is the left or the right argument.
1965 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1966 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1968 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1970 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1971 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1974 Value *Op0 = SO, *Op1 = ConstOperand;
1976 std::swap(Op0, Op1);
1978 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1979 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1980 SO->getName()+".op");
1981 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1982 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1983 SO->getName()+".cmp");
1984 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1985 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1986 SO->getName()+".cmp");
1987 llvm_unreachable("Unknown binary instruction type!");
1990 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1991 // constant as the other operand, try to fold the binary operator into the
1992 // select arguments. This also works for Cast instructions, which obviously do
1993 // not have a second operand.
1994 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1996 // Don't modify shared select instructions
1997 if (!SI->hasOneUse()) return 0;
1998 Value *TV = SI->getOperand(1);
1999 Value *FV = SI->getOperand(2);
2001 if (isa<Constant>(TV) || isa<Constant>(FV)) {
2002 // Bool selects with constant operands can be folded to logical ops.
2003 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
2005 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2006 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2008 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2015 /// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2016 /// has a PHI node as operand #0, see if we can fold the instruction into the
2017 /// PHI (which is only possible if all operands to the PHI are constants).
2019 /// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2020 /// that would normally be unprofitable because they strongly encourage jump
2022 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2023 bool AllowAggressive) {
2024 AllowAggressive = false;
2025 PHINode *PN = cast<PHINode>(I.getOperand(0));
2026 unsigned NumPHIValues = PN->getNumIncomingValues();
2027 if (NumPHIValues == 0 ||
2028 // We normally only transform phis with a single use, unless we're trying
2029 // hard to make jump threading happen.
2030 (!PN->hasOneUse() && !AllowAggressive))
2034 // Check to see if all of the operands of the PHI are simple constants
2035 // (constantint/constantfp/undef). If there is one non-constant value,
2036 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2037 // bail out. We don't do arbitrary constant expressions here because moving
2038 // their computation can be expensive without a cost model.
2039 BasicBlock *NonConstBB = 0;
2040 for (unsigned i = 0; i != NumPHIValues; ++i)
2041 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2042 isa<ConstantExpr>(PN->getIncomingValue(i))) {
2043 if (NonConstBB) return 0; // More than one non-const value.
2044 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
2045 NonConstBB = PN->getIncomingBlock(i);
2047 // If the incoming non-constant value is in I's block, we have an infinite
2049 if (NonConstBB == I.getParent())
2053 // If there is exactly one non-constant value, we can insert a copy of the
2054 // operation in that block. However, if this is a critical edge, we would be
2055 // inserting the computation one some other paths (e.g. inside a loop). Only
2056 // do this if the pred block is unconditionally branching into the phi block.
2057 if (NonConstBB != 0 && !AllowAggressive) {
2058 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2059 if (!BI || !BI->isUnconditional()) return 0;
2062 // Okay, we can do the transformation: create the new PHI node.
2063 PHINode *NewPN = PHINode::Create(I.getType(), "");
2064 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2065 InsertNewInstBefore(NewPN, *PN);
2066 NewPN->takeName(PN);
2068 // Next, add all of the operands to the PHI.
2069 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2070 // We only currently try to fold the condition of a select when it is a phi,
2071 // not the true/false values.
2072 Value *TrueV = SI->getTrueValue();
2073 Value *FalseV = SI->getFalseValue();
2074 BasicBlock *PhiTransBB = PN->getParent();
2075 for (unsigned i = 0; i != NumPHIValues; ++i) {
2076 BasicBlock *ThisBB = PN->getIncomingBlock(i);
2077 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2078 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
2080 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2081 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
2083 assert(PN->getIncomingBlock(i) == NonConstBB);
2084 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2086 "phitmp", NonConstBB->getTerminator());
2087 Worklist.Add(cast<Instruction>(InV));
2089 NewPN->addIncoming(InV, ThisBB);
2091 } else if (I.getNumOperands() == 2) {
2092 Constant *C = cast<Constant>(I.getOperand(1));
2093 for (unsigned i = 0; i != NumPHIValues; ++i) {
2095 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2096 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2097 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2099 InV = ConstantExpr::get(I.getOpcode(), InC, C);
2101 assert(PN->getIncomingBlock(i) == NonConstBB);
2102 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2103 InV = BinaryOperator::Create(BO->getOpcode(),
2104 PN->getIncomingValue(i), C, "phitmp",
2105 NonConstBB->getTerminator());
2106 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2107 InV = CmpInst::Create(CI->getOpcode(),
2109 PN->getIncomingValue(i), C, "phitmp",
2110 NonConstBB->getTerminator());
2112 llvm_unreachable("Unknown binop!");
2114 Worklist.Add(cast<Instruction>(InV));
2116 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2119 CastInst *CI = cast<CastInst>(&I);
2120 const Type *RetTy = CI->getType();
2121 for (unsigned i = 0; i != NumPHIValues; ++i) {
2123 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2124 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2126 assert(PN->getIncomingBlock(i) == NonConstBB);
2127 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
2128 I.getType(), "phitmp",
2129 NonConstBB->getTerminator());
2130 Worklist.Add(cast<Instruction>(InV));
2132 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2135 return ReplaceInstUsesWith(I, NewPN);
2139 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2140 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2141 /// This basically requires proving that the add in the original type would not
2142 /// overflow to change the sign bit or have a carry out.
2143 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2144 // There are different heuristics we can use for this. Here are some simple
2147 // Add has the property that adding any two 2's complement numbers can only
2148 // have one carry bit which can change a sign. As such, if LHS and RHS each
2149 // have at least two sign bits, we know that the addition of the two values will
2150 // sign extend fine.
2151 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2155 // If one of the operands only has one non-zero bit, and if the other operand
2156 // has a known-zero bit in a more significant place than it (not including the
2157 // sign bit) the ripple may go up to and fill the zero, but won't change the
2158 // sign. For example, (X & ~4) + 1.
2166 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2167 bool Changed = SimplifyCommutative(I);
2168 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2170 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2171 // X + undef -> undef
2172 if (isa<UndefValue>(RHS))
2173 return ReplaceInstUsesWith(I, RHS);
2176 if (RHSC->isNullValue())
2177 return ReplaceInstUsesWith(I, LHS);
2179 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2180 // X + (signbit) --> X ^ signbit
2181 const APInt& Val = CI->getValue();
2182 uint32_t BitWidth = Val.getBitWidth();
2183 if (Val == APInt::getSignBit(BitWidth))
2184 return BinaryOperator::CreateXor(LHS, RHS);
2186 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2187 // (X & 254)+1 -> (X&254)|1
2188 if (SimplifyDemandedInstructionBits(I))
2191 // zext(bool) + C -> bool ? C + 1 : C
2192 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2193 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2194 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
2197 if (isa<PHINode>(LHS))
2198 if (Instruction *NV = FoldOpIntoPhi(I))
2201 ConstantInt *XorRHS = 0;
2203 if (isa<ConstantInt>(RHSC) &&
2204 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2205 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2206 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2208 uint32_t Size = TySizeBits / 2;
2209 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2210 APInt CFF80Val(-C0080Val);
2212 if (TySizeBits > Size) {
2213 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2214 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2215 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2216 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2217 // This is a sign extend if the top bits are known zero.
2218 if (!MaskedValueIsZero(XorLHS,
2219 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2220 Size = 0; // Not a sign ext, but can't be any others either.
2225 C0080Val = APIntOps::lshr(C0080Val, Size);
2226 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2227 } while (Size >= 1);
2229 // FIXME: This shouldn't be necessary. When the backends can handle types
2230 // with funny bit widths then this switch statement should be removed. It
2231 // is just here to get the size of the "middle" type back up to something
2232 // that the back ends can handle.
2233 const Type *MiddleType = 0;
2236 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2237 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2238 case 8: MiddleType = Type::getInt8Ty(*Context); break;
2241 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
2242 return new SExtInst(NewTrunc, I.getType(), I.getName());
2247 if (I.getType() == Type::getInt1Ty(*Context))
2248 return BinaryOperator::CreateXor(LHS, RHS);
2251 if (I.getType()->isInteger()) {
2252 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
2255 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2256 if (RHSI->getOpcode() == Instruction::Sub)
2257 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2258 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2260 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2261 if (LHSI->getOpcode() == Instruction::Sub)
2262 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2263 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2268 // -A + -B --> -(A + B)
2269 if (Value *LHSV = dyn_castNegVal(LHS)) {
2270 if (LHS->getType()->isIntOrIntVector()) {
2271 if (Value *RHSV = dyn_castNegVal(RHS)) {
2272 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
2273 return BinaryOperator::CreateNeg(NewAdd);
2277 return BinaryOperator::CreateSub(RHS, LHSV);
2281 if (!isa<Constant>(RHS))
2282 if (Value *V = dyn_castNegVal(RHS))
2283 return BinaryOperator::CreateSub(LHS, V);
2287 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2288 if (X == RHS) // X*C + X --> X * (C+1)
2289 return BinaryOperator::CreateMul(RHS, AddOne(C2));
2291 // X*C1 + X*C2 --> X * (C1+C2)
2293 if (X == dyn_castFoldableMul(RHS, C1))
2294 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
2297 // X + X*C --> X * (C+1)
2298 if (dyn_castFoldableMul(RHS, C2) == LHS)
2299 return BinaryOperator::CreateMul(LHS, AddOne(C2));
2301 // X + ~X --> -1 since ~X = -X-1
2302 if (dyn_castNotVal(LHS) == RHS ||
2303 dyn_castNotVal(RHS) == LHS)
2304 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2307 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2308 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2309 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2312 // A+B --> A|B iff A and B have no bits set in common.
2313 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2314 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2315 APInt LHSKnownOne(IT->getBitWidth(), 0);
2316 APInt LHSKnownZero(IT->getBitWidth(), 0);
2317 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2318 if (LHSKnownZero != 0) {
2319 APInt RHSKnownOne(IT->getBitWidth(), 0);
2320 APInt RHSKnownZero(IT->getBitWidth(), 0);
2321 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2323 // No bits in common -> bitwise or.
2324 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2325 return BinaryOperator::CreateOr(LHS, RHS);
2329 // W*X + Y*Z --> W * (X+Z) iff W == Y
2330 if (I.getType()->isIntOrIntVector()) {
2331 Value *W, *X, *Y, *Z;
2332 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2333 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2337 } else if (Y == X) {
2339 } else if (X == Z) {
2346 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
2347 return BinaryOperator::CreateMul(W, NewAdd);
2352 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2354 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2355 return BinaryOperator::CreateSub(SubOne(CRHS), X);
2357 // (X & FF00) + xx00 -> (X+xx00) & FF00
2358 if (LHS->hasOneUse() &&
2359 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2360 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
2361 if (Anded == CRHS) {
2362 // See if all bits from the first bit set in the Add RHS up are included
2363 // in the mask. First, get the rightmost bit.
2364 const APInt& AddRHSV = CRHS->getValue();
2366 // Form a mask of all bits from the lowest bit added through the top.
2367 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2369 // See if the and mask includes all of these bits.
2370 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2372 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2373 // Okay, the xform is safe. Insert the new add pronto.
2374 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
2375 return BinaryOperator::CreateAnd(NewAdd, C2);
2380 // Try to fold constant add into select arguments.
2381 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2382 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2386 // add (select X 0 (sub n A)) A --> select X A n
2388 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2391 SI = dyn_cast<SelectInst>(RHS);
2394 if (SI && SI->hasOneUse()) {
2395 Value *TV = SI->getTrueValue();
2396 Value *FV = SI->getFalseValue();
2399 // Can we fold the add into the argument of the select?
2400 // We check both true and false select arguments for a matching subtract.
2401 if (match(FV, m_Zero()) &&
2402 match(TV, m_Sub(m_Value(N), m_Specific(A))))
2403 // Fold the add into the true select value.
2404 return SelectInst::Create(SI->getCondition(), N, A);
2405 if (match(TV, m_Zero()) &&
2406 match(FV, m_Sub(m_Value(N), m_Specific(A))))
2407 // Fold the add into the false select value.
2408 return SelectInst::Create(SI->getCondition(), A, N);
2412 // Check for (add (sext x), y), see if we can merge this into an
2413 // integer add followed by a sext.
2414 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2415 // (add (sext x), cst) --> (sext (add x, cst'))
2416 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2418 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2419 if (LHSConv->hasOneUse() &&
2420 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2421 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2422 // Insert the new, smaller add.
2423 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2425 return new SExtInst(NewAdd, I.getType());
2429 // (add (sext x), (sext y)) --> (sext (add int x, y))
2430 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2431 // Only do this if x/y have the same type, if at last one of them has a
2432 // single use (so we don't increase the number of sexts), and if the
2433 // integer add will not overflow.
2434 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2435 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2436 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2437 RHSConv->getOperand(0))) {
2438 // Insert the new integer add.
2439 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2440 RHSConv->getOperand(0), "addconv");
2441 return new SExtInst(NewAdd, I.getType());
2446 return Changed ? &I : 0;
2449 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2450 bool Changed = SimplifyCommutative(I);
2451 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2453 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2455 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2456 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2457 (I.getType())->getValueAPF()))
2458 return ReplaceInstUsesWith(I, LHS);
2461 if (isa<PHINode>(LHS))
2462 if (Instruction *NV = FoldOpIntoPhi(I))
2467 // -A + -B --> -(A + B)
2468 if (Value *LHSV = dyn_castFNegVal(LHS))
2469 return BinaryOperator::CreateFSub(RHS, LHSV);
2472 if (!isa<Constant>(RHS))
2473 if (Value *V = dyn_castFNegVal(RHS))
2474 return BinaryOperator::CreateFSub(LHS, V);
2476 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2477 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2478 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2479 return ReplaceInstUsesWith(I, LHS);
2481 // Check for (add double (sitofp x), y), see if we can merge this into an
2482 // integer add followed by a promotion.
2483 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2484 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2485 // ... if the constant fits in the integer value. This is useful for things
2486 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2487 // requires a constant pool load, and generally allows the add to be better
2489 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2491 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2492 if (LHSConv->hasOneUse() &&
2493 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2494 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2495 // Insert the new integer add.
2496 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2498 return new SIToFPInst(NewAdd, I.getType());
2502 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2503 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2504 // Only do this if x/y have the same type, if at last one of them has a
2505 // single use (so we don't increase the number of int->fp conversions),
2506 // and if the integer add will not overflow.
2507 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2508 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2509 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2510 RHSConv->getOperand(0))) {
2511 // Insert the new integer add.
2512 Value *NewAdd = Builder->CreateAdd(LHSConv->getOperand(0),
2513 RHSConv->getOperand(0), "addconv");
2514 return new SIToFPInst(NewAdd, I.getType());
2519 return Changed ? &I : 0;
2522 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2523 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2525 if (Op0 == Op1) // sub X, X -> 0
2526 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2528 // If this is a 'B = x-(-A)', change to B = x+A...
2529 if (Value *V = dyn_castNegVal(Op1))
2530 return BinaryOperator::CreateAdd(Op0, V);
2532 if (isa<UndefValue>(Op0))
2533 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2534 if (isa<UndefValue>(Op1))
2535 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2537 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2538 // Replace (-1 - A) with (~A)...
2539 if (C->isAllOnesValue())
2540 return BinaryOperator::CreateNot(Op1);
2542 // C - ~X == X + (1+C)
2544 if (match(Op1, m_Not(m_Value(X))))
2545 return BinaryOperator::CreateAdd(X, AddOne(C));
2547 // -(X >>u 31) -> (X >>s 31)
2548 // -(X >>s 31) -> (X >>u 31)
2550 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2551 if (SI->getOpcode() == Instruction::LShr) {
2552 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2553 // Check to see if we are shifting out everything but the sign bit.
2554 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2555 SI->getType()->getPrimitiveSizeInBits()-1) {
2556 // Ok, the transformation is safe. Insert AShr.
2557 return BinaryOperator::Create(Instruction::AShr,
2558 SI->getOperand(0), CU, SI->getName());
2562 else if (SI->getOpcode() == Instruction::AShr) {
2563 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2564 // Check to see if we are shifting out everything but the sign bit.
2565 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2566 SI->getType()->getPrimitiveSizeInBits()-1) {
2567 // Ok, the transformation is safe. Insert LShr.
2568 return BinaryOperator::CreateLShr(
2569 SI->getOperand(0), CU, SI->getName());
2576 // Try to fold constant sub into select arguments.
2577 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2578 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2581 // C - zext(bool) -> bool ? C - 1 : C
2582 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
2583 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
2584 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
2587 if (I.getType() == Type::getInt1Ty(*Context))
2588 return BinaryOperator::CreateXor(Op0, Op1);
2590 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2591 if (Op1I->getOpcode() == Instruction::Add) {
2592 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2593 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
2595 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2596 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
2598 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2599 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2600 // C1-(X+C2) --> (C1-C2)-X
2601 return BinaryOperator::CreateSub(
2602 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
2606 if (Op1I->hasOneUse()) {
2607 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2608 // is not used by anyone else...
2610 if (Op1I->getOpcode() == Instruction::Sub) {
2611 // Swap the two operands of the subexpr...
2612 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2613 Op1I->setOperand(0, IIOp1);
2614 Op1I->setOperand(1, IIOp0);
2616 // Create the new top level add instruction...
2617 return BinaryOperator::CreateAdd(Op0, Op1);
2620 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2622 if (Op1I->getOpcode() == Instruction::And &&
2623 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2624 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2626 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
2627 return BinaryOperator::CreateAnd(Op0, NewNot);
2630 // 0 - (X sdiv C) -> (X sdiv -C)
2631 if (Op1I->getOpcode() == Instruction::SDiv)
2632 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2634 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2635 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2636 ConstantExpr::getNeg(DivRHS));
2638 // X - X*C --> X * (1-C)
2639 ConstantInt *C2 = 0;
2640 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2642 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
2644 return BinaryOperator::CreateMul(Op0, CP1);
2649 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2650 if (Op0I->getOpcode() == Instruction::Add) {
2651 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2652 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2653 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2654 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2655 } else if (Op0I->getOpcode() == Instruction::Sub) {
2656 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2657 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
2663 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2664 if (X == Op1) // X*C - X --> X * (C-1)
2665 return BinaryOperator::CreateMul(Op1, SubOne(C1));
2667 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2668 if (X == dyn_castFoldableMul(Op1, C2))
2669 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
2674 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2675 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2677 // If this is a 'B = x-(-A)', change to B = x+A...
2678 if (Value *V = dyn_castFNegVal(Op1))
2679 return BinaryOperator::CreateFAdd(Op0, V);
2681 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2682 if (Op1I->getOpcode() == Instruction::FAdd) {
2683 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2684 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
2686 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2687 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
2695 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2696 /// comparison only checks the sign bit. If it only checks the sign bit, set
2697 /// TrueIfSigned if the result of the comparison is true when the input value is
2699 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2700 bool &TrueIfSigned) {
2702 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2703 TrueIfSigned = true;
2704 return RHS->isZero();
2705 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2706 TrueIfSigned = true;
2707 return RHS->isAllOnesValue();
2708 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2709 TrueIfSigned = false;
2710 return RHS->isAllOnesValue();
2711 case ICmpInst::ICMP_UGT:
2712 // True if LHS u> RHS and RHS == high-bit-mask - 1
2713 TrueIfSigned = true;
2714 return RHS->getValue() ==
2715 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2716 case ICmpInst::ICMP_UGE:
2717 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2718 TrueIfSigned = true;
2719 return RHS->getValue().isSignBit();
2725 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2726 bool Changed = SimplifyCommutative(I);
2727 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2729 if (isa<UndefValue>(Op1)) // undef * X -> 0
2730 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2732 // Simplify mul instructions with a constant RHS.
2733 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2734 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
2736 // ((X << C1)*C2) == (X * (C2 << C1))
2737 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2738 if (SI->getOpcode() == Instruction::Shl)
2739 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2740 return BinaryOperator::CreateMul(SI->getOperand(0),
2741 ConstantExpr::getShl(CI, ShOp));
2744 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
2745 if (CI->equalsInt(1)) // X * 1 == X
2746 return ReplaceInstUsesWith(I, Op0);
2747 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2748 return BinaryOperator::CreateNeg(Op0, I.getName());
2750 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2751 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2752 return BinaryOperator::CreateShl(Op0,
2753 ConstantInt::get(Op0->getType(), Val.logBase2()));
2755 } else if (isa<VectorType>(Op1C->getType())) {
2756 if (Op1C->isNullValue())
2757 return ReplaceInstUsesWith(I, Op1C);
2759 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
2760 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2761 return BinaryOperator::CreateNeg(Op0, I.getName());
2763 // As above, vector X*splat(1.0) -> X in all defined cases.
2764 if (Constant *Splat = Op1V->getSplatValue()) {
2765 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2766 if (CI->equalsInt(1))
2767 return ReplaceInstUsesWith(I, Op0);
2772 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2773 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2774 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
2775 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2776 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
2777 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
2778 return BinaryOperator::CreateAdd(Add, C1C2);
2782 // Try to fold constant mul into select arguments.
2783 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2784 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2787 if (isa<PHINode>(Op0))
2788 if (Instruction *NV = FoldOpIntoPhi(I))
2792 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2793 if (Value *Op1v = dyn_castNegVal(Op1))
2794 return BinaryOperator::CreateMul(Op0v, Op1v);
2796 // (X / Y) * Y = X - (X % Y)
2797 // (X / Y) * -Y = (X % Y) - X
2800 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2802 (BO->getOpcode() != Instruction::UDiv &&
2803 BO->getOpcode() != Instruction::SDiv)) {
2805 BO = dyn_cast<BinaryOperator>(Op1);
2807 Value *Neg = dyn_castNegVal(Op1C);
2808 if (BO && BO->hasOneUse() &&
2809 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
2810 (BO->getOpcode() == Instruction::UDiv ||
2811 BO->getOpcode() == Instruction::SDiv)) {
2812 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2814 // If the division is exact, X % Y is zero.
2815 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
2816 if (SDiv->isExact()) {
2818 return ReplaceInstUsesWith(I, Op0BO);
2819 return BinaryOperator::CreateNeg(Op0BO);
2823 if (BO->getOpcode() == Instruction::UDiv)
2824 Rem = Builder->CreateURem(Op0BO, Op1BO);
2826 Rem = Builder->CreateSRem(Op0BO, Op1BO);
2830 return BinaryOperator::CreateSub(Op0BO, Rem);
2831 return BinaryOperator::CreateSub(Rem, Op0BO);
2835 /// i1 mul -> i1 and.
2836 if (I.getType() == Type::getInt1Ty(*Context))
2837 return BinaryOperator::CreateAnd(Op0, Op1);
2839 // X*(1 << Y) --> X << Y
2840 // (1 << Y)*X --> X << Y
2843 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
2844 return BinaryOperator::CreateShl(Op1, Y);
2845 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
2846 return BinaryOperator::CreateShl(Op0, Y);
2849 // If one of the operands of the multiply is a cast from a boolean value, then
2850 // we know the bool is either zero or one, so this is a 'masking' multiply.
2851 // X * Y (where Y is 0 or 1) -> X & (0-Y)
2852 if (!isa<VectorType>(I.getType())) {
2853 // -2 is "-1 << 1" so it is all bits set except the low one.
2854 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
2856 Value *BoolCast = 0, *OtherOp = 0;
2857 if (MaskedValueIsZero(Op0, Negative2))
2858 BoolCast = Op0, OtherOp = Op1;
2859 else if (MaskedValueIsZero(Op1, Negative2))
2860 BoolCast = Op1, OtherOp = Op0;
2863 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
2865 return BinaryOperator::CreateAnd(V, OtherOp);
2869 return Changed ? &I : 0;
2872 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2873 bool Changed = SimplifyCommutative(I);
2874 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2876 // Simplify mul instructions with a constant RHS...
2877 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2878 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
2879 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2880 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2881 if (Op1F->isExactlyValue(1.0))
2882 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2883 } else if (isa<VectorType>(Op1C->getType())) {
2884 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
2885 // As above, vector X*splat(1.0) -> X in all defined cases.
2886 if (Constant *Splat = Op1V->getSplatValue()) {
2887 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2888 if (F->isExactlyValue(1.0))
2889 return ReplaceInstUsesWith(I, Op0);
2894 // Try to fold constant mul into select arguments.
2895 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2896 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2899 if (isa<PHINode>(Op0))
2900 if (Instruction *NV = FoldOpIntoPhi(I))
2904 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
2905 if (Value *Op1v = dyn_castFNegVal(Op1))
2906 return BinaryOperator::CreateFMul(Op0v, Op1v);
2908 return Changed ? &I : 0;
2911 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2913 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2914 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2916 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2917 int NonNullOperand = -1;
2918 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2919 if (ST->isNullValue())
2921 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2922 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2923 if (ST->isNullValue())
2926 if (NonNullOperand == -1)
2929 Value *SelectCond = SI->getOperand(0);
2931 // Change the div/rem to use 'Y' instead of the select.
2932 I.setOperand(1, SI->getOperand(NonNullOperand));
2934 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2935 // problem. However, the select, or the condition of the select may have
2936 // multiple uses. Based on our knowledge that the operand must be non-zero,
2937 // propagate the known value for the select into other uses of it, and
2938 // propagate a known value of the condition into its other users.
2940 // If the select and condition only have a single use, don't bother with this,
2942 if (SI->use_empty() && SelectCond->hasOneUse())
2945 // Scan the current block backward, looking for other uses of SI.
2946 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2948 while (BBI != BBFront) {
2950 // If we found a call to a function, we can't assume it will return, so
2951 // information from below it cannot be propagated above it.
2952 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2955 // Replace uses of the select or its condition with the known values.
2956 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2959 *I = SI->getOperand(NonNullOperand);
2961 } else if (*I == SelectCond) {
2962 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
2963 ConstantInt::getFalse(*Context);
2968 // If we past the instruction, quit looking for it.
2971 if (&*BBI == SelectCond)
2974 // If we ran out of things to eliminate, break out of the loop.
2975 if (SelectCond == 0 && SI == 0)
2983 /// This function implements the transforms on div instructions that work
2984 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2985 /// used by the visitors to those instructions.
2986 /// @brief Transforms common to all three div instructions
2987 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2988 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2990 // undef / X -> 0 for integer.
2991 // undef / X -> undef for FP (the undef could be a snan).
2992 if (isa<UndefValue>(Op0)) {
2993 if (Op0->getType()->isFPOrFPVector())
2994 return ReplaceInstUsesWith(I, Op0);
2995 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2998 // X / undef -> undef
2999 if (isa<UndefValue>(Op1))
3000 return ReplaceInstUsesWith(I, Op1);
3005 /// This function implements the transforms common to both integer division
3006 /// instructions (udiv and sdiv). It is called by the visitors to those integer
3007 /// division instructions.
3008 /// @brief Common integer divide transforms
3009 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3010 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3012 // (sdiv X, X) --> 1 (udiv X, X) --> 1
3014 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
3015 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
3016 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
3017 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
3020 Constant *CI = ConstantInt::get(I.getType(), 1);
3021 return ReplaceInstUsesWith(I, CI);
3024 if (Instruction *Common = commonDivTransforms(I))
3027 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3028 // This does not apply for fdiv.
3029 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3032 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3034 if (RHS->equalsInt(1))
3035 return ReplaceInstUsesWith(I, Op0);
3037 // (X / C1) / C2 -> X / (C1*C2)
3038 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3039 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3040 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
3041 if (MultiplyOverflows(RHS, LHSRHS,
3042 I.getOpcode()==Instruction::SDiv))
3043 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3045 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
3046 ConstantExpr::getMul(RHS, LHSRHS));
3049 if (!RHS->isZero()) { // avoid X udiv 0
3050 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3051 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3053 if (isa<PHINode>(Op0))
3054 if (Instruction *NV = FoldOpIntoPhi(I))
3059 // 0 / X == 0, we don't need to preserve faults!
3060 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3061 if (LHS->equalsInt(0))
3062 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3064 // It can't be division by zero, hence it must be division by one.
3065 if (I.getType() == Type::getInt1Ty(*Context))
3066 return ReplaceInstUsesWith(I, Op0);
3068 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3069 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3072 return ReplaceInstUsesWith(I, Op0);
3078 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3079 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3081 // Handle the integer div common cases
3082 if (Instruction *Common = commonIDivTransforms(I))
3085 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3086 // X udiv C^2 -> X >> C
3087 // Check to see if this is an unsigned division with an exact power of 2,
3088 // if so, convert to a right shift.
3089 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
3090 return BinaryOperator::CreateLShr(Op0,
3091 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3093 // X udiv C, where C >= signbit
3094 if (C->getValue().isNegative()) {
3095 Value *IC = Builder->CreateICmpULT( Op0, C);
3096 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
3097 ConstantInt::get(I.getType(), 1));
3101 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3102 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3103 if (RHSI->getOpcode() == Instruction::Shl &&
3104 isa<ConstantInt>(RHSI->getOperand(0))) {
3105 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3106 if (C1.isPowerOf2()) {
3107 Value *N = RHSI->getOperand(1);
3108 const Type *NTy = N->getType();
3109 if (uint32_t C2 = C1.logBase2())
3110 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
3111 return BinaryOperator::CreateLShr(Op0, N);
3116 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3117 // where C1&C2 are powers of two.
3118 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3119 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3120 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3121 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3122 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3123 // Compute the shift amounts
3124 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3125 // Construct the "on true" case of the select
3126 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
3127 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
3129 // Construct the "on false" case of the select
3130 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
3131 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
3133 // construct the select instruction and return it.
3134 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3140 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3141 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3143 // Handle the integer div common cases
3144 if (Instruction *Common = commonIDivTransforms(I))
3147 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3149 if (RHS->isAllOnesValue())
3150 return BinaryOperator::CreateNeg(Op0);
3152 // sdiv X, C --> ashr X, log2(C)
3153 if (cast<SDivOperator>(&I)->isExact() &&
3154 RHS->getValue().isNonNegative() &&
3155 RHS->getValue().isPowerOf2()) {
3156 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3157 RHS->getValue().exactLogBase2());
3158 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3161 // -X/C --> X/-C provided the negation doesn't overflow.
3162 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3163 if (isa<Constant>(Sub->getOperand(0)) &&
3164 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
3165 Sub->hasNoSignedWrap())
3166 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3167 ConstantExpr::getNeg(RHS));
3170 // If the sign bits of both operands are zero (i.e. we can prove they are
3171 // unsigned inputs), turn this into a udiv.
3172 if (I.getType()->isInteger()) {
3173 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3174 if (MaskedValueIsZero(Op0, Mask)) {
3175 if (MaskedValueIsZero(Op1, Mask)) {
3176 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3177 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3179 ConstantInt *ShiftedInt;
3180 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
3181 ShiftedInt->getValue().isPowerOf2()) {
3182 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3183 // Safe because the only negative value (1 << Y) can take on is
3184 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3185 // the sign bit set.
3186 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3194 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3195 return commonDivTransforms(I);
3198 /// This function implements the transforms on rem instructions that work
3199 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3200 /// is used by the visitors to those instructions.
3201 /// @brief Transforms common to all three rem instructions
3202 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3203 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3205 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3206 if (I.getType()->isFPOrFPVector())
3207 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
3208 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3210 if (isa<UndefValue>(Op1))
3211 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3213 // Handle cases involving: rem X, (select Cond, Y, Z)
3214 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3220 /// This function implements the transforms common to both integer remainder
3221 /// instructions (urem and srem). It is called by the visitors to those integer
3222 /// remainder instructions.
3223 /// @brief Common integer remainder transforms
3224 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3225 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3227 if (Instruction *common = commonRemTransforms(I))
3230 // 0 % X == 0 for integer, we don't need to preserve faults!
3231 if (Constant *LHS = dyn_cast<Constant>(Op0))
3232 if (LHS->isNullValue())
3233 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3235 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3236 // X % 0 == undef, we don't need to preserve faults!
3237 if (RHS->equalsInt(0))
3238 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3240 if (RHS->equalsInt(1)) // X % 1 == 0
3241 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3243 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3244 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3245 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3247 } else if (isa<PHINode>(Op0I)) {
3248 if (Instruction *NV = FoldOpIntoPhi(I))
3252 // See if we can fold away this rem instruction.
3253 if (SimplifyDemandedInstructionBits(I))
3261 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3262 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3264 if (Instruction *common = commonIRemTransforms(I))
3267 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3268 // X urem C^2 -> X and C
3269 // Check to see if this is an unsigned remainder with an exact power of 2,
3270 // if so, convert to a bitwise and.
3271 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3272 if (C->getValue().isPowerOf2())
3273 return BinaryOperator::CreateAnd(Op0, SubOne(C));
3276 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3277 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3278 if (RHSI->getOpcode() == Instruction::Shl &&
3279 isa<ConstantInt>(RHSI->getOperand(0))) {
3280 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3281 Constant *N1 = Constant::getAllOnesValue(I.getType());
3282 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
3283 return BinaryOperator::CreateAnd(Op0, Add);
3288 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3289 // where C1&C2 are powers of two.
3290 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3291 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3292 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3293 // STO == 0 and SFO == 0 handled above.
3294 if ((STO->getValue().isPowerOf2()) &&
3295 (SFO->getValue().isPowerOf2())) {
3296 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3297 SI->getName()+".t");
3298 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3299 SI->getName()+".f");
3300 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3308 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3309 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3311 // Handle the integer rem common cases
3312 if (Instruction *Common = commonIRemTransforms(I))
3315 if (Value *RHSNeg = dyn_castNegVal(Op1))
3316 if (!isa<Constant>(RHSNeg) ||
3317 (isa<ConstantInt>(RHSNeg) &&
3318 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3320 Worklist.AddValue(I.getOperand(1));
3321 I.setOperand(1, RHSNeg);
3325 // If the sign bits of both operands are zero (i.e. we can prove they are
3326 // unsigned inputs), turn this into a urem.
3327 if (I.getType()->isInteger()) {
3328 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3329 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3330 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3331 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3335 // If it's a constant vector, flip any negative values positive.
3336 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3337 unsigned VWidth = RHSV->getNumOperands();
3339 bool hasNegative = false;
3340 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3341 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3342 if (RHS->getValue().isNegative())
3346 std::vector<Constant *> Elts(VWidth);
3347 for (unsigned i = 0; i != VWidth; ++i) {
3348 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3349 if (RHS->getValue().isNegative())
3350 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3356 Constant *NewRHSV = ConstantVector::get(Elts);
3357 if (NewRHSV != RHSV) {
3358 Worklist.AddValue(I.getOperand(1));
3359 I.setOperand(1, NewRHSV);
3368 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3369 return commonRemTransforms(I);
3372 // isOneBitSet - Return true if there is exactly one bit set in the specified
3374 static bool isOneBitSet(const ConstantInt *CI) {
3375 return CI->getValue().isPowerOf2();
3378 // isHighOnes - Return true if the constant is of the form 1+0+.
3379 // This is the same as lowones(~X).
3380 static bool isHighOnes(const ConstantInt *CI) {
3381 return (~CI->getValue() + 1).isPowerOf2();
3384 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3385 /// are carefully arranged to allow folding of expressions such as:
3387 /// (A < B) | (A > B) --> (A != B)
3389 /// Note that this is only valid if the first and second predicates have the
3390 /// same sign. Is illegal to do: (A u< B) | (A s> B)
3392 /// Three bits are used to represent the condition, as follows:
3397 /// <=> Value Definition
3398 /// 000 0 Always false
3405 /// 111 7 Always true
3407 static unsigned getICmpCode(const ICmpInst *ICI) {
3408 switch (ICI->getPredicate()) {
3410 case ICmpInst::ICMP_UGT: return 1; // 001
3411 case ICmpInst::ICMP_SGT: return 1; // 001
3412 case ICmpInst::ICMP_EQ: return 2; // 010
3413 case ICmpInst::ICMP_UGE: return 3; // 011
3414 case ICmpInst::ICMP_SGE: return 3; // 011
3415 case ICmpInst::ICMP_ULT: return 4; // 100
3416 case ICmpInst::ICMP_SLT: return 4; // 100
3417 case ICmpInst::ICMP_NE: return 5; // 101
3418 case ICmpInst::ICMP_ULE: return 6; // 110
3419 case ICmpInst::ICMP_SLE: return 6; // 110
3422 llvm_unreachable("Invalid ICmp predicate!");
3427 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3428 /// predicate into a three bit mask. It also returns whether it is an ordered
3429 /// predicate by reference.
3430 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3433 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3434 case FCmpInst::FCMP_UNO: return 0; // 000
3435 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3436 case FCmpInst::FCMP_UGT: return 1; // 001
3437 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3438 case FCmpInst::FCMP_UEQ: return 2; // 010
3439 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3440 case FCmpInst::FCMP_UGE: return 3; // 011
3441 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3442 case FCmpInst::FCMP_ULT: return 4; // 100
3443 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3444 case FCmpInst::FCMP_UNE: return 5; // 101
3445 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3446 case FCmpInst::FCMP_ULE: return 6; // 110
3449 // Not expecting FCMP_FALSE and FCMP_TRUE;
3450 llvm_unreachable("Unexpected FCmp predicate!");
3455 /// getICmpValue - This is the complement of getICmpCode, which turns an
3456 /// opcode and two operands into either a constant true or false, or a brand
3457 /// new ICmp instruction. The sign is passed in to determine which kind
3458 /// of predicate to use in the new icmp instruction.
3459 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3460 LLVMContext *Context) {
3462 default: llvm_unreachable("Illegal ICmp code!");
3463 case 0: return ConstantInt::getFalse(*Context);
3466 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3468 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3469 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3472 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3474 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3477 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3479 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3480 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3483 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3485 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3486 case 7: return ConstantInt::getTrue(*Context);
3490 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3491 /// opcode and two operands into either a FCmp instruction. isordered is passed
3492 /// in to determine which kind of predicate to use in the new fcmp instruction.
3493 static Value *getFCmpValue(bool isordered, unsigned code,
3494 Value *LHS, Value *RHS, LLVMContext *Context) {
3496 default: llvm_unreachable("Illegal FCmp code!");
3499 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3501 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3504 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3506 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
3509 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3511 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
3514 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3516 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3519 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3521 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3524 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3526 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3529 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3531 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
3532 case 7: return ConstantInt::getTrue(*Context);
3536 /// PredicatesFoldable - Return true if both predicates match sign or if at
3537 /// least one of them is an equality comparison (which is signless).
3538 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3539 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3540 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3541 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
3545 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3546 struct FoldICmpLogical {
3549 ICmpInst::Predicate pred;
3550 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3551 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3552 pred(ICI->getPredicate()) {}
3553 bool shouldApply(Value *V) const {
3554 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3555 if (PredicatesFoldable(pred, ICI->getPredicate()))
3556 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3557 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3560 Instruction *apply(Instruction &Log) const {
3561 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3562 if (ICI->getOperand(0) != LHS) {
3563 assert(ICI->getOperand(1) == LHS);
3564 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3567 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3568 unsigned LHSCode = getICmpCode(ICI);
3569 unsigned RHSCode = getICmpCode(RHSICI);
3571 switch (Log.getOpcode()) {
3572 case Instruction::And: Code = LHSCode & RHSCode; break;
3573 case Instruction::Or: Code = LHSCode | RHSCode; break;
3574 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3575 default: llvm_unreachable("Illegal logical opcode!"); return 0;
3578 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
3579 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3580 if (Instruction *I = dyn_cast<Instruction>(RV))
3582 // Otherwise, it's a constant boolean value...
3583 return IC.ReplaceInstUsesWith(Log, RV);
3586 } // end anonymous namespace
3588 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3589 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3590 // guaranteed to be a binary operator.
3591 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3593 ConstantInt *AndRHS,
3594 BinaryOperator &TheAnd) {
3595 Value *X = Op->getOperand(0);
3596 Constant *Together = 0;
3598 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
3600 switch (Op->getOpcode()) {
3601 case Instruction::Xor:
3602 if (Op->hasOneUse()) {
3603 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3604 Value *And = Builder->CreateAnd(X, AndRHS);
3606 return BinaryOperator::CreateXor(And, Together);
3609 case Instruction::Or:
3610 if (Together == AndRHS) // (X | C) & C --> C
3611 return ReplaceInstUsesWith(TheAnd, AndRHS);
3613 if (Op->hasOneUse() && Together != OpRHS) {
3614 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3615 Value *Or = Builder->CreateOr(X, Together);
3617 return BinaryOperator::CreateAnd(Or, AndRHS);
3620 case Instruction::Add:
3621 if (Op->hasOneUse()) {
3622 // Adding a one to a single bit bit-field should be turned into an XOR
3623 // of the bit. First thing to check is to see if this AND is with a
3624 // single bit constant.
3625 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3627 // If there is only one bit set...
3628 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3629 // Ok, at this point, we know that we are masking the result of the
3630 // ADD down to exactly one bit. If the constant we are adding has
3631 // no bits set below this bit, then we can eliminate the ADD.
3632 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3634 // Check to see if any bits below the one bit set in AndRHSV are set.
3635 if ((AddRHS & (AndRHSV-1)) == 0) {
3636 // If not, the only thing that can effect the output of the AND is
3637 // the bit specified by AndRHSV. If that bit is set, the effect of
3638 // the XOR is to toggle the bit. If it is clear, then the ADD has
3640 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3641 TheAnd.setOperand(0, X);
3644 // Pull the XOR out of the AND.
3645 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
3646 NewAnd->takeName(Op);
3647 return BinaryOperator::CreateXor(NewAnd, AndRHS);
3654 case Instruction::Shl: {
3655 // We know that the AND will not produce any of the bits shifted in, so if
3656 // the anded constant includes them, clear them now!
3658 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3659 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3660 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3661 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
3663 if (CI->getValue() == ShlMask) {
3664 // Masking out bits that the shift already masks
3665 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3666 } else if (CI != AndRHS) { // Reducing bits set in and.
3667 TheAnd.setOperand(1, CI);
3672 case Instruction::LShr:
3674 // We know that the AND will not produce any of the bits shifted in, so if
3675 // the anded constant includes them, clear them now! This only applies to
3676 // unsigned shifts, because a signed shr may bring in set bits!
3678 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3679 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3680 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3681 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3683 if (CI->getValue() == ShrMask) {
3684 // Masking out bits that the shift already masks.
3685 return ReplaceInstUsesWith(TheAnd, Op);
3686 } else if (CI != AndRHS) {
3687 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3692 case Instruction::AShr:
3694 // See if this is shifting in some sign extension, then masking it out
3696 if (Op->hasOneUse()) {
3697 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3698 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3699 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3700 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
3701 if (C == AndRHS) { // Masking out bits shifted in.
3702 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3703 // Make the argument unsigned.
3704 Value *ShVal = Op->getOperand(0);
3705 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
3706 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3715 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3716 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3717 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3718 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3719 /// insert new instructions.
3720 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3721 bool isSigned, bool Inside,
3723 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3724 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3725 "Lo is not <= Hi in range emission code!");
3728 if (Lo == Hi) // Trivially false.
3729 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3731 // V >= Min && V < Hi --> V < Hi
3732 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3733 ICmpInst::Predicate pred = (isSigned ?
3734 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3735 return new ICmpInst(pred, V, Hi);
3738 // Emit V-Lo <u Hi-Lo
3739 Constant *NegLo = ConstantExpr::getNeg(Lo);
3740 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3741 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3742 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3745 if (Lo == Hi) // Trivially true.
3746 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3748 // V < Min || V >= Hi -> V > Hi-1
3749 Hi = SubOne(cast<ConstantInt>(Hi));
3750 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3751 ICmpInst::Predicate pred = (isSigned ?
3752 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3753 return new ICmpInst(pred, V, Hi);
3756 // Emit V-Lo >u Hi-1-Lo
3757 // Note that Hi has already had one subtracted from it, above.
3758 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3759 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
3760 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3761 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3764 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3765 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3766 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3767 // not, since all 1s are not contiguous.
3768 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3769 const APInt& V = Val->getValue();
3770 uint32_t BitWidth = Val->getType()->getBitWidth();
3771 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3773 // look for the first zero bit after the run of ones
3774 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3775 // look for the first non-zero bit
3776 ME = V.getActiveBits();
3780 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3781 /// where isSub determines whether the operator is a sub. If we can fold one of
3782 /// the following xforms:
3784 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3785 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3786 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3788 /// return (A +/- B).
3790 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3791 ConstantInt *Mask, bool isSub,
3793 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3794 if (!LHSI || LHSI->getNumOperands() != 2 ||
3795 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3797 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3799 switch (LHSI->getOpcode()) {
3801 case Instruction::And:
3802 if (ConstantExpr::getAnd(N, Mask) == Mask) {
3803 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3804 if ((Mask->getValue().countLeadingZeros() +
3805 Mask->getValue().countPopulation()) ==
3806 Mask->getValue().getBitWidth())
3809 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3810 // part, we don't need any explicit masks to take them out of A. If that
3811 // is all N is, ignore it.
3812 uint32_t MB = 0, ME = 0;
3813 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3814 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3815 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3816 if (MaskedValueIsZero(RHS, Mask))
3821 case Instruction::Or:
3822 case Instruction::Xor:
3823 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3824 if ((Mask->getValue().countLeadingZeros() +
3825 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3826 && ConstantExpr::getAnd(N, Mask)->isNullValue())
3832 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
3833 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
3836 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3837 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3838 ICmpInst *LHS, ICmpInst *RHS) {
3840 ConstantInt *LHSCst, *RHSCst;
3841 ICmpInst::Predicate LHSCC, RHSCC;
3843 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3844 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3845 m_ConstantInt(LHSCst))) ||
3846 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3847 m_ConstantInt(RHSCst))))
3850 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3851 // where C is a power of 2
3852 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3853 LHSCst->getValue().isPowerOf2()) {
3854 Value *NewOr = Builder->CreateOr(Val, Val2);
3855 return new ICmpInst(LHSCC, NewOr, LHSCst);
3858 // From here on, we only handle:
3859 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3860 if (Val != Val2) return 0;
3862 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3863 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3864 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3865 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3866 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3869 // We can't fold (ugt x, C) & (sgt x, C2).
3870 if (!PredicatesFoldable(LHSCC, RHSCC))
3873 // Ensure that the larger constant is on the RHS.
3875 if (CmpInst::isSigned(LHSCC) ||
3876 (ICmpInst::isEquality(LHSCC) &&
3877 CmpInst::isSigned(RHSCC)))
3878 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3880 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3883 std::swap(LHS, RHS);
3884 std::swap(LHSCst, RHSCst);
3885 std::swap(LHSCC, RHSCC);
3888 // At this point, we know we have have two icmp instructions
3889 // comparing a value against two constants and and'ing the result
3890 // together. Because of the above check, we know that we only have
3891 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3892 // (from the FoldICmpLogical check above), that the two constants
3893 // are not equal and that the larger constant is on the RHS
3894 assert(LHSCst != RHSCst && "Compares not folded above?");
3897 default: llvm_unreachable("Unknown integer condition code!");
3898 case ICmpInst::ICMP_EQ:
3900 default: llvm_unreachable("Unknown integer condition code!");
3901 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3902 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3903 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3904 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3905 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3906 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3907 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3908 return ReplaceInstUsesWith(I, LHS);
3910 case ICmpInst::ICMP_NE:
3912 default: llvm_unreachable("Unknown integer condition code!");
3913 case ICmpInst::ICMP_ULT:
3914 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3915 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3916 break; // (X != 13 & X u< 15) -> no change
3917 case ICmpInst::ICMP_SLT:
3918 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3919 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3920 break; // (X != 13 & X s< 15) -> no change
3921 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3922 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3923 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3924 return ReplaceInstUsesWith(I, RHS);
3925 case ICmpInst::ICMP_NE:
3926 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3927 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3928 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
3929 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3930 ConstantInt::get(Add->getType(), 1));
3932 break; // (X != 13 & X != 15) -> no change
3935 case ICmpInst::ICMP_ULT:
3937 default: llvm_unreachable("Unknown integer condition code!");
3938 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3939 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3940 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3941 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3943 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3944 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3945 return ReplaceInstUsesWith(I, LHS);
3946 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3950 case ICmpInst::ICMP_SLT:
3952 default: llvm_unreachable("Unknown integer condition code!");
3953 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3954 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3955 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
3956 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3958 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3959 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3960 return ReplaceInstUsesWith(I, LHS);
3961 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3965 case ICmpInst::ICMP_UGT:
3967 default: llvm_unreachable("Unknown integer condition code!");
3968 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3969 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3970 return ReplaceInstUsesWith(I, RHS);
3971 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3973 case ICmpInst::ICMP_NE:
3974 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3975 return new ICmpInst(LHSCC, Val, RHSCst);
3976 break; // (X u> 13 & X != 15) -> no change
3977 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
3978 return InsertRangeTest(Val, AddOne(LHSCst),
3979 RHSCst, false, true, I);
3980 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3984 case ICmpInst::ICMP_SGT:
3986 default: llvm_unreachable("Unknown integer condition code!");
3987 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3988 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3989 return ReplaceInstUsesWith(I, RHS);
3990 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3992 case ICmpInst::ICMP_NE:
3993 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3994 return new ICmpInst(LHSCC, Val, RHSCst);
3995 break; // (X s> 13 & X != 15) -> no change
3996 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
3997 return InsertRangeTest(Val, AddOne(LHSCst),
3998 RHSCst, true, true, I);
3999 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4008 Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4011 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4012 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4013 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4014 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4015 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4016 // If either of the constants are nans, then the whole thing returns
4018 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4019 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4020 return new FCmpInst(FCmpInst::FCMP_ORD,
4021 LHS->getOperand(0), RHS->getOperand(0));
4024 // Handle vector zeros. This occurs because the canonical form of
4025 // "fcmp ord x,x" is "fcmp ord x, 0".
4026 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4027 isa<ConstantAggregateZero>(RHS->getOperand(1)))
4028 return new FCmpInst(FCmpInst::FCMP_ORD,
4029 LHS->getOperand(0), RHS->getOperand(0));
4033 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4034 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4035 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4038 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4039 // Swap RHS operands to match LHS.
4040 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4041 std::swap(Op1LHS, Op1RHS);
4044 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4045 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4047 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4049 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
4050 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4051 if (Op0CC == FCmpInst::FCMP_TRUE)
4052 return ReplaceInstUsesWith(I, RHS);
4053 if (Op1CC == FCmpInst::FCMP_TRUE)
4054 return ReplaceInstUsesWith(I, LHS);
4058 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4059 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4061 std::swap(LHS, RHS);
4062 std::swap(Op0Pred, Op1Pred);
4063 std::swap(Op0Ordered, Op1Ordered);
4066 // uno && ueq -> uno && (uno || eq) -> ueq
4067 // ord && olt -> ord && (ord && lt) -> olt
4068 if (Op0Ordered == Op1Ordered)
4069 return ReplaceInstUsesWith(I, RHS);
4071 // uno && oeq -> uno && (ord && eq) -> false
4072 // uno && ord -> false
4074 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
4075 // ord && ueq -> ord && (uno || eq) -> oeq
4076 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4077 Op0LHS, Op0RHS, Context));
4085 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
4086 bool Changed = SimplifyCommutative(I);
4087 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4089 if (isa<UndefValue>(Op1)) // X & undef -> 0
4090 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4094 return ReplaceInstUsesWith(I, Op1);
4096 // See if we can simplify any instructions used by the instruction whose sole
4097 // purpose is to compute bits we don't care about.
4098 if (SimplifyDemandedInstructionBits(I))
4100 if (isa<VectorType>(I.getType())) {
4101 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4102 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
4103 return ReplaceInstUsesWith(I, I.getOperand(0));
4104 } else if (isa<ConstantAggregateZero>(Op1)) {
4105 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
4109 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
4110 const APInt &AndRHSMask = AndRHS->getValue();
4111 APInt NotAndRHS(~AndRHSMask);
4113 // Optimize a variety of ((val OP C1) & C2) combinations...
4114 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4115 Value *Op0LHS = Op0I->getOperand(0);
4116 Value *Op0RHS = Op0I->getOperand(1);
4117 switch (Op0I->getOpcode()) {
4119 case Instruction::Xor:
4120 case Instruction::Or:
4121 // If the mask is only needed on one incoming arm, push it up.
4122 if (!Op0I->hasOneUse()) break;
4124 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4125 // Not masking anything out for the LHS, move to RHS.
4126 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4127 Op0RHS->getName()+".masked");
4128 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4130 if (!isa<Constant>(Op0RHS) &&
4131 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4132 // Not masking anything out for the RHS, move to LHS.
4133 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4134 Op0LHS->getName()+".masked");
4135 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
4139 case Instruction::Add:
4140 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4141 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4142 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4143 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4144 return BinaryOperator::CreateAnd(V, AndRHS);
4145 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4146 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
4149 case Instruction::Sub:
4150 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4151 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4152 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4153 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4154 return BinaryOperator::CreateAnd(V, AndRHS);
4156 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4157 // has 1's for all bits that the subtraction with A might affect.
4158 if (Op0I->hasOneUse()) {
4159 uint32_t BitWidth = AndRHSMask.getBitWidth();
4160 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4161 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4163 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4164 if (!(A && A->isZero()) && // avoid infinite recursion.
4165 MaskedValueIsZero(Op0LHS, Mask)) {
4166 Value *NewNeg = Builder->CreateNeg(Op0RHS);
4167 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4172 case Instruction::Shl:
4173 case Instruction::LShr:
4174 // (1 << x) & 1 --> zext(x == 0)
4175 // (1 >> x) & 1 --> zext(x == 0)
4176 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4178 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
4179 return new ZExtInst(NewICmp, I.getType());
4184 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4185 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4187 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4188 // If this is an integer truncation or change from signed-to-unsigned, and
4189 // if the source is an and/or with immediate, transform it. This
4190 // frequently occurs for bitfield accesses.
4191 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4192 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4193 CastOp->getNumOperands() == 2)
4194 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
4195 if (CastOp->getOpcode() == Instruction::And) {
4196 // Change: and (cast (and X, C1) to T), C2
4197 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4198 // This will fold the two constants together, which may allow
4199 // other simplifications.
4200 Value *NewCast = Builder->CreateTruncOrBitCast(
4201 CastOp->getOperand(0), I.getType(),
4202 CastOp->getName()+".shrunk");
4203 // trunc_or_bitcast(C1)&C2
4204 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4205 C3 = ConstantExpr::getAnd(C3, AndRHS);
4206 return BinaryOperator::CreateAnd(NewCast, C3);
4207 } else if (CastOp->getOpcode() == Instruction::Or) {
4208 // Change: and (cast (or X, C1) to T), C2
4209 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4210 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
4211 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
4213 return ReplaceInstUsesWith(I, AndRHS);
4219 // Try to fold constant and into select arguments.
4220 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4221 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4223 if (isa<PHINode>(Op0))
4224 if (Instruction *NV = FoldOpIntoPhi(I))
4228 Value *Op0NotVal = dyn_castNotVal(Op0);
4229 Value *Op1NotVal = dyn_castNotVal(Op1);
4231 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4232 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4234 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4235 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4236 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4237 I.getName()+".demorgan");
4238 return BinaryOperator::CreateNot(Or);
4242 Value *A = 0, *B = 0, *C = 0, *D = 0;
4243 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4244 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4245 return ReplaceInstUsesWith(I, Op1);
4247 // (A|B) & ~(A&B) -> A^B
4248 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4249 if ((A == C && B == D) || (A == D && B == C))
4250 return BinaryOperator::CreateXor(A, B);
4254 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4255 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4256 return ReplaceInstUsesWith(I, Op0);
4258 // ~(A&B) & (A|B) -> A^B
4259 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4260 if ((A == C && B == D) || (A == D && B == C))
4261 return BinaryOperator::CreateXor(A, B);
4265 if (Op0->hasOneUse() &&
4266 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4267 if (A == Op1) { // (A^B)&A -> A&(A^B)
4268 I.swapOperands(); // Simplify below
4269 std::swap(Op0, Op1);
4270 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4271 cast<BinaryOperator>(Op0)->swapOperands();
4272 I.swapOperands(); // Simplify below
4273 std::swap(Op0, Op1);
4277 if (Op1->hasOneUse() &&
4278 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4279 if (B == Op0) { // B&(A^B) -> B&(B^A)
4280 cast<BinaryOperator>(Op1)->swapOperands();
4283 if (A == Op0) // A&(A^B) -> A & ~B
4284 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
4287 // (A&((~A)|B)) -> A&B
4288 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4289 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4290 return BinaryOperator::CreateAnd(A, Op1);
4291 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4292 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4293 return BinaryOperator::CreateAnd(A, Op0);
4296 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4297 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4298 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4301 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4302 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4306 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4307 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4308 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4309 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4310 const Type *SrcTy = Op0C->getOperand(0)->getType();
4311 if (SrcTy == Op1C->getOperand(0)->getType() &&
4312 SrcTy->isIntOrIntVector() &&
4313 // Only do this if the casts both really cause code to be generated.
4314 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4316 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4318 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4319 Op1C->getOperand(0), I.getName());
4320 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4324 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4325 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4326 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4327 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4328 SI0->getOperand(1) == SI1->getOperand(1) &&
4329 (SI0->hasOneUse() || SI1->hasOneUse())) {
4331 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4333 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4334 SI1->getOperand(1));
4338 // If and'ing two fcmp, try combine them into one.
4339 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4340 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4341 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4345 return Changed ? &I : 0;
4348 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4349 /// capable of providing pieces of a bswap. The subexpression provides pieces
4350 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4351 /// the expression came from the corresponding "byte swapped" byte in some other
4352 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4353 /// we know that the expression deposits the low byte of %X into the high byte
4354 /// of the bswap result and that all other bytes are zero. This expression is
4355 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4358 /// This function returns true if the match was unsuccessful and false if so.
4359 /// On entry to the function the "OverallLeftShift" is a signed integer value
4360 /// indicating the number of bytes that the subexpression is later shifted. For
4361 /// example, if the expression is later right shifted by 16 bits, the
4362 /// OverallLeftShift value would be -2 on entry. This is used to specify which
4363 /// byte of ByteValues is actually being set.
4365 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4366 /// byte is masked to zero by a user. For example, in (X & 255), X will be
4367 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4368 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
4369 /// always in the local (OverallLeftShift) coordinate space.
4371 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4372 SmallVector<Value*, 8> &ByteValues) {
4373 if (Instruction *I = dyn_cast<Instruction>(V)) {
4374 // If this is an or instruction, it may be an inner node of the bswap.
4375 if (I->getOpcode() == Instruction::Or) {
4376 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4378 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4382 // If this is a logical shift by a constant multiple of 8, recurse with
4383 // OverallLeftShift and ByteMask adjusted.
4384 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4386 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4387 // Ensure the shift amount is defined and of a byte value.
4388 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4391 unsigned ByteShift = ShAmt >> 3;
4392 if (I->getOpcode() == Instruction::Shl) {
4393 // X << 2 -> collect(X, +2)
4394 OverallLeftShift += ByteShift;
4395 ByteMask >>= ByteShift;
4397 // X >>u 2 -> collect(X, -2)
4398 OverallLeftShift -= ByteShift;
4399 ByteMask <<= ByteShift;
4400 ByteMask &= (~0U >> (32-ByteValues.size()));
4403 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4404 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4406 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4410 // If this is a logical 'and' with a mask that clears bytes, clear the
4411 // corresponding bytes in ByteMask.
4412 if (I->getOpcode() == Instruction::And &&
4413 isa<ConstantInt>(I->getOperand(1))) {
4414 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4415 unsigned NumBytes = ByteValues.size();
4416 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4417 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4419 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4420 // If this byte is masked out by a later operation, we don't care what
4422 if ((ByteMask & (1 << i)) == 0)
4425 // If the AndMask is all zeros for this byte, clear the bit.
4426 APInt MaskB = AndMask & Byte;
4428 ByteMask &= ~(1U << i);
4432 // If the AndMask is not all ones for this byte, it's not a bytezap.
4436 // Otherwise, this byte is kept.
4439 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4444 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4445 // the input value to the bswap. Some observations: 1) if more than one byte
4446 // is demanded from this input, then it could not be successfully assembled
4447 // into a byteswap. At least one of the two bytes would not be aligned with
4448 // their ultimate destination.
4449 if (!isPowerOf2_32(ByteMask)) return true;
4450 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4452 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4453 // is demanded, it needs to go into byte 0 of the result. This means that the
4454 // byte needs to be shifted until it lands in the right byte bucket. The
4455 // shift amount depends on the position: if the byte is coming from the high
4456 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4457 // low part, it must be shifted left.
4458 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4459 if (InputByteNo < ByteValues.size()/2) {
4460 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4463 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4467 // If the destination byte value is already defined, the values are or'd
4468 // together, which isn't a bswap (unless it's an or of the same bits).
4469 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4471 ByteValues[DestByteNo] = V;
4475 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4476 /// If so, insert the new bswap intrinsic and return it.
4477 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4478 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4479 if (!ITy || ITy->getBitWidth() % 16 ||
4480 // ByteMask only allows up to 32-byte values.
4481 ITy->getBitWidth() > 32*8)
4482 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4484 /// ByteValues - For each byte of the result, we keep track of which value
4485 /// defines each byte.
4486 SmallVector<Value*, 8> ByteValues;
4487 ByteValues.resize(ITy->getBitWidth()/8);
4489 // Try to find all the pieces corresponding to the bswap.
4490 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4491 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4494 // Check to see if all of the bytes come from the same value.
4495 Value *V = ByteValues[0];
4496 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4498 // Check to make sure that all of the bytes come from the same value.
4499 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4500 if (ByteValues[i] != V)
4502 const Type *Tys[] = { ITy };
4503 Module *M = I.getParent()->getParent()->getParent();
4504 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4505 return CallInst::Create(F, V);
4508 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4509 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4510 /// we can simplify this expression to "cond ? C : D or B".
4511 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4513 LLVMContext *Context) {
4514 // If A is not a select of -1/0, this cannot match.
4516 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4519 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4520 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4521 return SelectInst::Create(Cond, C, B);
4522 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4523 return SelectInst::Create(Cond, C, B);
4524 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4525 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4526 return SelectInst::Create(Cond, C, D);
4527 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4528 return SelectInst::Create(Cond, C, D);
4532 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4533 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4534 ICmpInst *LHS, ICmpInst *RHS) {
4536 ConstantInt *LHSCst, *RHSCst;
4537 ICmpInst::Predicate LHSCC, RHSCC;
4539 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4540 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4541 m_ConstantInt(LHSCst))) ||
4542 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4543 m_ConstantInt(RHSCst))))
4546 // From here on, we only handle:
4547 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4548 if (Val != Val2) return 0;
4550 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4551 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4552 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4553 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4554 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4557 // We can't fold (ugt x, C) | (sgt x, C2).
4558 if (!PredicatesFoldable(LHSCC, RHSCC))
4561 // Ensure that the larger constant is on the RHS.
4563 if (CmpInst::isSigned(LHSCC) ||
4564 (ICmpInst::isEquality(LHSCC) &&
4565 CmpInst::isSigned(RHSCC)))
4566 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4568 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4571 std::swap(LHS, RHS);
4572 std::swap(LHSCst, RHSCst);
4573 std::swap(LHSCC, RHSCC);
4576 // At this point, we know we have have two icmp instructions
4577 // comparing a value against two constants and or'ing the result
4578 // together. Because of the above check, we know that we only have
4579 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4580 // FoldICmpLogical check above), that the two constants are not
4582 assert(LHSCst != RHSCst && "Compares not folded above?");
4585 default: llvm_unreachable("Unknown integer condition code!");
4586 case ICmpInst::ICMP_EQ:
4588 default: llvm_unreachable("Unknown integer condition code!");
4589 case ICmpInst::ICMP_EQ:
4590 if (LHSCst == SubOne(RHSCst)) {
4591 // (X == 13 | X == 14) -> X-13 <u 2
4592 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4593 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
4594 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
4595 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4597 break; // (X == 13 | X == 15) -> no change
4598 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4599 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4601 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4602 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4603 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4604 return ReplaceInstUsesWith(I, RHS);
4607 case ICmpInst::ICMP_NE:
4609 default: llvm_unreachable("Unknown integer condition code!");
4610 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4611 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4612 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4613 return ReplaceInstUsesWith(I, LHS);
4614 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4615 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4616 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4617 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4620 case ICmpInst::ICMP_ULT:
4622 default: llvm_unreachable("Unknown integer condition code!");
4623 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4625 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4626 // If RHSCst is [us]MAXINT, it is always false. Not handling
4627 // this can cause overflow.
4628 if (RHSCst->isMaxValue(false))
4629 return ReplaceInstUsesWith(I, LHS);
4630 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4632 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4634 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4635 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4636 return ReplaceInstUsesWith(I, RHS);
4637 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4641 case ICmpInst::ICMP_SLT:
4643 default: llvm_unreachable("Unknown integer condition code!");
4644 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4646 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4647 // If RHSCst is [us]MAXINT, it is always false. Not handling
4648 // this can cause overflow.
4649 if (RHSCst->isMaxValue(true))
4650 return ReplaceInstUsesWith(I, LHS);
4651 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
4653 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4655 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4656 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4657 return ReplaceInstUsesWith(I, RHS);
4658 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4662 case ICmpInst::ICMP_UGT:
4664 default: llvm_unreachable("Unknown integer condition code!");
4665 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4666 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4667 return ReplaceInstUsesWith(I, LHS);
4668 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4670 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4671 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4672 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4673 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4677 case ICmpInst::ICMP_SGT:
4679 default: llvm_unreachable("Unknown integer condition code!");
4680 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4681 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4682 return ReplaceInstUsesWith(I, LHS);
4683 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4685 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4686 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4687 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4688 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4696 Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4698 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4699 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4700 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4701 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4702 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4703 // If either of the constants are nans, then the whole thing returns
4705 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4706 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4708 // Otherwise, no need to compare the two constants, compare the
4710 return new FCmpInst(FCmpInst::FCMP_UNO,
4711 LHS->getOperand(0), RHS->getOperand(0));
4714 // Handle vector zeros. This occurs because the canonical form of
4715 // "fcmp uno x,x" is "fcmp uno x, 0".
4716 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4717 isa<ConstantAggregateZero>(RHS->getOperand(1)))
4718 return new FCmpInst(FCmpInst::FCMP_UNO,
4719 LHS->getOperand(0), RHS->getOperand(0));
4724 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4725 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4726 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4728 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4729 // Swap RHS operands to match LHS.
4730 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4731 std::swap(Op1LHS, Op1RHS);
4733 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4734 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4736 return new FCmpInst((FCmpInst::Predicate)Op0CC,
4738 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
4739 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
4740 if (Op0CC == FCmpInst::FCMP_FALSE)
4741 return ReplaceInstUsesWith(I, RHS);
4742 if (Op1CC == FCmpInst::FCMP_FALSE)
4743 return ReplaceInstUsesWith(I, LHS);
4746 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4747 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4748 if (Op0Ordered == Op1Ordered) {
4749 // If both are ordered or unordered, return a new fcmp with
4750 // or'ed predicates.
4751 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4752 Op0LHS, Op0RHS, Context);
4753 if (Instruction *I = dyn_cast<Instruction>(RV))
4755 // Otherwise, it's a constant boolean value...
4756 return ReplaceInstUsesWith(I, RV);
4762 /// FoldOrWithConstants - This helper function folds:
4764 /// ((A | B) & C1) | (B & C2)
4770 /// when the XOR of the two constants is "all ones" (-1).
4771 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4772 Value *A, Value *B, Value *C) {
4773 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4777 ConstantInt *CI2 = 0;
4778 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4780 APInt Xor = CI1->getValue() ^ CI2->getValue();
4781 if (!Xor.isAllOnesValue()) return 0;
4783 if (V1 == A || V1 == B) {
4784 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
4785 return BinaryOperator::CreateOr(NewOp, V1);
4791 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4792 bool Changed = SimplifyCommutative(I);
4793 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4795 if (isa<UndefValue>(Op1)) // X | undef -> -1
4796 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4800 return ReplaceInstUsesWith(I, Op0);
4802 // See if we can simplify any instructions used by the instruction whose sole
4803 // purpose is to compute bits we don't care about.
4804 if (SimplifyDemandedInstructionBits(I))
4806 if (isa<VectorType>(I.getType())) {
4807 if (isa<ConstantAggregateZero>(Op1)) {
4808 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4809 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4810 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4811 return ReplaceInstUsesWith(I, I.getOperand(1));
4816 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4817 ConstantInt *C1 = 0; Value *X = 0;
4818 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4819 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
4821 Value *Or = Builder->CreateOr(X, RHS);
4823 return BinaryOperator::CreateAnd(Or,
4824 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
4827 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4828 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
4830 Value *Or = Builder->CreateOr(X, RHS);
4832 return BinaryOperator::CreateXor(Or,
4833 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
4836 // Try to fold constant and into select arguments.
4837 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4838 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4840 if (isa<PHINode>(Op0))
4841 if (Instruction *NV = FoldOpIntoPhi(I))
4845 Value *A = 0, *B = 0;
4846 ConstantInt *C1 = 0, *C2 = 0;
4848 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4849 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4850 return ReplaceInstUsesWith(I, Op1);
4851 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4852 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4853 return ReplaceInstUsesWith(I, Op0);
4855 // (A | B) | C and A | (B | C) -> bswap if possible.
4856 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4857 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4858 match(Op1, m_Or(m_Value(), m_Value())) ||
4859 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4860 match(Op1, m_Shift(m_Value(), m_Value())))) {
4861 if (Instruction *BSwap = MatchBSwap(I))
4865 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4866 if (Op0->hasOneUse() &&
4867 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4868 MaskedValueIsZero(Op1, C1->getValue())) {
4869 Value *NOr = Builder->CreateOr(A, Op1);
4871 return BinaryOperator::CreateXor(NOr, C1);
4874 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4875 if (Op1->hasOneUse() &&
4876 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4877 MaskedValueIsZero(Op0, C1->getValue())) {
4878 Value *NOr = Builder->CreateOr(A, Op0);
4880 return BinaryOperator::CreateXor(NOr, C1);
4884 Value *C = 0, *D = 0;
4885 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4886 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4887 Value *V1 = 0, *V2 = 0, *V3 = 0;
4888 C1 = dyn_cast<ConstantInt>(C);
4889 C2 = dyn_cast<ConstantInt>(D);
4890 if (C1 && C2) { // (A & C1)|(B & C2)
4891 // If we have: ((V + N) & C1) | (V & C2)
4892 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4893 // replace with V+N.
4894 if (C1->getValue() == ~C2->getValue()) {
4895 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4896 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4897 // Add commutes, try both ways.
4898 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4899 return ReplaceInstUsesWith(I, A);
4900 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4901 return ReplaceInstUsesWith(I, A);
4903 // Or commutes, try both ways.
4904 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4905 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4906 // Add commutes, try both ways.
4907 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4908 return ReplaceInstUsesWith(I, B);
4909 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4910 return ReplaceInstUsesWith(I, B);
4913 V1 = 0; V2 = 0; V3 = 0;
4916 // Check to see if we have any common things being and'ed. If so, find the
4917 // terms for V1 & (V2|V3).
4918 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4919 if (A == B) // (A & C)|(A & D) == A & (C|D)
4920 V1 = A, V2 = C, V3 = D;
4921 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4922 V1 = A, V2 = B, V3 = C;
4923 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4924 V1 = C, V2 = A, V3 = D;
4925 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4926 V1 = C, V2 = A, V3 = B;
4929 Value *Or = Builder->CreateOr(V2, V3, "tmp");
4930 return BinaryOperator::CreateAnd(V1, Or);
4934 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
4935 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
4937 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
4939 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
4941 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
4944 // ((A&~B)|(~A&B)) -> A^B
4945 if ((match(C, m_Not(m_Specific(D))) &&
4946 match(B, m_Not(m_Specific(A)))))
4947 return BinaryOperator::CreateXor(A, D);
4948 // ((~B&A)|(~A&B)) -> A^B
4949 if ((match(A, m_Not(m_Specific(D))) &&
4950 match(B, m_Not(m_Specific(C)))))
4951 return BinaryOperator::CreateXor(C, D);
4952 // ((A&~B)|(B&~A)) -> A^B
4953 if ((match(C, m_Not(m_Specific(B))) &&
4954 match(D, m_Not(m_Specific(A)))))
4955 return BinaryOperator::CreateXor(A, B);
4956 // ((~B&A)|(B&~A)) -> A^B
4957 if ((match(A, m_Not(m_Specific(B))) &&
4958 match(D, m_Not(m_Specific(C)))))
4959 return BinaryOperator::CreateXor(C, B);
4962 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4963 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4964 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4965 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4966 SI0->getOperand(1) == SI1->getOperand(1) &&
4967 (SI0->hasOneUse() || SI1->hasOneUse())) {
4968 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
4970 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4971 SI1->getOperand(1));
4975 // ((A|B)&1)|(B&-2) -> (A&1) | B
4976 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4977 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4978 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4979 if (Ret) return Ret;
4981 // (B&-2)|((A|B)&1) -> (A&1) | B
4982 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4983 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4984 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4985 if (Ret) return Ret;
4988 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4989 if (A == Op1) // ~A | A == -1
4990 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4994 // Note, A is still live here!
4995 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4997 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4999 // (~A | ~B) == (~(A & B)) - De Morgan's Law
5000 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
5001 Value *And = Builder->CreateAnd(A, B, I.getName()+".demorgan");
5002 return BinaryOperator::CreateNot(And);
5006 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5007 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
5008 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5011 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5012 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5016 // fold (or (cast A), (cast B)) -> (cast (or A, B))
5017 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5018 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5019 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
5020 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5021 !isa<ICmpInst>(Op1C->getOperand(0))) {
5022 const Type *SrcTy = Op0C->getOperand(0)->getType();
5023 if (SrcTy == Op1C->getOperand(0)->getType() &&
5024 SrcTy->isIntOrIntVector() &&
5025 // Only do this if the casts both really cause code to be
5027 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5029 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5031 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5032 Op1C->getOperand(0), I.getName());
5033 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5040 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5041 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
5042 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5043 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5047 return Changed ? &I : 0;
5052 // XorSelf - Implements: X ^ X --> 0
5055 XorSelf(Value *rhs) : RHS(rhs) {}
5056 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5057 Instruction *apply(BinaryOperator &Xor) const {
5064 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5065 bool Changed = SimplifyCommutative(I);
5066 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5068 if (isa<UndefValue>(Op1)) {
5069 if (isa<UndefValue>(Op0))
5070 // Handle undef ^ undef -> 0 special case. This is a common
5072 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5073 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
5076 // xor X, X = 0, even if X is nested in a sequence of Xor's.
5077 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
5078 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5079 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5082 // See if we can simplify any instructions used by the instruction whose sole
5083 // purpose is to compute bits we don't care about.
5084 if (SimplifyDemandedInstructionBits(I))
5086 if (isa<VectorType>(I.getType()))
5087 if (isa<ConstantAggregateZero>(Op1))
5088 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
5090 // Is this a ~ operation?
5091 if (Value *NotOp = dyn_castNotVal(&I)) {
5092 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5093 if (Op0I->getOpcode() == Instruction::And ||
5094 Op0I->getOpcode() == Instruction::Or) {
5095 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5096 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5097 if (dyn_castNotVal(Op0I->getOperand(1)))
5098 Op0I->swapOperands();
5099 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
5101 Builder->CreateNot(Op0I->getOperand(1),
5102 Op0I->getOperand(1)->getName()+".not");
5103 if (Op0I->getOpcode() == Instruction::And)
5104 return BinaryOperator::CreateOr(Op0NotVal, NotY);
5105 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5108 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5109 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5110 if (isFreeToInvert(Op0I->getOperand(0)) &&
5111 isFreeToInvert(Op0I->getOperand(1))) {
5113 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5115 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5116 if (Op0I->getOpcode() == Instruction::And)
5117 return BinaryOperator::CreateOr(NotX, NotY);
5118 return BinaryOperator::CreateAnd(NotX, NotY);
5125 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5126 if (RHS->isOne() && Op0->hasOneUse()) {
5127 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5128 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5129 return new ICmpInst(ICI->getInversePredicate(),
5130 ICI->getOperand(0), ICI->getOperand(1));
5132 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5133 return new FCmpInst(FCI->getInversePredicate(),
5134 FCI->getOperand(0), FCI->getOperand(1));
5137 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5138 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5139 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5140 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5141 Instruction::CastOps Opcode = Op0C->getOpcode();
5142 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5143 (RHS == ConstantExpr::getCast(Opcode,
5144 ConstantInt::getTrue(*Context),
5145 Op0C->getDestTy()))) {
5146 CI->setPredicate(CI->getInversePredicate());
5147 return CastInst::Create(Opcode, CI, Op0C->getType());
5153 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5154 // ~(c-X) == X-c-1 == X+(-c-1)
5155 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5156 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5157 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5158 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
5159 ConstantInt::get(I.getType(), 1));
5160 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5163 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5164 if (Op0I->getOpcode() == Instruction::Add) {
5165 // ~(X-c) --> (-c-1)-X
5166 if (RHS->isAllOnesValue()) {
5167 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
5168 return BinaryOperator::CreateSub(
5169 ConstantExpr::getSub(NegOp0CI,
5170 ConstantInt::get(I.getType(), 1)),
5171 Op0I->getOperand(0));
5172 } else if (RHS->getValue().isSignBit()) {
5173 // (X + C) ^ signbit -> (X + C + signbit)
5174 Constant *C = ConstantInt::get(*Context,
5175 RHS->getValue() + Op0CI->getValue());
5176 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5179 } else if (Op0I->getOpcode() == Instruction::Or) {
5180 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5181 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5182 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
5183 // Anything in both C1 and C2 is known to be zero, remove it from
5185 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5186 NewRHS = ConstantExpr::getAnd(NewRHS,
5187 ConstantExpr::getNot(CommonBits));
5189 I.setOperand(0, Op0I->getOperand(0));
5190 I.setOperand(1, NewRHS);
5197 // Try to fold constant and into select arguments.
5198 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5199 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5201 if (isa<PHINode>(Op0))
5202 if (Instruction *NV = FoldOpIntoPhi(I))
5206 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
5208 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5210 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
5212 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
5215 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5218 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5219 if (A == Op0) { // B^(B|A) == (A|B)^B
5220 Op1I->swapOperands();
5222 std::swap(Op0, Op1);
5223 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5224 I.swapOperands(); // Simplified below.
5225 std::swap(Op0, Op1);
5227 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5228 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5229 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5230 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
5231 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
5233 if (A == Op0) { // A^(A&B) -> A^(B&A)
5234 Op1I->swapOperands();
5237 if (B == Op0) { // A^(B&A) -> (B&A)^A
5238 I.swapOperands(); // Simplified below.
5239 std::swap(Op0, Op1);
5244 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5247 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5248 Op0I->hasOneUse()) {
5249 if (A == Op1) // (B|A)^B == (A|B)^B
5251 if (B == Op1) // (A|B)^B == A & ~B
5252 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
5253 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5254 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5255 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5256 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
5257 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5259 if (A == Op1) // (A&B)^A -> (B&A)^A
5261 if (B == Op1 && // (B&A)^A == ~B & A
5262 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5263 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
5268 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5269 if (Op0I && Op1I && Op0I->isShift() &&
5270 Op0I->getOpcode() == Op1I->getOpcode() &&
5271 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5272 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5274 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5276 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
5277 Op1I->getOperand(1));
5281 Value *A, *B, *C, *D;
5282 // (A & B)^(A | B) -> A ^ B
5283 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5284 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5285 if ((A == C && B == D) || (A == D && B == C))
5286 return BinaryOperator::CreateXor(A, B);
5288 // (A | B)^(A & B) -> A ^ B
5289 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5290 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5291 if ((A == C && B == D) || (A == D && B == C))
5292 return BinaryOperator::CreateXor(A, B);
5296 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5297 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5298 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5299 // (X & Y)^(X & Y) -> (Y^Z) & X
5300 Value *X = 0, *Y = 0, *Z = 0;
5302 X = A, Y = B, Z = D;
5304 X = A, Y = B, Z = C;
5306 X = B, Y = A, Z = D;
5308 X = B, Y = A, Z = C;
5311 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
5312 return BinaryOperator::CreateAnd(NewOp, X);
5317 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5318 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5319 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5322 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5323 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5324 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5325 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5326 const Type *SrcTy = Op0C->getOperand(0)->getType();
5327 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5328 // Only do this if the casts both really cause code to be generated.
5329 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5331 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5333 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5334 Op1C->getOperand(0), I.getName());
5335 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5340 return Changed ? &I : 0;
5343 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5344 LLVMContext *Context) {
5345 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
5348 static bool HasAddOverflow(ConstantInt *Result,
5349 ConstantInt *In1, ConstantInt *In2,
5352 if (In2->getValue().isNegative())
5353 return Result->getValue().sgt(In1->getValue());
5355 return Result->getValue().slt(In1->getValue());
5357 return Result->getValue().ult(In1->getValue());
5360 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5361 /// overflowed for this type.
5362 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5363 Constant *In2, LLVMContext *Context,
5364 bool IsSigned = false) {
5365 Result = ConstantExpr::getAdd(In1, In2);
5367 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5368 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5369 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5370 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5371 ExtractElement(In1, Idx, Context),
5372 ExtractElement(In2, Idx, Context),
5379 return HasAddOverflow(cast<ConstantInt>(Result),
5380 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5384 static bool HasSubOverflow(ConstantInt *Result,
5385 ConstantInt *In1, ConstantInt *In2,
5388 if (In2->getValue().isNegative())
5389 return Result->getValue().slt(In1->getValue());
5391 return Result->getValue().sgt(In1->getValue());
5393 return Result->getValue().ugt(In1->getValue());
5396 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5397 /// overflowed for this type.
5398 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5399 Constant *In2, LLVMContext *Context,
5400 bool IsSigned = false) {
5401 Result = ConstantExpr::getSub(In1, In2);
5403 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5404 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5405 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
5406 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5407 ExtractElement(In1, Idx, Context),
5408 ExtractElement(In2, Idx, Context),
5415 return HasSubOverflow(cast<ConstantInt>(Result),
5416 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5420 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5421 /// code necessary to compute the offset from the base pointer (without adding
5422 /// in the base pointer). Return the result as a signed integer of intptr size.
5423 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5424 TargetData &TD = *IC.getTargetData();
5425 gep_type_iterator GTI = gep_type_begin(GEP);
5426 const Type *IntPtrTy = TD.getIntPtrType(I.getContext());
5427 Value *Result = Constant::getNullValue(IntPtrTy);
5429 // Build a mask for high order bits.
5430 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5431 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5433 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5436 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5437 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5438 if (OpC->isZero()) continue;
5440 // Handle a struct index, which adds its field offset to the pointer.
5441 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5442 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5444 Result = IC.Builder->CreateAdd(Result,
5445 ConstantInt::get(IntPtrTy, Size),
5446 GEP->getName()+".offs");
5450 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5452 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5453 Scale = ConstantExpr::getMul(OC, Scale);
5454 // Emit an add instruction.
5455 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
5458 // Convert to correct type.
5459 if (Op->getType() != IntPtrTy)
5460 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
5462 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5463 // We'll let instcombine(mul) convert this to a shl if possible.
5464 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
5467 // Emit an add instruction.
5468 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
5474 /// EvaluateGEPOffsetExpression - Return a value that can be used to compare
5475 /// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
5476 /// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
5477 /// be complex, and scales are involved. The above expression would also be
5478 /// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
5479 /// This later form is less amenable to optimization though, and we are allowed
5480 /// to generate the first by knowing that pointer arithmetic doesn't overflow.
5482 /// If we can't emit an optimized form for this expression, this returns null.
5484 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5486 TargetData &TD = *IC.getTargetData();
5487 gep_type_iterator GTI = gep_type_begin(GEP);
5489 // Check to see if this gep only has a single variable index. If so, and if
5490 // any constant indices are a multiple of its scale, then we can compute this
5491 // in terms of the scale of the variable index. For example, if the GEP
5492 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5493 // because the expression will cross zero at the same point.
5494 unsigned i, e = GEP->getNumOperands();
5496 for (i = 1; i != e; ++i, ++GTI) {
5497 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5498 // Compute the aggregate offset of constant indices.
5499 if (CI->isZero()) continue;
5501 // Handle a struct index, which adds its field offset to the pointer.
5502 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5503 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5505 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5506 Offset += Size*CI->getSExtValue();
5509 // Found our variable index.
5514 // If there are no variable indices, we must have a constant offset, just
5515 // evaluate it the general way.
5516 if (i == e) return 0;
5518 Value *VariableIdx = GEP->getOperand(i);
5519 // Determine the scale factor of the variable element. For example, this is
5520 // 4 if the variable index is into an array of i32.
5521 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5523 // Verify that there are no other variable indices. If so, emit the hard way.
5524 for (++i, ++GTI; i != e; ++i, ++GTI) {
5525 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5528 // Compute the aggregate offset of constant indices.
5529 if (CI->isZero()) continue;
5531 // Handle a struct index, which adds its field offset to the pointer.
5532 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5533 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5535 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5536 Offset += Size*CI->getSExtValue();
5540 // Okay, we know we have a single variable index, which must be a
5541 // pointer/array/vector index. If there is no offset, life is simple, return
5543 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5545 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5546 // we don't need to bother extending: the extension won't affect where the
5547 // computation crosses zero.
5548 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5549 VariableIdx = new TruncInst(VariableIdx,
5550 TD.getIntPtrType(VariableIdx->getContext()),
5551 VariableIdx->getName(), &I);
5555 // Otherwise, there is an index. The computation we will do will be modulo
5556 // the pointer size, so get it.
5557 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5559 Offset &= PtrSizeMask;
5560 VariableScale &= PtrSizeMask;
5562 // To do this transformation, any constant index must be a multiple of the
5563 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5564 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5565 // multiple of the variable scale.
5566 int64_t NewOffs = Offset / (int64_t)VariableScale;
5567 if (Offset != NewOffs*(int64_t)VariableScale)
5570 // Okay, we can do this evaluation. Start by converting the index to intptr.
5571 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
5572 if (VariableIdx->getType() != IntPtrTy)
5573 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5575 VariableIdx->getName(), &I);
5576 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
5577 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5581 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5582 /// else. At this point we know that the GEP is on the LHS of the comparison.
5583 Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
5584 ICmpInst::Predicate Cond,
5586 // Look through bitcasts.
5587 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5588 RHS = BCI->getOperand(0);
5590 Value *PtrBase = GEPLHS->getOperand(0);
5591 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
5592 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
5593 // This transformation (ignoring the base and scales) is valid because we
5594 // know pointers can't overflow since the gep is inbounds. See if we can
5595 // output an optimized form.
5596 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5598 // If not, synthesize the offset the hard way.
5600 Offset = EmitGEPOffset(GEPLHS, I, *this);
5601 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5602 Constant::getNullValue(Offset->getType()));
5603 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
5604 // If the base pointers are different, but the indices are the same, just
5605 // compare the base pointer.
5606 if (PtrBase != GEPRHS->getOperand(0)) {
5607 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5608 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5609 GEPRHS->getOperand(0)->getType();
5611 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5612 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5613 IndicesTheSame = false;
5617 // If all indices are the same, just compare the base pointers.
5619 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5620 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5622 // Otherwise, the base pointers are different and the indices are
5623 // different, bail out.
5627 // If one of the GEPs has all zero indices, recurse.
5628 bool AllZeros = true;
5629 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5630 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5631 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5636 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5637 ICmpInst::getSwappedPredicate(Cond), I);
5639 // If the other GEP has all zero indices, recurse.
5641 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5642 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5643 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5648 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5650 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5651 // If the GEPs only differ by one index, compare it.
5652 unsigned NumDifferences = 0; // Keep track of # differences.
5653 unsigned DiffOperand = 0; // The operand that differs.
5654 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5655 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5656 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5657 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5658 // Irreconcilable differences.
5662 if (NumDifferences++) break;
5667 if (NumDifferences == 0) // SAME GEP?
5668 return ReplaceInstUsesWith(I, // No comparison is needed here.
5669 ConstantInt::get(Type::getInt1Ty(*Context),
5670 ICmpInst::isTrueWhenEqual(Cond)));
5672 else if (NumDifferences == 1) {
5673 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5674 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5675 // Make sure we do a signed comparison here.
5676 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5680 // Only lower this if the icmp is the only user of the GEP or if we expect
5681 // the result to fold to a constant!
5683 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5684 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5685 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5686 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5687 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5688 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5694 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5696 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5699 if (!isa<ConstantFP>(RHSC)) return 0;
5700 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5702 // Get the width of the mantissa. We don't want to hack on conversions that
5703 // might lose information from the integer, e.g. "i64 -> float"
5704 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5705 if (MantissaWidth == -1) return 0; // Unknown.
5707 // Check to see that the input is converted from an integer type that is small
5708 // enough that preserves all bits. TODO: check here for "known" sign bits.
5709 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5710 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5712 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5713 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5717 // If the conversion would lose info, don't hack on this.
5718 if ((int)InputSize > MantissaWidth)
5721 // Otherwise, we can potentially simplify the comparison. We know that it
5722 // will always come through as an integer value and we know the constant is
5723 // not a NAN (it would have been previously simplified).
5724 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5726 ICmpInst::Predicate Pred;
5727 switch (I.getPredicate()) {
5728 default: llvm_unreachable("Unexpected predicate!");
5729 case FCmpInst::FCMP_UEQ:
5730 case FCmpInst::FCMP_OEQ:
5731 Pred = ICmpInst::ICMP_EQ;
5733 case FCmpInst::FCMP_UGT:
5734 case FCmpInst::FCMP_OGT:
5735 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5737 case FCmpInst::FCMP_UGE:
5738 case FCmpInst::FCMP_OGE:
5739 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5741 case FCmpInst::FCMP_ULT:
5742 case FCmpInst::FCMP_OLT:
5743 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5745 case FCmpInst::FCMP_ULE:
5746 case FCmpInst::FCMP_OLE:
5747 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5749 case FCmpInst::FCMP_UNE:
5750 case FCmpInst::FCMP_ONE:
5751 Pred = ICmpInst::ICMP_NE;
5753 case FCmpInst::FCMP_ORD:
5754 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5755 case FCmpInst::FCMP_UNO:
5756 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5759 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5761 // Now we know that the APFloat is a normal number, zero or inf.
5763 // See if the FP constant is too large for the integer. For example,
5764 // comparing an i8 to 300.0.
5765 unsigned IntWidth = IntTy->getScalarSizeInBits();
5768 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5769 // and large values.
5770 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5771 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5772 APFloat::rmNearestTiesToEven);
5773 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5774 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5775 Pred == ICmpInst::ICMP_SLE)
5776 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5777 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5780 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5781 // +INF and large values.
5782 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5783 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5784 APFloat::rmNearestTiesToEven);
5785 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5786 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5787 Pred == ICmpInst::ICMP_ULE)
5788 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5789 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5794 // See if the RHS value is < SignedMin.
5795 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5796 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5797 APFloat::rmNearestTiesToEven);
5798 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5799 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5800 Pred == ICmpInst::ICMP_SGE)
5801 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5802 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5806 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5807 // [0, UMAX], but it may still be fractional. See if it is fractional by
5808 // casting the FP value to the integer value and back, checking for equality.
5809 // Don't do this for zero, because -0.0 is not fractional.
5810 Constant *RHSInt = LHSUnsigned
5811 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5812 : ConstantExpr::getFPToSI(RHSC, IntTy);
5813 if (!RHS.isZero()) {
5814 bool Equal = LHSUnsigned
5815 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5816 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
5818 // If we had a comparison against a fractional value, we have to adjust
5819 // the compare predicate and sometimes the value. RHSC is rounded towards
5820 // zero at this point.
5822 default: llvm_unreachable("Unexpected integer comparison!");
5823 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5824 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5825 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5826 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5827 case ICmpInst::ICMP_ULE:
5828 // (float)int <= 4.4 --> int <= 4
5829 // (float)int <= -4.4 --> false
5830 if (RHS.isNegative())
5831 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5833 case ICmpInst::ICMP_SLE:
5834 // (float)int <= 4.4 --> int <= 4
5835 // (float)int <= -4.4 --> int < -4
5836 if (RHS.isNegative())
5837 Pred = ICmpInst::ICMP_SLT;
5839 case ICmpInst::ICMP_ULT:
5840 // (float)int < -4.4 --> false
5841 // (float)int < 4.4 --> int <= 4
5842 if (RHS.isNegative())
5843 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5844 Pred = ICmpInst::ICMP_ULE;
5846 case ICmpInst::ICMP_SLT:
5847 // (float)int < -4.4 --> int < -4
5848 // (float)int < 4.4 --> int <= 4
5849 if (!RHS.isNegative())
5850 Pred = ICmpInst::ICMP_SLE;
5852 case ICmpInst::ICMP_UGT:
5853 // (float)int > 4.4 --> int > 4
5854 // (float)int > -4.4 --> true
5855 if (RHS.isNegative())
5856 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5858 case ICmpInst::ICMP_SGT:
5859 // (float)int > 4.4 --> int > 4
5860 // (float)int > -4.4 --> int >= -4
5861 if (RHS.isNegative())
5862 Pred = ICmpInst::ICMP_SGE;
5864 case ICmpInst::ICMP_UGE:
5865 // (float)int >= -4.4 --> true
5866 // (float)int >= 4.4 --> int > 4
5867 if (!RHS.isNegative())
5868 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5869 Pred = ICmpInst::ICMP_UGT;
5871 case ICmpInst::ICMP_SGE:
5872 // (float)int >= -4.4 --> int >= -4
5873 // (float)int >= 4.4 --> int > 4
5874 if (!RHS.isNegative())
5875 Pred = ICmpInst::ICMP_SGT;
5881 // Lower this FP comparison into an appropriate integer version of the
5883 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5886 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5887 bool Changed = SimplifyCompare(I);
5888 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5890 // Fold trivial predicates.
5891 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5892 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
5893 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5894 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
5896 // Simplify 'fcmp pred X, X'
5898 switch (I.getPredicate()) {
5899 default: llvm_unreachable("Unknown predicate!");
5900 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5901 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5902 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5903 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
5904 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5905 case FCmpInst::FCMP_OLT: // True if ordered and less than
5906 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5907 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 0));
5909 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5910 case FCmpInst::FCMP_ULT: // True if unordered or less than
5911 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5912 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5913 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5914 I.setPredicate(FCmpInst::FCMP_UNO);
5915 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5918 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5919 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5920 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5921 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5922 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5923 I.setPredicate(FCmpInst::FCMP_ORD);
5924 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5929 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5930 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
5932 // Handle fcmp with constant RHS
5933 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5934 // If the constant is a nan, see if we can fold the comparison based on it.
5935 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5936 if (CFP->getValueAPF().isNaN()) {
5937 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5938 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
5939 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5940 "Comparison must be either ordered or unordered!");
5941 // True if unordered.
5942 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5946 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5947 switch (LHSI->getOpcode()) {
5948 case Instruction::PHI:
5949 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5950 // block. If in the same block, we're encouraging jump threading. If
5951 // not, we are just pessimizing the code by making an i1 phi.
5952 if (LHSI->getParent() == I.getParent())
5953 if (Instruction *NV = FoldOpIntoPhi(I, true))
5956 case Instruction::SIToFP:
5957 case Instruction::UIToFP:
5958 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5961 case Instruction::Select:
5962 // If either operand of the select is a constant, we can fold the
5963 // comparison into the select arms, which will cause one to be
5964 // constant folded and the select turned into a bitwise or.
5965 Value *Op1 = 0, *Op2 = 0;
5966 if (LHSI->hasOneUse()) {
5967 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5968 // Fold the known value into the constant operand.
5969 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5970 // Insert a new FCmp of the other select operand.
5971 Op2 = Builder->CreateFCmp(I.getPredicate(),
5972 LHSI->getOperand(2), RHSC, I.getName());
5973 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5974 // Fold the known value into the constant operand.
5975 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5976 // Insert a new FCmp of the other select operand.
5977 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
5983 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5988 return Changed ? &I : 0;
5991 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5992 bool Changed = SimplifyCompare(I);
5993 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5994 const Type *Ty = Op0->getType();
5998 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(),
5999 I.isTrueWhenEqual()));
6001 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
6002 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
6004 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
6005 // addresses never equal each other! We already know that Op0 != Op1.
6006 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
6007 isa<ConstantPointerNull>(Op0)) &&
6008 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
6009 isa<ConstantPointerNull>(Op1)))
6010 return ReplaceInstUsesWith(I, ConstantInt::get(Type::getInt1Ty(*Context),
6011 !I.isTrueWhenEqual()));
6013 // icmp's with boolean values can always be turned into bitwise operations
6014 if (Ty == Type::getInt1Ty(*Context)) {
6015 switch (I.getPredicate()) {
6016 default: llvm_unreachable("Invalid icmp instruction!");
6017 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
6018 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
6019 return BinaryOperator::CreateNot(Xor);
6021 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
6022 return BinaryOperator::CreateXor(Op0, Op1);
6024 case ICmpInst::ICMP_UGT:
6025 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
6027 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
6028 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6029 return BinaryOperator::CreateAnd(Not, Op1);
6031 case ICmpInst::ICMP_SGT:
6032 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
6034 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
6035 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6036 return BinaryOperator::CreateAnd(Not, Op0);
6038 case ICmpInst::ICMP_UGE:
6039 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6041 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
6042 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
6043 return BinaryOperator::CreateOr(Not, Op1);
6045 case ICmpInst::ICMP_SGE:
6046 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6048 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
6049 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
6050 return BinaryOperator::CreateOr(Not, Op0);
6055 unsigned BitWidth = 0;
6057 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6058 else if (Ty->isIntOrIntVector())
6059 BitWidth = Ty->getScalarSizeInBits();
6061 bool isSignBit = false;
6063 // See if we are doing a comparison with a constant.
6064 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6065 Value *A = 0, *B = 0;
6067 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6068 if (I.isEquality() && CI->isNullValue() &&
6069 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6070 // (icmp cond A B) if cond is equality
6071 return new ICmpInst(I.getPredicate(), A, B);
6074 // If we have an icmp le or icmp ge instruction, turn it into the
6075 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6076 // them being folded in the code below.
6077 switch (I.getPredicate()) {
6079 case ICmpInst::ICMP_ULE:
6080 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
6081 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6082 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
6084 case ICmpInst::ICMP_SLE:
6085 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
6086 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6087 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6089 case ICmpInst::ICMP_UGE:
6090 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
6091 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6092 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
6094 case ICmpInst::ICMP_SGE:
6095 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
6096 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6097 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6101 // If this comparison is a normal comparison, it demands all
6102 // bits, if it is a sign bit comparison, it only demands the sign bit.
6104 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6107 // See if we can fold the comparison based on range information we can get
6108 // by checking whether bits are known to be zero or one in the input.
6109 if (BitWidth != 0) {
6110 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6111 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6113 if (SimplifyDemandedBits(I.getOperandUse(0),
6114 isSignBit ? APInt::getSignBit(BitWidth)
6115 : APInt::getAllOnesValue(BitWidth),
6116 Op0KnownZero, Op0KnownOne, 0))
6118 if (SimplifyDemandedBits(I.getOperandUse(1),
6119 APInt::getAllOnesValue(BitWidth),
6120 Op1KnownZero, Op1KnownOne, 0))
6123 // Given the known and unknown bits, compute a range that the LHS could be
6124 // in. Compute the Min, Max and RHS values based on the known bits. For the
6125 // EQ and NE we use unsigned values.
6126 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6127 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6129 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6131 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6134 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6136 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6140 // If Min and Max are known to be the same, then SimplifyDemandedBits
6141 // figured out that the LHS is a constant. Just constant fold this now so
6142 // that code below can assume that Min != Max.
6143 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6144 return new ICmpInst(I.getPredicate(),
6145 ConstantInt::get(*Context, Op0Min), Op1);
6146 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6147 return new ICmpInst(I.getPredicate(), Op0,
6148 ConstantInt::get(*Context, Op1Min));
6150 // Based on the range information we know about the LHS, see if we can
6151 // simplify this comparison. For example, (x&4) < 8 is always true.
6152 switch (I.getPredicate()) {
6153 default: llvm_unreachable("Unknown icmp opcode!");
6154 case ICmpInst::ICMP_EQ:
6155 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6156 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6158 case ICmpInst::ICMP_NE:
6159 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6160 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6162 case ICmpInst::ICMP_ULT:
6163 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
6164 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6165 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
6166 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6167 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
6168 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6169 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6170 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
6171 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6174 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6175 if (CI->isMinValue(true))
6176 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
6177 Constant::getAllOnesValue(Op0->getType()));
6180 case ICmpInst::ICMP_UGT:
6181 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
6182 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6183 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
6184 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6186 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
6187 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6188 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6189 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
6190 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6193 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6194 if (CI->isMaxValue(true))
6195 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
6196 Constant::getNullValue(Op0->getType()));
6199 case ICmpInst::ICMP_SLT:
6200 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
6201 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6202 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
6203 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6204 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
6205 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6206 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6207 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
6208 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6212 case ICmpInst::ICMP_SGT:
6213 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
6214 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6215 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
6216 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6218 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
6219 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
6220 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6221 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
6222 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
6226 case ICmpInst::ICMP_SGE:
6227 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6228 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
6229 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6230 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
6231 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6233 case ICmpInst::ICMP_SLE:
6234 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6235 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
6236 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6237 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
6238 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6240 case ICmpInst::ICMP_UGE:
6241 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6242 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
6243 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6244 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
6245 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6247 case ICmpInst::ICMP_ULE:
6248 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6249 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
6250 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
6251 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
6252 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
6256 // Turn a signed comparison into an unsigned one if both operands
6257 // are known to have the same sign.
6259 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6260 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6261 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
6264 // Test if the ICmpInst instruction is used exclusively by a select as
6265 // part of a minimum or maximum operation. If so, refrain from doing
6266 // any other folding. This helps out other analyses which understand
6267 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6268 // and CodeGen. And in this case, at least one of the comparison
6269 // operands has at least one user besides the compare (the select),
6270 // which would often largely negate the benefit of folding anyway.
6272 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6273 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6274 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6277 // See if we are doing a comparison between a constant and an instruction that
6278 // can be folded into the comparison.
6279 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6280 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6281 // instruction, see if that instruction also has constants so that the
6282 // instruction can be folded into the icmp
6283 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6284 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6288 // Handle icmp with constant (but not simple integer constant) RHS
6289 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6290 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6291 switch (LHSI->getOpcode()) {
6292 case Instruction::GetElementPtr:
6293 if (RHSC->isNullValue()) {
6294 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6295 bool isAllZeros = true;
6296 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6297 if (!isa<Constant>(LHSI->getOperand(i)) ||
6298 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6303 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6304 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6308 case Instruction::PHI:
6309 // Only fold icmp into the PHI if the phi and icmp are in the same
6310 // block. If in the same block, we're encouraging jump threading. If
6311 // not, we are just pessimizing the code by making an i1 phi.
6312 if (LHSI->getParent() == I.getParent())
6313 if (Instruction *NV = FoldOpIntoPhi(I, true))
6316 case Instruction::Select: {
6317 // If either operand of the select is a constant, we can fold the
6318 // comparison into the select arms, which will cause one to be
6319 // constant folded and the select turned into a bitwise or.
6320 Value *Op1 = 0, *Op2 = 0;
6321 if (LHSI->hasOneUse()) {
6322 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6323 // Fold the known value into the constant operand.
6324 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6325 // Insert a new ICmp of the other select operand.
6326 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6328 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6329 // Fold the known value into the constant operand.
6330 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6331 // Insert a new ICmp of the other select operand.
6332 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6338 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6341 case Instruction::Call:
6342 // If we have (malloc != null), and if the malloc has a single use, we
6343 // can assume it is successful and remove the malloc.
6344 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6345 isa<ConstantPointerNull>(RHSC)) {
6346 // Need to explicitly erase malloc call here, instead of adding it to
6347 // Worklist, because it won't get DCE'd from the Worklist since
6348 // isInstructionTriviallyDead() returns false for function calls.
6349 // It is OK to replace LHSI/MallocCall with Undef because the
6350 // instruction that uses it will be erased via Worklist.
6351 if (extractMallocCall(LHSI)) {
6352 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6353 EraseInstFromFunction(*LHSI);
6354 return ReplaceInstUsesWith(I,
6355 ConstantInt::get(Type::getInt1Ty(*Context),
6356 !I.isTrueWhenEqual()));
6358 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6359 if (MallocCall->hasOneUse()) {
6360 MallocCall->replaceAllUsesWith(
6361 UndefValue::get(MallocCall->getType()));
6362 EraseInstFromFunction(*MallocCall);
6363 Worklist.Add(LHSI); // The malloc's bitcast use.
6364 return ReplaceInstUsesWith(I,
6365 ConstantInt::get(Type::getInt1Ty(*Context),
6366 !I.isTrueWhenEqual()));
6373 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6374 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
6375 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6377 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
6378 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6379 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6382 // Test to see if the operands of the icmp are casted versions of other
6383 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6385 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6386 if (isa<PointerType>(Op0->getType()) &&
6387 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6388 // We keep moving the cast from the left operand over to the right
6389 // operand, where it can often be eliminated completely.
6390 Op0 = CI->getOperand(0);
6392 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6393 // so eliminate it as well.
6394 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6395 Op1 = CI2->getOperand(0);
6397 // If Op1 is a constant, we can fold the cast into the constant.
6398 if (Op0->getType() != Op1->getType()) {
6399 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6400 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6402 // Otherwise, cast the RHS right before the icmp
6403 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
6406 return new ICmpInst(I.getPredicate(), Op0, Op1);
6410 if (isa<CastInst>(Op0)) {
6411 // Handle the special case of: icmp (cast bool to X), <cst>
6412 // This comes up when you have code like
6415 // For generality, we handle any zero-extension of any operand comparison
6416 // with a constant or another cast from the same type.
6417 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6418 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6422 // See if it's the same type of instruction on the left and right.
6423 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6424 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6425 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6426 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6427 switch (Op0I->getOpcode()) {
6429 case Instruction::Add:
6430 case Instruction::Sub:
6431 case Instruction::Xor:
6432 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
6433 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6434 Op1I->getOperand(0));
6435 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6436 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6437 if (CI->getValue().isSignBit()) {
6438 ICmpInst::Predicate Pred = I.isSigned()
6439 ? I.getUnsignedPredicate()
6440 : I.getSignedPredicate();
6441 return new ICmpInst(Pred, Op0I->getOperand(0),
6442 Op1I->getOperand(0));
6445 if (CI->getValue().isMaxSignedValue()) {
6446 ICmpInst::Predicate Pred = I.isSigned()
6447 ? I.getUnsignedPredicate()
6448 : I.getSignedPredicate();
6449 Pred = I.getSwappedPredicate(Pred);
6450 return new ICmpInst(Pred, Op0I->getOperand(0),
6451 Op1I->getOperand(0));
6455 case Instruction::Mul:
6456 if (!I.isEquality())
6459 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6460 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6461 // Mask = -1 >> count-trailing-zeros(Cst).
6462 if (!CI->isZero() && !CI->isOne()) {
6463 const APInt &AP = CI->getValue();
6464 ConstantInt *Mask = ConstantInt::get(*Context,
6465 APInt::getLowBitsSet(AP.getBitWidth(),
6467 AP.countTrailingZeros()));
6468 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6469 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
6470 return new ICmpInst(I.getPredicate(), And1, And2);
6479 // ~x < ~y --> y < x
6481 if (match(Op0, m_Not(m_Value(A))) &&
6482 match(Op1, m_Not(m_Value(B))))
6483 return new ICmpInst(I.getPredicate(), B, A);
6486 if (I.isEquality()) {
6487 Value *A, *B, *C, *D;
6489 // -x == -y --> x == y
6490 if (match(Op0, m_Neg(m_Value(A))) &&
6491 match(Op1, m_Neg(m_Value(B))))
6492 return new ICmpInst(I.getPredicate(), A, B);
6494 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6495 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6496 Value *OtherVal = A == Op1 ? B : A;
6497 return new ICmpInst(I.getPredicate(), OtherVal,
6498 Constant::getNullValue(A->getType()));
6501 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6502 // A^c1 == C^c2 --> A == C^(c1^c2)
6503 ConstantInt *C1, *C2;
6504 if (match(B, m_ConstantInt(C1)) &&
6505 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6507 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
6508 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6509 return new ICmpInst(I.getPredicate(), A, Xor);
6512 // A^B == A^D -> B == D
6513 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6514 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6515 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6516 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6520 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6521 (A == Op0 || B == Op0)) {
6522 // A == (A^B) -> B == 0
6523 Value *OtherVal = A == Op0 ? B : A;
6524 return new ICmpInst(I.getPredicate(), OtherVal,
6525 Constant::getNullValue(A->getType()));
6528 // (A-B) == A -> B == 0
6529 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6530 return new ICmpInst(I.getPredicate(), B,
6531 Constant::getNullValue(B->getType()));
6533 // A == (A-B) -> B == 0
6534 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6535 return new ICmpInst(I.getPredicate(), B,
6536 Constant::getNullValue(B->getType()));
6538 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6539 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6540 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6541 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6542 Value *X = 0, *Y = 0, *Z = 0;
6545 X = B; Y = D; Z = A;
6546 } else if (A == D) {
6547 X = B; Y = C; Z = A;
6548 } else if (B == C) {
6549 X = A; Y = D; Z = B;
6550 } else if (B == D) {
6551 X = A; Y = C; Z = B;
6554 if (X) { // Build (X^Y) & Z
6555 Op1 = Builder->CreateXor(X, Y, "tmp");
6556 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
6557 I.setOperand(0, Op1);
6558 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6563 return Changed ? &I : 0;
6567 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6568 /// and CmpRHS are both known to be integer constants.
6569 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6570 ConstantInt *DivRHS) {
6571 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6572 const APInt &CmpRHSV = CmpRHS->getValue();
6574 // FIXME: If the operand types don't match the type of the divide
6575 // then don't attempt this transform. The code below doesn't have the
6576 // logic to deal with a signed divide and an unsigned compare (and
6577 // vice versa). This is because (x /s C1) <s C2 produces different
6578 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6579 // (x /u C1) <u C2. Simply casting the operands and result won't
6580 // work. :( The if statement below tests that condition and bails
6582 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6583 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
6585 if (DivRHS->isZero())
6586 return 0; // The ProdOV computation fails on divide by zero.
6587 if (DivIsSigned && DivRHS->isAllOnesValue())
6588 return 0; // The overflow computation also screws up here
6589 if (DivRHS->isOne())
6590 return 0; // Not worth bothering, and eliminates some funny cases
6593 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6594 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6595 // C2 (CI). By solving for X we can turn this into a range check
6596 // instead of computing a divide.
6597 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
6599 // Determine if the product overflows by seeing if the product is
6600 // not equal to the divide. Make sure we do the same kind of divide
6601 // as in the LHS instruction that we're folding.
6602 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6603 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6605 // Get the ICmp opcode
6606 ICmpInst::Predicate Pred = ICI.getPredicate();
6608 // Figure out the interval that is being checked. For example, a comparison
6609 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6610 // Compute this interval based on the constants involved and the signedness of
6611 // the compare/divide. This computes a half-open interval, keeping track of
6612 // whether either value in the interval overflows. After analysis each
6613 // overflow variable is set to 0 if it's corresponding bound variable is valid
6614 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6615 int LoOverflow = 0, HiOverflow = 0;
6616 Constant *LoBound = 0, *HiBound = 0;
6618 if (!DivIsSigned) { // udiv
6619 // e.g. X/5 op 3 --> [15, 20)
6621 HiOverflow = LoOverflow = ProdOV;
6623 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6624 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6625 if (CmpRHSV == 0) { // (X / pos) op 0
6626 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
6627 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6629 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
6630 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6631 HiOverflow = LoOverflow = ProdOV;
6633 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6634 } else { // (X / pos) op neg
6635 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
6636 HiBound = AddOne(Prod);
6637 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6639 ConstantInt* DivNeg =
6640 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6641 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6645 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6646 if (CmpRHSV == 0) { // (X / neg) op 0
6647 // e.g. X/-5 op 0 --> [-4, 5)
6648 LoBound = AddOne(DivRHS);
6649 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6650 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6651 HiOverflow = 1; // [INTMIN+1, overflow)
6652 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6654 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
6655 // e.g. X/-5 op 3 --> [-19, -14)
6656 HiBound = AddOne(Prod);
6657 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6659 LoOverflow = AddWithOverflow(LoBound, HiBound,
6660 DivRHS, Context, true) ? -1 : 0;
6661 } else { // (X / neg) op neg
6662 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6663 LoOverflow = HiOverflow = ProdOV;
6665 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6668 // Dividing by a negative swaps the condition. LT <-> GT
6669 Pred = ICmpInst::getSwappedPredicate(Pred);
6672 Value *X = DivI->getOperand(0);
6674 default: llvm_unreachable("Unhandled icmp opcode!");
6675 case ICmpInst::ICMP_EQ:
6676 if (LoOverflow && HiOverflow)
6677 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6678 else if (HiOverflow)
6679 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6680 ICmpInst::ICMP_UGE, X, LoBound);
6681 else if (LoOverflow)
6682 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6683 ICmpInst::ICMP_ULT, X, HiBound);
6685 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6686 case ICmpInst::ICMP_NE:
6687 if (LoOverflow && HiOverflow)
6688 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6689 else if (HiOverflow)
6690 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6691 ICmpInst::ICMP_ULT, X, LoBound);
6692 else if (LoOverflow)
6693 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6694 ICmpInst::ICMP_UGE, X, HiBound);
6696 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6697 case ICmpInst::ICMP_ULT:
6698 case ICmpInst::ICMP_SLT:
6699 if (LoOverflow == +1) // Low bound is greater than input range.
6700 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6701 if (LoOverflow == -1) // Low bound is less than input range.
6702 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6703 return new ICmpInst(Pred, X, LoBound);
6704 case ICmpInst::ICMP_UGT:
6705 case ICmpInst::ICMP_SGT:
6706 if (HiOverflow == +1) // High bound greater than input range.
6707 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6708 else if (HiOverflow == -1) // High bound less than input range.
6709 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6710 if (Pred == ICmpInst::ICMP_UGT)
6711 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6713 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6718 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6720 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6723 const APInt &RHSV = RHS->getValue();
6725 switch (LHSI->getOpcode()) {
6726 case Instruction::Trunc:
6727 if (ICI.isEquality() && LHSI->hasOneUse()) {
6728 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6729 // of the high bits truncated out of x are known.
6730 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6731 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6732 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6733 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6734 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6736 // If all the high bits are known, we can do this xform.
6737 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6738 // Pull in the high bits from known-ones set.
6739 APInt NewRHS(RHS->getValue());
6740 NewRHS.zext(SrcBits);
6742 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6743 ConstantInt::get(*Context, NewRHS));
6748 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6749 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6750 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6752 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6753 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6754 Value *CompareVal = LHSI->getOperand(0);
6756 // If the sign bit of the XorCST is not set, there is no change to
6757 // the operation, just stop using the Xor.
6758 if (!XorCST->getValue().isNegative()) {
6759 ICI.setOperand(0, CompareVal);
6764 // Was the old condition true if the operand is positive?
6765 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6767 // If so, the new one isn't.
6768 isTrueIfPositive ^= true;
6770 if (isTrueIfPositive)
6771 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
6774 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
6778 if (LHSI->hasOneUse()) {
6779 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6780 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6781 const APInt &SignBit = XorCST->getValue();
6782 ICmpInst::Predicate Pred = ICI.isSigned()
6783 ? ICI.getUnsignedPredicate()
6784 : ICI.getSignedPredicate();
6785 return new ICmpInst(Pred, LHSI->getOperand(0),
6786 ConstantInt::get(*Context, RHSV ^ SignBit));
6789 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6790 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6791 const APInt &NotSignBit = XorCST->getValue();
6792 ICmpInst::Predicate Pred = ICI.isSigned()
6793 ? ICI.getUnsignedPredicate()
6794 : ICI.getSignedPredicate();
6795 Pred = ICI.getSwappedPredicate(Pred);
6796 return new ICmpInst(Pred, LHSI->getOperand(0),
6797 ConstantInt::get(*Context, RHSV ^ NotSignBit));
6802 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6803 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6804 LHSI->getOperand(0)->hasOneUse()) {
6805 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6807 // If the LHS is an AND of a truncating cast, we can widen the
6808 // and/compare to be the input width without changing the value
6809 // produced, eliminating a cast.
6810 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6811 // We can do this transformation if either the AND constant does not
6812 // have its sign bit set or if it is an equality comparison.
6813 // Extending a relational comparison when we're checking the sign
6814 // bit would not work.
6815 if (Cast->hasOneUse() &&
6816 (ICI.isEquality() ||
6817 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6819 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6820 APInt NewCST = AndCST->getValue();
6821 NewCST.zext(BitWidth);
6823 NewCI.zext(BitWidth);
6825 Builder->CreateAnd(Cast->getOperand(0),
6826 ConstantInt::get(*Context, NewCST), LHSI->getName());
6827 return new ICmpInst(ICI.getPredicate(), NewAnd,
6828 ConstantInt::get(*Context, NewCI));
6832 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6833 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6834 // happens a LOT in code produced by the C front-end, for bitfield
6836 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6837 if (Shift && !Shift->isShift())
6841 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6842 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6843 const Type *AndTy = AndCST->getType(); // Type of the and.
6845 // We can fold this as long as we can't shift unknown bits
6846 // into the mask. This can only happen with signed shift
6847 // rights, as they sign-extend.
6849 bool CanFold = Shift->isLogicalShift();
6851 // To test for the bad case of the signed shr, see if any
6852 // of the bits shifted in could be tested after the mask.
6853 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6854 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6856 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6857 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6858 AndCST->getValue()) == 0)
6864 if (Shift->getOpcode() == Instruction::Shl)
6865 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6867 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6869 // Check to see if we are shifting out any of the bits being
6871 if (ConstantExpr::get(Shift->getOpcode(),
6872 NewCst, ShAmt) != RHS) {
6873 // If we shifted bits out, the fold is not going to work out.
6874 // As a special case, check to see if this means that the
6875 // result is always true or false now.
6876 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6877 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6878 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6879 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6881 ICI.setOperand(1, NewCst);
6882 Constant *NewAndCST;
6883 if (Shift->getOpcode() == Instruction::Shl)
6884 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6886 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6887 LHSI->setOperand(1, NewAndCST);
6888 LHSI->setOperand(0, Shift->getOperand(0));
6889 Worklist.Add(Shift); // Shift is dead.
6895 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6896 // preferable because it allows the C<<Y expression to be hoisted out
6897 // of a loop if Y is invariant and X is not.
6898 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6899 ICI.isEquality() && !Shift->isArithmeticShift() &&
6900 !isa<Constant>(Shift->getOperand(0))) {
6903 if (Shift->getOpcode() == Instruction::LShr) {
6904 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
6906 // Insert a logical shift.
6907 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
6910 // Compute X & (C << Y).
6912 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6914 ICI.setOperand(0, NewAnd);
6920 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6921 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6924 uint32_t TypeBits = RHSV.getBitWidth();
6926 // Check that the shift amount is in range. If not, don't perform
6927 // undefined shifts. When the shift is visited it will be
6929 if (ShAmt->uge(TypeBits))
6932 if (ICI.isEquality()) {
6933 // If we are comparing against bits always shifted out, the
6934 // comparison cannot succeed.
6936 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
6938 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6939 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6940 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6941 return ReplaceInstUsesWith(ICI, Cst);
6944 if (LHSI->hasOneUse()) {
6945 // Otherwise strength reduce the shift into an and.
6946 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6948 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
6949 TypeBits-ShAmtVal));
6952 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
6953 return new ICmpInst(ICI.getPredicate(), And,
6954 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
6958 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6959 bool TrueIfSigned = false;
6960 if (LHSI->hasOneUse() &&
6961 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6962 // (X << 31) <s 0 --> (X&1) != 0
6963 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
6964 (TypeBits-ShAmt->getZExtValue()-1));
6966 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
6967 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6968 And, Constant::getNullValue(And->getType()));
6973 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6974 case Instruction::AShr: {
6975 // Only handle equality comparisons of shift-by-constant.
6976 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6977 if (!ShAmt || !ICI.isEquality()) break;
6979 // Check that the shift amount is in range. If not, don't perform
6980 // undefined shifts. When the shift is visited it will be
6982 uint32_t TypeBits = RHSV.getBitWidth();
6983 if (ShAmt->uge(TypeBits))
6986 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6988 // If we are comparing against bits always shifted out, the
6989 // comparison cannot succeed.
6990 APInt Comp = RHSV << ShAmtVal;
6991 if (LHSI->getOpcode() == Instruction::LShr)
6992 Comp = Comp.lshr(ShAmtVal);
6994 Comp = Comp.ashr(ShAmtVal);
6996 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6997 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6998 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
6999 return ReplaceInstUsesWith(ICI, Cst);
7002 // Otherwise, check to see if the bits shifted out are known to be zero.
7003 // If so, we can compare against the unshifted value:
7004 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
7005 if (LHSI->hasOneUse() &&
7006 MaskedValueIsZero(LHSI->getOperand(0),
7007 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
7008 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
7009 ConstantExpr::getShl(RHS, ShAmt));
7012 if (LHSI->hasOneUse()) {
7013 // Otherwise strength reduce the shift into an and.
7014 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
7015 Constant *Mask = ConstantInt::get(*Context, Val);
7017 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7018 Mask, LHSI->getName()+".mask");
7019 return new ICmpInst(ICI.getPredicate(), And,
7020 ConstantExpr::getShl(RHS, ShAmt));
7025 case Instruction::SDiv:
7026 case Instruction::UDiv:
7027 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7028 // Fold this div into the comparison, producing a range check.
7029 // Determine, based on the divide type, what the range is being
7030 // checked. If there is an overflow on the low or high side, remember
7031 // it, otherwise compute the range [low, hi) bounding the new value.
7032 // See: InsertRangeTest above for the kinds of replacements possible.
7033 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7034 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7039 case Instruction::Add:
7040 // Fold: icmp pred (add, X, C1), C2
7042 if (!ICI.isEquality()) {
7043 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7045 const APInt &LHSV = LHSC->getValue();
7047 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7050 if (ICI.isSigned()) {
7051 if (CR.getLower().isSignBit()) {
7052 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7053 ConstantInt::get(*Context, CR.getUpper()));
7054 } else if (CR.getUpper().isSignBit()) {
7055 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7056 ConstantInt::get(*Context, CR.getLower()));
7059 if (CR.getLower().isMinValue()) {
7060 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7061 ConstantInt::get(*Context, CR.getUpper()));
7062 } else if (CR.getUpper().isMinValue()) {
7063 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7064 ConstantInt::get(*Context, CR.getLower()));
7071 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7072 if (ICI.isEquality()) {
7073 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7075 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7076 // the second operand is a constant, simplify a bit.
7077 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7078 switch (BO->getOpcode()) {
7079 case Instruction::SRem:
7080 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7081 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7082 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7083 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7085 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7087 return new ICmpInst(ICI.getPredicate(), NewRem,
7088 Constant::getNullValue(BO->getType()));
7092 case Instruction::Add:
7093 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7094 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7095 if (BO->hasOneUse())
7096 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7097 ConstantExpr::getSub(RHS, BOp1C));
7098 } else if (RHSV == 0) {
7099 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7100 // efficiently invertible, or if the add has just this one use.
7101 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7103 if (Value *NegVal = dyn_castNegVal(BOp1))
7104 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
7105 else if (Value *NegVal = dyn_castNegVal(BOp0))
7106 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
7107 else if (BO->hasOneUse()) {
7108 Value *Neg = Builder->CreateNeg(BOp1);
7110 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
7114 case Instruction::Xor:
7115 // For the xor case, we can xor two constants together, eliminating
7116 // the explicit xor.
7117 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7118 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7119 ConstantExpr::getXor(RHS, BOC));
7122 case Instruction::Sub:
7123 // Replace (([sub|xor] A, B) != 0) with (A != B)
7125 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
7129 case Instruction::Or:
7130 // If bits are being or'd in that are not present in the constant we
7131 // are comparing against, then the comparison could never succeed!
7132 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7133 Constant *NotCI = ConstantExpr::getNot(RHS);
7134 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
7135 return ReplaceInstUsesWith(ICI,
7136 ConstantInt::get(Type::getInt1Ty(*Context),
7141 case Instruction::And:
7142 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7143 // If bits are being compared against that are and'd out, then the
7144 // comparison can never succeed!
7145 if ((RHSV & ~BOC->getValue()) != 0)
7146 return ReplaceInstUsesWith(ICI,
7147 ConstantInt::get(Type::getInt1Ty(*Context),
7150 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7151 if (RHS == BOC && RHSV.isPowerOf2())
7152 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
7153 ICmpInst::ICMP_NE, LHSI,
7154 Constant::getNullValue(RHS->getType()));
7156 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7157 if (BOC->getValue().isSignBit()) {
7158 Value *X = BO->getOperand(0);
7159 Constant *Zero = Constant::getNullValue(X->getType());
7160 ICmpInst::Predicate pred = isICMP_NE ?
7161 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7162 return new ICmpInst(pred, X, Zero);
7165 // ((X & ~7) == 0) --> X < 8
7166 if (RHSV == 0 && isHighOnes(BOC)) {
7167 Value *X = BO->getOperand(0);
7168 Constant *NegX = ConstantExpr::getNeg(BOC);
7169 ICmpInst::Predicate pred = isICMP_NE ?
7170 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7171 return new ICmpInst(pred, X, NegX);
7176 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7177 // Handle icmp {eq|ne} <intrinsic>, intcst.
7178 if (II->getIntrinsicID() == Intrinsic::bswap) {
7180 ICI.setOperand(0, II->getOperand(1));
7181 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
7189 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7190 /// We only handle extending casts so far.
7192 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7193 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7194 Value *LHSCIOp = LHSCI->getOperand(0);
7195 const Type *SrcTy = LHSCIOp->getType();
7196 const Type *DestTy = LHSCI->getType();
7199 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7200 // integer type is the same size as the pointer type.
7201 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7202 TD->getPointerSizeInBits() ==
7203 cast<IntegerType>(DestTy)->getBitWidth()) {
7205 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7206 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
7207 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7208 RHSOp = RHSC->getOperand(0);
7209 // If the pointer types don't match, insert a bitcast.
7210 if (LHSCIOp->getType() != RHSOp->getType())
7211 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
7215 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
7218 // The code below only handles extension cast instructions, so far.
7220 if (LHSCI->getOpcode() != Instruction::ZExt &&
7221 LHSCI->getOpcode() != Instruction::SExt)
7224 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7225 bool isSignedCmp = ICI.isSigned();
7227 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7228 // Not an extension from the same type?
7229 RHSCIOp = CI->getOperand(0);
7230 if (RHSCIOp->getType() != LHSCIOp->getType())
7233 // If the signedness of the two casts doesn't agree (i.e. one is a sext
7234 // and the other is a zext), then we can't handle this.
7235 if (CI->getOpcode() != LHSCI->getOpcode())
7238 // Deal with equality cases early.
7239 if (ICI.isEquality())
7240 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7242 // A signed comparison of sign extended values simplifies into a
7243 // signed comparison.
7244 if (isSignedCmp && isSignedExt)
7245 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
7247 // The other three cases all fold into an unsigned comparison.
7248 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7251 // If we aren't dealing with a constant on the RHS, exit early
7252 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7256 // Compute the constant that would happen if we truncated to SrcTy then
7257 // reextended to DestTy.
7258 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7259 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
7262 // If the re-extended constant didn't change...
7264 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7265 // For example, we might have:
7266 // %A = sext i16 %X to i32
7267 // %B = icmp ugt i32 %A, 1330
7268 // It is incorrect to transform this into
7269 // %B = icmp ugt i16 %X, 1330
7270 // because %A may have negative value.
7272 // However, we allow this when the compare is EQ/NE, because they are
7274 if (isSignedExt == isSignedCmp || ICI.isEquality())
7275 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7279 // The re-extended constant changed so the constant cannot be represented
7280 // in the shorter type. Consequently, we cannot emit a simple comparison.
7282 // First, handle some easy cases. We know the result cannot be equal at this
7283 // point so handle the ICI.isEquality() cases
7284 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7285 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
7286 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7287 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
7289 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7290 // should have been folded away previously and not enter in here.
7293 // We're performing a signed comparison.
7294 if (cast<ConstantInt>(CI)->getValue().isNegative())
7295 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
7297 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
7299 // We're performing an unsigned comparison.
7301 // We're performing an unsigned comp with a sign extended value.
7302 // This is true if the input is >= 0. [aka >s -1]
7303 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
7304 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
7306 // Unsigned extend & unsigned compare -> always true.
7307 Result = ConstantInt::getTrue(*Context);
7311 // Finally, return the value computed.
7312 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7313 ICI.getPredicate() == ICmpInst::ICMP_SLT)
7314 return ReplaceInstUsesWith(ICI, Result);
7316 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7317 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7318 "ICmp should be folded!");
7319 if (Constant *CI = dyn_cast<Constant>(Result))
7320 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
7321 return BinaryOperator::CreateNot(Result);
7324 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7325 return commonShiftTransforms(I);
7328 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7329 return commonShiftTransforms(I);
7332 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7333 if (Instruction *R = commonShiftTransforms(I))
7336 Value *Op0 = I.getOperand(0);
7338 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7339 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7340 if (CSI->isAllOnesValue())
7341 return ReplaceInstUsesWith(I, CSI);
7343 // See if we can turn a signed shr into an unsigned shr.
7344 if (MaskedValueIsZero(Op0,
7345 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7346 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7348 // Arithmetic shifting an all-sign-bit value is a no-op.
7349 unsigned NumSignBits = ComputeNumSignBits(Op0);
7350 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7351 return ReplaceInstUsesWith(I, Op0);
7356 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7357 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7358 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7360 // shl X, 0 == X and shr X, 0 == X
7361 // shl 0, X == 0 and shr 0, X == 0
7362 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7363 Op0 == Constant::getNullValue(Op0->getType()))
7364 return ReplaceInstUsesWith(I, Op0);
7366 if (isa<UndefValue>(Op0)) {
7367 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7368 return ReplaceInstUsesWith(I, Op0);
7369 else // undef << X -> 0, undef >>u X -> 0
7370 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7372 if (isa<UndefValue>(Op1)) {
7373 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7374 return ReplaceInstUsesWith(I, Op0);
7375 else // X << undef, X >>u undef -> 0
7376 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7379 // See if we can fold away this shift.
7380 if (SimplifyDemandedInstructionBits(I))
7383 // Try to fold constant and into select arguments.
7384 if (isa<Constant>(Op0))
7385 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7386 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7389 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7390 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7395 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7396 BinaryOperator &I) {
7397 bool isLeftShift = I.getOpcode() == Instruction::Shl;
7399 // See if we can simplify any instructions used by the instruction whose sole
7400 // purpose is to compute bits we don't care about.
7401 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7403 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7406 if (Op1->uge(TypeBits)) {
7407 if (I.getOpcode() != Instruction::AShr)
7408 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7410 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7415 // ((X*C1) << C2) == (X * (C1 << C2))
7416 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7417 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7418 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7419 return BinaryOperator::CreateMul(BO->getOperand(0),
7420 ConstantExpr::getShl(BOOp, Op1));
7422 // Try to fold constant and into select arguments.
7423 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7424 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7426 if (isa<PHINode>(Op0))
7427 if (Instruction *NV = FoldOpIntoPhi(I))
7430 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7431 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7432 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7433 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7434 // place. Don't try to do this transformation in this case. Also, we
7435 // require that the input operand is a shift-by-constant so that we have
7436 // confidence that the shifts will get folded together. We could do this
7437 // xform in more cases, but it is unlikely to be profitable.
7438 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7439 isa<ConstantInt>(TrOp->getOperand(1))) {
7440 // Okay, we'll do this xform. Make the shift of shift.
7441 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
7442 // (shift2 (shift1 & 0x00FF), c2)
7443 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
7445 // For logical shifts, the truncation has the effect of making the high
7446 // part of the register be zeros. Emulate this by inserting an AND to
7447 // clear the top bits as needed. This 'and' will usually be zapped by
7448 // other xforms later if dead.
7449 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7450 unsigned DstSize = TI->getType()->getScalarSizeInBits();
7451 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7453 // The mask we constructed says what the trunc would do if occurring
7454 // between the shifts. We want to know the effect *after* the second
7455 // shift. We know that it is a logical shift by a constant, so adjust the
7456 // mask as appropriate.
7457 if (I.getOpcode() == Instruction::Shl)
7458 MaskV <<= Op1->getZExtValue();
7460 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7461 MaskV = MaskV.lshr(Op1->getZExtValue());
7465 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7468 // Return the value truncated to the interesting size.
7469 return new TruncInst(And, I.getType());
7473 if (Op0->hasOneUse()) {
7474 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7475 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7478 switch (Op0BO->getOpcode()) {
7480 case Instruction::Add:
7481 case Instruction::And:
7482 case Instruction::Or:
7483 case Instruction::Xor: {
7484 // These operators commute.
7485 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7486 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7487 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7488 m_Specific(Op1)))) {
7489 Value *YS = // (Y << C)
7490 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7492 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7493 Op0BO->getOperand(1)->getName());
7494 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7495 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7496 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7499 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7500 Value *Op0BOOp1 = Op0BO->getOperand(1);
7501 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7503 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7504 m_ConstantInt(CC))) &&
7505 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7506 Value *YS = // (Y << C)
7507 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7510 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7511 V1->getName()+".mask");
7512 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7517 case Instruction::Sub: {
7518 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7519 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7520 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7521 m_Specific(Op1)))) {
7522 Value *YS = // (Y << C)
7523 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7525 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7526 Op0BO->getOperand(0)->getName());
7527 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7528 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
7529 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7532 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7533 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7534 match(Op0BO->getOperand(0),
7535 m_And(m_Shr(m_Value(V1), m_Value(V2)),
7536 m_ConstantInt(CC))) && V2 == Op1 &&
7537 cast<BinaryOperator>(Op0BO->getOperand(0))
7538 ->getOperand(0)->hasOneUse()) {
7539 Value *YS = // (Y << C)
7540 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7542 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7543 V1->getName()+".mask");
7545 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7553 // If the operand is an bitwise operator with a constant RHS, and the
7554 // shift is the only use, we can pull it out of the shift.
7555 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7556 bool isValid = true; // Valid only for And, Or, Xor
7557 bool highBitSet = false; // Transform if high bit of constant set?
7559 switch (Op0BO->getOpcode()) {
7560 default: isValid = false; break; // Do not perform transform!
7561 case Instruction::Add:
7562 isValid = isLeftShift;
7564 case Instruction::Or:
7565 case Instruction::Xor:
7568 case Instruction::And:
7573 // If this is a signed shift right, and the high bit is modified
7574 // by the logical operation, do not perform the transformation.
7575 // The highBitSet boolean indicates the value of the high bit of
7576 // the constant which would cause it to be modified for this
7579 if (isValid && I.getOpcode() == Instruction::AShr)
7580 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7583 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7586 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
7587 NewShift->takeName(Op0BO);
7589 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7596 // Find out if this is a shift of a shift by a constant.
7597 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7598 if (ShiftOp && !ShiftOp->isShift())
7601 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7602 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7603 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7604 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7605 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7606 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7607 Value *X = ShiftOp->getOperand(0);
7609 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
7611 const IntegerType *Ty = cast<IntegerType>(I.getType());
7613 // Check for (X << c1) << c2 and (X >> c1) >> c2
7614 if (I.getOpcode() == ShiftOp->getOpcode()) {
7615 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7617 if (AmtSum >= TypeBits) {
7618 if (I.getOpcode() != Instruction::AShr)
7619 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7620 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7623 return BinaryOperator::Create(I.getOpcode(), X,
7624 ConstantInt::get(Ty, AmtSum));
7627 if (ShiftOp->getOpcode() == Instruction::LShr &&
7628 I.getOpcode() == Instruction::AShr) {
7629 if (AmtSum >= TypeBits)
7630 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
7632 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
7633 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
7636 if (ShiftOp->getOpcode() == Instruction::AShr &&
7637 I.getOpcode() == Instruction::LShr) {
7638 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7639 if (AmtSum >= TypeBits)
7640 AmtSum = TypeBits-1;
7642 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
7644 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7645 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
7648 // Okay, if we get here, one shift must be left, and the other shift must be
7649 // right. See if the amounts are equal.
7650 if (ShiftAmt1 == ShiftAmt2) {
7651 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7652 if (I.getOpcode() == Instruction::Shl) {
7653 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7654 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7656 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7657 if (I.getOpcode() == Instruction::LShr) {
7658 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7659 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
7661 // We can simplify ((X << C) >>s C) into a trunc + sext.
7662 // NOTE: we could do this for any C, but that would make 'unusual' integer
7663 // types. For now, just stick to ones well-supported by the code
7665 const Type *SExtType = 0;
7666 switch (Ty->getBitWidth() - ShiftAmt1) {
7673 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
7678 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
7679 // Otherwise, we can't handle it yet.
7680 } else if (ShiftAmt1 < ShiftAmt2) {
7681 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7683 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7684 if (I.getOpcode() == Instruction::Shl) {
7685 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7686 ShiftOp->getOpcode() == Instruction::AShr);
7687 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7689 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7690 return BinaryOperator::CreateAnd(Shift,
7691 ConstantInt::get(*Context, Mask));
7694 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7695 if (I.getOpcode() == Instruction::LShr) {
7696 assert(ShiftOp->getOpcode() == Instruction::Shl);
7697 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
7699 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7700 return BinaryOperator::CreateAnd(Shift,
7701 ConstantInt::get(*Context, Mask));
7704 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7706 assert(ShiftAmt2 < ShiftAmt1);
7707 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7709 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7710 if (I.getOpcode() == Instruction::Shl) {
7711 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7712 ShiftOp->getOpcode() == Instruction::AShr);
7713 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
7714 ConstantInt::get(Ty, ShiftDiff));
7716 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7717 return BinaryOperator::CreateAnd(Shift,
7718 ConstantInt::get(*Context, Mask));
7721 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7722 if (I.getOpcode() == Instruction::LShr) {
7723 assert(ShiftOp->getOpcode() == Instruction::Shl);
7724 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
7726 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7727 return BinaryOperator::CreateAnd(Shift,
7728 ConstantInt::get(*Context, Mask));
7731 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7738 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7739 /// expression. If so, decompose it, returning some value X, such that Val is
7742 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7743 int &Offset, LLVMContext *Context) {
7744 assert(Val->getType() == Type::getInt32Ty(*Context) &&
7745 "Unexpected allocation size type!");
7746 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7747 Offset = CI->getZExtValue();
7749 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
7750 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7751 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7752 if (I->getOpcode() == Instruction::Shl) {
7753 // This is a value scaled by '1 << the shift amt'.
7754 Scale = 1U << RHS->getZExtValue();
7756 return I->getOperand(0);
7757 } else if (I->getOpcode() == Instruction::Mul) {
7758 // This value is scaled by 'RHS'.
7759 Scale = RHS->getZExtValue();
7761 return I->getOperand(0);
7762 } else if (I->getOpcode() == Instruction::Add) {
7763 // We have X+C. Check to see if we really have (X*C2)+C1,
7764 // where C1 is divisible by C2.
7767 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7769 Offset += RHS->getZExtValue();
7776 // Otherwise, we can't look past this.
7783 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7784 /// try to eliminate the cast by moving the type information into the alloc.
7785 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7787 const PointerType *PTy = cast<PointerType>(CI.getType());
7789 BuilderTy AllocaBuilder(*Builder);
7790 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
7792 // Remove any uses of AI that are dead.
7793 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7795 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7796 Instruction *User = cast<Instruction>(*UI++);
7797 if (isInstructionTriviallyDead(User)) {
7798 while (UI != E && *UI == User)
7799 ++UI; // If this instruction uses AI more than once, don't break UI.
7802 DEBUG(errs() << "IC: DCE: " << *User << '\n');
7803 EraseInstFromFunction(*User);
7807 // This requires TargetData to get the alloca alignment and size information.
7810 // Get the type really allocated and the type casted to.
7811 const Type *AllocElTy = AI.getAllocatedType();
7812 const Type *CastElTy = PTy->getElementType();
7813 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7815 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7816 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7817 if (CastElTyAlign < AllocElTyAlign) return 0;
7819 // If the allocation has multiple uses, only promote it if we are strictly
7820 // increasing the alignment of the resultant allocation. If we keep it the
7821 // same, we open the door to infinite loops of various kinds. (A reference
7822 // from a dbg.declare doesn't count as a use for this purpose.)
7823 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7824 CastElTyAlign == AllocElTyAlign) return 0;
7826 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7827 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7828 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7830 // See if we can satisfy the modulus by pulling a scale out of the array
7832 unsigned ArraySizeScale;
7834 Value *NumElements = // See if the array size is a decomposable linear expr.
7835 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7836 ArrayOffset, Context);
7838 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7840 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7841 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7843 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7848 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
7849 // Insert before the alloca, not before the cast.
7850 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
7853 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7854 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
7855 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
7858 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
7859 New->setAlignment(AI.getAlignment());
7862 // If the allocation has one real use plus a dbg.declare, just remove the
7864 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7865 EraseInstFromFunction(*DI);
7867 // If the allocation has multiple real uses, insert a cast and change all
7868 // things that used it to use the new cast. This will also hack on CI, but it
7870 else if (!AI.hasOneUse()) {
7871 // New is the allocation instruction, pointer typed. AI is the original
7872 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7873 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
7874 AI.replaceAllUsesWith(NewCast);
7876 return ReplaceInstUsesWith(CI, New);
7879 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7880 /// and return it as type Ty without inserting any new casts and without
7881 /// changing the computed value. This is used by code that tries to decide
7882 /// whether promoting or shrinking integer operations to wider or smaller types
7883 /// will allow us to eliminate a truncate or extend.
7885 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7886 /// extension operation if Ty is larger.
7888 /// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7889 /// should return true if trunc(V) can be computed by computing V in the smaller
7890 /// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7891 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7892 /// efficiently truncated.
7894 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7895 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7896 /// the final result.
7897 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7899 int &NumCastsRemoved){
7900 // We can always evaluate constants in another type.
7901 if (isa<Constant>(V))
7904 Instruction *I = dyn_cast<Instruction>(V);
7905 if (!I) return false;
7907 const Type *OrigTy = V->getType();
7909 // If this is an extension or truncate, we can often eliminate it.
7910 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7911 // If this is a cast from the destination type, we can trivially eliminate
7912 // it, and this will remove a cast overall.
7913 if (I->getOperand(0)->getType() == Ty) {
7914 // If the first operand is itself a cast, and is eliminable, do not count
7915 // this as an eliminable cast. We would prefer to eliminate those two
7917 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7923 // We can't extend or shrink something that has multiple uses: doing so would
7924 // require duplicating the instruction in general, which isn't profitable.
7925 if (!I->hasOneUse()) return false;
7927 unsigned Opc = I->getOpcode();
7929 case Instruction::Add:
7930 case Instruction::Sub:
7931 case Instruction::Mul:
7932 case Instruction::And:
7933 case Instruction::Or:
7934 case Instruction::Xor:
7935 // These operators can all arbitrarily be extended or truncated.
7936 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7938 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7941 case Instruction::UDiv:
7942 case Instruction::URem: {
7943 // UDiv and URem can be truncated if all the truncated bits are zero.
7944 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7945 uint32_t BitWidth = Ty->getScalarSizeInBits();
7946 if (BitWidth < OrigBitWidth) {
7947 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
7948 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
7949 MaskedValueIsZero(I->getOperand(1), Mask)) {
7950 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7952 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7958 case Instruction::Shl:
7959 // If we are truncating the result of this SHL, and if it's a shift of a
7960 // constant amount, we can always perform a SHL in a smaller type.
7961 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7962 uint32_t BitWidth = Ty->getScalarSizeInBits();
7963 if (BitWidth < OrigTy->getScalarSizeInBits() &&
7964 CI->getLimitedValue(BitWidth) < BitWidth)
7965 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7969 case Instruction::LShr:
7970 // If this is a truncate of a logical shr, we can truncate it to a smaller
7971 // lshr iff we know that the bits we would otherwise be shifting in are
7973 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7974 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7975 uint32_t BitWidth = Ty->getScalarSizeInBits();
7976 if (BitWidth < OrigBitWidth &&
7977 MaskedValueIsZero(I->getOperand(0),
7978 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7979 CI->getLimitedValue(BitWidth) < BitWidth) {
7980 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7985 case Instruction::ZExt:
7986 case Instruction::SExt:
7987 case Instruction::Trunc:
7988 // If this is the same kind of case as our original (e.g. zext+zext), we
7989 // can safely replace it. Note that replacing it does not reduce the number
7990 // of casts in the input.
7994 // sext (zext ty1), ty2 -> zext ty2
7995 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7998 case Instruction::Select: {
7999 SelectInst *SI = cast<SelectInst>(I);
8000 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
8002 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
8005 case Instruction::PHI: {
8006 // We can change a phi if we can change all operands.
8007 PHINode *PN = cast<PHINode>(I);
8008 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8009 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
8015 // TODO: Can handle more cases here.
8022 /// EvaluateInDifferentType - Given an expression that
8023 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8024 /// evaluate the expression.
8025 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
8027 if (Constant *C = dyn_cast<Constant>(V))
8028 return ConstantExpr::getIntegerCast(C, Ty,
8029 isSigned /*Sext or ZExt*/);
8031 // Otherwise, it must be an instruction.
8032 Instruction *I = cast<Instruction>(V);
8033 Instruction *Res = 0;
8034 unsigned Opc = I->getOpcode();
8036 case Instruction::Add:
8037 case Instruction::Sub:
8038 case Instruction::Mul:
8039 case Instruction::And:
8040 case Instruction::Or:
8041 case Instruction::Xor:
8042 case Instruction::AShr:
8043 case Instruction::LShr:
8044 case Instruction::Shl:
8045 case Instruction::UDiv:
8046 case Instruction::URem: {
8047 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8048 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8049 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8052 case Instruction::Trunc:
8053 case Instruction::ZExt:
8054 case Instruction::SExt:
8055 // If the source type of the cast is the type we're trying for then we can
8056 // just return the source. There's no need to insert it because it is not
8058 if (I->getOperand(0)->getType() == Ty)
8059 return I->getOperand(0);
8061 // Otherwise, must be the same type of cast, so just reinsert a new one.
8062 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8065 case Instruction::Select: {
8066 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8067 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8068 Res = SelectInst::Create(I->getOperand(0), True, False);
8071 case Instruction::PHI: {
8072 PHINode *OPN = cast<PHINode>(I);
8073 PHINode *NPN = PHINode::Create(Ty);
8074 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8075 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8076 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8082 // TODO: Can handle more cases here.
8083 llvm_unreachable("Unreachable!");
8088 return InsertNewInstBefore(Res, *I);
8091 /// @brief Implement the transforms common to all CastInst visitors.
8092 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8093 Value *Src = CI.getOperand(0);
8095 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8096 // eliminate it now.
8097 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8098 if (Instruction::CastOps opc =
8099 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8100 // The first cast (CSrc) is eliminable so we need to fix up or replace
8101 // the second cast (CI). CSrc will then have a good chance of being dead.
8102 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8106 // If we are casting a select then fold the cast into the select
8107 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8108 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8111 // If we are casting a PHI then fold the cast into the PHI
8112 if (isa<PHINode>(Src))
8113 if (Instruction *NV = FoldOpIntoPhi(CI))
8119 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8120 /// or not there is a sequence of GEP indices into the type that will land us at
8121 /// the specified offset. If so, fill them into NewIndices and return the
8122 /// resultant element type, otherwise return null.
8123 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8124 SmallVectorImpl<Value*> &NewIndices,
8125 const TargetData *TD,
8126 LLVMContext *Context) {
8128 if (!Ty->isSized()) return 0;
8130 // Start with the index over the outer type. Note that the type size
8131 // might be zero (even if the offset isn't zero) if the indexed type
8132 // is something like [0 x {int, int}]
8133 const Type *IntPtrTy = TD->getIntPtrType(*Context);
8134 int64_t FirstIdx = 0;
8135 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8136 FirstIdx = Offset/TySize;
8137 Offset -= FirstIdx*TySize;
8139 // Handle hosts where % returns negative instead of values [0..TySize).
8143 assert(Offset >= 0);
8145 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8148 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
8150 // Index into the types. If we fail, set OrigBase to null.
8152 // Indexing into tail padding between struct/array elements.
8153 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8156 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8157 const StructLayout *SL = TD->getStructLayout(STy);
8158 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8159 "Offset must stay within the indexed type");
8161 unsigned Elt = SL->getElementContainingOffset(Offset);
8162 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
8164 Offset -= SL->getElementOffset(Elt);
8165 Ty = STy->getElementType(Elt);
8166 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8167 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8168 assert(EltSize && "Cannot index into a zero-sized array");
8169 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
8171 Ty = AT->getElementType();
8173 // Otherwise, we can't index into the middle of this atomic type, bail.
8181 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8182 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8183 Value *Src = CI.getOperand(0);
8185 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8186 // If casting the result of a getelementptr instruction with no offset, turn
8187 // this into a cast of the original pointer!
8188 if (GEP->hasAllZeroIndices()) {
8189 // Changing the cast operand is usually not a good idea but it is safe
8190 // here because the pointer operand is being replaced with another
8191 // pointer operand so the opcode doesn't need to change.
8193 CI.setOperand(0, GEP->getOperand(0));
8197 // If the GEP has a single use, and the base pointer is a bitcast, and the
8198 // GEP computes a constant offset, see if we can convert these three
8199 // instructions into fewer. This typically happens with unions and other
8200 // non-type-safe code.
8201 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8202 if (GEP->hasAllConstantIndices()) {
8203 // We are guaranteed to get a constant from EmitGEPOffset.
8204 ConstantInt *OffsetV =
8205 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8206 int64_t Offset = OffsetV->getSExtValue();
8208 // Get the base pointer input of the bitcast, and the type it points to.
8209 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8210 const Type *GEPIdxTy =
8211 cast<PointerType>(OrigBase->getType())->getElementType();
8212 SmallVector<Value*, 8> NewIndices;
8213 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8214 // If we were able to index down into an element, create the GEP
8215 // and bitcast the result. This eliminates one bitcast, potentially
8217 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8218 Builder->CreateInBoundsGEP(OrigBase,
8219 NewIndices.begin(), NewIndices.end()) :
8220 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
8221 NGEP->takeName(GEP);
8223 if (isa<BitCastInst>(CI))
8224 return new BitCastInst(NGEP, CI.getType());
8225 assert(isa<PtrToIntInst>(CI));
8226 return new PtrToIntInst(NGEP, CI.getType());
8232 return commonCastTransforms(CI);
8235 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8236 /// type like i42. We don't want to introduce operations on random non-legal
8237 /// integer types where they don't already exist in the code. In the future,
8238 /// we should consider making this based off target-data, so that 32-bit targets
8239 /// won't get i64 operations etc.
8240 static bool isSafeIntegerType(const Type *Ty) {
8241 switch (Ty->getPrimitiveSizeInBits()) {
8252 /// commonIntCastTransforms - This function implements the common transforms
8253 /// for trunc, zext, and sext.
8254 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8255 if (Instruction *Result = commonCastTransforms(CI))
8258 Value *Src = CI.getOperand(0);
8259 const Type *SrcTy = Src->getType();
8260 const Type *DestTy = CI.getType();
8261 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8262 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8264 // See if we can simplify any instructions used by the LHS whose sole
8265 // purpose is to compute bits we don't care about.
8266 if (SimplifyDemandedInstructionBits(CI))
8269 // If the source isn't an instruction or has more than one use then we
8270 // can't do anything more.
8271 Instruction *SrcI = dyn_cast<Instruction>(Src);
8272 if (!SrcI || !Src->hasOneUse())
8275 // Attempt to propagate the cast into the instruction for int->int casts.
8276 int NumCastsRemoved = 0;
8277 // Only do this if the dest type is a simple type, don't convert the
8278 // expression tree to something weird like i93 unless the source is also
8280 if ((isSafeIntegerType(DestTy->getScalarType()) ||
8281 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8282 CanEvaluateInDifferentType(SrcI, DestTy,
8283 CI.getOpcode(), NumCastsRemoved)) {
8284 // If this cast is a truncate, evaluting in a different type always
8285 // eliminates the cast, so it is always a win. If this is a zero-extension,
8286 // we need to do an AND to maintain the clear top-part of the computation,
8287 // so we require that the input have eliminated at least one cast. If this
8288 // is a sign extension, we insert two new casts (to do the extension) so we
8289 // require that two casts have been eliminated.
8290 bool DoXForm = false;
8291 bool JustReplace = false;
8292 switch (CI.getOpcode()) {
8294 // All the others use floating point so we shouldn't actually
8295 // get here because of the check above.
8296 llvm_unreachable("Unknown cast type");
8297 case Instruction::Trunc:
8300 case Instruction::ZExt: {
8301 DoXForm = NumCastsRemoved >= 1;
8302 if (!DoXForm && 0) {
8303 // If it's unnecessary to issue an AND to clear the high bits, it's
8304 // always profitable to do this xform.
8305 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8306 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8307 if (MaskedValueIsZero(TryRes, Mask))
8308 return ReplaceInstUsesWith(CI, TryRes);
8310 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8311 if (TryI->use_empty())
8312 EraseInstFromFunction(*TryI);
8316 case Instruction::SExt: {
8317 DoXForm = NumCastsRemoved >= 2;
8318 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8319 // If we do not have to emit the truncate + sext pair, then it's always
8320 // profitable to do this xform.
8322 // It's not safe to eliminate the trunc + sext pair if one of the
8323 // eliminated cast is a truncate. e.g.
8324 // t2 = trunc i32 t1 to i16
8325 // t3 = sext i16 t2 to i32
8328 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8329 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8330 if (NumSignBits > (DestBitSize - SrcBitSize))
8331 return ReplaceInstUsesWith(CI, TryRes);
8333 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8334 if (TryI->use_empty())
8335 EraseInstFromFunction(*TryI);
8342 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8343 " to avoid cast: " << CI);
8344 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8345 CI.getOpcode() == Instruction::SExt);
8347 // Just replace this cast with the result.
8348 return ReplaceInstUsesWith(CI, Res);
8350 assert(Res->getType() == DestTy);
8351 switch (CI.getOpcode()) {
8352 default: llvm_unreachable("Unknown cast type!");
8353 case Instruction::Trunc:
8354 // Just replace this cast with the result.
8355 return ReplaceInstUsesWith(CI, Res);
8356 case Instruction::ZExt: {
8357 assert(SrcBitSize < DestBitSize && "Not a zext?");
8359 // If the high bits are already zero, just replace this cast with the
8361 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8362 if (MaskedValueIsZero(Res, Mask))
8363 return ReplaceInstUsesWith(CI, Res);
8365 // We need to emit an AND to clear the high bits.
8366 Constant *C = ConstantInt::get(*Context,
8367 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
8368 return BinaryOperator::CreateAnd(Res, C);
8370 case Instruction::SExt: {
8371 // If the high bits are already filled with sign bit, just replace this
8372 // cast with the result.
8373 unsigned NumSignBits = ComputeNumSignBits(Res);
8374 if (NumSignBits > (DestBitSize - SrcBitSize))
8375 return ReplaceInstUsesWith(CI, Res);
8377 // We need to emit a cast to truncate, then a cast to sext.
8378 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
8384 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8385 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8387 switch (SrcI->getOpcode()) {
8388 case Instruction::Add:
8389 case Instruction::Mul:
8390 case Instruction::And:
8391 case Instruction::Or:
8392 case Instruction::Xor:
8393 // If we are discarding information, rewrite.
8394 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8395 // Don't insert two casts unless at least one can be eliminated.
8396 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8397 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8398 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8399 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8400 return BinaryOperator::Create(
8401 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8405 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8406 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8407 SrcI->getOpcode() == Instruction::Xor &&
8408 Op1 == ConstantInt::getTrue(*Context) &&
8409 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8410 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
8411 return BinaryOperator::CreateXor(New,
8412 ConstantInt::get(CI.getType(), 1));
8416 case Instruction::Shl: {
8417 // Canonicalize trunc inside shl, if we can.
8418 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8419 if (CI && DestBitSize < SrcBitSize &&
8420 CI->getLimitedValue(DestBitSize) < DestBitSize) {
8421 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8422 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
8423 return BinaryOperator::CreateShl(Op0c, Op1c);
8431 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8432 if (Instruction *Result = commonIntCastTransforms(CI))
8435 Value *Src = CI.getOperand(0);
8436 const Type *Ty = CI.getType();
8437 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8438 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8440 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8441 if (DestBitWidth == 1) {
8442 Constant *One = ConstantInt::get(Src->getType(), 1);
8443 Src = Builder->CreateAnd(Src, One, "tmp");
8444 Value *Zero = Constant::getNullValue(Src->getType());
8445 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
8448 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8449 ConstantInt *ShAmtV = 0;
8451 if (Src->hasOneUse() &&
8452 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8453 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8455 // Get a mask for the bits shifting in.
8456 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8457 if (MaskedValueIsZero(ShiftOp, Mask)) {
8458 if (ShAmt >= DestBitWidth) // All zeros.
8459 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8461 // Okay, we can shrink this. Truncate the input, then return a new
8463 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
8464 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
8465 return BinaryOperator::CreateLShr(V1, V2);
8472 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8473 /// in order to eliminate the icmp.
8474 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8476 // If we are just checking for a icmp eq of a single bit and zext'ing it
8477 // to an integer, then shift the bit to the appropriate place and then
8478 // cast to integer to avoid the comparison.
8479 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8480 const APInt &Op1CV = Op1C->getValue();
8482 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8483 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8484 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8485 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8486 if (!DoXform) return ICI;
8488 Value *In = ICI->getOperand(0);
8489 Value *Sh = ConstantInt::get(In->getType(),
8490 In->getType()->getScalarSizeInBits()-1);
8491 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
8492 if (In->getType() != CI.getType())
8493 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
8495 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8496 Constant *One = ConstantInt::get(In->getType(), 1);
8497 In = Builder->CreateXor(In, One, In->getName()+".not");
8500 return ReplaceInstUsesWith(CI, In);
8505 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8506 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8507 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8508 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8509 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8510 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8511 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8512 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8513 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8514 // This only works for EQ and NE
8515 ICI->isEquality()) {
8516 // If Op1C some other power of two, convert:
8517 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8518 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8519 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8520 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8522 APInt KnownZeroMask(~KnownZero);
8523 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8524 if (!DoXform) return ICI;
8526 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8527 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8528 // (X&4) == 2 --> false
8529 // (X&4) != 2 --> true
8530 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
8531 Res = ConstantExpr::getZExt(Res, CI.getType());
8532 return ReplaceInstUsesWith(CI, Res);
8535 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8536 Value *In = ICI->getOperand(0);
8538 // Perform a logical shr by shiftamt.
8539 // Insert the shift to put the result in the low bit.
8540 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8541 In->getName()+".lobit");
8544 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8545 Constant *One = ConstantInt::get(In->getType(), 1);
8546 In = Builder->CreateXor(In, One, "tmp");
8549 if (CI.getType() == In->getType())
8550 return ReplaceInstUsesWith(CI, In);
8552 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8560 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8561 // If one of the common conversion will work ..
8562 if (Instruction *Result = commonIntCastTransforms(CI))
8565 Value *Src = CI.getOperand(0);
8567 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8568 // types and if the sizes are just right we can convert this into a logical
8569 // 'and' which will be much cheaper than the pair of casts.
8570 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8571 // Get the sizes of the types involved. We know that the intermediate type
8572 // will be smaller than A or C, but don't know the relation between A and C.
8573 Value *A = CSrc->getOperand(0);
8574 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8575 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8576 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8577 // If we're actually extending zero bits, then if
8578 // SrcSize < DstSize: zext(a & mask)
8579 // SrcSize == DstSize: a & mask
8580 // SrcSize > DstSize: trunc(a) & mask
8581 if (SrcSize < DstSize) {
8582 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8583 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
8584 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
8585 return new ZExtInst(And, CI.getType());
8588 if (SrcSize == DstSize) {
8589 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8590 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
8593 if (SrcSize > DstSize) {
8594 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
8595 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8596 return BinaryOperator::CreateAnd(Trunc,
8597 ConstantInt::get(Trunc->getType(),
8602 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8603 return transformZExtICmp(ICI, CI);
8605 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8606 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8607 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8608 // of the (zext icmp) will be transformed.
8609 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8610 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8611 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8612 (transformZExtICmp(LHS, CI, false) ||
8613 transformZExtICmp(RHS, CI, false))) {
8614 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
8615 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
8616 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8620 // zext(trunc(t) & C) -> (t & zext(C)).
8621 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8622 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8623 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8624 Value *TI0 = TI->getOperand(0);
8625 if (TI0->getType() == CI.getType())
8627 BinaryOperator::CreateAnd(TI0,
8628 ConstantExpr::getZExt(C, CI.getType()));
8631 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8632 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8633 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8634 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8635 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8636 And->getOperand(1) == C)
8637 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8638 Value *TI0 = TI->getOperand(0);
8639 if (TI0->getType() == CI.getType()) {
8640 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
8641 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
8642 return BinaryOperator::CreateXor(NewAnd, ZC);
8649 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8650 if (Instruction *I = commonIntCastTransforms(CI))
8653 Value *Src = CI.getOperand(0);
8655 // Canonicalize sign-extend from i1 to a select.
8656 if (Src->getType() == Type::getInt1Ty(*Context))
8657 return SelectInst::Create(Src,
8658 Constant::getAllOnesValue(CI.getType()),
8659 Constant::getNullValue(CI.getType()));
8661 // See if the value being truncated is already sign extended. If so, just
8662 // eliminate the trunc/sext pair.
8663 if (Operator::getOpcode(Src) == Instruction::Trunc) {
8664 Value *Op = cast<User>(Src)->getOperand(0);
8665 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8666 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8667 unsigned DestBits = CI.getType()->getScalarSizeInBits();
8668 unsigned NumSignBits = ComputeNumSignBits(Op);
8670 if (OpBits == DestBits) {
8671 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8672 // bits, it is already ready.
8673 if (NumSignBits > DestBits-MidBits)
8674 return ReplaceInstUsesWith(CI, Op);
8675 } else if (OpBits < DestBits) {
8676 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8677 // bits, just sext from i32.
8678 if (NumSignBits > OpBits-MidBits)
8679 return new SExtInst(Op, CI.getType(), "tmp");
8681 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8682 // bits, just truncate to i32.
8683 if (NumSignBits > OpBits-MidBits)
8684 return new TruncInst(Op, CI.getType(), "tmp");
8688 // If the input is a shl/ashr pair of a same constant, then this is a sign
8689 // extension from a smaller value. If we could trust arbitrary bitwidth
8690 // integers, we could turn this into a truncate to the smaller bit and then
8691 // use a sext for the whole extension. Since we don't, look deeper and check
8692 // for a truncate. If the source and dest are the same type, eliminate the
8693 // trunc and extend and just do shifts. For example, turn:
8694 // %a = trunc i32 %i to i8
8695 // %b = shl i8 %a, 6
8696 // %c = ashr i8 %b, 6
8697 // %d = sext i8 %c to i32
8699 // %a = shl i32 %i, 30
8700 // %d = ashr i32 %a, 30
8702 ConstantInt *BA = 0, *CA = 0;
8703 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8704 m_ConstantInt(CA))) &&
8705 BA == CA && isa<TruncInst>(A)) {
8706 Value *I = cast<TruncInst>(A)->getOperand(0);
8707 if (I->getType() == CI.getType()) {
8708 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8709 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8710 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8711 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8712 I = Builder->CreateShl(I, ShAmtV, CI.getName());
8713 return BinaryOperator::CreateAShr(I, ShAmtV);
8720 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8721 /// in the specified FP type without changing its value.
8722 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8723 LLVMContext *Context) {
8725 APFloat F = CFP->getValueAPF();
8726 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8728 return ConstantFP::get(*Context, F);
8732 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8733 /// through it until we get the source value.
8734 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8735 if (Instruction *I = dyn_cast<Instruction>(V))
8736 if (I->getOpcode() == Instruction::FPExt)
8737 return LookThroughFPExtensions(I->getOperand(0), Context);
8739 // If this value is a constant, return the constant in the smallest FP type
8740 // that can accurately represent it. This allows us to turn
8741 // (float)((double)X+2.0) into x+2.0f.
8742 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8743 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
8744 return V; // No constant folding of this.
8745 // See if the value can be truncated to float and then reextended.
8746 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8748 if (CFP->getType() == Type::getDoubleTy(*Context))
8749 return V; // Won't shrink.
8750 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8752 // Don't try to shrink to various long double types.
8758 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8759 if (Instruction *I = commonCastTransforms(CI))
8762 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8763 // smaller than the destination type, we can eliminate the truncate by doing
8764 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
8765 // many builtins (sqrt, etc).
8766 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8767 if (OpI && OpI->hasOneUse()) {
8768 switch (OpI->getOpcode()) {
8770 case Instruction::FAdd:
8771 case Instruction::FSub:
8772 case Instruction::FMul:
8773 case Instruction::FDiv:
8774 case Instruction::FRem:
8775 const Type *SrcTy = OpI->getType();
8776 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8777 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8778 if (LHSTrunc->getType() != SrcTy &&
8779 RHSTrunc->getType() != SrcTy) {
8780 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8781 // If the source types were both smaller than the destination type of
8782 // the cast, do this xform.
8783 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8784 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8785 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
8786 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
8787 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8796 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8797 return commonCastTransforms(CI);
8800 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8801 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8803 return commonCastTransforms(FI);
8805 // fptoui(uitofp(X)) --> X
8806 // fptoui(sitofp(X)) --> X
8807 // This is safe if the intermediate type has enough bits in its mantissa to
8808 // accurately represent all values of X. For example, do not do this with
8809 // i64->float->i64. This is also safe for sitofp case, because any negative
8810 // 'X' value would cause an undefined result for the fptoui.
8811 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8812 OpI->getOperand(0)->getType() == FI.getType() &&
8813 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8814 OpI->getType()->getFPMantissaWidth())
8815 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8817 return commonCastTransforms(FI);
8820 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8821 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8823 return commonCastTransforms(FI);
8825 // fptosi(sitofp(X)) --> X
8826 // fptosi(uitofp(X)) --> X
8827 // This is safe if the intermediate type has enough bits in its mantissa to
8828 // accurately represent all values of X. For example, do not do this with
8829 // i64->float->i64. This is also safe for sitofp case, because any negative
8830 // 'X' value would cause an undefined result for the fptoui.
8831 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8832 OpI->getOperand(0)->getType() == FI.getType() &&
8833 (int)FI.getType()->getScalarSizeInBits() <=
8834 OpI->getType()->getFPMantissaWidth())
8835 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8837 return commonCastTransforms(FI);
8840 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8841 return commonCastTransforms(CI);
8844 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8845 return commonCastTransforms(CI);
8848 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8849 // If the destination integer type is smaller than the intptr_t type for
8850 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8851 // trunc to be exposed to other transforms. Don't do this for extending
8852 // ptrtoint's, because we don't know if the target sign or zero extends its
8855 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8856 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
8857 TD->getIntPtrType(CI.getContext()),
8859 return new TruncInst(P, CI.getType());
8862 return commonPointerCastTransforms(CI);
8865 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8866 // If the source integer type is larger than the intptr_t type for
8867 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8868 // allows the trunc to be exposed to other transforms. Don't do this for
8869 // extending inttoptr's, because we don't know if the target sign or zero
8870 // extends to pointers.
8871 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
8872 TD->getPointerSizeInBits()) {
8873 Value *P = Builder->CreateTrunc(CI.getOperand(0),
8874 TD->getIntPtrType(CI.getContext()), "tmp");
8875 return new IntToPtrInst(P, CI.getType());
8878 if (Instruction *I = commonCastTransforms(CI))
8884 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8885 // If the operands are integer typed then apply the integer transforms,
8886 // otherwise just apply the common ones.
8887 Value *Src = CI.getOperand(0);
8888 const Type *SrcTy = Src->getType();
8889 const Type *DestTy = CI.getType();
8891 if (isa<PointerType>(SrcTy)) {
8892 if (Instruction *I = commonPointerCastTransforms(CI))
8895 if (Instruction *Result = commonCastTransforms(CI))
8900 // Get rid of casts from one type to the same type. These are useless and can
8901 // be replaced by the operand.
8902 if (DestTy == Src->getType())
8903 return ReplaceInstUsesWith(CI, Src);
8905 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8906 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8907 const Type *DstElTy = DstPTy->getElementType();
8908 const Type *SrcElTy = SrcPTy->getElementType();
8910 // If the address spaces don't match, don't eliminate the bitcast, which is
8911 // required for changing types.
8912 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8915 // If we are casting a alloca to a pointer to a type of the same
8916 // size, rewrite the allocation instruction to allocate the "right" type.
8917 // There is no need to modify malloc calls because it is their bitcast that
8918 // needs to be cleaned up.
8919 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
8920 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8923 // If the source and destination are pointers, and this cast is equivalent
8924 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8925 // This can enhance SROA and other transforms that want type-safe pointers.
8926 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
8927 unsigned NumZeros = 0;
8928 while (SrcElTy != DstElTy &&
8929 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8930 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8931 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8935 // If we found a path from the src to dest, create the getelementptr now.
8936 if (SrcElTy == DstElTy) {
8937 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
8938 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
8939 ((Instruction*) NULL));
8943 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
8944 if (DestVTy->getNumElements() == 1) {
8945 if (!isa<VectorType>(SrcTy)) {
8946 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
8947 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
8948 Constant::getNullValue(Type::getInt32Ty(*Context)));
8950 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
8954 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
8955 if (SrcVTy->getNumElements() == 1) {
8956 if (!isa<VectorType>(DestTy)) {
8958 Builder->CreateExtractElement(Src,
8959 Constant::getNullValue(Type::getInt32Ty(*Context)));
8960 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
8965 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8966 if (SVI->hasOneUse()) {
8967 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8968 // a bitconvert to a vector with the same # elts.
8969 if (isa<VectorType>(DestTy) &&
8970 cast<VectorType>(DestTy)->getNumElements() ==
8971 SVI->getType()->getNumElements() &&
8972 SVI->getType()->getNumElements() ==
8973 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
8975 // If either of the operands is a cast from CI.getType(), then
8976 // evaluating the shuffle in the casted destination's type will allow
8977 // us to eliminate at least one cast.
8978 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8979 Tmp->getOperand(0)->getType() == DestTy) ||
8980 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8981 Tmp->getOperand(0)->getType() == DestTy)) {
8982 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
8983 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
8984 // Return a new shuffle vector. Use the same element ID's, as we
8985 // know the vector types match #elts.
8986 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8994 /// GetSelectFoldableOperands - We want to turn code that looks like this:
8996 /// %D = select %cond, %C, %A
8998 /// %C = select %cond, %B, 0
9001 /// Assuming that the specified instruction is an operand to the select, return
9002 /// a bitmask indicating which operands of this instruction are foldable if they
9003 /// equal the other incoming value of the select.
9005 static unsigned GetSelectFoldableOperands(Instruction *I) {
9006 switch (I->getOpcode()) {
9007 case Instruction::Add:
9008 case Instruction::Mul:
9009 case Instruction::And:
9010 case Instruction::Or:
9011 case Instruction::Xor:
9012 return 3; // Can fold through either operand.
9013 case Instruction::Sub: // Can only fold on the amount subtracted.
9014 case Instruction::Shl: // Can only fold on the shift amount.
9015 case Instruction::LShr:
9016 case Instruction::AShr:
9019 return 0; // Cannot fold
9023 /// GetSelectFoldableConstant - For the same transformation as the previous
9024 /// function, return the identity constant that goes into the select.
9025 static Constant *GetSelectFoldableConstant(Instruction *I,
9026 LLVMContext *Context) {
9027 switch (I->getOpcode()) {
9028 default: llvm_unreachable("This cannot happen!");
9029 case Instruction::Add:
9030 case Instruction::Sub:
9031 case Instruction::Or:
9032 case Instruction::Xor:
9033 case Instruction::Shl:
9034 case Instruction::LShr:
9035 case Instruction::AShr:
9036 return Constant::getNullValue(I->getType());
9037 case Instruction::And:
9038 return Constant::getAllOnesValue(I->getType());
9039 case Instruction::Mul:
9040 return ConstantInt::get(I->getType(), 1);
9044 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9045 /// have the same opcode and only one use each. Try to simplify this.
9046 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9048 if (TI->getNumOperands() == 1) {
9049 // If this is a non-volatile load or a cast from the same type,
9052 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9055 return 0; // unknown unary op.
9058 // Fold this by inserting a select from the input values.
9059 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9060 FI->getOperand(0), SI.getName()+".v");
9061 InsertNewInstBefore(NewSI, SI);
9062 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
9066 // Only handle binary operators here.
9067 if (!isa<BinaryOperator>(TI))
9070 // Figure out if the operations have any operands in common.
9071 Value *MatchOp, *OtherOpT, *OtherOpF;
9073 if (TI->getOperand(0) == FI->getOperand(0)) {
9074 MatchOp = TI->getOperand(0);
9075 OtherOpT = TI->getOperand(1);
9076 OtherOpF = FI->getOperand(1);
9077 MatchIsOpZero = true;
9078 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9079 MatchOp = TI->getOperand(1);
9080 OtherOpT = TI->getOperand(0);
9081 OtherOpF = FI->getOperand(0);
9082 MatchIsOpZero = false;
9083 } else if (!TI->isCommutative()) {
9085 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9086 MatchOp = TI->getOperand(0);
9087 OtherOpT = TI->getOperand(1);
9088 OtherOpF = FI->getOperand(0);
9089 MatchIsOpZero = true;
9090 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9091 MatchOp = TI->getOperand(1);
9092 OtherOpT = TI->getOperand(0);
9093 OtherOpF = FI->getOperand(1);
9094 MatchIsOpZero = true;
9099 // If we reach here, they do have operations in common.
9100 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9101 OtherOpF, SI.getName()+".v");
9102 InsertNewInstBefore(NewSI, SI);
9104 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9106 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9108 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9110 llvm_unreachable("Shouldn't get here");
9114 static bool isSelect01(Constant *C1, Constant *C2) {
9115 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9118 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9121 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9124 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9125 /// facilitate further optimization.
9126 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9128 // See the comment above GetSelectFoldableOperands for a description of the
9129 // transformation we are doing here.
9130 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9131 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9132 !isa<Constant>(FalseVal)) {
9133 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9134 unsigned OpToFold = 0;
9135 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9137 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9142 Constant *C = GetSelectFoldableConstant(TVI, Context);
9143 Value *OOp = TVI->getOperand(2-OpToFold);
9144 // Avoid creating select between 2 constants unless it's selecting
9146 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9147 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9148 InsertNewInstBefore(NewSel, SI);
9149 NewSel->takeName(TVI);
9150 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9151 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9152 llvm_unreachable("Unknown instruction!!");
9159 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9160 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9161 !isa<Constant>(TrueVal)) {
9162 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9163 unsigned OpToFold = 0;
9164 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9166 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9171 Constant *C = GetSelectFoldableConstant(FVI, Context);
9172 Value *OOp = FVI->getOperand(2-OpToFold);
9173 // Avoid creating select between 2 constants unless it's selecting
9175 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9176 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9177 InsertNewInstBefore(NewSel, SI);
9178 NewSel->takeName(FVI);
9179 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9180 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9181 llvm_unreachable("Unknown instruction!!");
9191 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9192 /// ICmpInst as its first operand.
9194 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9196 bool Changed = false;
9197 ICmpInst::Predicate Pred = ICI->getPredicate();
9198 Value *CmpLHS = ICI->getOperand(0);
9199 Value *CmpRHS = ICI->getOperand(1);
9200 Value *TrueVal = SI.getTrueValue();
9201 Value *FalseVal = SI.getFalseValue();
9203 // Check cases where the comparison is with a constant that
9204 // can be adjusted to fit the min/max idiom. We may edit ICI in
9205 // place here, so make sure the select is the only user.
9206 if (ICI->hasOneUse())
9207 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9210 case ICmpInst::ICMP_ULT:
9211 case ICmpInst::ICMP_SLT: {
9212 // X < MIN ? T : F --> F
9213 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9214 return ReplaceInstUsesWith(SI, FalseVal);
9215 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
9216 Constant *AdjustedRHS = SubOne(CI);
9217 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9218 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9219 Pred = ICmpInst::getSwappedPredicate(Pred);
9220 CmpRHS = AdjustedRHS;
9221 std::swap(FalseVal, TrueVal);
9222 ICI->setPredicate(Pred);
9223 ICI->setOperand(1, CmpRHS);
9224 SI.setOperand(1, TrueVal);
9225 SI.setOperand(2, FalseVal);
9230 case ICmpInst::ICMP_UGT:
9231 case ICmpInst::ICMP_SGT: {
9232 // X > MAX ? T : F --> F
9233 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9234 return ReplaceInstUsesWith(SI, FalseVal);
9235 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
9236 Constant *AdjustedRHS = AddOne(CI);
9237 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9238 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9239 Pred = ICmpInst::getSwappedPredicate(Pred);
9240 CmpRHS = AdjustedRHS;
9241 std::swap(FalseVal, TrueVal);
9242 ICI->setPredicate(Pred);
9243 ICI->setOperand(1, CmpRHS);
9244 SI.setOperand(1, TrueVal);
9245 SI.setOperand(2, FalseVal);
9252 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9253 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
9254 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9255 if (match(TrueVal, m_ConstantInt<-1>()) &&
9256 match(FalseVal, m_ConstantInt<0>()))
9257 Pred = ICI->getPredicate();
9258 else if (match(TrueVal, m_ConstantInt<0>()) &&
9259 match(FalseVal, m_ConstantInt<-1>()))
9260 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9262 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9263 // If we are just checking for a icmp eq of a single bit and zext'ing it
9264 // to an integer, then shift the bit to the appropriate place and then
9265 // cast to integer to avoid the comparison.
9266 const APInt &Op1CV = CI->getValue();
9268 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9269 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9270 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9271 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9272 Value *In = ICI->getOperand(0);
9273 Value *Sh = ConstantInt::get(In->getType(),
9274 In->getType()->getScalarSizeInBits()-1);
9275 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9276 In->getName()+".lobit"),
9278 if (In->getType() != SI.getType())
9279 In = CastInst::CreateIntegerCast(In, SI.getType(),
9280 true/*SExt*/, "tmp", ICI);
9282 if (Pred == ICmpInst::ICMP_SGT)
9283 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9284 In->getName()+".not"), *ICI);
9286 return ReplaceInstUsesWith(SI, In);
9291 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9292 // Transform (X == Y) ? X : Y -> Y
9293 if (Pred == ICmpInst::ICMP_EQ)
9294 return ReplaceInstUsesWith(SI, FalseVal);
9295 // Transform (X != Y) ? X : Y -> X
9296 if (Pred == ICmpInst::ICMP_NE)
9297 return ReplaceInstUsesWith(SI, TrueVal);
9298 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9300 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9301 // Transform (X == Y) ? Y : X -> X
9302 if (Pred == ICmpInst::ICMP_EQ)
9303 return ReplaceInstUsesWith(SI, FalseVal);
9304 // Transform (X != Y) ? Y : X -> Y
9305 if (Pred == ICmpInst::ICMP_NE)
9306 return ReplaceInstUsesWith(SI, TrueVal);
9307 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9310 /// NOTE: if we wanted to, this is where to detect integer ABS
9312 return Changed ? &SI : 0;
9316 /// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9317 /// PHI node (but the two may be in different blocks). See if the true/false
9318 /// values (V) are live in all of the predecessor blocks of the PHI. For
9319 /// example, cases like this cannot be mapped:
9321 /// X = phi [ C1, BB1], [C2, BB2]
9323 /// Z = select X, Y, 0
9325 /// because Y is not live in BB1/BB2.
9327 static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9328 const SelectInst &SI) {
9329 // If the value is a non-instruction value like a constant or argument, it
9330 // can always be mapped.
9331 const Instruction *I = dyn_cast<Instruction>(V);
9332 if (I == 0) return true;
9334 // If V is a PHI node defined in the same block as the condition PHI, we can
9335 // map the arguments.
9336 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9338 if (const PHINode *VP = dyn_cast<PHINode>(I))
9339 if (VP->getParent() == CondPHI->getParent())
9342 // Otherwise, if the PHI and select are defined in the same block and if V is
9343 // defined in a different block, then we can transform it.
9344 if (SI.getParent() == CondPHI->getParent() &&
9345 I->getParent() != CondPHI->getParent())
9348 // Otherwise we have a 'hard' case and we can't tell without doing more
9349 // detailed dominator based analysis, punt.
9353 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9354 Value *CondVal = SI.getCondition();
9355 Value *TrueVal = SI.getTrueValue();
9356 Value *FalseVal = SI.getFalseValue();
9358 // select true, X, Y -> X
9359 // select false, X, Y -> Y
9360 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9361 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9363 // select C, X, X -> X
9364 if (TrueVal == FalseVal)
9365 return ReplaceInstUsesWith(SI, TrueVal);
9367 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9368 return ReplaceInstUsesWith(SI, FalseVal);
9369 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9370 return ReplaceInstUsesWith(SI, TrueVal);
9371 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9372 if (isa<Constant>(TrueVal))
9373 return ReplaceInstUsesWith(SI, TrueVal);
9375 return ReplaceInstUsesWith(SI, FalseVal);
9378 if (SI.getType() == Type::getInt1Ty(*Context)) {
9379 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9380 if (C->getZExtValue()) {
9381 // Change: A = select B, true, C --> A = or B, C
9382 return BinaryOperator::CreateOr(CondVal, FalseVal);
9384 // Change: A = select B, false, C --> A = and !B, C
9386 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9387 "not."+CondVal->getName()), SI);
9388 return BinaryOperator::CreateAnd(NotCond, FalseVal);
9390 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9391 if (C->getZExtValue() == false) {
9392 // Change: A = select B, C, false --> A = and B, C
9393 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9395 // Change: A = select B, C, true --> A = or !B, C
9397 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9398 "not."+CondVal->getName()), SI);
9399 return BinaryOperator::CreateOr(NotCond, TrueVal);
9403 // select a, b, a -> a&b
9404 // select a, a, b -> a|b
9405 if (CondVal == TrueVal)
9406 return BinaryOperator::CreateOr(CondVal, FalseVal);
9407 else if (CondVal == FalseVal)
9408 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9411 // Selecting between two integer constants?
9412 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9413 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9414 // select C, 1, 0 -> zext C to int
9415 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9416 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9417 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9418 // select C, 0, 1 -> zext !C to int
9420 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9421 "not."+CondVal->getName()), SI);
9422 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9425 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9426 // If one of the constants is zero (we know they can't both be) and we
9427 // have an icmp instruction with zero, and we have an 'and' with the
9428 // non-constant value, eliminate this whole mess. This corresponds to
9429 // cases like this: ((X & 27) ? 27 : 0)
9430 if (TrueValC->isZero() || FalseValC->isZero())
9431 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9432 cast<Constant>(IC->getOperand(1))->isNullValue())
9433 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9434 if (ICA->getOpcode() == Instruction::And &&
9435 isa<ConstantInt>(ICA->getOperand(1)) &&
9436 (ICA->getOperand(1) == TrueValC ||
9437 ICA->getOperand(1) == FalseValC) &&
9438 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9439 // Okay, now we know that everything is set up, we just don't
9440 // know whether we have a icmp_ne or icmp_eq and whether the
9441 // true or false val is the zero.
9442 bool ShouldNotVal = !TrueValC->isZero();
9443 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9446 V = InsertNewInstBefore(BinaryOperator::Create(
9447 Instruction::Xor, V, ICA->getOperand(1)), SI);
9448 return ReplaceInstUsesWith(SI, V);
9453 // See if we are selecting two values based on a comparison of the two values.
9454 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9455 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9456 // Transform (X == Y) ? X : Y -> Y
9457 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9458 // This is not safe in general for floating point:
9459 // consider X== -0, Y== +0.
9460 // It becomes safe if either operand is a nonzero constant.
9461 ConstantFP *CFPt, *CFPf;
9462 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9463 !CFPt->getValueAPF().isZero()) ||
9464 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9465 !CFPf->getValueAPF().isZero()))
9466 return ReplaceInstUsesWith(SI, FalseVal);
9468 // Transform (X != Y) ? X : Y -> X
9469 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9470 return ReplaceInstUsesWith(SI, TrueVal);
9471 // NOTE: if we wanted to, this is where to detect MIN/MAX
9473 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9474 // Transform (X == Y) ? Y : X -> X
9475 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9476 // This is not safe in general for floating point:
9477 // consider X== -0, Y== +0.
9478 // It becomes safe if either operand is a nonzero constant.
9479 ConstantFP *CFPt, *CFPf;
9480 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9481 !CFPt->getValueAPF().isZero()) ||
9482 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9483 !CFPf->getValueAPF().isZero()))
9484 return ReplaceInstUsesWith(SI, FalseVal);
9486 // Transform (X != Y) ? Y : X -> Y
9487 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9488 return ReplaceInstUsesWith(SI, TrueVal);
9489 // NOTE: if we wanted to, this is where to detect MIN/MAX
9491 // NOTE: if we wanted to, this is where to detect ABS
9494 // See if we are selecting two values based on a comparison of the two values.
9495 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9496 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9499 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9500 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9501 if (TI->hasOneUse() && FI->hasOneUse()) {
9502 Instruction *AddOp = 0, *SubOp = 0;
9504 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9505 if (TI->getOpcode() == FI->getOpcode())
9506 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9509 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9510 // even legal for FP.
9511 if ((TI->getOpcode() == Instruction::Sub &&
9512 FI->getOpcode() == Instruction::Add) ||
9513 (TI->getOpcode() == Instruction::FSub &&
9514 FI->getOpcode() == Instruction::FAdd)) {
9515 AddOp = FI; SubOp = TI;
9516 } else if ((FI->getOpcode() == Instruction::Sub &&
9517 TI->getOpcode() == Instruction::Add) ||
9518 (FI->getOpcode() == Instruction::FSub &&
9519 TI->getOpcode() == Instruction::FAdd)) {
9520 AddOp = TI; SubOp = FI;
9524 Value *OtherAddOp = 0;
9525 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9526 OtherAddOp = AddOp->getOperand(1);
9527 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9528 OtherAddOp = AddOp->getOperand(0);
9532 // So at this point we know we have (Y -> OtherAddOp):
9533 // select C, (add X, Y), (sub X, Z)
9534 Value *NegVal; // Compute -Z
9535 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9536 NegVal = ConstantExpr::getNeg(C);
9538 NegVal = InsertNewInstBefore(
9539 BinaryOperator::CreateNeg(SubOp->getOperand(1),
9543 Value *NewTrueOp = OtherAddOp;
9544 Value *NewFalseOp = NegVal;
9546 std::swap(NewTrueOp, NewFalseOp);
9547 Instruction *NewSel =
9548 SelectInst::Create(CondVal, NewTrueOp,
9549 NewFalseOp, SI.getName() + ".p");
9551 NewSel = InsertNewInstBefore(NewSel, SI);
9552 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9557 // See if we can fold the select into one of our operands.
9558 if (SI.getType()->isInteger()) {
9559 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9564 // See if we can fold the select into a phi node if the condition is a select.
9565 if (isa<PHINode>(SI.getCondition()))
9566 // The true/false values have to be live in the PHI predecessor's blocks.
9567 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
9568 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
9569 if (Instruction *NV = FoldOpIntoPhi(SI))
9572 if (BinaryOperator::isNot(CondVal)) {
9573 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9574 SI.setOperand(1, FalseVal);
9575 SI.setOperand(2, TrueVal);
9582 /// EnforceKnownAlignment - If the specified pointer points to an object that
9583 /// we control, modify the object's alignment to PrefAlign. This isn't
9584 /// often possible though. If alignment is important, a more reliable approach
9585 /// is to simply align all global variables and allocation instructions to
9586 /// their preferred alignment from the beginning.
9588 static unsigned EnforceKnownAlignment(Value *V,
9589 unsigned Align, unsigned PrefAlign) {
9591 User *U = dyn_cast<User>(V);
9592 if (!U) return Align;
9594 switch (Operator::getOpcode(U)) {
9596 case Instruction::BitCast:
9597 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9598 case Instruction::GetElementPtr: {
9599 // If all indexes are zero, it is just the alignment of the base pointer.
9600 bool AllZeroOperands = true;
9601 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9602 if (!isa<Constant>(*i) ||
9603 !cast<Constant>(*i)->isNullValue()) {
9604 AllZeroOperands = false;
9608 if (AllZeroOperands) {
9609 // Treat this like a bitcast.
9610 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9616 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9617 // If there is a large requested alignment and we can, bump up the alignment
9619 if (!GV->isDeclaration()) {
9620 if (GV->getAlignment() >= PrefAlign)
9621 Align = GV->getAlignment();
9623 GV->setAlignment(PrefAlign);
9627 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
9628 // If there is a requested alignment and if this is an alloca, round up.
9629 if (AI->getAlignment() >= PrefAlign)
9630 Align = AI->getAlignment();
9632 AI->setAlignment(PrefAlign);
9640 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9641 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9642 /// and it is more than the alignment of the ultimate object, see if we can
9643 /// increase the alignment of the ultimate object, making this check succeed.
9644 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9645 unsigned PrefAlign) {
9646 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9647 sizeof(PrefAlign) * CHAR_BIT;
9648 APInt Mask = APInt::getAllOnesValue(BitWidth);
9649 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9650 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9651 unsigned TrailZ = KnownZero.countTrailingOnes();
9652 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9654 if (PrefAlign > Align)
9655 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9657 // We don't need to make any adjustment.
9661 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9662 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9663 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9664 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9665 unsigned CopyAlign = MI->getAlignment();
9667 if (CopyAlign < MinAlign) {
9668 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9673 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9675 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9676 if (MemOpLength == 0) return 0;
9678 // Source and destination pointer types are always "i8*" for intrinsic. See
9679 // if the size is something we can handle with a single primitive load/store.
9680 // A single load+store correctly handles overlapping memory in the memmove
9682 unsigned Size = MemOpLength->getZExtValue();
9683 if (Size == 0) return MI; // Delete this mem transfer.
9685 if (Size > 8 || (Size&(Size-1)))
9686 return 0; // If not 1/2/4/8 bytes, exit.
9688 // Use an integer load+store unless we can find something better.
9690 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
9692 // Memcpy forces the use of i8* for the source and destination. That means
9693 // that if you're using memcpy to move one double around, you'll get a cast
9694 // from double* to i8*. We'd much rather use a double load+store rather than
9695 // an i64 load+store, here because this improves the odds that the source or
9696 // dest address will be promotable. See if we can find a better type than the
9697 // integer datatype.
9698 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9699 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9700 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9701 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9702 // down through these levels if so.
9703 while (!SrcETy->isSingleValueType()) {
9704 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9705 if (STy->getNumElements() == 1)
9706 SrcETy = STy->getElementType(0);
9709 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9710 if (ATy->getNumElements() == 1)
9711 SrcETy = ATy->getElementType();
9718 if (SrcETy->isSingleValueType())
9719 NewPtrTy = PointerType::getUnqual(SrcETy);
9724 // If the memcpy/memmove provides better alignment info than we can
9726 SrcAlign = std::max(SrcAlign, CopyAlign);
9727 DstAlign = std::max(DstAlign, CopyAlign);
9729 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
9730 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
9731 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9732 InsertNewInstBefore(L, *MI);
9733 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9735 // Set the size of the copy to 0, it will be deleted on the next iteration.
9736 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9740 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9741 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9742 if (MI->getAlignment() < Alignment) {
9743 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
9748 // Extract the length and alignment and fill if they are constant.
9749 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9750 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9751 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
9753 uint64_t Len = LenC->getZExtValue();
9754 Alignment = MI->getAlignment();
9756 // If the length is zero, this is a no-op
9757 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9759 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9760 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9761 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
9763 Value *Dest = MI->getDest();
9764 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
9766 // Alignment 0 is identity for alignment 1 for memset, but not store.
9767 if (Alignment == 0) Alignment = 1;
9769 // Extract the fill value and store.
9770 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9771 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
9772 Dest, false, Alignment), *MI);
9774 // Set the size of the copy to 0, it will be deleted on the next iteration.
9775 MI->setLength(Constant::getNullValue(LenC->getType()));
9783 /// visitCallInst - CallInst simplification. This mostly only handles folding
9784 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9785 /// the heavy lifting.
9787 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9788 if (isFreeCall(&CI))
9789 return visitFree(CI);
9791 // If the caller function is nounwind, mark the call as nounwind, even if the
9793 if (CI.getParent()->getParent()->doesNotThrow() &&
9794 !CI.doesNotThrow()) {
9795 CI.setDoesNotThrow();
9799 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9800 if (!II) return visitCallSite(&CI);
9802 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9804 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9805 bool Changed = false;
9807 // memmove/cpy/set of zero bytes is a noop.
9808 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9809 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9811 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9812 if (CI->getZExtValue() == 1) {
9813 // Replace the instruction with just byte operations. We would
9814 // transform other cases to loads/stores, but we don't know if
9815 // alignment is sufficient.
9819 // If we have a memmove and the source operation is a constant global,
9820 // then the source and dest pointers can't alias, so we can change this
9821 // into a call to memcpy.
9822 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9823 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9824 if (GVSrc->isConstant()) {
9825 Module *M = CI.getParent()->getParent()->getParent();
9826 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9828 Tys[0] = CI.getOperand(3)->getType();
9830 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9834 // memmove(x,x,size) -> noop.
9835 if (MMI->getSource() == MMI->getDest())
9836 return EraseInstFromFunction(CI);
9839 // If we can determine a pointer alignment that is bigger than currently
9840 // set, update the alignment.
9841 if (isa<MemTransferInst>(MI)) {
9842 if (Instruction *I = SimplifyMemTransfer(MI))
9844 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9845 if (Instruction *I = SimplifyMemSet(MSI))
9849 if (Changed) return II;
9852 switch (II->getIntrinsicID()) {
9854 case Intrinsic::bswap:
9855 // bswap(bswap(x)) -> x
9856 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9857 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9858 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9860 case Intrinsic::ppc_altivec_lvx:
9861 case Intrinsic::ppc_altivec_lvxl:
9862 case Intrinsic::x86_sse_loadu_ps:
9863 case Intrinsic::x86_sse2_loadu_pd:
9864 case Intrinsic::x86_sse2_loadu_dq:
9865 // Turn PPC lvx -> load if the pointer is known aligned.
9866 // Turn X86 loadups -> load if the pointer is known aligned.
9867 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9868 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
9869 PointerType::getUnqual(II->getType()));
9870 return new LoadInst(Ptr);
9873 case Intrinsic::ppc_altivec_stvx:
9874 case Intrinsic::ppc_altivec_stvxl:
9875 // Turn stvx -> store if the pointer is known aligned.
9876 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9877 const Type *OpPtrTy =
9878 PointerType::getUnqual(II->getOperand(1)->getType());
9879 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
9880 return new StoreInst(II->getOperand(1), Ptr);
9883 case Intrinsic::x86_sse_storeu_ps:
9884 case Intrinsic::x86_sse2_storeu_pd:
9885 case Intrinsic::x86_sse2_storeu_dq:
9886 // Turn X86 storeu -> store if the pointer is known aligned.
9887 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9888 const Type *OpPtrTy =
9889 PointerType::getUnqual(II->getOperand(2)->getType());
9890 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
9891 return new StoreInst(II->getOperand(2), Ptr);
9895 case Intrinsic::x86_sse_cvttss2si: {
9896 // These intrinsics only demands the 0th element of its input vector. If
9897 // we can simplify the input based on that, do so now.
9899 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9900 APInt DemandedElts(VWidth, 1);
9901 APInt UndefElts(VWidth, 0);
9902 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9904 II->setOperand(1, V);
9910 case Intrinsic::ppc_altivec_vperm:
9911 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9912 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9913 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9915 // Check that all of the elements are integer constants or undefs.
9916 bool AllEltsOk = true;
9917 for (unsigned i = 0; i != 16; ++i) {
9918 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9919 !isa<UndefValue>(Mask->getOperand(i))) {
9926 // Cast the input vectors to byte vectors.
9927 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
9928 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
9929 Value *Result = UndefValue::get(Op0->getType());
9931 // Only extract each element once.
9932 Value *ExtractedElts[32];
9933 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9935 for (unsigned i = 0; i != 16; ++i) {
9936 if (isa<UndefValue>(Mask->getOperand(i)))
9938 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9939 Idx &= 31; // Match the hardware behavior.
9941 if (ExtractedElts[Idx] == 0) {
9942 ExtractedElts[Idx] =
9943 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
9944 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
9948 // Insert this value into the result vector.
9949 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
9950 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
9953 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
9958 case Intrinsic::stackrestore: {
9959 // If the save is right next to the restore, remove the restore. This can
9960 // happen when variable allocas are DCE'd.
9961 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9962 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9963 BasicBlock::iterator BI = SS;
9965 return EraseInstFromFunction(CI);
9969 // Scan down this block to see if there is another stack restore in the
9970 // same block without an intervening call/alloca.
9971 BasicBlock::iterator BI = II;
9972 TerminatorInst *TI = II->getParent()->getTerminator();
9973 bool CannotRemove = false;
9974 for (++BI; &*BI != TI; ++BI) {
9975 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
9976 CannotRemove = true;
9979 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9980 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9981 // If there is a stackrestore below this one, remove this one.
9982 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9983 return EraseInstFromFunction(CI);
9984 // Otherwise, ignore the intrinsic.
9986 // If we found a non-intrinsic call, we can't remove the stack
9988 CannotRemove = true;
9994 // If the stack restore is in a return/unwind block and if there are no
9995 // allocas or calls between the restore and the return, nuke the restore.
9996 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9997 return EraseInstFromFunction(CI);
10002 return visitCallSite(II);
10005 // InvokeInst simplification
10007 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10008 return visitCallSite(&II);
10011 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
10012 /// passed through the varargs area, we can eliminate the use of the cast.
10013 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10014 const CastInst * const CI,
10015 const TargetData * const TD,
10017 if (!CI->isLosslessCast())
10020 // The size of ByVal arguments is derived from the type, so we
10021 // can't change to a type with a different size. If the size were
10022 // passed explicitly we could avoid this check.
10023 if (!CS.paramHasAttr(ix, Attribute::ByVal))
10026 const Type* SrcTy =
10027 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10028 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10029 if (!SrcTy->isSized() || !DstTy->isSized())
10031 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10036 // visitCallSite - Improvements for call and invoke instructions.
10038 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10039 bool Changed = false;
10041 // If the callee is a constexpr cast of a function, attempt to move the cast
10042 // to the arguments of the call/invoke.
10043 if (transformConstExprCastCall(CS)) return 0;
10045 Value *Callee = CS.getCalledValue();
10047 if (Function *CalleeF = dyn_cast<Function>(Callee))
10048 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10049 Instruction *OldCall = CS.getInstruction();
10050 // If the call and callee calling conventions don't match, this call must
10051 // be unreachable, as the call is undefined.
10052 new StoreInst(ConstantInt::getTrue(*Context),
10053 UndefValue::get(Type::getInt1PtrTy(*Context)),
10055 // If OldCall dues not return void then replaceAllUsesWith undef.
10056 // This allows ValueHandlers and custom metadata to adjust itself.
10057 if (!OldCall->getType()->isVoidTy())
10058 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
10059 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10060 return EraseInstFromFunction(*OldCall);
10064 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10065 // This instruction is not reachable, just remove it. We insert a store to
10066 // undef so that we know that this code is not reachable, despite the fact
10067 // that we can't modify the CFG here.
10068 new StoreInst(ConstantInt::getTrue(*Context),
10069 UndefValue::get(Type::getInt1PtrTy(*Context)),
10070 CS.getInstruction());
10072 // If CS dues not return void then replaceAllUsesWith undef.
10073 // This allows ValueHandlers and custom metadata to adjust itself.
10074 if (!CS.getInstruction()->getType()->isVoidTy())
10075 CS.getInstruction()->
10076 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
10078 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10079 // Don't break the CFG, insert a dummy cond branch.
10080 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10081 ConstantInt::getTrue(*Context), II);
10083 return EraseInstFromFunction(*CS.getInstruction());
10086 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10087 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10088 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10089 return transformCallThroughTrampoline(CS);
10091 const PointerType *PTy = cast<PointerType>(Callee->getType());
10092 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10093 if (FTy->isVarArg()) {
10094 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10095 // See if we can optimize any arguments passed through the varargs area of
10097 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10098 E = CS.arg_end(); I != E; ++I, ++ix) {
10099 CastInst *CI = dyn_cast<CastInst>(*I);
10100 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10101 *I = CI->getOperand(0);
10107 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10108 // Inline asm calls cannot throw - mark them 'nounwind'.
10109 CS.setDoesNotThrow();
10113 return Changed ? CS.getInstruction() : 0;
10116 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10117 // attempt to move the cast to the arguments of the call/invoke.
10119 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10120 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10121 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10122 if (CE->getOpcode() != Instruction::BitCast ||
10123 !isa<Function>(CE->getOperand(0)))
10125 Function *Callee = cast<Function>(CE->getOperand(0));
10126 Instruction *Caller = CS.getInstruction();
10127 const AttrListPtr &CallerPAL = CS.getAttributes();
10129 // Okay, this is a cast from a function to a different type. Unless doing so
10130 // would cause a type conversion of one of our arguments, change this call to
10131 // be a direct call with arguments casted to the appropriate types.
10133 const FunctionType *FT = Callee->getFunctionType();
10134 const Type *OldRetTy = Caller->getType();
10135 const Type *NewRetTy = FT->getReturnType();
10137 if (isa<StructType>(NewRetTy))
10138 return false; // TODO: Handle multiple return values.
10140 // Check to see if we are changing the return type...
10141 if (OldRetTy != NewRetTy) {
10142 if (Callee->isDeclaration() &&
10143 // Conversion is ok if changing from one pointer type to another or from
10144 // a pointer to an integer of the same size.
10145 !((isa<PointerType>(OldRetTy) || !TD ||
10146 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
10147 (isa<PointerType>(NewRetTy) || !TD ||
10148 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
10149 return false; // Cannot transform this return value.
10151 if (!Caller->use_empty() &&
10152 // void -> non-void is handled specially
10153 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
10154 return false; // Cannot transform this return value.
10156 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10157 Attributes RAttrs = CallerPAL.getRetAttributes();
10158 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10159 return false; // Attribute not compatible with transformed value.
10162 // If the callsite is an invoke instruction, and the return value is used by
10163 // a PHI node in a successor, we cannot change the return type of the call
10164 // because there is no place to put the cast instruction (without breaking
10165 // the critical edge). Bail out in this case.
10166 if (!Caller->use_empty())
10167 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10168 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10170 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10171 if (PN->getParent() == II->getNormalDest() ||
10172 PN->getParent() == II->getUnwindDest())
10176 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10177 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10179 CallSite::arg_iterator AI = CS.arg_begin();
10180 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10181 const Type *ParamTy = FT->getParamType(i);
10182 const Type *ActTy = (*AI)->getType();
10184 if (!CastInst::isCastable(ActTy, ParamTy))
10185 return false; // Cannot transform this parameter value.
10187 if (CallerPAL.getParamAttributes(i + 1)
10188 & Attribute::typeIncompatible(ParamTy))
10189 return false; // Attribute not compatible with transformed value.
10191 // Converting from one pointer type to another or between a pointer and an
10192 // integer of the same size is safe even if we do not have a body.
10193 bool isConvertible = ActTy == ParamTy ||
10194 (TD && ((isa<PointerType>(ParamTy) ||
10195 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10196 (isa<PointerType>(ActTy) ||
10197 ActTy == TD->getIntPtrType(Caller->getContext()))));
10198 if (Callee->isDeclaration() && !isConvertible) return false;
10201 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10202 Callee->isDeclaration())
10203 return false; // Do not delete arguments unless we have a function body.
10205 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10206 !CallerPAL.isEmpty())
10207 // In this case we have more arguments than the new function type, but we
10208 // won't be dropping them. Check that these extra arguments have attributes
10209 // that are compatible with being a vararg call argument.
10210 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10211 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10213 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10214 if (PAttrs & Attribute::VarArgsIncompatible)
10218 // Okay, we decided that this is a safe thing to do: go ahead and start
10219 // inserting cast instructions as necessary...
10220 std::vector<Value*> Args;
10221 Args.reserve(NumActualArgs);
10222 SmallVector<AttributeWithIndex, 8> attrVec;
10223 attrVec.reserve(NumCommonArgs);
10225 // Get any return attributes.
10226 Attributes RAttrs = CallerPAL.getRetAttributes();
10228 // If the return value is not being used, the type may not be compatible
10229 // with the existing attributes. Wipe out any problematic attributes.
10230 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10232 // Add the new return attributes.
10234 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10236 AI = CS.arg_begin();
10237 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10238 const Type *ParamTy = FT->getParamType(i);
10239 if ((*AI)->getType() == ParamTy) {
10240 Args.push_back(*AI);
10242 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10243 false, ParamTy, false);
10244 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
10247 // Add any parameter attributes.
10248 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10249 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10252 // If the function takes more arguments than the call was taking, add them
10254 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10255 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
10257 // If we are removing arguments to the function, emit an obnoxious warning.
10258 if (FT->getNumParams() < NumActualArgs) {
10259 if (!FT->isVarArg()) {
10260 errs() << "WARNING: While resolving call to function '"
10261 << Callee->getName() << "' arguments were dropped!\n";
10263 // Add all of the arguments in their promoted form to the arg list.
10264 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10265 const Type *PTy = getPromotedType((*AI)->getType());
10266 if (PTy != (*AI)->getType()) {
10267 // Must promote to pass through va_arg area!
10268 Instruction::CastOps opcode =
10269 CastInst::getCastOpcode(*AI, false, PTy, false);
10270 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
10272 Args.push_back(*AI);
10275 // Add any parameter attributes.
10276 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10277 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10282 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10283 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10285 if (NewRetTy->isVoidTy())
10286 Caller->setName(""); // Void type should not have a name.
10288 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10292 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10293 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10294 Args.begin(), Args.end(),
10295 Caller->getName(), Caller);
10296 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10297 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10299 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10300 Caller->getName(), Caller);
10301 CallInst *CI = cast<CallInst>(Caller);
10302 if (CI->isTailCall())
10303 cast<CallInst>(NC)->setTailCall();
10304 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10305 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10308 // Insert a cast of the return type as necessary.
10310 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10311 if (!NV->getType()->isVoidTy()) {
10312 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
10314 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10316 // If this is an invoke instruction, we should insert it after the first
10317 // non-phi, instruction in the normal successor block.
10318 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10319 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10320 InsertNewInstBefore(NC, *I);
10322 // Otherwise, it's a call, just insert cast right after the call instr
10323 InsertNewInstBefore(NC, *Caller);
10325 Worklist.AddUsersToWorkList(*Caller);
10327 NV = UndefValue::get(Caller->getType());
10332 if (!Caller->use_empty())
10333 Caller->replaceAllUsesWith(NV);
10335 EraseInstFromFunction(*Caller);
10339 // transformCallThroughTrampoline - Turn a call to a function created by the
10340 // init_trampoline intrinsic into a direct call to the underlying function.
10342 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10343 Value *Callee = CS.getCalledValue();
10344 const PointerType *PTy = cast<PointerType>(Callee->getType());
10345 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10346 const AttrListPtr &Attrs = CS.getAttributes();
10348 // If the call already has the 'nest' attribute somewhere then give up -
10349 // otherwise 'nest' would occur twice after splicing in the chain.
10350 if (Attrs.hasAttrSomewhere(Attribute::Nest))
10353 IntrinsicInst *Tramp =
10354 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10356 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10357 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10358 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10360 const AttrListPtr &NestAttrs = NestF->getAttributes();
10361 if (!NestAttrs.isEmpty()) {
10362 unsigned NestIdx = 1;
10363 const Type *NestTy = 0;
10364 Attributes NestAttr = Attribute::None;
10366 // Look for a parameter marked with the 'nest' attribute.
10367 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10368 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10369 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10370 // Record the parameter type and any other attributes.
10372 NestAttr = NestAttrs.getParamAttributes(NestIdx);
10377 Instruction *Caller = CS.getInstruction();
10378 std::vector<Value*> NewArgs;
10379 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10381 SmallVector<AttributeWithIndex, 8> NewAttrs;
10382 NewAttrs.reserve(Attrs.getNumSlots() + 1);
10384 // Insert the nest argument into the call argument list, which may
10385 // mean appending it. Likewise for attributes.
10387 // Add any result attributes.
10388 if (Attributes Attr = Attrs.getRetAttributes())
10389 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10393 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10395 if (Idx == NestIdx) {
10396 // Add the chain argument and attributes.
10397 Value *NestVal = Tramp->getOperand(3);
10398 if (NestVal->getType() != NestTy)
10399 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10400 NewArgs.push_back(NestVal);
10401 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10407 // Add the original argument and attributes.
10408 NewArgs.push_back(*I);
10409 if (Attributes Attr = Attrs.getParamAttributes(Idx))
10411 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10417 // Add any function attributes.
10418 if (Attributes Attr = Attrs.getFnAttributes())
10419 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10421 // The trampoline may have been bitcast to a bogus type (FTy).
10422 // Handle this by synthesizing a new function type, equal to FTy
10423 // with the chain parameter inserted.
10425 std::vector<const Type*> NewTypes;
10426 NewTypes.reserve(FTy->getNumParams()+1);
10428 // Insert the chain's type into the list of parameter types, which may
10429 // mean appending it.
10432 FunctionType::param_iterator I = FTy->param_begin(),
10433 E = FTy->param_end();
10436 if (Idx == NestIdx)
10437 // Add the chain's type.
10438 NewTypes.push_back(NestTy);
10443 // Add the original type.
10444 NewTypes.push_back(*I);
10450 // Replace the trampoline call with a direct call. Let the generic
10451 // code sort out any function type mismatches.
10452 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
10454 Constant *NewCallee =
10455 NestF->getType() == PointerType::getUnqual(NewFTy) ?
10456 NestF : ConstantExpr::getBitCast(NestF,
10457 PointerType::getUnqual(NewFTy));
10458 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
10461 Instruction *NewCaller;
10462 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10463 NewCaller = InvokeInst::Create(NewCallee,
10464 II->getNormalDest(), II->getUnwindDest(),
10465 NewArgs.begin(), NewArgs.end(),
10466 Caller->getName(), Caller);
10467 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10468 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10470 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10471 Caller->getName(), Caller);
10472 if (cast<CallInst>(Caller)->isTailCall())
10473 cast<CallInst>(NewCaller)->setTailCall();
10474 cast<CallInst>(NewCaller)->
10475 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10476 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10478 if (!Caller->getType()->isVoidTy())
10479 Caller->replaceAllUsesWith(NewCaller);
10480 Caller->eraseFromParent();
10481 Worklist.Remove(Caller);
10486 // Replace the trampoline call with a direct call. Since there is no 'nest'
10487 // parameter, there is no need to adjust the argument list. Let the generic
10488 // code sort out any function type mismatches.
10489 Constant *NewCallee =
10490 NestF->getType() == PTy ? NestF :
10491 ConstantExpr::getBitCast(NestF, PTy);
10492 CS.setCalledFunction(NewCallee);
10493 return CS.getInstruction();
10496 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
10497 /// and if a/b/c and the add's all have a single use, turn this into a phi
10498 /// and a single binop.
10499 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10500 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10501 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10502 unsigned Opc = FirstInst->getOpcode();
10503 Value *LHSVal = FirstInst->getOperand(0);
10504 Value *RHSVal = FirstInst->getOperand(1);
10506 const Type *LHSType = LHSVal->getType();
10507 const Type *RHSType = RHSVal->getType();
10509 // Scan to see if all operands are the same opcode, and all have one use.
10510 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10511 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10512 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10513 // Verify type of the LHS matches so we don't fold cmp's of different
10514 // types or GEP's with different index types.
10515 I->getOperand(0)->getType() != LHSType ||
10516 I->getOperand(1)->getType() != RHSType)
10519 // If they are CmpInst instructions, check their predicates
10520 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10521 if (cast<CmpInst>(I)->getPredicate() !=
10522 cast<CmpInst>(FirstInst)->getPredicate())
10525 // Keep track of which operand needs a phi node.
10526 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10527 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10530 // If both LHS and RHS would need a PHI, don't do this transformation,
10531 // because it would increase the number of PHIs entering the block,
10532 // which leads to higher register pressure. This is especially
10533 // bad when the PHIs are in the header of a loop.
10534 if (!LHSVal && !RHSVal)
10537 // Otherwise, this is safe to transform!
10539 Value *InLHS = FirstInst->getOperand(0);
10540 Value *InRHS = FirstInst->getOperand(1);
10541 PHINode *NewLHS = 0, *NewRHS = 0;
10543 NewLHS = PHINode::Create(LHSType,
10544 FirstInst->getOperand(0)->getName() + ".pn");
10545 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10546 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10547 InsertNewInstBefore(NewLHS, PN);
10552 NewRHS = PHINode::Create(RHSType,
10553 FirstInst->getOperand(1)->getName() + ".pn");
10554 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10555 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10556 InsertNewInstBefore(NewRHS, PN);
10560 // Add all operands to the new PHIs.
10561 if (NewLHS || NewRHS) {
10562 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10563 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10565 Value *NewInLHS = InInst->getOperand(0);
10566 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10569 Value *NewInRHS = InInst->getOperand(1);
10570 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10575 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10576 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10577 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10578 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10582 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10583 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10585 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10586 FirstInst->op_end());
10587 // This is true if all GEP bases are allocas and if all indices into them are
10589 bool AllBasePointersAreAllocas = true;
10591 // We don't want to replace this phi if the replacement would require
10592 // more than one phi, which leads to higher register pressure. This is
10593 // especially bad when the PHIs are in the header of a loop.
10594 bool NeededPhi = false;
10596 // Scan to see if all operands are the same opcode, and all have one use.
10597 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10598 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10599 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10600 GEP->getNumOperands() != FirstInst->getNumOperands())
10603 // Keep track of whether or not all GEPs are of alloca pointers.
10604 if (AllBasePointersAreAllocas &&
10605 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10606 !GEP->hasAllConstantIndices()))
10607 AllBasePointersAreAllocas = false;
10609 // Compare the operand lists.
10610 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10611 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10614 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10615 // if one of the PHIs has a constant for the index. The index may be
10616 // substantially cheaper to compute for the constants, so making it a
10617 // variable index could pessimize the path. This also handles the case
10618 // for struct indices, which must always be constant.
10619 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10620 isa<ConstantInt>(GEP->getOperand(op)))
10623 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10626 // If we already needed a PHI for an earlier operand, and another operand
10627 // also requires a PHI, we'd be introducing more PHIs than we're
10628 // eliminating, which increases register pressure on entry to the PHI's
10633 FixedOperands[op] = 0; // Needs a PHI.
10638 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10639 // bother doing this transformation. At best, this will just save a bit of
10640 // offset calculation, but all the predecessors will have to materialize the
10641 // stack address into a register anyway. We'd actually rather *clone* the
10642 // load up into the predecessors so that we have a load of a gep of an alloca,
10643 // which can usually all be folded into the load.
10644 if (AllBasePointersAreAllocas)
10647 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10648 // that is variable.
10649 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10651 bool HasAnyPHIs = false;
10652 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10653 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10654 Value *FirstOp = FirstInst->getOperand(i);
10655 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10656 FirstOp->getName()+".pn");
10657 InsertNewInstBefore(NewPN, PN);
10659 NewPN->reserveOperandSpace(e);
10660 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10661 OperandPhis[i] = NewPN;
10662 FixedOperands[i] = NewPN;
10667 // Add all operands to the new PHIs.
10669 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10670 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10671 BasicBlock *InBB = PN.getIncomingBlock(i);
10673 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10674 if (PHINode *OpPhi = OperandPhis[op])
10675 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10679 Value *Base = FixedOperands[0];
10680 return cast<GEPOperator>(FirstInst)->isInBounds() ?
10681 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
10682 FixedOperands.end()) :
10683 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10684 FixedOperands.end());
10688 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10689 /// sink the load out of the block that defines it. This means that it must be
10690 /// obvious the value of the load is not changed from the point of the load to
10691 /// the end of the block it is in.
10693 /// Finally, it is safe, but not profitable, to sink a load targetting a
10694 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
10696 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10697 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10699 for (++BBI; BBI != E; ++BBI)
10700 if (BBI->mayWriteToMemory())
10703 // Check for non-address taken alloca. If not address-taken already, it isn't
10704 // profitable to do this xform.
10705 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10706 bool isAddressTaken = false;
10707 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10709 if (isa<LoadInst>(UI)) continue;
10710 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10711 // If storing TO the alloca, then the address isn't taken.
10712 if (SI->getOperand(1) == AI) continue;
10714 isAddressTaken = true;
10718 if (!isAddressTaken && AI->isStaticAlloca())
10722 // If this load is a load from a GEP with a constant offset from an alloca,
10723 // then we don't want to sink it. In its present form, it will be
10724 // load [constant stack offset]. Sinking it will cause us to have to
10725 // materialize the stack addresses in each predecessor in a register only to
10726 // do a shared load from register in the successor.
10727 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10728 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10729 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10736 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10737 // operator and they all are only used by the PHI, PHI together their
10738 // inputs, and do the operation once, to the result of the PHI.
10739 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10740 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10742 // Scan the instruction, looking for input operations that can be folded away.
10743 // If all input operands to the phi are the same instruction (e.g. a cast from
10744 // the same type or "+42") we can pull the operation through the PHI, reducing
10745 // code size and simplifying code.
10746 Constant *ConstantOp = 0;
10747 const Type *CastSrcTy = 0;
10748 bool isVolatile = false;
10749 if (isa<CastInst>(FirstInst)) {
10750 CastSrcTy = FirstInst->getOperand(0)->getType();
10751 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10752 // Can fold binop, compare or shift here if the RHS is a constant,
10753 // otherwise call FoldPHIArgBinOpIntoPHI.
10754 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10755 if (ConstantOp == 0)
10756 return FoldPHIArgBinOpIntoPHI(PN);
10757 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10758 isVolatile = LI->isVolatile();
10759 // We can't sink the load if the loaded value could be modified between the
10760 // load and the PHI.
10761 if (LI->getParent() != PN.getIncomingBlock(0) ||
10762 !isSafeAndProfitableToSinkLoad(LI))
10765 // If the PHI is of volatile loads and the load block has multiple
10766 // successors, sinking it would remove a load of the volatile value from
10767 // the path through the other successor.
10769 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10772 } else if (isa<GetElementPtrInst>(FirstInst)) {
10773 return FoldPHIArgGEPIntoPHI(PN);
10775 return 0; // Cannot fold this operation.
10778 // Check to see if all arguments are the same operation.
10779 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10780 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10781 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10782 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10785 if (I->getOperand(0)->getType() != CastSrcTy)
10786 return 0; // Cast operation must match.
10787 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10788 // We can't sink the load if the loaded value could be modified between
10789 // the load and the PHI.
10790 if (LI->isVolatile() != isVolatile ||
10791 LI->getParent() != PN.getIncomingBlock(i) ||
10792 !isSafeAndProfitableToSinkLoad(LI))
10795 // If the PHI is of volatile loads and the load block has multiple
10796 // successors, sinking it would remove a load of the volatile value from
10797 // the path through the other successor.
10799 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10802 } else if (I->getOperand(1) != ConstantOp) {
10807 // Okay, they are all the same operation. Create a new PHI node of the
10808 // correct type, and PHI together all of the LHS's of the instructions.
10809 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10810 PN.getName()+".in");
10811 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10813 Value *InVal = FirstInst->getOperand(0);
10814 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10816 // Add all operands to the new PHI.
10817 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10818 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10819 if (NewInVal != InVal)
10821 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10826 // The new PHI unions all of the same values together. This is really
10827 // common, so we handle it intelligently here for compile-time speed.
10831 InsertNewInstBefore(NewPN, PN);
10835 // Insert and return the new operation.
10836 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10837 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10838 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10839 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10840 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10841 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
10842 PhiVal, ConstantOp);
10843 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10845 // If this was a volatile load that we are merging, make sure to loop through
10846 // and mark all the input loads as non-volatile. If we don't do this, we will
10847 // insert a new volatile load and the old ones will not be deletable.
10849 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10850 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10852 return new LoadInst(PhiVal, "", isVolatile);
10855 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10857 static bool DeadPHICycle(PHINode *PN,
10858 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10859 if (PN->use_empty()) return true;
10860 if (!PN->hasOneUse()) return false;
10862 // Remember this node, and if we find the cycle, return.
10863 if (!PotentiallyDeadPHIs.insert(PN))
10866 // Don't scan crazily complex things.
10867 if (PotentiallyDeadPHIs.size() == 16)
10870 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10871 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10876 /// PHIsEqualValue - Return true if this phi node is always equal to
10877 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10878 /// z = some value; x = phi (y, z); y = phi (x, z)
10879 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10880 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10881 // See if we already saw this PHI node.
10882 if (!ValueEqualPHIs.insert(PN))
10885 // Don't scan crazily complex things.
10886 if (ValueEqualPHIs.size() == 16)
10889 // Scan the operands to see if they are either phi nodes or are equal to
10891 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10892 Value *Op = PN->getIncomingValue(i);
10893 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10894 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10896 } else if (Op != NonPhiInVal)
10904 // PHINode simplification
10906 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10907 // If LCSSA is around, don't mess with Phi nodes
10908 if (MustPreserveLCSSA) return 0;
10910 if (Value *V = PN.hasConstantValue())
10911 return ReplaceInstUsesWith(PN, V);
10913 // If all PHI operands are the same operation, pull them through the PHI,
10914 // reducing code size.
10915 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10916 isa<Instruction>(PN.getIncomingValue(1)) &&
10917 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10918 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10919 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10920 // than themselves more than once.
10921 PN.getIncomingValue(0)->hasOneUse())
10922 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10925 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10926 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10927 // PHI)... break the cycle.
10928 if (PN.hasOneUse()) {
10929 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10930 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10931 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10932 PotentiallyDeadPHIs.insert(&PN);
10933 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10934 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10937 // If this phi has a single use, and if that use just computes a value for
10938 // the next iteration of a loop, delete the phi. This occurs with unused
10939 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10940 // common case here is good because the only other things that catch this
10941 // are induction variable analysis (sometimes) and ADCE, which is only run
10943 if (PHIUser->hasOneUse() &&
10944 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10945 PHIUser->use_back() == &PN) {
10946 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10950 // We sometimes end up with phi cycles that non-obviously end up being the
10951 // same value, for example:
10952 // z = some value; x = phi (y, z); y = phi (x, z)
10953 // where the phi nodes don't necessarily need to be in the same block. Do a
10954 // quick check to see if the PHI node only contains a single non-phi value, if
10955 // so, scan to see if the phi cycle is actually equal to that value.
10957 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10958 // Scan for the first non-phi operand.
10959 while (InValNo != NumOperandVals &&
10960 isa<PHINode>(PN.getIncomingValue(InValNo)))
10963 if (InValNo != NumOperandVals) {
10964 Value *NonPhiInVal = PN.getOperand(InValNo);
10966 // Scan the rest of the operands to see if there are any conflicts, if so
10967 // there is no need to recursively scan other phis.
10968 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10969 Value *OpVal = PN.getIncomingValue(InValNo);
10970 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10974 // If we scanned over all operands, then we have one unique value plus
10975 // phi values. Scan PHI nodes to see if they all merge in each other or
10977 if (InValNo == NumOperandVals) {
10978 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10979 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10980 return ReplaceInstUsesWith(PN, NonPhiInVal);
10987 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10988 Value *PtrOp = GEP.getOperand(0);
10989 // Eliminate 'getelementptr %P, i32 0' and 'getelementptr %P', they are noops.
10990 if (GEP.getNumOperands() == 1)
10991 return ReplaceInstUsesWith(GEP, PtrOp);
10993 if (isa<UndefValue>(GEP.getOperand(0)))
10994 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10996 bool HasZeroPointerIndex = false;
10997 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10998 HasZeroPointerIndex = C->isNullValue();
11000 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11001 return ReplaceInstUsesWith(GEP, PtrOp);
11003 // Eliminate unneeded casts for indices.
11005 bool MadeChange = false;
11006 unsigned PtrSize = TD->getPointerSizeInBits();
11008 gep_type_iterator GTI = gep_type_begin(GEP);
11009 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
11010 I != E; ++I, ++GTI) {
11011 if (!isa<SequentialType>(*GTI)) continue;
11013 // If we are using a wider index than needed for this platform, shrink it
11014 // to what we need. If narrower, sign-extend it to what we need. This
11015 // explicit cast can make subsequent optimizations more obvious.
11016 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
11017 if (OpBits == PtrSize)
11020 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
11023 if (MadeChange) return &GEP;
11026 // Combine Indices - If the source pointer to this getelementptr instruction
11027 // is a getelementptr instruction, combine the indices of the two
11028 // getelementptr instructions into a single instruction.
11030 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
11031 // Note that if our source is a gep chain itself that we wait for that
11032 // chain to be resolved before we perform this transformation. This
11033 // avoids us creating a TON of code in some cases.
11035 if (GetElementPtrInst *SrcGEP =
11036 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
11037 if (SrcGEP->getNumOperands() == 2)
11038 return 0; // Wait until our source is folded to completion.
11040 SmallVector<Value*, 8> Indices;
11042 // Find out whether the last index in the source GEP is a sequential idx.
11043 bool EndsWithSequential = false;
11044 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
11046 EndsWithSequential = !isa<StructType>(*I);
11048 // Can we combine the two pointer arithmetics offsets?
11049 if (EndsWithSequential) {
11050 // Replace: gep (gep %P, long B), long A, ...
11051 // With: T = long A+B; gep %P, T, ...
11054 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
11055 Value *GO1 = GEP.getOperand(1);
11056 if (SO1 == Constant::getNullValue(SO1->getType())) {
11058 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
11061 // If they aren't the same type, then the input hasn't been processed
11062 // by the loop above yet (which canonicalizes sequential index types to
11063 // intptr_t). Just avoid transforming this until the input has been
11065 if (SO1->getType() != GO1->getType())
11067 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11070 // Update the GEP in place if possible.
11071 if (Src->getNumOperands() == 2) {
11072 GEP.setOperand(0, Src->getOperand(0));
11073 GEP.setOperand(1, Sum);
11076 Indices.append(Src->op_begin()+1, Src->op_end()-1);
11077 Indices.push_back(Sum);
11078 Indices.append(GEP.op_begin()+2, GEP.op_end());
11079 } else if (isa<Constant>(*GEP.idx_begin()) &&
11080 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11081 Src->getNumOperands() != 1) {
11082 // Otherwise we can do the fold if the first index of the GEP is a zero
11083 Indices.append(Src->op_begin()+1, Src->op_end());
11084 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
11087 if (!Indices.empty())
11088 return (cast<GEPOperator>(&GEP)->isInBounds() &&
11089 Src->isInBounds()) ?
11090 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
11091 Indices.end(), GEP.getName()) :
11092 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
11093 Indices.end(), GEP.getName());
11096 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
11097 if (Value *X = getBitCastOperand(PtrOp)) {
11098 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
11100 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
11101 // want to change the gep until the bitcasts are eliminated.
11102 if (getBitCastOperand(X)) {
11103 Worklist.AddValue(PtrOp);
11107 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11108 // into : GEP [10 x i8]* X, i32 0, ...
11110 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11111 // into : GEP i8* X, ...
11113 // This occurs when the program declares an array extern like "int X[];"
11114 if (HasZeroPointerIndex) {
11115 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11116 const PointerType *XTy = cast<PointerType>(X->getType());
11117 if (const ArrayType *CATy =
11118 dyn_cast<ArrayType>(CPTy->getElementType())) {
11119 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11120 if (CATy->getElementType() == XTy->getElementType()) {
11121 // -> GEP i8* X, ...
11122 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11123 return cast<GEPOperator>(&GEP)->isInBounds() ?
11124 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
11126 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11130 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
11131 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11132 if (CATy->getElementType() == XATy->getElementType()) {
11133 // -> GEP [10 x i8]* X, i32 0, ...
11134 // At this point, we know that the cast source type is a pointer
11135 // to an array of the same type as the destination pointer
11136 // array. Because the array type is never stepped over (there
11137 // is a leading zero) we can fold the cast into this GEP.
11138 GEP.setOperand(0, X);
11143 } else if (GEP.getNumOperands() == 2) {
11144 // Transform things like:
11145 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11146 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11147 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11148 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11149 if (TD && isa<ArrayType>(SrcElTy) &&
11150 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11151 TD->getTypeAllocSize(ResElTy)) {
11153 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11154 Idx[1] = GEP.getOperand(1);
11155 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11156 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11157 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11158 // V and GEP are both pointer types --> BitCast
11159 return new BitCastInst(NewGEP, GEP.getType());
11162 // Transform things like:
11163 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11164 // (where tmp = 8*tmp2) into:
11165 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11167 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
11168 uint64_t ArrayEltSize =
11169 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11171 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11172 // allow either a mul, shift, or constant here.
11174 ConstantInt *Scale = 0;
11175 if (ArrayEltSize == 1) {
11176 NewIdx = GEP.getOperand(1);
11177 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
11178 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11179 NewIdx = ConstantInt::get(CI->getType(), 1);
11181 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11182 if (Inst->getOpcode() == Instruction::Shl &&
11183 isa<ConstantInt>(Inst->getOperand(1))) {
11184 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11185 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11186 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
11188 NewIdx = Inst->getOperand(0);
11189 } else if (Inst->getOpcode() == Instruction::Mul &&
11190 isa<ConstantInt>(Inst->getOperand(1))) {
11191 Scale = cast<ConstantInt>(Inst->getOperand(1));
11192 NewIdx = Inst->getOperand(0);
11196 // If the index will be to exactly the right offset with the scale taken
11197 // out, perform the transformation. Note, we don't know whether Scale is
11198 // signed or not. We'll use unsigned version of division/modulo
11199 // operation after making sure Scale doesn't have the sign bit set.
11200 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11201 Scale->getZExtValue() % ArrayEltSize == 0) {
11202 Scale = ConstantInt::get(Scale->getType(),
11203 Scale->getZExtValue() / ArrayEltSize);
11204 if (Scale->getZExtValue() != 1) {
11205 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
11207 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
11210 // Insert the new GEP instruction.
11212 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11214 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11215 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
11216 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
11217 // The NewGEP must be pointer typed, so must the old one -> BitCast
11218 return new BitCastInst(NewGEP, GEP.getType());
11224 /// See if we can simplify:
11225 /// X = bitcast A* to B*
11226 /// Y = gep X, <...constant indices...>
11227 /// into a gep of the original struct. This is important for SROA and alias
11228 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
11229 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11231 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11232 // Determine how much the GEP moves the pointer. We are guaranteed to get
11233 // a constant back from EmitGEPOffset.
11234 ConstantInt *OffsetV =
11235 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11236 int64_t Offset = OffsetV->getSExtValue();
11238 // If this GEP instruction doesn't move the pointer, just replace the GEP
11239 // with a bitcast of the real input to the dest type.
11241 // If the bitcast is of an allocation, and the allocation will be
11242 // converted to match the type of the cast, don't touch this.
11243 if (isa<AllocaInst>(BCI->getOperand(0)) ||
11244 isMalloc(BCI->getOperand(0))) {
11245 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11246 if (Instruction *I = visitBitCast(*BCI)) {
11249 BCI->getParent()->getInstList().insert(BCI, I);
11250 ReplaceInstUsesWith(*BCI, I);
11255 return new BitCastInst(BCI->getOperand(0), GEP.getType());
11258 // Otherwise, if the offset is non-zero, we need to find out if there is a
11259 // field at Offset in 'A's type. If so, we can pull the cast through the
11261 SmallVector<Value*, 8> NewIndices;
11263 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11264 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11265 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
11266 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
11267 NewIndices.end()) :
11268 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
11271 if (NGEP->getType() == GEP.getType())
11272 return ReplaceInstUsesWith(GEP, NGEP);
11273 NGEP->takeName(&GEP);
11274 return new BitCastInst(NGEP, GEP.getType());
11282 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
11283 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11284 if (AI.isArrayAllocation()) { // Check C != 1
11285 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11286 const Type *NewTy =
11287 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
11288 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11289 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
11290 New->setAlignment(AI.getAlignment());
11292 // Scan to the end of the allocation instructions, to skip over a block of
11293 // allocas if possible...also skip interleaved debug info
11295 BasicBlock::iterator It = New;
11296 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11298 // Now that I is pointing to the first non-allocation-inst in the block,
11299 // insert our getelementptr instruction...
11301 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
11305 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
11306 New->getName()+".sub", It);
11308 // Now make everything use the getelementptr instead of the original
11310 return ReplaceInstUsesWith(AI, V);
11311 } else if (isa<UndefValue>(AI.getArraySize())) {
11312 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11316 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11317 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11318 // Note that we only do this for alloca's, because malloc should allocate
11319 // and return a unique pointer, even for a zero byte allocation.
11320 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11321 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
11323 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11324 if (AI.getAlignment() == 0)
11325 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11331 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11332 Value *Op = FI.getOperand(0);
11334 // free undef -> unreachable.
11335 if (isa<UndefValue>(Op)) {
11336 // Insert a new store to null because we cannot modify the CFG here.
11337 new StoreInst(ConstantInt::getTrue(*Context),
11338 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11339 return EraseInstFromFunction(FI);
11342 // If we have 'free null' delete the instruction. This can happen in stl code
11343 // when lots of inlining happens.
11344 if (isa<ConstantPointerNull>(Op))
11345 return EraseInstFromFunction(FI);
11347 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11348 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11349 FI.setOperand(0, CI->getOperand(0));
11353 // Change free (gep X, 0,0,0,0) into free(X)
11354 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11355 if (GEPI->hasAllZeroIndices()) {
11356 Worklist.Add(GEPI);
11357 FI.setOperand(0, GEPI->getOperand(0));
11362 if (isMalloc(Op)) {
11363 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11364 if (Op->hasOneUse() && CI->hasOneUse()) {
11365 EraseInstFromFunction(FI);
11366 EraseInstFromFunction(*CI);
11367 return EraseInstFromFunction(*cast<Instruction>(Op));
11370 // Op is a call to malloc
11371 if (Op->hasOneUse()) {
11372 EraseInstFromFunction(FI);
11373 return EraseInstFromFunction(*cast<Instruction>(Op));
11381 Instruction *InstCombiner::visitFree(Instruction &FI) {
11382 Value *Op = FI.getOperand(1);
11384 // free undef -> unreachable.
11385 if (isa<UndefValue>(Op)) {
11386 // Insert a new store to null because we cannot modify the CFG here.
11387 new StoreInst(ConstantInt::getTrue(*Context),
11388 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
11389 return EraseInstFromFunction(FI);
11392 // If we have 'free null' delete the instruction. This can happen in stl code
11393 // when lots of inlining happens.
11394 if (isa<ConstantPointerNull>(Op))
11395 return EraseInstFromFunction(FI);
11397 // FIXME: Bring back free (gep X, 0,0,0,0) into free(X) transform
11399 if (isMalloc(Op)) {
11400 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
11401 if (Op->hasOneUse() && CI->hasOneUse()) {
11402 EraseInstFromFunction(FI);
11403 EraseInstFromFunction(*CI);
11404 return EraseInstFromFunction(*cast<Instruction>(Op));
11407 // Op is a call to malloc
11408 if (Op->hasOneUse()) {
11409 EraseInstFromFunction(FI);
11410 return EraseInstFromFunction(*cast<Instruction>(Op));
11418 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11419 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11420 const TargetData *TD) {
11421 User *CI = cast<User>(LI.getOperand(0));
11422 Value *CastOp = CI->getOperand(0);
11423 LLVMContext *Context = IC.getContext();
11425 const PointerType *DestTy = cast<PointerType>(CI->getType());
11426 const Type *DestPTy = DestTy->getElementType();
11427 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11429 // If the address spaces don't match, don't eliminate the cast.
11430 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11433 const Type *SrcPTy = SrcTy->getElementType();
11435 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11436 isa<VectorType>(DestPTy)) {
11437 // If the source is an array, the code below will not succeed. Check to
11438 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11440 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11441 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11442 if (ASrcTy->getNumElements() != 0) {
11444 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
11446 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11447 SrcTy = cast<PointerType>(CastOp->getType());
11448 SrcPTy = SrcTy->getElementType();
11451 if (IC.getTargetData() &&
11452 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
11453 isa<VectorType>(SrcPTy)) &&
11454 // Do not allow turning this into a load of an integer, which is then
11455 // casted to a pointer, this pessimizes pointer analysis a lot.
11456 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11457 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
11458 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
11460 // Okay, we are casting from one integer or pointer type to another of
11461 // the same size. Instead of casting the pointer before the load, cast
11462 // the result of the loaded value.
11464 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
11465 // Now cast the result of the load.
11466 return new BitCastInst(NewLoad, LI.getType());
11473 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11474 Value *Op = LI.getOperand(0);
11476 // Attempt to improve the alignment.
11478 unsigned KnownAlign =
11479 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11481 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11482 LI.getAlignment()))
11483 LI.setAlignment(KnownAlign);
11486 // load (cast X) --> cast (load X) iff safe.
11487 if (isa<CastInst>(Op))
11488 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11491 // None of the following transforms are legal for volatile loads.
11492 if (LI.isVolatile()) return 0;
11494 // Do really simple store-to-load forwarding and load CSE, to catch cases
11495 // where there are several consequtive memory accesses to the same location,
11496 // separated by a few arithmetic operations.
11497 BasicBlock::iterator BBI = &LI;
11498 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11499 return ReplaceInstUsesWith(LI, AvailableVal);
11501 // load(gep null, ...) -> unreachable
11502 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11503 const Value *GEPI0 = GEPI->getOperand(0);
11504 // TODO: Consider a target hook for valid address spaces for this xform.
11505 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
11506 // Insert a new store to null instruction before the load to indicate
11507 // that this code is not reachable. We do this instead of inserting
11508 // an unreachable instruction directly because we cannot modify the
11510 new StoreInst(UndefValue::get(LI.getType()),
11511 Constant::getNullValue(Op->getType()), &LI);
11512 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11516 // load null/undef -> unreachable
11517 // TODO: Consider a target hook for valid address spaces for this xform.
11518 if (isa<UndefValue>(Op) ||
11519 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
11520 // Insert a new store to null instruction before the load to indicate that
11521 // this code is not reachable. We do this instead of inserting an
11522 // unreachable instruction directly because we cannot modify the CFG.
11523 new StoreInst(UndefValue::get(LI.getType()),
11524 Constant::getNullValue(Op->getType()), &LI);
11525 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11528 // Instcombine load (constantexpr_cast global) -> cast (load global)
11529 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
11531 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11534 if (Op->hasOneUse()) {
11535 // Change select and PHI nodes to select values instead of addresses: this
11536 // helps alias analysis out a lot, allows many others simplifications, and
11537 // exposes redundancy in the code.
11539 // Note that we cannot do the transformation unless we know that the
11540 // introduced loads cannot trap! Something like this is valid as long as
11541 // the condition is always false: load (select bool %C, int* null, int* %G),
11542 // but it would not be valid if we transformed it to load from null
11543 // unconditionally.
11545 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11546 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11547 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11548 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11549 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
11550 SI->getOperand(1)->getName()+".val");
11551 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
11552 SI->getOperand(2)->getName()+".val");
11553 return SelectInst::Create(SI->getCondition(), V1, V2);
11556 // load (select (cond, null, P)) -> load P
11557 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11558 if (C->isNullValue()) {
11559 LI.setOperand(0, SI->getOperand(2));
11563 // load (select (cond, P, null)) -> load P
11564 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11565 if (C->isNullValue()) {
11566 LI.setOperand(0, SI->getOperand(1));
11574 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11575 /// when possible. This makes it generally easy to do alias analysis and/or
11576 /// SROA/mem2reg of the memory object.
11577 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11578 User *CI = cast<User>(SI.getOperand(1));
11579 Value *CastOp = CI->getOperand(0);
11581 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11582 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11583 if (SrcTy == 0) return 0;
11585 const Type *SrcPTy = SrcTy->getElementType();
11587 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11590 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11591 /// to its first element. This allows us to handle things like:
11592 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11593 /// on 32-bit hosts.
11594 SmallVector<Value*, 4> NewGEPIndices;
11596 // If the source is an array, the code below will not succeed. Check to
11597 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11599 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11600 // Index through pointer.
11601 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
11602 NewGEPIndices.push_back(Zero);
11605 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11606 if (!STy->getNumElements()) /* Struct can be empty {} */
11608 NewGEPIndices.push_back(Zero);
11609 SrcPTy = STy->getElementType(0);
11610 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11611 NewGEPIndices.push_back(Zero);
11612 SrcPTy = ATy->getElementType();
11618 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
11621 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11624 // If the pointers point into different address spaces or if they point to
11625 // values with different sizes, we can't do the transformation.
11626 if (!IC.getTargetData() ||
11627 SrcTy->getAddressSpace() !=
11628 cast<PointerType>(CI->getType())->getAddressSpace() ||
11629 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
11630 IC.getTargetData()->getTypeSizeInBits(DestPTy))
11633 // Okay, we are casting from one integer or pointer type to another of
11634 // the same size. Instead of casting the pointer before
11635 // the store, cast the value to be stored.
11637 Value *SIOp0 = SI.getOperand(0);
11638 Instruction::CastOps opcode = Instruction::BitCast;
11639 const Type* CastSrcTy = SIOp0->getType();
11640 const Type* CastDstTy = SrcPTy;
11641 if (isa<PointerType>(CastDstTy)) {
11642 if (CastSrcTy->isInteger())
11643 opcode = Instruction::IntToPtr;
11644 } else if (isa<IntegerType>(CastDstTy)) {
11645 if (isa<PointerType>(SIOp0->getType()))
11646 opcode = Instruction::PtrToInt;
11649 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11650 // emit a GEP to index into its first field.
11651 if (!NewGEPIndices.empty())
11652 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
11653 NewGEPIndices.end());
11655 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
11656 SIOp0->getName()+".c");
11657 return new StoreInst(NewCast, CastOp);
11660 /// equivalentAddressValues - Test if A and B will obviously have the same
11661 /// value. This includes recognizing that %t0 and %t1 will have the same
11662 /// value in code like this:
11663 /// %t0 = getelementptr \@a, 0, 3
11664 /// store i32 0, i32* %t0
11665 /// %t1 = getelementptr \@a, 0, 3
11666 /// %t2 = load i32* %t1
11668 static bool equivalentAddressValues(Value *A, Value *B) {
11669 // Test if the values are trivially equivalent.
11670 if (A == B) return true;
11672 // Test if the values come form identical arithmetic instructions.
11673 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
11674 // its only used to compare two uses within the same basic block, which
11675 // means that they'll always either have the same value or one of them
11676 // will have an undefined value.
11677 if (isa<BinaryOperator>(A) ||
11678 isa<CastInst>(A) ||
11680 isa<GetElementPtrInst>(A))
11681 if (Instruction *BI = dyn_cast<Instruction>(B))
11682 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
11685 // Otherwise they may not be equivalent.
11689 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11690 // return the llvm.dbg.declare.
11691 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11692 if (!V->hasNUses(2))
11694 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11696 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11698 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11699 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11706 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11707 Value *Val = SI.getOperand(0);
11708 Value *Ptr = SI.getOperand(1);
11710 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11711 EraseInstFromFunction(SI);
11716 // If the RHS is an alloca with a single use, zapify the store, making the
11718 // If the RHS is an alloca with a two uses, the other one being a
11719 // llvm.dbg.declare, zapify the store and the declare, making the
11720 // alloca dead. We must do this to prevent declare's from affecting
11722 if (!SI.isVolatile()) {
11723 if (Ptr->hasOneUse()) {
11724 if (isa<AllocaInst>(Ptr)) {
11725 EraseInstFromFunction(SI);
11729 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11730 if (isa<AllocaInst>(GEP->getOperand(0))) {
11731 if (GEP->getOperand(0)->hasOneUse()) {
11732 EraseInstFromFunction(SI);
11736 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11737 EraseInstFromFunction(*DI);
11738 EraseInstFromFunction(SI);
11745 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11746 EraseInstFromFunction(*DI);
11747 EraseInstFromFunction(SI);
11753 // Attempt to improve the alignment.
11755 unsigned KnownAlign =
11756 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11758 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11759 SI.getAlignment()))
11760 SI.setAlignment(KnownAlign);
11763 // Do really simple DSE, to catch cases where there are several consecutive
11764 // stores to the same location, separated by a few arithmetic operations. This
11765 // situation often occurs with bitfield accesses.
11766 BasicBlock::iterator BBI = &SI;
11767 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11770 // Don't count debug info directives, lest they affect codegen,
11771 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11772 // It is necessary for correctness to skip those that feed into a
11773 // llvm.dbg.declare, as these are not present when debugging is off.
11774 if (isa<DbgInfoIntrinsic>(BBI) ||
11775 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11780 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11781 // Prev store isn't volatile, and stores to the same location?
11782 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11783 SI.getOperand(1))) {
11786 EraseInstFromFunction(*PrevSI);
11792 // If this is a load, we have to stop. However, if the loaded value is from
11793 // the pointer we're loading and is producing the pointer we're storing,
11794 // then *this* store is dead (X = load P; store X -> P).
11795 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11796 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11797 !SI.isVolatile()) {
11798 EraseInstFromFunction(SI);
11802 // Otherwise, this is a load from some other location. Stores before it
11803 // may not be dead.
11807 // Don't skip over loads or things that can modify memory.
11808 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11813 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11815 // store X, null -> turns into 'unreachable' in SimplifyCFG
11816 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
11817 if (!isa<UndefValue>(Val)) {
11818 SI.setOperand(0, UndefValue::get(Val->getType()));
11819 if (Instruction *U = dyn_cast<Instruction>(Val))
11820 Worklist.Add(U); // Dropped a use.
11823 return 0; // Do not modify these!
11826 // store undef, Ptr -> noop
11827 if (isa<UndefValue>(Val)) {
11828 EraseInstFromFunction(SI);
11833 // If the pointer destination is a cast, see if we can fold the cast into the
11835 if (isa<CastInst>(Ptr))
11836 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11838 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11840 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11844 // If this store is the last instruction in the basic block (possibly
11845 // excepting debug info instructions and the pointer bitcasts that feed
11846 // into them), and if the block ends with an unconditional branch, try
11847 // to move it to the successor block.
11851 } while (isa<DbgInfoIntrinsic>(BBI) ||
11852 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11853 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11854 if (BI->isUnconditional())
11855 if (SimplifyStoreAtEndOfBlock(SI))
11856 return 0; // xform done!
11861 /// SimplifyStoreAtEndOfBlock - Turn things like:
11862 /// if () { *P = v1; } else { *P = v2 }
11863 /// into a phi node with a store in the successor.
11865 /// Simplify things like:
11866 /// *P = v1; if () { *P = v2; }
11867 /// into a phi node with a store in the successor.
11869 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11870 BasicBlock *StoreBB = SI.getParent();
11872 // Check to see if the successor block has exactly two incoming edges. If
11873 // so, see if the other predecessor contains a store to the same location.
11874 // if so, insert a PHI node (if needed) and move the stores down.
11875 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11877 // Determine whether Dest has exactly two predecessors and, if so, compute
11878 // the other predecessor.
11879 pred_iterator PI = pred_begin(DestBB);
11880 BasicBlock *OtherBB = 0;
11881 if (*PI != StoreBB)
11884 if (PI == pred_end(DestBB))
11887 if (*PI != StoreBB) {
11892 if (++PI != pred_end(DestBB))
11895 // Bail out if all the relevant blocks aren't distinct (this can happen,
11896 // for example, if SI is in an infinite loop)
11897 if (StoreBB == DestBB || OtherBB == DestBB)
11900 // Verify that the other block ends in a branch and is not otherwise empty.
11901 BasicBlock::iterator BBI = OtherBB->getTerminator();
11902 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11903 if (!OtherBr || BBI == OtherBB->begin())
11906 // If the other block ends in an unconditional branch, check for the 'if then
11907 // else' case. there is an instruction before the branch.
11908 StoreInst *OtherStore = 0;
11909 if (OtherBr->isUnconditional()) {
11911 // Skip over debugging info.
11912 while (isa<DbgInfoIntrinsic>(BBI) ||
11913 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11914 if (BBI==OtherBB->begin())
11918 // If this isn't a store, or isn't a store to the same location, bail out.
11919 OtherStore = dyn_cast<StoreInst>(BBI);
11920 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11923 // Otherwise, the other block ended with a conditional branch. If one of the
11924 // destinations is StoreBB, then we have the if/then case.
11925 if (OtherBr->getSuccessor(0) != StoreBB &&
11926 OtherBr->getSuccessor(1) != StoreBB)
11929 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11930 // if/then triangle. See if there is a store to the same ptr as SI that
11931 // lives in OtherBB.
11933 // Check to see if we find the matching store.
11934 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11935 if (OtherStore->getOperand(1) != SI.getOperand(1))
11939 // If we find something that may be using or overwriting the stored
11940 // value, or if we run out of instructions, we can't do the xform.
11941 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
11942 BBI == OtherBB->begin())
11946 // In order to eliminate the store in OtherBr, we have to
11947 // make sure nothing reads or overwrites the stored value in
11949 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11950 // FIXME: This should really be AA driven.
11951 if (I->mayReadFromMemory() || I->mayWriteToMemory())
11956 // Insert a PHI node now if we need it.
11957 Value *MergedVal = OtherStore->getOperand(0);
11958 if (MergedVal != SI.getOperand(0)) {
11959 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
11960 PN->reserveOperandSpace(2);
11961 PN->addIncoming(SI.getOperand(0), SI.getParent());
11962 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11963 MergedVal = InsertNewInstBefore(PN, DestBB->front());
11966 // Advance to a place where it is safe to insert the new store and
11968 BBI = DestBB->getFirstNonPHI();
11969 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11970 OtherStore->isVolatile()), *BBI);
11972 // Nuke the old stores.
11973 EraseInstFromFunction(SI);
11974 EraseInstFromFunction(*OtherStore);
11980 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11981 // Change br (not X), label True, label False to: br X, label False, True
11983 BasicBlock *TrueDest;
11984 BasicBlock *FalseDest;
11985 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11986 !isa<Constant>(X)) {
11987 // Swap Destinations and condition...
11988 BI.setCondition(X);
11989 BI.setSuccessor(0, FalseDest);
11990 BI.setSuccessor(1, TrueDest);
11994 // Cannonicalize fcmp_one -> fcmp_oeq
11995 FCmpInst::Predicate FPred; Value *Y;
11996 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11997 TrueDest, FalseDest)) &&
11998 BI.getCondition()->hasOneUse())
11999 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12000 FPred == FCmpInst::FCMP_OGE) {
12001 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12002 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12004 // Swap Destinations and condition.
12005 BI.setSuccessor(0, FalseDest);
12006 BI.setSuccessor(1, TrueDest);
12007 Worklist.Add(Cond);
12011 // Cannonicalize icmp_ne -> icmp_eq
12012 ICmpInst::Predicate IPred;
12013 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12014 TrueDest, FalseDest)) &&
12015 BI.getCondition()->hasOneUse())
12016 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12017 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12018 IPred == ICmpInst::ICMP_SGE) {
12019 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12020 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12021 // Swap Destinations and condition.
12022 BI.setSuccessor(0, FalseDest);
12023 BI.setSuccessor(1, TrueDest);
12024 Worklist.Add(Cond);
12031 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12032 Value *Cond = SI.getCondition();
12033 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12034 if (I->getOpcode() == Instruction::Add)
12035 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12036 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12037 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12039 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
12041 SI.setOperand(0, I->getOperand(0));
12049 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12050 Value *Agg = EV.getAggregateOperand();
12052 if (!EV.hasIndices())
12053 return ReplaceInstUsesWith(EV, Agg);
12055 if (Constant *C = dyn_cast<Constant>(Agg)) {
12056 if (isa<UndefValue>(C))
12057 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
12059 if (isa<ConstantAggregateZero>(C))
12060 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
12062 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12063 // Extract the element indexed by the first index out of the constant
12064 Value *V = C->getOperand(*EV.idx_begin());
12065 if (EV.getNumIndices() > 1)
12066 // Extract the remaining indices out of the constant indexed by the
12068 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12070 return ReplaceInstUsesWith(EV, V);
12072 return 0; // Can't handle other constants
12074 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12075 // We're extracting from an insertvalue instruction, compare the indices
12076 const unsigned *exti, *exte, *insi, *inse;
12077 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12078 exte = EV.idx_end(), inse = IV->idx_end();
12079 exti != exte && insi != inse;
12081 if (*insi != *exti)
12082 // The insert and extract both reference distinctly different elements.
12083 // This means the extract is not influenced by the insert, and we can
12084 // replace the aggregate operand of the extract with the aggregate
12085 // operand of the insert. i.e., replace
12086 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12087 // %E = extractvalue { i32, { i32 } } %I, 0
12089 // %E = extractvalue { i32, { i32 } } %A, 0
12090 return ExtractValueInst::Create(IV->getAggregateOperand(),
12091 EV.idx_begin(), EV.idx_end());
12093 if (exti == exte && insi == inse)
12094 // Both iterators are at the end: Index lists are identical. Replace
12095 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12096 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12098 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12099 if (exti == exte) {
12100 // The extract list is a prefix of the insert list. i.e. replace
12101 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12102 // %E = extractvalue { i32, { i32 } } %I, 1
12104 // %X = extractvalue { i32, { i32 } } %A, 1
12105 // %E = insertvalue { i32 } %X, i32 42, 0
12106 // by switching the order of the insert and extract (though the
12107 // insertvalue should be left in, since it may have other uses).
12108 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
12109 EV.idx_begin(), EV.idx_end());
12110 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12114 // The insert list is a prefix of the extract list
12115 // We can simply remove the common indices from the extract and make it
12116 // operate on the inserted value instead of the insertvalue result.
12118 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12119 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12121 // %E extractvalue { i32 } { i32 42 }, 0
12122 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12125 // Can't simplify extracts from other values. Note that nested extracts are
12126 // already simplified implicitely by the above (extract ( extract (insert) )
12127 // will be translated into extract ( insert ( extract ) ) first and then just
12128 // the value inserted, if appropriate).
12132 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12133 /// is to leave as a vector operation.
12134 static bool CheapToScalarize(Value *V, bool isConstant) {
12135 if (isa<ConstantAggregateZero>(V))
12137 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12138 if (isConstant) return true;
12139 // If all elts are the same, we can extract.
12140 Constant *Op0 = C->getOperand(0);
12141 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12142 if (C->getOperand(i) != Op0)
12146 Instruction *I = dyn_cast<Instruction>(V);
12147 if (!I) return false;
12149 // Insert element gets simplified to the inserted element or is deleted if
12150 // this is constant idx extract element and its a constant idx insertelt.
12151 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12152 isa<ConstantInt>(I->getOperand(2)))
12154 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12156 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12157 if (BO->hasOneUse() &&
12158 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12159 CheapToScalarize(BO->getOperand(1), isConstant)))
12161 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12162 if (CI->hasOneUse() &&
12163 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12164 CheapToScalarize(CI->getOperand(1), isConstant)))
12170 /// Read and decode a shufflevector mask.
12172 /// It turns undef elements into values that are larger than the number of
12173 /// elements in the input.
12174 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12175 unsigned NElts = SVI->getType()->getNumElements();
12176 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12177 return std::vector<unsigned>(NElts, 0);
12178 if (isa<UndefValue>(SVI->getOperand(2)))
12179 return std::vector<unsigned>(NElts, 2*NElts);
12181 std::vector<unsigned> Result;
12182 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12183 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12184 if (isa<UndefValue>(*i))
12185 Result.push_back(NElts*2); // undef -> 8
12187 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12191 /// FindScalarElement - Given a vector and an element number, see if the scalar
12192 /// value is already around as a register, for example if it were inserted then
12193 /// extracted from the vector.
12194 static Value *FindScalarElement(Value *V, unsigned EltNo,
12195 LLVMContext *Context) {
12196 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12197 const VectorType *PTy = cast<VectorType>(V->getType());
12198 unsigned Width = PTy->getNumElements();
12199 if (EltNo >= Width) // Out of range access.
12200 return UndefValue::get(PTy->getElementType());
12202 if (isa<UndefValue>(V))
12203 return UndefValue::get(PTy->getElementType());
12204 else if (isa<ConstantAggregateZero>(V))
12205 return Constant::getNullValue(PTy->getElementType());
12206 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12207 return CP->getOperand(EltNo);
12208 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12209 // If this is an insert to a variable element, we don't know what it is.
12210 if (!isa<ConstantInt>(III->getOperand(2)))
12212 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12214 // If this is an insert to the element we are looking for, return the
12216 if (EltNo == IIElt)
12217 return III->getOperand(1);
12219 // Otherwise, the insertelement doesn't modify the value, recurse on its
12221 return FindScalarElement(III->getOperand(0), EltNo, Context);
12222 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12223 unsigned LHSWidth =
12224 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12225 unsigned InEl = getShuffleMask(SVI)[EltNo];
12226 if (InEl < LHSWidth)
12227 return FindScalarElement(SVI->getOperand(0), InEl, Context);
12228 else if (InEl < LHSWidth*2)
12229 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12231 return UndefValue::get(PTy->getElementType());
12234 // Otherwise, we don't know.
12238 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12239 // If vector val is undef, replace extract with scalar undef.
12240 if (isa<UndefValue>(EI.getOperand(0)))
12241 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12243 // If vector val is constant 0, replace extract with scalar 0.
12244 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12245 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
12247 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12248 // If vector val is constant with all elements the same, replace EI with
12249 // that element. When the elements are not identical, we cannot replace yet
12250 // (we do that below, but only when the index is constant).
12251 Constant *op0 = C->getOperand(0);
12252 for (unsigned i = 1; i != C->getNumOperands(); ++i)
12253 if (C->getOperand(i) != op0) {
12258 return ReplaceInstUsesWith(EI, op0);
12261 // If extracting a specified index from the vector, see if we can recursively
12262 // find a previously computed scalar that was inserted into the vector.
12263 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12264 unsigned IndexVal = IdxC->getZExtValue();
12265 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
12267 // If this is extracting an invalid index, turn this into undef, to avoid
12268 // crashing the code below.
12269 if (IndexVal >= VectorWidth)
12270 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12272 // This instruction only demands the single element from the input vector.
12273 // If the input vector has a single use, simplify it based on this use
12275 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12276 APInt UndefElts(VectorWidth, 0);
12277 APInt DemandedMask(VectorWidth, 1 << IndexVal);
12278 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12279 DemandedMask, UndefElts)) {
12280 EI.setOperand(0, V);
12285 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12286 return ReplaceInstUsesWith(EI, Elt);
12288 // If the this extractelement is directly using a bitcast from a vector of
12289 // the same number of elements, see if we can find the source element from
12290 // it. In this case, we will end up needing to bitcast the scalars.
12291 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12292 if (const VectorType *VT =
12293 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12294 if (VT->getNumElements() == VectorWidth)
12295 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12296 IndexVal, Context))
12297 return new BitCastInst(Elt, EI.getType());
12301 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12302 // Push extractelement into predecessor operation if legal and
12303 // profitable to do so
12304 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12305 if (I->hasOneUse() &&
12306 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
12308 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
12309 EI.getName()+".lhs");
12311 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
12312 EI.getName()+".rhs");
12313 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12315 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12316 // Extracting the inserted element?
12317 if (IE->getOperand(2) == EI.getOperand(1))
12318 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12319 // If the inserted and extracted elements are constants, they must not
12320 // be the same value, extract from the pre-inserted value instead.
12321 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
12322 Worklist.AddValue(EI.getOperand(0));
12323 EI.setOperand(0, IE->getOperand(0));
12326 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12327 // If this is extracting an element from a shufflevector, figure out where
12328 // it came from and extract from the appropriate input element instead.
12329 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12330 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12332 unsigned LHSWidth =
12333 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12335 if (SrcIdx < LHSWidth)
12336 Src = SVI->getOperand(0);
12337 else if (SrcIdx < LHSWidth*2) {
12338 SrcIdx -= LHSWidth;
12339 Src = SVI->getOperand(1);
12341 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
12343 return ExtractElementInst::Create(Src,
12344 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
12348 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
12353 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12354 /// elements from either LHS or RHS, return the shuffle mask and true.
12355 /// Otherwise, return false.
12356 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12357 std::vector<Constant*> &Mask,
12358 LLVMContext *Context) {
12359 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12360 "Invalid CollectSingleShuffleElements");
12361 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12363 if (isa<UndefValue>(V)) {
12364 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12366 } else if (V == LHS) {
12367 for (unsigned i = 0; i != NumElts; ++i)
12368 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12370 } else if (V == RHS) {
12371 for (unsigned i = 0; i != NumElts; ++i)
12372 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
12374 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12375 // If this is an insert of an extract from some other vector, include it.
12376 Value *VecOp = IEI->getOperand(0);
12377 Value *ScalarOp = IEI->getOperand(1);
12378 Value *IdxOp = IEI->getOperand(2);
12380 if (!isa<ConstantInt>(IdxOp))
12382 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12384 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12385 // Okay, we can handle this if the vector we are insertinting into is
12386 // transitively ok.
12387 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12388 // If so, update the mask to reflect the inserted undef.
12389 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
12392 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12393 if (isa<ConstantInt>(EI->getOperand(1)) &&
12394 EI->getOperand(0)->getType() == V->getType()) {
12395 unsigned ExtractedIdx =
12396 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12398 // This must be extracting from either LHS or RHS.
12399 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12400 // Okay, we can handle this if the vector we are insertinting into is
12401 // transitively ok.
12402 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12403 // If so, update the mask to reflect the inserted value.
12404 if (EI->getOperand(0) == LHS) {
12405 Mask[InsertedIdx % NumElts] =
12406 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
12408 assert(EI->getOperand(0) == RHS);
12409 Mask[InsertedIdx % NumElts] =
12410 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
12419 // TODO: Handle shufflevector here!
12424 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12425 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12426 /// that computes V and the LHS value of the shuffle.
12427 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12428 Value *&RHS, LLVMContext *Context) {
12429 assert(isa<VectorType>(V->getType()) &&
12430 (RHS == 0 || V->getType() == RHS->getType()) &&
12431 "Invalid shuffle!");
12432 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12434 if (isa<UndefValue>(V)) {
12435 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
12437 } else if (isa<ConstantAggregateZero>(V)) {
12438 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
12440 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12441 // If this is an insert of an extract from some other vector, include it.
12442 Value *VecOp = IEI->getOperand(0);
12443 Value *ScalarOp = IEI->getOperand(1);
12444 Value *IdxOp = IEI->getOperand(2);
12446 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12447 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12448 EI->getOperand(0)->getType() == V->getType()) {
12449 unsigned ExtractedIdx =
12450 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12451 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12453 // Either the extracted from or inserted into vector must be RHSVec,
12454 // otherwise we'd end up with a shuffle of three inputs.
12455 if (EI->getOperand(0) == RHS || RHS == 0) {
12456 RHS = EI->getOperand(0);
12457 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12458 Mask[InsertedIdx % NumElts] =
12459 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
12463 if (VecOp == RHS) {
12464 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12466 // Everything but the extracted element is replaced with the RHS.
12467 for (unsigned i = 0; i != NumElts; ++i) {
12468 if (i != InsertedIdx)
12469 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
12474 // If this insertelement is a chain that comes from exactly these two
12475 // vectors, return the vector and the effective shuffle.
12476 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12478 return EI->getOperand(0);
12483 // TODO: Handle shufflevector here!
12485 // Otherwise, can't do anything fancy. Return an identity vector.
12486 for (unsigned i = 0; i != NumElts; ++i)
12487 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
12491 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12492 Value *VecOp = IE.getOperand(0);
12493 Value *ScalarOp = IE.getOperand(1);
12494 Value *IdxOp = IE.getOperand(2);
12496 // Inserting an undef or into an undefined place, remove this.
12497 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12498 ReplaceInstUsesWith(IE, VecOp);
12500 // If the inserted element was extracted from some other vector, and if the
12501 // indexes are constant, try to turn this into a shufflevector operation.
12502 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12503 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12504 EI->getOperand(0)->getType() == IE.getType()) {
12505 unsigned NumVectorElts = IE.getType()->getNumElements();
12506 unsigned ExtractedIdx =
12507 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12508 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12510 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12511 return ReplaceInstUsesWith(IE, VecOp);
12513 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12514 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12516 // If we are extracting a value from a vector, then inserting it right
12517 // back into the same place, just use the input vector.
12518 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12519 return ReplaceInstUsesWith(IE, VecOp);
12521 // If this insertelement isn't used by some other insertelement, turn it
12522 // (and any insertelements it points to), into one big shuffle.
12523 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12524 std::vector<Constant*> Mask;
12526 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12527 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12528 // We now have a shuffle of LHS, RHS, Mask.
12529 return new ShuffleVectorInst(LHS, RHS,
12530 ConstantVector::get(Mask));
12535 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12536 APInt UndefElts(VWidth, 0);
12537 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12538 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12545 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12546 Value *LHS = SVI.getOperand(0);
12547 Value *RHS = SVI.getOperand(1);
12548 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12550 bool MadeChange = false;
12552 // Undefined shuffle mask -> undefined value.
12553 if (isa<UndefValue>(SVI.getOperand(2)))
12554 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
12556 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12558 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12561 APInt UndefElts(VWidth, 0);
12562 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12563 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12564 LHS = SVI.getOperand(0);
12565 RHS = SVI.getOperand(1);
12569 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12570 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12571 if (LHS == RHS || isa<UndefValue>(LHS)) {
12572 if (isa<UndefValue>(LHS) && LHS == RHS) {
12573 // shuffle(undef,undef,mask) -> undef.
12574 return ReplaceInstUsesWith(SVI, LHS);
12577 // Remap any references to RHS to use LHS.
12578 std::vector<Constant*> Elts;
12579 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12580 if (Mask[i] >= 2*e)
12581 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12583 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12584 (Mask[i] < e && isa<UndefValue>(LHS))) {
12585 Mask[i] = 2*e; // Turn into undef.
12586 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12588 Mask[i] = Mask[i] % e; // Force to LHS.
12589 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
12593 SVI.setOperand(0, SVI.getOperand(1));
12594 SVI.setOperand(1, UndefValue::get(RHS->getType()));
12595 SVI.setOperand(2, ConstantVector::get(Elts));
12596 LHS = SVI.getOperand(0);
12597 RHS = SVI.getOperand(1);
12601 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12602 bool isLHSID = true, isRHSID = true;
12604 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12605 if (Mask[i] >= e*2) continue; // Ignore undef values.
12606 // Is this an identity shuffle of the LHS value?
12607 isLHSID &= (Mask[i] == i);
12609 // Is this an identity shuffle of the RHS value?
12610 isRHSID &= (Mask[i]-e == i);
12613 // Eliminate identity shuffles.
12614 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12615 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12617 // If the LHS is a shufflevector itself, see if we can combine it with this
12618 // one without producing an unusual shuffle. Here we are really conservative:
12619 // we are absolutely afraid of producing a shuffle mask not in the input
12620 // program, because the code gen may not be smart enough to turn a merged
12621 // shuffle into two specific shuffles: it may produce worse code. As such,
12622 // we only merge two shuffles if the result is one of the two input shuffle
12623 // masks. In this case, merging the shuffles just removes one instruction,
12624 // which we know is safe. This is good for things like turning:
12625 // (splat(splat)) -> splat.
12626 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12627 if (isa<UndefValue>(RHS)) {
12628 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12630 std::vector<unsigned> NewMask;
12631 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12632 if (Mask[i] >= 2*e)
12633 NewMask.push_back(2*e);
12635 NewMask.push_back(LHSMask[Mask[i]]);
12637 // If the result mask is equal to the src shuffle or this shuffle mask, do
12638 // the replacement.
12639 if (NewMask == LHSMask || NewMask == Mask) {
12640 unsigned LHSInNElts =
12641 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12642 std::vector<Constant*> Elts;
12643 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12644 if (NewMask[i] >= LHSInNElts*2) {
12645 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
12647 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), NewMask[i]));
12650 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12651 LHSSVI->getOperand(1),
12652 ConstantVector::get(Elts));
12657 return MadeChange ? &SVI : 0;
12663 /// TryToSinkInstruction - Try to move the specified instruction from its
12664 /// current block into the beginning of DestBlock, which can only happen if it's
12665 /// safe to move the instruction past all of the instructions between it and the
12666 /// end of its block.
12667 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12668 assert(I->hasOneUse() && "Invariants didn't hold!");
12670 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12671 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12674 // Do not sink alloca instructions out of the entry block.
12675 if (isa<AllocaInst>(I) && I->getParent() ==
12676 &DestBlock->getParent()->getEntryBlock())
12679 // We can only sink load instructions if there is nothing between the load and
12680 // the end of block that could change the value.
12681 if (I->mayReadFromMemory()) {
12682 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12684 if (Scan->mayWriteToMemory())
12688 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12690 CopyPrecedingStopPoint(I, InsertPos);
12691 I->moveBefore(InsertPos);
12697 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12698 /// all reachable code to the worklist.
12700 /// This has a couple of tricks to make the code faster and more powerful. In
12701 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12702 /// them to the worklist (this significantly speeds up instcombine on code where
12703 /// many instructions are dead or constant). Additionally, if we find a branch
12704 /// whose condition is a known constant, we only visit the reachable successors.
12706 static bool AddReachableCodeToWorklist(BasicBlock *BB,
12707 SmallPtrSet<BasicBlock*, 64> &Visited,
12709 const TargetData *TD) {
12710 bool MadeIRChange = false;
12711 SmallVector<BasicBlock*, 256> Worklist;
12712 Worklist.push_back(BB);
12714 std::vector<Instruction*> InstrsForInstCombineWorklist;
12715 InstrsForInstCombineWorklist.reserve(128);
12717 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
12719 while (!Worklist.empty()) {
12720 BB = Worklist.back();
12721 Worklist.pop_back();
12723 // We have now visited this block! If we've already been here, ignore it.
12724 if (!Visited.insert(BB)) continue;
12726 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12727 Instruction *Inst = BBI++;
12729 // DCE instruction if trivially dead.
12730 if (isInstructionTriviallyDead(Inst)) {
12732 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
12733 Inst->eraseFromParent();
12737 // ConstantProp instruction if trivially constant.
12738 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
12739 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12740 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
12742 Inst->replaceAllUsesWith(C);
12744 Inst->eraseFromParent();
12751 // See if we can constant fold its operands.
12752 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
12754 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
12755 if (CE == 0) continue;
12757 // If we already folded this constant, don't try again.
12758 if (!FoldedConstants.insert(CE))
12762 ConstantFoldConstantExpression(CE, BB->getContext(), TD);
12763 if (NewC && NewC != CE) {
12765 MadeIRChange = true;
12771 InstrsForInstCombineWorklist.push_back(Inst);
12774 // Recursively visit successors. If this is a branch or switch on a
12775 // constant, only visit the reachable successor.
12776 TerminatorInst *TI = BB->getTerminator();
12777 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12778 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12779 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12780 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12781 Worklist.push_back(ReachableBB);
12784 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12785 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12786 // See if this is an explicit destination.
12787 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12788 if (SI->getCaseValue(i) == Cond) {
12789 BasicBlock *ReachableBB = SI->getSuccessor(i);
12790 Worklist.push_back(ReachableBB);
12794 // Otherwise it is the default destination.
12795 Worklist.push_back(SI->getSuccessor(0));
12800 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12801 Worklist.push_back(TI->getSuccessor(i));
12804 // Once we've found all of the instructions to add to instcombine's worklist,
12805 // add them in reverse order. This way instcombine will visit from the top
12806 // of the function down. This jives well with the way that it adds all uses
12807 // of instructions to the worklist after doing a transformation, thus avoiding
12808 // some N^2 behavior in pathological cases.
12809 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
12810 InstrsForInstCombineWorklist.size());
12812 return MadeIRChange;
12815 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12816 MadeIRChange = false;
12818 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12819 << F.getNameStr() << "\n");
12822 // Do a depth-first traversal of the function, populate the worklist with
12823 // the reachable instructions. Ignore blocks that are not reachable. Keep
12824 // track of which blocks we visit.
12825 SmallPtrSet<BasicBlock*, 64> Visited;
12826 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12828 // Do a quick scan over the function. If we find any blocks that are
12829 // unreachable, remove any instructions inside of them. This prevents
12830 // the instcombine code from having to deal with some bad special cases.
12831 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12832 if (!Visited.count(BB)) {
12833 Instruction *Term = BB->getTerminator();
12834 while (Term != BB->begin()) { // Remove instrs bottom-up
12835 BasicBlock::iterator I = Term; --I;
12837 DEBUG(errs() << "IC: DCE: " << *I << '\n');
12838 // A debug intrinsic shouldn't force another iteration if we weren't
12839 // going to do one without it.
12840 if (!isa<DbgInfoIntrinsic>(I)) {
12842 MadeIRChange = true;
12845 // If I is not void type then replaceAllUsesWith undef.
12846 // This allows ValueHandlers and custom metadata to adjust itself.
12847 if (!I->getType()->isVoidTy())
12848 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12849 I->eraseFromParent();
12854 while (!Worklist.isEmpty()) {
12855 Instruction *I = Worklist.RemoveOne();
12856 if (I == 0) continue; // skip null values.
12858 // Check to see if we can DCE the instruction.
12859 if (isInstructionTriviallyDead(I)) {
12860 DEBUG(errs() << "IC: DCE: " << *I << '\n');
12861 EraseInstFromFunction(*I);
12863 MadeIRChange = true;
12867 // Instruction isn't dead, see if we can constant propagate it.
12868 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
12869 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
12870 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
12872 // Add operands to the worklist.
12873 ReplaceInstUsesWith(*I, C);
12875 EraseInstFromFunction(*I);
12876 MadeIRChange = true;
12880 // See if we can trivially sink this instruction to a successor basic block.
12881 if (I->hasOneUse()) {
12882 BasicBlock *BB = I->getParent();
12883 Instruction *UserInst = cast<Instruction>(I->use_back());
12884 BasicBlock *UserParent;
12886 // Get the block the use occurs in.
12887 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
12888 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
12890 UserParent = UserInst->getParent();
12892 if (UserParent != BB) {
12893 bool UserIsSuccessor = false;
12894 // See if the user is one of our successors.
12895 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12896 if (*SI == UserParent) {
12897 UserIsSuccessor = true;
12901 // If the user is one of our immediate successors, and if that successor
12902 // only has us as a predecessors (we'd have to split the critical edge
12903 // otherwise), we can keep going.
12904 if (UserIsSuccessor && UserParent->getSinglePredecessor())
12905 // Okay, the CFG is simple enough, try to sink this instruction.
12906 MadeIRChange |= TryToSinkInstruction(I, UserParent);
12910 // Now that we have an instruction, try combining it to simplify it.
12911 Builder->SetInsertPoint(I->getParent(), I);
12916 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
12917 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
12919 if (Instruction *Result = visit(*I)) {
12921 // Should we replace the old instruction with a new one?
12923 DEBUG(errs() << "IC: Old = " << *I << '\n'
12924 << " New = " << *Result << '\n');
12926 // Everything uses the new instruction now.
12927 I->replaceAllUsesWith(Result);
12929 // Push the new instruction and any users onto the worklist.
12930 Worklist.Add(Result);
12931 Worklist.AddUsersToWorkList(*Result);
12933 // Move the name to the new instruction first.
12934 Result->takeName(I);
12936 // Insert the new instruction into the basic block...
12937 BasicBlock *InstParent = I->getParent();
12938 BasicBlock::iterator InsertPos = I;
12940 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12941 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12944 InstParent->getInstList().insert(InsertPos, Result);
12946 EraseInstFromFunction(*I);
12949 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
12950 << " New = " << *I << '\n');
12953 // If the instruction was modified, it's possible that it is now dead.
12954 // if so, remove it.
12955 if (isInstructionTriviallyDead(I)) {
12956 EraseInstFromFunction(*I);
12959 Worklist.AddUsersToWorkList(*I);
12962 MadeIRChange = true;
12967 return MadeIRChange;
12971 bool InstCombiner::runOnFunction(Function &F) {
12972 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12973 Context = &F.getContext();
12974 TD = getAnalysisIfAvailable<TargetData>();
12977 /// Builder - This is an IRBuilder that automatically inserts new
12978 /// instructions into the worklist when they are created.
12979 IRBuilder<true, TargetFolder, InstCombineIRInserter>
12980 TheBuilder(F.getContext(), TargetFolder(TD, F.getContext()),
12981 InstCombineIRInserter(Worklist));
12982 Builder = &TheBuilder;
12984 bool EverMadeChange = false;
12986 // Iterate while there is work to do.
12987 unsigned Iteration = 0;
12988 while (DoOneIteration(F, Iteration++))
12989 EverMadeChange = true;
12992 return EverMadeChange;
12995 FunctionPass *llvm::createInstructionCombiningPass() {
12996 return new InstCombiner();