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/Analysis/ConstantFolding.h"
44 #include "llvm/Analysis/ValueTracking.h"
45 #include "llvm/Target/TargetData.h"
46 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
47 #include "llvm/Transforms/Utils/Local.h"
48 #include "llvm/Support/CallSite.h"
49 #include "llvm/Support/ConstantRange.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/GetElementPtrTypeIterator.h"
52 #include "llvm/Support/InstVisitor.h"
53 #include "llvm/Support/MathExtras.h"
54 #include "llvm/Support/PatternMatch.h"
55 #include "llvm/Support/Compiler.h"
56 #include "llvm/ADT/DenseMap.h"
57 #include "llvm/ADT/SmallVector.h"
58 #include "llvm/ADT/SmallPtrSet.h"
59 #include "llvm/ADT/Statistic.h"
60 #include "llvm/ADT/STLExtras.h"
65 using namespace llvm::PatternMatch;
67 STATISTIC(NumCombined , "Number of insts combined");
68 STATISTIC(NumConstProp, "Number of constant folds");
69 STATISTIC(NumDeadInst , "Number of dead inst eliminated");
70 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
71 STATISTIC(NumSunkInst , "Number of instructions sunk");
74 class VISIBILITY_HIDDEN InstCombiner
75 : public FunctionPass,
76 public InstVisitor<InstCombiner, Instruction*> {
77 // Worklist of all of the instructions that need to be simplified.
78 SmallVector<Instruction*, 256> Worklist;
79 DenseMap<Instruction*, unsigned> WorklistMap;
81 bool MustPreserveLCSSA;
83 static char ID; // Pass identification, replacement for typeid
84 InstCombiner() : FunctionPass(&ID) {}
86 LLVMContext *getContext() { return Context; }
88 /// AddToWorkList - Add the specified instruction to the worklist if it
89 /// isn't already in it.
90 void AddToWorkList(Instruction *I) {
91 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
92 Worklist.push_back(I);
95 // RemoveFromWorkList - remove I from the worklist if it exists.
96 void RemoveFromWorkList(Instruction *I) {
97 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
98 if (It == WorklistMap.end()) return; // Not in worklist.
100 // Don't bother moving everything down, just null out the slot.
101 Worklist[It->second] = 0;
103 WorklistMap.erase(It);
106 Instruction *RemoveOneFromWorkList() {
107 Instruction *I = Worklist.back();
109 WorklistMap.erase(I);
114 /// AddUsersToWorkList - When an instruction is simplified, add all users of
115 /// the instruction to the work lists because they might get more simplified
118 void AddUsersToWorkList(Value &I) {
119 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
121 AddToWorkList(cast<Instruction>(*UI));
124 /// AddUsesToWorkList - When an instruction is simplified, add operands to
125 /// the work lists because they might get more simplified now.
127 void AddUsesToWorkList(Instruction &I) {
128 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
129 if (Instruction *Op = dyn_cast<Instruction>(*i))
133 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
134 /// dead. Add all of its operands to the worklist, turning them into
135 /// undef's to reduce the number of uses of those instructions.
137 /// Return the specified operand before it is turned into an undef.
139 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
140 Value *R = I.getOperand(op);
142 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
143 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
145 // Set the operand to undef to drop the use.
146 *i = Context->getUndef(Op->getType());
153 virtual bool runOnFunction(Function &F);
155 bool DoOneIteration(Function &F, unsigned ItNum);
157 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
158 AU.addRequired<TargetData>();
159 AU.addPreservedID(LCSSAID);
160 AU.setPreservesCFG();
163 TargetData &getTargetData() const { return *TD; }
165 // Visitation implementation - Implement instruction combining for different
166 // instruction types. The semantics are as follows:
168 // null - No change was made
169 // I - Change was made, I is still valid, I may be dead though
170 // otherwise - Change was made, replace I with returned instruction
172 Instruction *visitAdd(BinaryOperator &I);
173 Instruction *visitFAdd(BinaryOperator &I);
174 Instruction *visitSub(BinaryOperator &I);
175 Instruction *visitFSub(BinaryOperator &I);
176 Instruction *visitMul(BinaryOperator &I);
177 Instruction *visitFMul(BinaryOperator &I);
178 Instruction *visitURem(BinaryOperator &I);
179 Instruction *visitSRem(BinaryOperator &I);
180 Instruction *visitFRem(BinaryOperator &I);
181 bool SimplifyDivRemOfSelect(BinaryOperator &I);
182 Instruction *commonRemTransforms(BinaryOperator &I);
183 Instruction *commonIRemTransforms(BinaryOperator &I);
184 Instruction *commonDivTransforms(BinaryOperator &I);
185 Instruction *commonIDivTransforms(BinaryOperator &I);
186 Instruction *visitUDiv(BinaryOperator &I);
187 Instruction *visitSDiv(BinaryOperator &I);
188 Instruction *visitFDiv(BinaryOperator &I);
189 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
190 Instruction *visitAnd(BinaryOperator &I);
191 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
192 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
193 Value *A, Value *B, Value *C);
194 Instruction *visitOr (BinaryOperator &I);
195 Instruction *visitXor(BinaryOperator &I);
196 Instruction *visitShl(BinaryOperator &I);
197 Instruction *visitAShr(BinaryOperator &I);
198 Instruction *visitLShr(BinaryOperator &I);
199 Instruction *commonShiftTransforms(BinaryOperator &I);
200 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
202 Instruction *visitFCmpInst(FCmpInst &I);
203 Instruction *visitICmpInst(ICmpInst &I);
204 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
205 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
208 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
209 ConstantInt *DivRHS);
211 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
212 ICmpInst::Predicate Cond, Instruction &I);
213 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
215 Instruction *commonCastTransforms(CastInst &CI);
216 Instruction *commonIntCastTransforms(CastInst &CI);
217 Instruction *commonPointerCastTransforms(CastInst &CI);
218 Instruction *visitTrunc(TruncInst &CI);
219 Instruction *visitZExt(ZExtInst &CI);
220 Instruction *visitSExt(SExtInst &CI);
221 Instruction *visitFPTrunc(FPTruncInst &CI);
222 Instruction *visitFPExt(CastInst &CI);
223 Instruction *visitFPToUI(FPToUIInst &FI);
224 Instruction *visitFPToSI(FPToSIInst &FI);
225 Instruction *visitUIToFP(CastInst &CI);
226 Instruction *visitSIToFP(CastInst &CI);
227 Instruction *visitPtrToInt(PtrToIntInst &CI);
228 Instruction *visitIntToPtr(IntToPtrInst &CI);
229 Instruction *visitBitCast(BitCastInst &CI);
230 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
232 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
233 Instruction *visitSelectInst(SelectInst &SI);
234 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
235 Instruction *visitCallInst(CallInst &CI);
236 Instruction *visitInvokeInst(InvokeInst &II);
237 Instruction *visitPHINode(PHINode &PN);
238 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
239 Instruction *visitAllocationInst(AllocationInst &AI);
240 Instruction *visitFreeInst(FreeInst &FI);
241 Instruction *visitLoadInst(LoadInst &LI);
242 Instruction *visitStoreInst(StoreInst &SI);
243 Instruction *visitBranchInst(BranchInst &BI);
244 Instruction *visitSwitchInst(SwitchInst &SI);
245 Instruction *visitInsertElementInst(InsertElementInst &IE);
246 Instruction *visitExtractElementInst(ExtractElementInst &EI);
247 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
248 Instruction *visitExtractValueInst(ExtractValueInst &EV);
250 // visitInstruction - Specify what to return for unhandled instructions...
251 Instruction *visitInstruction(Instruction &I) { return 0; }
254 Instruction *visitCallSite(CallSite CS);
255 bool transformConstExprCastCall(CallSite CS);
256 Instruction *transformCallThroughTrampoline(CallSite CS);
257 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
258 bool DoXform = true);
259 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
260 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
264 // InsertNewInstBefore - insert an instruction New before instruction Old
265 // in the program. Add the new instruction to the worklist.
267 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
268 assert(New && New->getParent() == 0 &&
269 "New instruction already inserted into a basic block!");
270 BasicBlock *BB = Old.getParent();
271 BB->getInstList().insert(&Old, New); // Insert inst
276 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
277 /// This also adds the cast to the worklist. Finally, this returns the
279 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
281 if (V->getType() == Ty) return V;
283 if (Constant *CV = dyn_cast<Constant>(V))
284 return Context->getConstantExprCast(opc, CV, Ty);
286 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
291 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
292 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
296 // ReplaceInstUsesWith - This method is to be used when an instruction is
297 // found to be dead, replacable with another preexisting expression. Here
298 // we add all uses of I to the worklist, replace all uses of I with the new
299 // value, then return I, so that the inst combiner will know that I was
302 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
303 AddUsersToWorkList(I); // Add all modified instrs to worklist
305 I.replaceAllUsesWith(V);
308 // If we are replacing the instruction with itself, this must be in a
309 // segment of unreachable code, so just clobber the instruction.
310 I.replaceAllUsesWith(Context->getUndef(I.getType()));
315 // EraseInstFromFunction - When dealing with an instruction that has side
316 // effects or produces a void value, we can't rely on DCE to delete the
317 // instruction. Instead, visit methods should return the value returned by
319 Instruction *EraseInstFromFunction(Instruction &I) {
320 assert(I.use_empty() && "Cannot erase instruction that is used!");
321 AddUsesToWorkList(I);
322 RemoveFromWorkList(&I);
324 return 0; // Don't do anything with FI
327 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
328 APInt &KnownOne, unsigned Depth = 0) const {
329 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
332 bool MaskedValueIsZero(Value *V, const APInt &Mask,
333 unsigned Depth = 0) const {
334 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
336 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
337 return llvm::ComputeNumSignBits(Op, TD, Depth);
342 /// SimplifyCommutative - This performs a few simplifications for
343 /// commutative operators.
344 bool SimplifyCommutative(BinaryOperator &I);
346 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
347 /// most-complex to least-complex order.
348 bool SimplifyCompare(CmpInst &I);
350 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
351 /// based on the demanded bits.
352 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
353 APInt& KnownZero, APInt& KnownOne,
355 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
356 APInt& KnownZero, APInt& KnownOne,
359 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
360 /// SimplifyDemandedBits knows about. See if the instruction has any
361 /// properties that allow us to simplify its operands.
362 bool SimplifyDemandedInstructionBits(Instruction &Inst);
364 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
365 APInt& UndefElts, unsigned Depth = 0);
367 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
368 // PHI node as operand #0, see if we can fold the instruction into the PHI
369 // (which is only possible if all operands to the PHI are constants).
370 Instruction *FoldOpIntoPhi(Instruction &I);
372 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
373 // operator and they all are only used by the PHI, PHI together their
374 // inputs, and do the operation once, to the result of the PHI.
375 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
376 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
377 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
380 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
381 ConstantInt *AndRHS, BinaryOperator &TheAnd);
383 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
384 bool isSub, Instruction &I);
385 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
386 bool isSigned, bool Inside, Instruction &IB);
387 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
388 Instruction *MatchBSwap(BinaryOperator &I);
389 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
390 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
391 Instruction *SimplifyMemSet(MemSetInst *MI);
394 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
396 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
397 unsigned CastOpc, int &NumCastsRemoved);
398 unsigned GetOrEnforceKnownAlignment(Value *V,
399 unsigned PrefAlign = 0);
404 char InstCombiner::ID = 0;
405 static RegisterPass<InstCombiner>
406 X("instcombine", "Combine redundant instructions");
408 // getComplexity: Assign a complexity or rank value to LLVM Values...
409 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
410 static unsigned getComplexity(Value *V) {
411 if (isa<Instruction>(V)) {
412 if (BinaryOperator::isNeg(V) || BinaryOperator::isFNeg(V) ||
413 BinaryOperator::isNot(V))
417 if (isa<Argument>(V)) return 3;
418 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
421 // isOnlyUse - Return true if this instruction will be deleted if we stop using
423 static bool isOnlyUse(Value *V) {
424 return V->hasOneUse() || isa<Constant>(V);
427 // getPromotedType - Return the specified type promoted as it would be to pass
428 // though a va_arg area...
429 static const Type *getPromotedType(const Type *Ty) {
430 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
431 if (ITy->getBitWidth() < 32)
432 return Type::Int32Ty;
437 /// getBitCastOperand - If the specified operand is a CastInst, a constant
438 /// expression bitcast, or a GetElementPtrInst with all zero indices, return the
439 /// operand value, otherwise return null.
440 static Value *getBitCastOperand(Value *V) {
441 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
443 return I->getOperand(0);
444 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
445 // GetElementPtrInst?
446 if (GEP->hasAllZeroIndices())
447 return GEP->getOperand(0);
448 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
449 if (CE->getOpcode() == Instruction::BitCast)
450 // BitCast ConstantExp?
451 return CE->getOperand(0);
452 else if (CE->getOpcode() == Instruction::GetElementPtr) {
453 // GetElementPtr ConstantExp?
454 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
456 ConstantInt *CI = dyn_cast<ConstantInt>(I);
457 if (!CI || !CI->isZero())
458 // Any non-zero indices? Not cast-like.
461 // All-zero indices? This is just like casting.
462 return CE->getOperand(0);
468 /// This function is a wrapper around CastInst::isEliminableCastPair. It
469 /// simply extracts arguments and returns what that function returns.
470 static Instruction::CastOps
471 isEliminableCastPair(
472 const CastInst *CI, ///< The first cast instruction
473 unsigned opcode, ///< The opcode of the second cast instruction
474 const Type *DstTy, ///< The target type for the second cast instruction
475 TargetData *TD ///< The target data for pointer size
478 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
479 const Type *MidTy = CI->getType(); // B from above
481 // Get the opcodes of the two Cast instructions
482 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
483 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
485 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
486 DstTy, TD->getIntPtrType());
488 // We don't want to form an inttoptr or ptrtoint that converts to an integer
489 // type that differs from the pointer size.
490 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
491 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
494 return Instruction::CastOps(Res);
497 /// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
498 /// in any code being generated. It does not require codegen if V is simple
499 /// enough or if the cast can be folded into other casts.
500 static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
501 const Type *Ty, TargetData *TD) {
502 if (V->getType() == Ty || isa<Constant>(V)) return false;
504 // If this is another cast that can be eliminated, it isn't codegen either.
505 if (const CastInst *CI = dyn_cast<CastInst>(V))
506 if (isEliminableCastPair(CI, opcode, Ty, TD))
511 // SimplifyCommutative - This performs a few simplifications for commutative
514 // 1. Order operands such that they are listed from right (least complex) to
515 // left (most complex). This puts constants before unary operators before
518 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
519 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
521 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
522 bool Changed = false;
523 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
524 Changed = !I.swapOperands();
526 if (!I.isAssociative()) return Changed;
527 Instruction::BinaryOps Opcode = I.getOpcode();
528 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
529 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
530 if (isa<Constant>(I.getOperand(1))) {
531 Constant *Folded = Context->getConstantExpr(I.getOpcode(),
532 cast<Constant>(I.getOperand(1)),
533 cast<Constant>(Op->getOperand(1)));
534 I.setOperand(0, Op->getOperand(0));
535 I.setOperand(1, Folded);
537 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
538 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
539 isOnlyUse(Op) && isOnlyUse(Op1)) {
540 Constant *C1 = cast<Constant>(Op->getOperand(1));
541 Constant *C2 = cast<Constant>(Op1->getOperand(1));
543 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
544 Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
545 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
549 I.setOperand(0, New);
550 I.setOperand(1, Folded);
557 /// SimplifyCompare - For a CmpInst this function just orders the operands
558 /// so that theyare listed from right (least complex) to left (most complex).
559 /// This puts constants before unary operators before binary operators.
560 bool InstCombiner::SimplifyCompare(CmpInst &I) {
561 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
564 // Compare instructions are not associative so there's nothing else we can do.
568 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
569 // if the LHS is a constant zero (which is the 'negate' form).
571 static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
572 if (BinaryOperator::isNeg(V))
573 return BinaryOperator::getNegArgument(V);
575 // Constants can be considered to be negated values if they can be folded.
576 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
577 return Context->getConstantExprNeg(C);
579 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
580 if (C->getType()->getElementType()->isInteger())
581 return Context->getConstantExprNeg(C);
586 // dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
587 // instruction if the LHS is a constant negative zero (which is the 'negate'
590 static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
591 if (BinaryOperator::isFNeg(V))
592 return BinaryOperator::getFNegArgument(V);
594 // Constants can be considered to be negated values if they can be folded.
595 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
596 return Context->getConstantExprFNeg(C);
598 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
599 if (C->getType()->getElementType()->isFloatingPoint())
600 return Context->getConstantExprFNeg(C);
605 static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
606 if (BinaryOperator::isNot(V))
607 return BinaryOperator::getNotArgument(V);
609 // Constants can be considered to be not'ed values...
610 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
611 return Context->getConstantInt(~C->getValue());
615 // dyn_castFoldableMul - If this value is a multiply that can be folded into
616 // other computations (because it has a constant operand), return the
617 // non-constant operand of the multiply, and set CST to point to the multiplier.
618 // Otherwise, return null.
620 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
621 LLVMContext *Context) {
622 if (V->hasOneUse() && V->getType()->isInteger())
623 if (Instruction *I = dyn_cast<Instruction>(V)) {
624 if (I->getOpcode() == Instruction::Mul)
625 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
626 return I->getOperand(0);
627 if (I->getOpcode() == Instruction::Shl)
628 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
629 // The multiplier is really 1 << CST.
630 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
631 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
632 CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
633 return I->getOperand(0);
639 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
640 /// expression, return it.
641 static User *dyn_castGetElementPtr(Value *V) {
642 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
643 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
644 if (CE->getOpcode() == Instruction::GetElementPtr)
645 return cast<User>(V);
649 /// getOpcode - If this is an Instruction or a ConstantExpr, return the
650 /// opcode value. Otherwise return UserOp1.
651 static unsigned getOpcode(const Value *V) {
652 if (const Instruction *I = dyn_cast<Instruction>(V))
653 return I->getOpcode();
654 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
655 return CE->getOpcode();
656 // Use UserOp1 to mean there's no opcode.
657 return Instruction::UserOp1;
660 /// AddOne - Add one to a ConstantInt
661 static Constant *AddOne(Constant *C, LLVMContext *Context) {
662 return Context->getConstantExprAdd(C,
663 Context->getConstantInt(C->getType(), 1));
665 /// SubOne - Subtract one from a ConstantInt
666 static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
667 return Context->getConstantExprSub(C,
668 Context->getConstantInt(C->getType(), 1));
670 /// MultiplyOverflows - True if the multiply can not be expressed in an int
672 static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
673 LLVMContext *Context) {
674 uint32_t W = C1->getBitWidth();
675 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
684 APInt MulExt = LHSExt * RHSExt;
687 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
688 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
689 return MulExt.slt(Min) || MulExt.sgt(Max);
691 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
695 /// ShrinkDemandedConstant - Check to see if the specified operand of the
696 /// specified instruction is a constant integer. If so, check to see if there
697 /// are any bits set in the constant that are not demanded. If so, shrink the
698 /// constant and return true.
699 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
700 APInt Demanded, LLVMContext *Context) {
701 assert(I && "No instruction?");
702 assert(OpNo < I->getNumOperands() && "Operand index too large");
704 // If the operand is not a constant integer, nothing to do.
705 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
706 if (!OpC) return false;
708 // If there are no bits set that aren't demanded, nothing to do.
709 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
710 if ((~Demanded & OpC->getValue()) == 0)
713 // This instruction is producing bits that are not demanded. Shrink the RHS.
714 Demanded &= OpC->getValue();
715 I->setOperand(OpNo, Context->getConstantInt(Demanded));
719 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
720 // set of known zero and one bits, compute the maximum and minimum values that
721 // could have the specified known zero and known one bits, returning them in
723 static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
724 const APInt& KnownOne,
725 APInt& Min, APInt& Max) {
726 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
727 KnownZero.getBitWidth() == Min.getBitWidth() &&
728 KnownZero.getBitWidth() == Max.getBitWidth() &&
729 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
730 APInt UnknownBits = ~(KnownZero|KnownOne);
732 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
733 // bit if it is unknown.
735 Max = KnownOne|UnknownBits;
737 if (UnknownBits.isNegative()) { // Sign bit is unknown
738 Min.set(Min.getBitWidth()-1);
739 Max.clear(Max.getBitWidth()-1);
743 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
744 // a set of known zero and one bits, compute the maximum and minimum values that
745 // could have the specified known zero and known one bits, returning them in
747 static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
748 const APInt &KnownOne,
749 APInt &Min, APInt &Max) {
750 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
751 KnownZero.getBitWidth() == Min.getBitWidth() &&
752 KnownZero.getBitWidth() == Max.getBitWidth() &&
753 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
754 APInt UnknownBits = ~(KnownZero|KnownOne);
756 // The minimum value is when the unknown bits are all zeros.
758 // The maximum value is when the unknown bits are all ones.
759 Max = KnownOne|UnknownBits;
762 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
763 /// SimplifyDemandedBits knows about. See if the instruction has any
764 /// properties that allow us to simplify its operands.
765 bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
766 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
767 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
768 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
770 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
771 KnownZero, KnownOne, 0);
772 if (V == 0) return false;
773 if (V == &Inst) return true;
774 ReplaceInstUsesWith(Inst, V);
778 /// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
779 /// specified instruction operand if possible, updating it in place. It returns
780 /// true if it made any change and false otherwise.
781 bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
782 APInt &KnownZero, APInt &KnownOne,
784 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
785 KnownZero, KnownOne, Depth);
786 if (NewVal == 0) return false;
792 /// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
793 /// value based on the demanded bits. When this function is called, it is known
794 /// that only the bits set in DemandedMask of the result of V are ever used
795 /// downstream. Consequently, depending on the mask and V, it may be possible
796 /// to replace V with a constant or one of its operands. In such cases, this
797 /// function does the replacement and returns true. In all other cases, it
798 /// returns false after analyzing the expression and setting KnownOne and known
799 /// to be one in the expression. KnownZero contains all the bits that are known
800 /// to be zero in the expression. These are provided to potentially allow the
801 /// caller (which might recursively be SimplifyDemandedBits itself) to simplify
802 /// the expression. KnownOne and KnownZero always follow the invariant that
803 /// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
804 /// the bits in KnownOne and KnownZero may only be accurate for those bits set
805 /// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
806 /// and KnownOne must all be the same.
808 /// This returns null if it did not change anything and it permits no
809 /// simplification. This returns V itself if it did some simplification of V's
810 /// operands based on the information about what bits are demanded. This returns
811 /// some other non-null value if it found out that V is equal to another value
812 /// in the context where the specified bits are demanded, but not for all users.
813 Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
814 APInt &KnownZero, APInt &KnownOne,
816 assert(V != 0 && "Null pointer of Value???");
817 assert(Depth <= 6 && "Limit Search Depth");
818 uint32_t BitWidth = DemandedMask.getBitWidth();
819 const Type *VTy = V->getType();
820 assert((TD || !isa<PointerType>(VTy)) &&
821 "SimplifyDemandedBits needs to know bit widths!");
822 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
823 (!VTy->isIntOrIntVector() ||
824 VTy->getScalarSizeInBits() == BitWidth) &&
825 KnownZero.getBitWidth() == BitWidth &&
826 KnownOne.getBitWidth() == BitWidth &&
827 "Value *V, DemandedMask, KnownZero and KnownOne "
828 "must have same BitWidth");
829 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
830 // We know all of the bits for a constant!
831 KnownOne = CI->getValue() & DemandedMask;
832 KnownZero = ~KnownOne & DemandedMask;
835 if (isa<ConstantPointerNull>(V)) {
836 // We know all of the bits for a constant!
838 KnownZero = DemandedMask;
844 if (DemandedMask == 0) { // Not demanding any bits from V.
845 if (isa<UndefValue>(V))
847 return Context->getUndef(VTy);
850 if (Depth == 6) // Limit search depth.
853 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
854 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
856 Instruction *I = dyn_cast<Instruction>(V);
858 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
859 return 0; // Only analyze instructions.
862 // If there are multiple uses of this value and we aren't at the root, then
863 // we can't do any simplifications of the operands, because DemandedMask
864 // only reflects the bits demanded by *one* of the users.
865 if (Depth != 0 && !I->hasOneUse()) {
866 // Despite the fact that we can't simplify this instruction in all User's
867 // context, we can at least compute the knownzero/knownone bits, and we can
868 // do simplifications that apply to *just* the one user if we know that
869 // this instruction has a simpler value in that context.
870 if (I->getOpcode() == Instruction::And) {
871 // If either the LHS or the RHS are Zero, the result is zero.
872 ComputeMaskedBits(I->getOperand(1), DemandedMask,
873 RHSKnownZero, RHSKnownOne, Depth+1);
874 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
875 LHSKnownZero, LHSKnownOne, Depth+1);
877 // If all of the demanded bits are known 1 on one side, return the other.
878 // These bits cannot contribute to the result of the 'and' in this
880 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
881 (DemandedMask & ~LHSKnownZero))
882 return I->getOperand(0);
883 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
884 (DemandedMask & ~RHSKnownZero))
885 return I->getOperand(1);
887 // If all of the demanded bits in the inputs are known zeros, return zero.
888 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
889 return Context->getNullValue(VTy);
891 } else if (I->getOpcode() == Instruction::Or) {
892 // We can simplify (X|Y) -> X or Y in the user's context if we know that
893 // only bits from X or Y are demanded.
895 // If either the LHS or the RHS are One, the result is One.
896 ComputeMaskedBits(I->getOperand(1), DemandedMask,
897 RHSKnownZero, RHSKnownOne, Depth+1);
898 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
899 LHSKnownZero, LHSKnownOne, Depth+1);
901 // If all of the demanded bits are known zero on one side, return the
902 // other. These bits cannot contribute to the result of the 'or' in this
904 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
905 (DemandedMask & ~LHSKnownOne))
906 return I->getOperand(0);
907 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
908 (DemandedMask & ~RHSKnownOne))
909 return I->getOperand(1);
911 // If all of the potentially set bits on one side are known to be set on
912 // the other side, just use the 'other' side.
913 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
914 (DemandedMask & (~RHSKnownZero)))
915 return I->getOperand(0);
916 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
917 (DemandedMask & (~LHSKnownZero)))
918 return I->getOperand(1);
921 // Compute the KnownZero/KnownOne bits to simplify things downstream.
922 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
926 // If this is the root being simplified, allow it to have multiple uses,
927 // just set the DemandedMask to all bits so that we can try to simplify the
928 // operands. This allows visitTruncInst (for example) to simplify the
929 // operand of a trunc without duplicating all the logic below.
930 if (Depth == 0 && !V->hasOneUse())
931 DemandedMask = APInt::getAllOnesValue(BitWidth);
933 switch (I->getOpcode()) {
935 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
937 case Instruction::And:
938 // If either the LHS or the RHS are Zero, the result is zero.
939 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
940 RHSKnownZero, RHSKnownOne, Depth+1) ||
941 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
942 LHSKnownZero, LHSKnownOne, Depth+1))
944 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
945 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
947 // If all of the demanded bits are known 1 on one side, return the other.
948 // These bits cannot contribute to the result of the 'and'.
949 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
950 (DemandedMask & ~LHSKnownZero))
951 return I->getOperand(0);
952 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
953 (DemandedMask & ~RHSKnownZero))
954 return I->getOperand(1);
956 // If all of the demanded bits in the inputs are known zeros, return zero.
957 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
958 return Context->getNullValue(VTy);
960 // If the RHS is a constant, see if we can simplify it.
961 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
964 // Output known-1 bits are only known if set in both the LHS & RHS.
965 RHSKnownOne &= LHSKnownOne;
966 // Output known-0 are known to be clear if zero in either the LHS | RHS.
967 RHSKnownZero |= LHSKnownZero;
969 case Instruction::Or:
970 // If either the LHS or the RHS are One, the result is One.
971 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
972 RHSKnownZero, RHSKnownOne, Depth+1) ||
973 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
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 zero on one side, return the other.
980 // These bits cannot contribute to the result of the 'or'.
981 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
982 (DemandedMask & ~LHSKnownOne))
983 return I->getOperand(0);
984 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
985 (DemandedMask & ~RHSKnownOne))
986 return I->getOperand(1);
988 // If all of the potentially set bits on one side are known to be set on
989 // the other side, just use the 'other' side.
990 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
991 (DemandedMask & (~RHSKnownZero)))
992 return I->getOperand(0);
993 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
994 (DemandedMask & (~LHSKnownZero)))
995 return I->getOperand(1);
997 // If the RHS is a constant, see if we can simplify it.
998 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
1001 // Output known-0 bits are only known if clear in both the LHS & RHS.
1002 RHSKnownZero &= LHSKnownZero;
1003 // Output known-1 are known to be set if set in either the LHS | RHS.
1004 RHSKnownOne |= LHSKnownOne;
1006 case Instruction::Xor: {
1007 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1008 RHSKnownZero, RHSKnownOne, Depth+1) ||
1009 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1010 LHSKnownZero, LHSKnownOne, Depth+1))
1012 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1013 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
1015 // If all of the demanded bits are known zero on one side, return the other.
1016 // These bits cannot contribute to the result of the 'xor'.
1017 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1018 return I->getOperand(0);
1019 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1020 return I->getOperand(1);
1022 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1023 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1024 (RHSKnownOne & LHSKnownOne);
1025 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1026 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1027 (RHSKnownOne & LHSKnownZero);
1029 // If all of the demanded bits are known to be zero on one side or the
1030 // other, turn this into an *inclusive* or.
1031 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1032 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1034 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1036 return InsertNewInstBefore(Or, *I);
1039 // If all of the demanded bits on one side are known, and all of the set
1040 // bits on that side are also known to be set on the other side, turn this
1041 // into an AND, as we know the bits will be cleared.
1042 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1043 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1045 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1046 Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
1048 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1049 return InsertNewInstBefore(And, *I);
1053 // If the RHS is a constant, see if we can simplify it.
1054 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1055 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
1058 RHSKnownZero = KnownZeroOut;
1059 RHSKnownOne = KnownOneOut;
1062 case Instruction::Select:
1063 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1064 RHSKnownZero, RHSKnownOne, Depth+1) ||
1065 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1066 LHSKnownZero, LHSKnownOne, Depth+1))
1068 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1069 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
1071 // If the operands are constants, see if we can simplify them.
1072 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1073 ShrinkDemandedConstant(I, 2, DemandedMask, Context))
1076 // Only known if known in both the LHS and RHS.
1077 RHSKnownOne &= LHSKnownOne;
1078 RHSKnownZero &= LHSKnownZero;
1080 case Instruction::Trunc: {
1081 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
1082 DemandedMask.zext(truncBf);
1083 RHSKnownZero.zext(truncBf);
1084 RHSKnownOne.zext(truncBf);
1085 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1086 RHSKnownZero, RHSKnownOne, Depth+1))
1088 DemandedMask.trunc(BitWidth);
1089 RHSKnownZero.trunc(BitWidth);
1090 RHSKnownOne.trunc(BitWidth);
1091 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1094 case Instruction::BitCast:
1095 if (!I->getOperand(0)->getType()->isIntOrIntVector())
1096 return false; // vector->int or fp->int?
1098 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1099 if (const VectorType *SrcVTy =
1100 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1101 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1102 // Don't touch a bitcast between vectors of different element counts.
1105 // Don't touch a scalar-to-vector bitcast.
1107 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1108 // Don't touch a vector-to-scalar bitcast.
1111 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1112 RHSKnownZero, RHSKnownOne, Depth+1))
1114 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1116 case Instruction::ZExt: {
1117 // Compute the bits in the result that are not present in the input.
1118 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1120 DemandedMask.trunc(SrcBitWidth);
1121 RHSKnownZero.trunc(SrcBitWidth);
1122 RHSKnownOne.trunc(SrcBitWidth);
1123 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
1124 RHSKnownZero, RHSKnownOne, Depth+1))
1126 DemandedMask.zext(BitWidth);
1127 RHSKnownZero.zext(BitWidth);
1128 RHSKnownOne.zext(BitWidth);
1129 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1130 // The top bits are known to be zero.
1131 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1134 case Instruction::SExt: {
1135 // Compute the bits in the result that are not present in the input.
1136 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
1138 APInt InputDemandedBits = DemandedMask &
1139 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1141 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1142 // If any of the sign extended bits are demanded, we know that the sign
1144 if ((NewBits & DemandedMask) != 0)
1145 InputDemandedBits.set(SrcBitWidth-1);
1147 InputDemandedBits.trunc(SrcBitWidth);
1148 RHSKnownZero.trunc(SrcBitWidth);
1149 RHSKnownOne.trunc(SrcBitWidth);
1150 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
1151 RHSKnownZero, RHSKnownOne, Depth+1))
1153 InputDemandedBits.zext(BitWidth);
1154 RHSKnownZero.zext(BitWidth);
1155 RHSKnownOne.zext(BitWidth);
1156 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1158 // If the sign bit of the input is known set or clear, then we know the
1159 // top bits of the result.
1161 // If the input sign bit is known zero, or if the NewBits are not demanded
1162 // convert this into a zero extension.
1163 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
1164 // Convert to ZExt cast
1165 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1166 return InsertNewInstBefore(NewCast, *I);
1167 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1168 RHSKnownOne |= NewBits;
1172 case Instruction::Add: {
1173 // Figure out what the input bits are. If the top bits of the and result
1174 // are not demanded, then the add doesn't demand them from its input
1176 unsigned NLZ = DemandedMask.countLeadingZeros();
1178 // If there is a constant on the RHS, there are a variety of xformations
1180 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1181 // If null, this should be simplified elsewhere. Some of the xforms here
1182 // won't work if the RHS is zero.
1186 // If the top bit of the output is demanded, demand everything from the
1187 // input. Otherwise, we demand all the input bits except NLZ top bits.
1188 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1190 // Find information about known zero/one bits in the input.
1191 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
1192 LHSKnownZero, LHSKnownOne, Depth+1))
1195 // If the RHS of the add has bits set that can't affect the input, reduce
1197 if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
1200 // Avoid excess work.
1201 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1204 // Turn it into OR if input bits are zero.
1205 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1207 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1209 return InsertNewInstBefore(Or, *I);
1212 // We can say something about the output known-zero and known-one bits,
1213 // depending on potential carries from the input constant and the
1214 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1215 // bits set and the RHS constant is 0x01001, then we know we have a known
1216 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1218 // To compute this, we first compute the potential carry bits. These are
1219 // the bits which may be modified. I'm not aware of a better way to do
1221 const APInt &RHSVal = RHS->getValue();
1222 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1224 // Now that we know which bits have carries, compute the known-1/0 sets.
1226 // Bits are known one if they are known zero in one operand and one in the
1227 // other, and there is no input carry.
1228 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1229 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1231 // Bits are known zero if they are known zero in both operands and there
1232 // is no input carry.
1233 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1235 // If the high-bits of this ADD are not demanded, then it does not demand
1236 // the high bits of its LHS or RHS.
1237 if (DemandedMask[BitWidth-1] == 0) {
1238 // Right fill the mask of bits for this ADD to demand the most
1239 // significant bit and all those below it.
1240 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1241 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1242 LHSKnownZero, LHSKnownOne, Depth+1) ||
1243 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1244 LHSKnownZero, LHSKnownOne, Depth+1))
1250 case Instruction::Sub:
1251 // If the high-bits of this SUB are not demanded, then it does not demand
1252 // the high bits of its LHS or RHS.
1253 if (DemandedMask[BitWidth-1] == 0) {
1254 // Right fill the mask of bits for this SUB to demand the most
1255 // significant bit and all those below it.
1256 uint32_t NLZ = DemandedMask.countLeadingZeros();
1257 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1258 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1259 LHSKnownZero, LHSKnownOne, Depth+1) ||
1260 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
1261 LHSKnownZero, LHSKnownOne, Depth+1))
1264 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1265 // the known zeros and ones.
1266 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1268 case Instruction::Shl:
1269 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1270 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1271 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1272 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1273 RHSKnownZero, RHSKnownOne, Depth+1))
1275 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1276 RHSKnownZero <<= ShiftAmt;
1277 RHSKnownOne <<= ShiftAmt;
1278 // low bits known zero.
1280 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1283 case Instruction::LShr:
1284 // For a logical shift right
1285 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1286 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1288 // Unsigned shift right.
1289 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1290 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1291 RHSKnownZero, RHSKnownOne, Depth+1))
1293 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1294 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1295 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1297 // Compute the new bits that are at the top now.
1298 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1299 RHSKnownZero |= HighBits; // high bits known zero.
1303 case Instruction::AShr:
1304 // If this is an arithmetic shift right and only the low-bit is set, we can
1305 // always convert this into a logical shr, even if the shift amount is
1306 // variable. The low bit of the shift cannot be an input sign bit unless
1307 // the shift amount is >= the size of the datatype, which is undefined.
1308 if (DemandedMask == 1) {
1309 // Perform the logical shift right.
1310 Instruction *NewVal = BinaryOperator::CreateLShr(
1311 I->getOperand(0), I->getOperand(1), I->getName());
1312 return InsertNewInstBefore(NewVal, *I);
1315 // If the sign bit is the only bit demanded by this ashr, then there is no
1316 // need to do it, the shift doesn't change the high bit.
1317 if (DemandedMask.isSignBit())
1318 return I->getOperand(0);
1320 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1321 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1323 // Signed shift right.
1324 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1325 // If any of the "high bits" are demanded, we should set the sign bit as
1327 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1328 DemandedMaskIn.set(BitWidth-1);
1329 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
1330 RHSKnownZero, RHSKnownOne, Depth+1))
1332 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1333 // Compute the new bits that are at the top now.
1334 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1335 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1336 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1338 // Handle the sign bits.
1339 APInt SignBit(APInt::getSignBit(BitWidth));
1340 // Adjust to where it is now in the mask.
1341 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1343 // If the input sign bit is known to be zero, or if none of the top bits
1344 // are demanded, turn this into an unsigned shift right.
1345 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
1346 (HighBits & ~DemandedMask) == HighBits) {
1347 // Perform the logical shift right.
1348 Instruction *NewVal = BinaryOperator::CreateLShr(
1349 I->getOperand(0), SA, I->getName());
1350 return InsertNewInstBefore(NewVal, *I);
1351 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1352 RHSKnownOne |= HighBits;
1356 case Instruction::SRem:
1357 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1358 APInt RA = Rem->getValue().abs();
1359 if (RA.isPowerOf2()) {
1360 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
1361 return I->getOperand(0);
1363 APInt LowBits = RA - 1;
1364 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1365 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
1366 LHSKnownZero, LHSKnownOne, Depth+1))
1369 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1370 LHSKnownZero |= ~LowBits;
1372 KnownZero |= LHSKnownZero & DemandedMask;
1374 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
1378 case Instruction::URem: {
1379 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1380 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1381 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1382 KnownZero2, KnownOne2, Depth+1) ||
1383 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
1384 KnownZero2, KnownOne2, Depth+1))
1387 unsigned Leaders = KnownZero2.countLeadingOnes();
1388 Leaders = std::max(Leaders,
1389 KnownZero2.countLeadingOnes());
1390 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
1393 case Instruction::Call:
1394 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1395 switch (II->getIntrinsicID()) {
1397 case Intrinsic::bswap: {
1398 // If the only bits demanded come from one byte of the bswap result,
1399 // just shift the input byte into position to eliminate the bswap.
1400 unsigned NLZ = DemandedMask.countLeadingZeros();
1401 unsigned NTZ = DemandedMask.countTrailingZeros();
1403 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1404 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1405 // have 14 leading zeros, round to 8.
1408 // If we need exactly one byte, we can do this transformation.
1409 if (BitWidth-NLZ-NTZ == 8) {
1410 unsigned ResultBit = NTZ;
1411 unsigned InputBit = BitWidth-NTZ-8;
1413 // Replace this with either a left or right shift to get the byte into
1415 Instruction *NewVal;
1416 if (InputBit > ResultBit)
1417 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1418 Context->getConstantInt(I->getType(), InputBit-ResultBit));
1420 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1421 Context->getConstantInt(I->getType(), ResultBit-InputBit));
1422 NewVal->takeName(I);
1423 return InsertNewInstBefore(NewVal, *I);
1426 // TODO: Could compute known zero/one bits based on the input.
1431 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1435 // If the client is only demanding bits that we know, return the known
1437 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1438 Constant *C = Context->getConstantInt(RHSKnownOne);
1439 if (isa<PointerType>(V->getType()))
1440 C = Context->getConstantExprIntToPtr(C, V->getType());
1447 /// SimplifyDemandedVectorElts - The specified value produces a vector with
1448 /// any number of elements. DemandedElts contains the set of elements that are
1449 /// actually used by the caller. This method analyzes which elements of the
1450 /// operand are undef and returns that information in UndefElts.
1452 /// If the information about demanded elements can be used to simplify the
1453 /// operation, the operation is simplified, then the resultant value is
1454 /// returned. This returns null if no change was made.
1455 Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1458 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1459 APInt EltMask(APInt::getAllOnesValue(VWidth));
1460 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
1462 if (isa<UndefValue>(V)) {
1463 // If the entire vector is undefined, just return this info.
1464 UndefElts = EltMask;
1466 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1467 UndefElts = EltMask;
1468 return Context->getUndef(V->getType());
1472 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1473 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1474 Constant *Undef = Context->getUndef(EltTy);
1476 std::vector<Constant*> Elts;
1477 for (unsigned i = 0; i != VWidth; ++i)
1478 if (!DemandedElts[i]) { // If not demanded, set to undef.
1479 Elts.push_back(Undef);
1481 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1482 Elts.push_back(Undef);
1484 } else { // Otherwise, defined.
1485 Elts.push_back(CP->getOperand(i));
1488 // If we changed the constant, return it.
1489 Constant *NewCP = Context->getConstantVector(Elts);
1490 return NewCP != CP ? NewCP : 0;
1491 } else if (isa<ConstantAggregateZero>(V)) {
1492 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1495 // Check if this is identity. If so, return 0 since we are not simplifying
1497 if (DemandedElts == ((1ULL << VWidth) -1))
1500 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1501 Constant *Zero = Context->getNullValue(EltTy);
1502 Constant *Undef = Context->getUndef(EltTy);
1503 std::vector<Constant*> Elts;
1504 for (unsigned i = 0; i != VWidth; ++i) {
1505 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1506 Elts.push_back(Elt);
1508 UndefElts = DemandedElts ^ EltMask;
1509 return Context->getConstantVector(Elts);
1512 // Limit search depth.
1516 // If multiple users are using the root value, procede with
1517 // simplification conservatively assuming that all elements
1519 if (!V->hasOneUse()) {
1520 // Quit if we find multiple users of a non-root value though.
1521 // They'll be handled when it's their turn to be visited by
1522 // the main instcombine process.
1524 // TODO: Just compute the UndefElts information recursively.
1527 // Conservatively assume that all elements are needed.
1528 DemandedElts = EltMask;
1531 Instruction *I = dyn_cast<Instruction>(V);
1532 if (!I) return 0; // Only analyze instructions.
1534 bool MadeChange = false;
1535 APInt UndefElts2(VWidth, 0);
1537 switch (I->getOpcode()) {
1540 case Instruction::InsertElement: {
1541 // If this is a variable index, we don't know which element it overwrites.
1542 // demand exactly the same input as we produce.
1543 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1545 // Note that we can't propagate undef elt info, because we don't know
1546 // which elt is getting updated.
1547 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1548 UndefElts2, Depth+1);
1549 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1553 // If this is inserting an element that isn't demanded, remove this
1555 unsigned IdxNo = Idx->getZExtValue();
1556 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
1557 return AddSoonDeadInstToWorklist(*I, 0);
1559 // Otherwise, the element inserted overwrites whatever was there, so the
1560 // input demanded set is simpler than the output set.
1561 APInt DemandedElts2 = DemandedElts;
1562 DemandedElts2.clear(IdxNo);
1563 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
1564 UndefElts, Depth+1);
1565 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1567 // The inserted element is defined.
1568 UndefElts.clear(IdxNo);
1571 case Instruction::ShuffleVector: {
1572 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
1573 uint64_t LHSVWidth =
1574 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
1575 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
1576 for (unsigned i = 0; i < VWidth; i++) {
1577 if (DemandedElts[i]) {
1578 unsigned MaskVal = Shuffle->getMaskValue(i);
1579 if (MaskVal != -1u) {
1580 assert(MaskVal < LHSVWidth * 2 &&
1581 "shufflevector mask index out of range!");
1582 if (MaskVal < LHSVWidth)
1583 LeftDemanded.set(MaskVal);
1585 RightDemanded.set(MaskVal - LHSVWidth);
1590 APInt UndefElts4(LHSVWidth, 0);
1591 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1592 UndefElts4, Depth+1);
1593 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1595 APInt UndefElts3(LHSVWidth, 0);
1596 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1597 UndefElts3, Depth+1);
1598 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1600 bool NewUndefElts = false;
1601 for (unsigned i = 0; i < VWidth; i++) {
1602 unsigned MaskVal = Shuffle->getMaskValue(i);
1603 if (MaskVal == -1u) {
1605 } else if (MaskVal < LHSVWidth) {
1606 if (UndefElts4[MaskVal]) {
1607 NewUndefElts = true;
1611 if (UndefElts3[MaskVal - LHSVWidth]) {
1612 NewUndefElts = true;
1619 // Add additional discovered undefs.
1620 std::vector<Constant*> Elts;
1621 for (unsigned i = 0; i < VWidth; ++i) {
1623 Elts.push_back(Context->getUndef(Type::Int32Ty));
1625 Elts.push_back(Context->getConstantInt(Type::Int32Ty,
1626 Shuffle->getMaskValue(i)));
1628 I->setOperand(2, Context->getConstantVector(Elts));
1633 case Instruction::BitCast: {
1634 // Vector->vector casts only.
1635 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1637 unsigned InVWidth = VTy->getNumElements();
1638 APInt InputDemandedElts(InVWidth, 0);
1641 if (VWidth == InVWidth) {
1642 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1643 // elements as are demanded of us.
1645 InputDemandedElts = DemandedElts;
1646 } else if (VWidth > InVWidth) {
1650 // If there are more elements in the result than there are in the source,
1651 // then an input element is live if any of the corresponding output
1652 // elements are live.
1653 Ratio = VWidth/InVWidth;
1654 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1655 if (DemandedElts[OutIdx])
1656 InputDemandedElts.set(OutIdx/Ratio);
1662 // If there are more elements in the source than there are in the result,
1663 // then an input element is live if the corresponding output element is
1665 Ratio = InVWidth/VWidth;
1666 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1667 if (DemandedElts[InIdx/Ratio])
1668 InputDemandedElts.set(InIdx);
1671 // div/rem demand all inputs, because they don't want divide by zero.
1672 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1673 UndefElts2, Depth+1);
1675 I->setOperand(0, TmpV);
1679 UndefElts = UndefElts2;
1680 if (VWidth > InVWidth) {
1681 assert(0 && "Unimp");
1682 // If there are more elements in the result than there are in the source,
1683 // then an output element is undef if the corresponding input element is
1685 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1686 if (UndefElts2[OutIdx/Ratio])
1687 UndefElts.set(OutIdx);
1688 } else if (VWidth < InVWidth) {
1689 assert(0 && "Unimp");
1690 // If there are more elements in the source than there are in the result,
1691 // then a result element is undef if all of the corresponding input
1692 // elements are undef.
1693 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1694 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1695 if (!UndefElts2[InIdx]) // Not undef?
1696 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
1700 case Instruction::And:
1701 case Instruction::Or:
1702 case Instruction::Xor:
1703 case Instruction::Add:
1704 case Instruction::Sub:
1705 case Instruction::Mul:
1706 // div/rem demand all inputs, because they don't want divide by zero.
1707 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1708 UndefElts, Depth+1);
1709 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1710 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1711 UndefElts2, Depth+1);
1712 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1714 // Output elements are undefined if both are undefined. Consider things
1715 // like undef&0. The result is known zero, not undef.
1716 UndefElts &= UndefElts2;
1719 case Instruction::Call: {
1720 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1722 switch (II->getIntrinsicID()) {
1725 // Binary vector operations that work column-wise. A dest element is a
1726 // function of the corresponding input elements from the two inputs.
1727 case Intrinsic::x86_sse_sub_ss:
1728 case Intrinsic::x86_sse_mul_ss:
1729 case Intrinsic::x86_sse_min_ss:
1730 case Intrinsic::x86_sse_max_ss:
1731 case Intrinsic::x86_sse2_sub_sd:
1732 case Intrinsic::x86_sse2_mul_sd:
1733 case Intrinsic::x86_sse2_min_sd:
1734 case Intrinsic::x86_sse2_max_sd:
1735 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1736 UndefElts, Depth+1);
1737 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1738 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1739 UndefElts2, Depth+1);
1740 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1742 // If only the low elt is demanded and this is a scalarizable intrinsic,
1743 // scalarize it now.
1744 if (DemandedElts == 1) {
1745 switch (II->getIntrinsicID()) {
1747 case Intrinsic::x86_sse_sub_ss:
1748 case Intrinsic::x86_sse_mul_ss:
1749 case Intrinsic::x86_sse2_sub_sd:
1750 case Intrinsic::x86_sse2_mul_sd:
1751 // TODO: Lower MIN/MAX/ABS/etc
1752 Value *LHS = II->getOperand(1);
1753 Value *RHS = II->getOperand(2);
1754 // Extract the element as scalars.
1755 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1756 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1758 switch (II->getIntrinsicID()) {
1759 default: assert(0 && "Case stmts out of sync!");
1760 case Intrinsic::x86_sse_sub_ss:
1761 case Intrinsic::x86_sse2_sub_sd:
1762 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
1763 II->getName()), *II);
1765 case Intrinsic::x86_sse_mul_ss:
1766 case Intrinsic::x86_sse2_mul_sd:
1767 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
1768 II->getName()), *II);
1773 InsertElementInst::Create(
1774 Context->getUndef(II->getType()), TmpV, 0U, II->getName());
1775 InsertNewInstBefore(New, *II);
1776 AddSoonDeadInstToWorklist(*II, 0);
1781 // Output elements are undefined if both are undefined. Consider things
1782 // like undef&0. The result is known zero, not undef.
1783 UndefElts &= UndefElts2;
1789 return MadeChange ? I : 0;
1793 /// AssociativeOpt - Perform an optimization on an associative operator. This
1794 /// function is designed to check a chain of associative operators for a
1795 /// potential to apply a certain optimization. Since the optimization may be
1796 /// applicable if the expression was reassociated, this checks the chain, then
1797 /// reassociates the expression as necessary to expose the optimization
1798 /// opportunity. This makes use of a special Functor, which must define
1799 /// 'shouldApply' and 'apply' methods.
1801 template<typename Functor>
1802 static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
1803 LLVMContext *Context) {
1804 unsigned Opcode = Root.getOpcode();
1805 Value *LHS = Root.getOperand(0);
1807 // Quick check, see if the immediate LHS matches...
1808 if (F.shouldApply(LHS))
1809 return F.apply(Root);
1811 // Otherwise, if the LHS is not of the same opcode as the root, return.
1812 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1813 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1814 // Should we apply this transform to the RHS?
1815 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1817 // If not to the RHS, check to see if we should apply to the LHS...
1818 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1819 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1823 // If the functor wants to apply the optimization to the RHS of LHSI,
1824 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1826 // Now all of the instructions are in the current basic block, go ahead
1827 // and perform the reassociation.
1828 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1830 // First move the selected RHS to the LHS of the root...
1831 Root.setOperand(0, LHSI->getOperand(1));
1833 // Make what used to be the LHS of the root be the user of the root...
1834 Value *ExtraOperand = TmpLHSI->getOperand(1);
1835 if (&Root == TmpLHSI) {
1836 Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
1839 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1840 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1841 BasicBlock::iterator ARI = &Root; ++ARI;
1842 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
1845 // Now propagate the ExtraOperand down the chain of instructions until we
1847 while (TmpLHSI != LHSI) {
1848 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1849 // Move the instruction to immediately before the chain we are
1850 // constructing to avoid breaking dominance properties.
1851 NextLHSI->moveBefore(ARI);
1854 Value *NextOp = NextLHSI->getOperand(1);
1855 NextLHSI->setOperand(1, ExtraOperand);
1857 ExtraOperand = NextOp;
1860 // Now that the instructions are reassociated, have the functor perform
1861 // the transformation...
1862 return F.apply(Root);
1865 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1872 // AddRHS - Implements: X + X --> X << 1
1875 LLVMContext *Context;
1876 AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
1877 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1878 Instruction *apply(BinaryOperator &Add) const {
1879 return BinaryOperator::CreateShl(Add.getOperand(0),
1880 Context->getConstantInt(Add.getType(), 1));
1884 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1886 struct AddMaskingAnd {
1888 LLVMContext *Context;
1889 AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
1890 bool shouldApply(Value *LHS) const {
1892 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1893 Context->getConstantExprAnd(C1, C2)->isNullValue();
1895 Instruction *apply(BinaryOperator &Add) const {
1896 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
1902 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1904 LLVMContext *Context = IC->getContext();
1906 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1907 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
1910 // Figure out if the constant is the left or the right argument.
1911 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1912 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1914 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1916 return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1917 return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
1920 Value *Op0 = SO, *Op1 = ConstOperand;
1922 std::swap(Op0, Op1);
1924 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1925 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1926 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1927 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1928 Op0, Op1, SO->getName()+".cmp");
1930 assert(0 && "Unknown binary instruction type!");
1933 return IC->InsertNewInstBefore(New, I);
1936 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1937 // constant as the other operand, try to fold the binary operator into the
1938 // select arguments. This also works for Cast instructions, which obviously do
1939 // not have a second operand.
1940 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1942 // Don't modify shared select instructions
1943 if (!SI->hasOneUse()) return 0;
1944 Value *TV = SI->getOperand(1);
1945 Value *FV = SI->getOperand(2);
1947 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1948 // Bool selects with constant operands can be folded to logical ops.
1949 if (SI->getType() == Type::Int1Ty) return 0;
1951 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1952 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1954 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1961 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1962 /// node as operand #0, see if we can fold the instruction into the PHI (which
1963 /// is only possible if all operands to the PHI are constants).
1964 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1965 PHINode *PN = cast<PHINode>(I.getOperand(0));
1966 unsigned NumPHIValues = PN->getNumIncomingValues();
1967 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1969 // Check to see if all of the operands of the PHI are constants. If there is
1970 // one non-constant value, remember the BB it is. If there is more than one
1971 // or if *it* is a PHI, bail out.
1972 BasicBlock *NonConstBB = 0;
1973 for (unsigned i = 0; i != NumPHIValues; ++i)
1974 if (!isa<Constant>(PN->getIncomingValue(i))) {
1975 if (NonConstBB) return 0; // More than one non-const value.
1976 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1977 NonConstBB = PN->getIncomingBlock(i);
1979 // If the incoming non-constant value is in I's block, we have an infinite
1981 if (NonConstBB == I.getParent())
1985 // If there is exactly one non-constant value, we can insert a copy of the
1986 // operation in that block. However, if this is a critical edge, we would be
1987 // inserting the computation one some other paths (e.g. inside a loop). Only
1988 // do this if the pred block is unconditionally branching into the phi block.
1990 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1991 if (!BI || !BI->isUnconditional()) return 0;
1994 // Okay, we can do the transformation: create the new PHI node.
1995 PHINode *NewPN = PHINode::Create(I.getType(), "");
1996 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1997 InsertNewInstBefore(NewPN, *PN);
1998 NewPN->takeName(PN);
2000 // Next, add all of the operands to the PHI.
2001 if (I.getNumOperands() == 2) {
2002 Constant *C = cast<Constant>(I.getOperand(1));
2003 for (unsigned i = 0; i != NumPHIValues; ++i) {
2005 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2006 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2007 InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
2009 InV = Context->getConstantExpr(I.getOpcode(), InC, C);
2011 assert(PN->getIncomingBlock(i) == NonConstBB);
2012 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
2013 InV = BinaryOperator::Create(BO->getOpcode(),
2014 PN->getIncomingValue(i), C, "phitmp",
2015 NonConstBB->getTerminator());
2016 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2017 InV = CmpInst::Create(*Context, CI->getOpcode(),
2019 PN->getIncomingValue(i), C, "phitmp",
2020 NonConstBB->getTerminator());
2022 assert(0 && "Unknown binop!");
2024 AddToWorkList(cast<Instruction>(InV));
2026 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2029 CastInst *CI = cast<CastInst>(&I);
2030 const Type *RetTy = CI->getType();
2031 for (unsigned i = 0; i != NumPHIValues; ++i) {
2033 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2034 InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
2036 assert(PN->getIncomingBlock(i) == NonConstBB);
2037 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
2038 I.getType(), "phitmp",
2039 NonConstBB->getTerminator());
2040 AddToWorkList(cast<Instruction>(InV));
2042 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2045 return ReplaceInstUsesWith(I, NewPN);
2049 /// WillNotOverflowSignedAdd - Return true if we can prove that:
2050 /// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2051 /// This basically requires proving that the add in the original type would not
2052 /// overflow to change the sign bit or have a carry out.
2053 bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2054 // There are different heuristics we can use for this. Here are some simple
2057 // Add has the property that adding any two 2's complement numbers can only
2058 // have one carry bit which can change a sign. As such, if LHS and RHS each
2059 // have at least two sign bits, we know that the addition of the two values will
2060 // sign extend fine.
2061 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2065 // If one of the operands only has one non-zero bit, and if the other operand
2066 // has a known-zero bit in a more significant place than it (not including the
2067 // sign bit) the ripple may go up to and fill the zero, but won't change the
2068 // sign. For example, (X & ~4) + 1.
2076 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2077 bool Changed = SimplifyCommutative(I);
2078 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2080 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2081 // X + undef -> undef
2082 if (isa<UndefValue>(RHS))
2083 return ReplaceInstUsesWith(I, RHS);
2086 if (RHSC->isNullValue())
2087 return ReplaceInstUsesWith(I, LHS);
2089 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2090 // X + (signbit) --> X ^ signbit
2091 const APInt& Val = CI->getValue();
2092 uint32_t BitWidth = Val.getBitWidth();
2093 if (Val == APInt::getSignBit(BitWidth))
2094 return BinaryOperator::CreateXor(LHS, RHS);
2096 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2097 // (X & 254)+1 -> (X&254)|1
2098 if (SimplifyDemandedInstructionBits(I))
2101 // zext(i1) - 1 -> select i1, 0, -1
2102 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2103 if (CI->isAllOnesValue() &&
2104 ZI->getOperand(0)->getType() == Type::Int1Ty)
2105 return SelectInst::Create(ZI->getOperand(0),
2106 Context->getNullValue(I.getType()),
2107 Context->getConstantIntAllOnesValue(I.getType()));
2110 if (isa<PHINode>(LHS))
2111 if (Instruction *NV = FoldOpIntoPhi(I))
2114 ConstantInt *XorRHS = 0;
2116 if (isa<ConstantInt>(RHSC) &&
2117 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2118 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
2119 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2121 uint32_t Size = TySizeBits / 2;
2122 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2123 APInt CFF80Val(-C0080Val);
2125 if (TySizeBits > Size) {
2126 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2127 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2128 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2129 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2130 // This is a sign extend if the top bits are known zero.
2131 if (!MaskedValueIsZero(XorLHS,
2132 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2133 Size = 0; // Not a sign ext, but can't be any others either.
2138 C0080Val = APIntOps::lshr(C0080Val, Size);
2139 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2140 } while (Size >= 1);
2142 // FIXME: This shouldn't be necessary. When the backends can handle types
2143 // with funny bit widths then this switch statement should be removed. It
2144 // is just here to get the size of the "middle" type back up to something
2145 // that the back ends can handle.
2146 const Type *MiddleType = 0;
2149 case 32: MiddleType = Type::Int32Ty; break;
2150 case 16: MiddleType = Type::Int16Ty; break;
2151 case 8: MiddleType = Type::Int8Ty; break;
2154 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2155 InsertNewInstBefore(NewTrunc, I);
2156 return new SExtInst(NewTrunc, I.getType(), I.getName());
2161 if (I.getType() == Type::Int1Ty)
2162 return BinaryOperator::CreateXor(LHS, RHS);
2165 if (I.getType()->isInteger()) {
2166 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2169 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2170 if (RHSI->getOpcode() == Instruction::Sub)
2171 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2172 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2174 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2175 if (LHSI->getOpcode() == Instruction::Sub)
2176 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2177 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2182 // -A + -B --> -(A + B)
2183 if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
2184 if (LHS->getType()->isIntOrIntVector()) {
2185 if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
2186 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
2187 InsertNewInstBefore(NewAdd, I);
2188 return BinaryOperator::CreateNeg(NewAdd);
2192 return BinaryOperator::CreateSub(RHS, LHSV);
2196 if (!isa<Constant>(RHS))
2197 if (Value *V = dyn_castNegVal(RHS, Context))
2198 return BinaryOperator::CreateSub(LHS, V);
2202 if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
2203 if (X == RHS) // X*C + X --> X * (C+1)
2204 return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
2206 // X*C1 + X*C2 --> X * (C1+C2)
2208 if (X == dyn_castFoldableMul(RHS, C1, Context))
2209 return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
2212 // X + X*C --> X * (C+1)
2213 if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2214 return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
2216 // X + ~X --> -1 since ~X = -X-1
2217 if (dyn_castNotVal(LHS, Context) == RHS ||
2218 dyn_castNotVal(RHS, Context) == LHS)
2219 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
2222 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2223 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2224 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
2227 // A+B --> A|B iff A and B have no bits set in common.
2228 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2229 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2230 APInt LHSKnownOne(IT->getBitWidth(), 0);
2231 APInt LHSKnownZero(IT->getBitWidth(), 0);
2232 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2233 if (LHSKnownZero != 0) {
2234 APInt RHSKnownOne(IT->getBitWidth(), 0);
2235 APInt RHSKnownZero(IT->getBitWidth(), 0);
2236 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2238 // No bits in common -> bitwise or.
2239 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
2240 return BinaryOperator::CreateOr(LHS, RHS);
2244 // W*X + Y*Z --> W * (X+Z) iff W == Y
2245 if (I.getType()->isIntOrIntVector()) {
2246 Value *W, *X, *Y, *Z;
2247 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2248 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2252 } else if (Y == X) {
2254 } else if (X == Z) {
2261 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
2262 LHS->getName()), I);
2263 return BinaryOperator::CreateMul(W, NewAdd);
2268 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2270 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2271 return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
2273 // (X & FF00) + xx00 -> (X+xx00) & FF00
2274 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2275 Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
2276 if (Anded == CRHS) {
2277 // See if all bits from the first bit set in the Add RHS up are included
2278 // in the mask. First, get the rightmost bit.
2279 const APInt& AddRHSV = CRHS->getValue();
2281 // Form a mask of all bits from the lowest bit added through the top.
2282 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2284 // See if the and mask includes all of these bits.
2285 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2287 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2288 // Okay, the xform is safe. Insert the new add pronto.
2289 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
2290 LHS->getName()), I);
2291 return BinaryOperator::CreateAnd(NewAdd, C2);
2296 // Try to fold constant add into select arguments.
2297 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2298 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2302 // add (cast *A to intptrtype) B ->
2303 // cast (GEP (cast *A to i8*) B) --> intptrtype
2305 CastInst *CI = dyn_cast<CastInst>(LHS);
2308 CI = dyn_cast<CastInst>(RHS);
2311 if (CI && CI->getType()->isSized() &&
2312 (CI->getType()->getScalarSizeInBits() ==
2313 TD->getIntPtrType()->getPrimitiveSizeInBits())
2314 && isa<PointerType>(CI->getOperand(0)->getType())) {
2316 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
2317 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2318 Context->getPointerType(Type::Int8Ty, AS), I);
2319 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
2320 return new PtrToIntInst(I2, CI->getType());
2324 // add (select X 0 (sub n A)) A --> select X A n
2326 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2329 SI = dyn_cast<SelectInst>(RHS);
2332 if (SI && SI->hasOneUse()) {
2333 Value *TV = SI->getTrueValue();
2334 Value *FV = SI->getFalseValue();
2337 // Can we fold the add into the argument of the select?
2338 // We check both true and false select arguments for a matching subtract.
2339 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2340 // Fold the add into the true select value.
2341 return SelectInst::Create(SI->getCondition(), N, A);
2342 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2343 // Fold the add into the false select value.
2344 return SelectInst::Create(SI->getCondition(), A, N);
2348 // Check for (add (sext x), y), see if we can merge this into an
2349 // integer add followed by a sext.
2350 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2351 // (add (sext x), cst) --> (sext (add x, cst'))
2352 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2354 Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
2355 if (LHSConv->hasOneUse() &&
2356 Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
2357 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2358 // Insert the new, smaller add.
2359 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2361 InsertNewInstBefore(NewAdd, I);
2362 return new SExtInst(NewAdd, I.getType());
2366 // (add (sext x), (sext y)) --> (sext (add int x, y))
2367 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2368 // Only do this if x/y have the same type, if at last one of them has a
2369 // single use (so we don't increase the number of sexts), and if the
2370 // integer add will not overflow.
2371 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2372 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2373 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2374 RHSConv->getOperand(0))) {
2375 // Insert the new integer add.
2376 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2377 RHSConv->getOperand(0),
2379 InsertNewInstBefore(NewAdd, I);
2380 return new SExtInst(NewAdd, I.getType());
2385 return Changed ? &I : 0;
2388 Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2389 bool Changed = SimplifyCommutative(I);
2390 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2392 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2394 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
2395 if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
2396 (I.getType())->getValueAPF()))
2397 return ReplaceInstUsesWith(I, LHS);
2400 if (isa<PHINode>(LHS))
2401 if (Instruction *NV = FoldOpIntoPhi(I))
2406 // -A + -B --> -(A + B)
2407 if (Value *LHSV = dyn_castFNegVal(LHS, Context))
2408 return BinaryOperator::CreateFSub(RHS, LHSV);
2411 if (!isa<Constant>(RHS))
2412 if (Value *V = dyn_castFNegVal(RHS, Context))
2413 return BinaryOperator::CreateFSub(LHS, V);
2415 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2416 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2417 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2418 return ReplaceInstUsesWith(I, LHS);
2420 // Check for (add double (sitofp x), y), see if we can merge this into an
2421 // integer add followed by a promotion.
2422 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2423 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2424 // ... if the constant fits in the integer value. This is useful for things
2425 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2426 // requires a constant pool load, and generally allows the add to be better
2428 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2430 Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
2431 if (LHSConv->hasOneUse() &&
2432 Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
2433 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2434 // Insert the new integer add.
2435 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2437 InsertNewInstBefore(NewAdd, I);
2438 return new SIToFPInst(NewAdd, I.getType());
2442 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2443 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2444 // Only do this if x/y have the same type, if at last one of them has a
2445 // single use (so we don't increase the number of int->fp conversions),
2446 // and if the integer add will not overflow.
2447 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2448 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2449 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2450 RHSConv->getOperand(0))) {
2451 // Insert the new integer add.
2452 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2453 RHSConv->getOperand(0),
2455 InsertNewInstBefore(NewAdd, I);
2456 return new SIToFPInst(NewAdd, I.getType());
2461 return Changed ? &I : 0;
2464 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2465 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2467 if (Op0 == Op1) // sub X, X -> 0
2468 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2470 // If this is a 'B = x-(-A)', change to B = x+A...
2471 if (Value *V = dyn_castNegVal(Op1, Context))
2472 return BinaryOperator::CreateAdd(Op0, V);
2474 if (isa<UndefValue>(Op0))
2475 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2476 if (isa<UndefValue>(Op1))
2477 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2479 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2480 // Replace (-1 - A) with (~A)...
2481 if (C->isAllOnesValue())
2482 return BinaryOperator::CreateNot(Op1);
2484 // C - ~X == X + (1+C)
2486 if (match(Op1, m_Not(m_Value(X))))
2487 return BinaryOperator::CreateAdd(X, AddOne(C, Context));
2489 // -(X >>u 31) -> (X >>s 31)
2490 // -(X >>s 31) -> (X >>u 31)
2492 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
2493 if (SI->getOpcode() == Instruction::LShr) {
2494 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2495 // Check to see if we are shifting out everything but the sign bit.
2496 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2497 SI->getType()->getPrimitiveSizeInBits()-1) {
2498 // Ok, the transformation is safe. Insert AShr.
2499 return BinaryOperator::Create(Instruction::AShr,
2500 SI->getOperand(0), CU, SI->getName());
2504 else if (SI->getOpcode() == Instruction::AShr) {
2505 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2506 // Check to see if we are shifting out everything but the sign bit.
2507 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2508 SI->getType()->getPrimitiveSizeInBits()-1) {
2509 // Ok, the transformation is safe. Insert LShr.
2510 return BinaryOperator::CreateLShr(
2511 SI->getOperand(0), CU, SI->getName());
2518 // Try to fold constant sub into select arguments.
2519 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2520 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2524 if (I.getType() == Type::Int1Ty)
2525 return BinaryOperator::CreateXor(Op0, Op1);
2527 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2528 if (Op1I->getOpcode() == Instruction::Add) {
2529 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2530 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
2531 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2532 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
2533 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2534 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2535 // C1-(X+C2) --> (C1-C2)-X
2536 return BinaryOperator::CreateSub(
2537 Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
2541 if (Op1I->hasOneUse()) {
2542 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2543 // is not used by anyone else...
2545 if (Op1I->getOpcode() == Instruction::Sub) {
2546 // Swap the two operands of the subexpr...
2547 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2548 Op1I->setOperand(0, IIOp1);
2549 Op1I->setOperand(1, IIOp0);
2551 // Create the new top level add instruction...
2552 return BinaryOperator::CreateAdd(Op0, Op1);
2555 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2557 if (Op1I->getOpcode() == Instruction::And &&
2558 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2559 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2562 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2563 return BinaryOperator::CreateAnd(Op0, NewNot);
2566 // 0 - (X sdiv C) -> (X sdiv -C)
2567 if (Op1I->getOpcode() == Instruction::SDiv)
2568 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2570 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2571 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
2572 Context->getConstantExprNeg(DivRHS));
2574 // X - X*C --> X * (1-C)
2575 ConstantInt *C2 = 0;
2576 if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2578 Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
2580 return BinaryOperator::CreateMul(Op0, CP1);
2585 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2586 if (Op0I->getOpcode() == Instruction::Add) {
2587 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2588 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2589 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2590 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2591 } else if (Op0I->getOpcode() == Instruction::Sub) {
2592 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2593 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
2598 if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
2599 if (X == Op1) // X*C - X --> X * (C-1)
2600 return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
2602 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2603 if (X == dyn_castFoldableMul(Op1, C2, Context))
2604 return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
2609 Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2610 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2612 // If this is a 'B = x-(-A)', change to B = x+A...
2613 if (Value *V = dyn_castFNegVal(Op1, Context))
2614 return BinaryOperator::CreateFAdd(Op0, V);
2616 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2617 if (Op1I->getOpcode() == Instruction::FAdd) {
2618 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2619 return BinaryOperator::CreateFNeg(Op1I->getOperand(1), I.getName());
2620 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2621 return BinaryOperator::CreateFNeg(Op1I->getOperand(0), I.getName());
2628 /// isSignBitCheck - Given an exploded icmp instruction, return true if the
2629 /// comparison only checks the sign bit. If it only checks the sign bit, set
2630 /// TrueIfSigned if the result of the comparison is true when the input value is
2632 static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2633 bool &TrueIfSigned) {
2635 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2636 TrueIfSigned = true;
2637 return RHS->isZero();
2638 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2639 TrueIfSigned = true;
2640 return RHS->isAllOnesValue();
2641 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2642 TrueIfSigned = false;
2643 return RHS->isAllOnesValue();
2644 case ICmpInst::ICMP_UGT:
2645 // True if LHS u> RHS and RHS == high-bit-mask - 1
2646 TrueIfSigned = true;
2647 return RHS->getValue() ==
2648 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2649 case ICmpInst::ICMP_UGE:
2650 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2651 TrueIfSigned = true;
2652 return RHS->getValue().isSignBit();
2658 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2659 bool Changed = SimplifyCommutative(I);
2660 Value *Op0 = I.getOperand(0);
2662 // TODO: If Op1 is undef and Op0 is finite, return zero.
2663 if (!I.getType()->isFPOrFPVector() &&
2664 isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2665 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2667 // Simplify mul instructions with a constant RHS...
2668 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2669 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2671 // ((X << C1)*C2) == (X * (C2 << C1))
2672 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2673 if (SI->getOpcode() == Instruction::Shl)
2674 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2675 return BinaryOperator::CreateMul(SI->getOperand(0),
2676 Context->getConstantExprShl(CI, ShOp));
2679 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2680 if (CI->equalsInt(1)) // X * 1 == X
2681 return ReplaceInstUsesWith(I, Op0);
2682 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2683 return BinaryOperator::CreateNeg(Op0, I.getName());
2685 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2686 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2687 return BinaryOperator::CreateShl(Op0,
2688 Context->getConstantInt(Op0->getType(), Val.logBase2()));
2690 } else if (isa<VectorType>(Op1->getType())) {
2691 // TODO: If Op1 is all zeros and Op0 is all finite, return all zeros.
2693 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2694 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2695 return BinaryOperator::CreateNeg(Op0, I.getName());
2697 // As above, vector X*splat(1.0) -> X in all defined cases.
2698 if (Constant *Splat = Op1V->getSplatValue()) {
2699 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2700 if (CI->equalsInt(1))
2701 return ReplaceInstUsesWith(I, Op0);
2706 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2707 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2708 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
2709 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2710 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
2712 InsertNewInstBefore(Add, I);
2713 Value *C1C2 = Context->getConstantExprMul(Op1,
2714 cast<Constant>(Op0I->getOperand(1)));
2715 return BinaryOperator::CreateAdd(Add, C1C2);
2719 // Try to fold constant mul into select arguments.
2720 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2721 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2724 if (isa<PHINode>(Op0))
2725 if (Instruction *NV = FoldOpIntoPhi(I))
2729 if (Value *Op0v = dyn_castNegVal(Op0, Context)) // -X * -Y = X*Y
2730 if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
2731 return BinaryOperator::CreateMul(Op0v, Op1v);
2733 // (X / Y) * Y = X - (X % Y)
2734 // (X / Y) * -Y = (X % Y) - X
2736 Value *Op1 = I.getOperand(1);
2737 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2739 (BO->getOpcode() != Instruction::UDiv &&
2740 BO->getOpcode() != Instruction::SDiv)) {
2742 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2744 Value *Neg = dyn_castNegVal(Op1, Context);
2745 if (BO && BO->hasOneUse() &&
2746 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2747 (BO->getOpcode() == Instruction::UDiv ||
2748 BO->getOpcode() == Instruction::SDiv)) {
2749 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2752 if (BO->getOpcode() == Instruction::UDiv)
2753 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2755 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2757 InsertNewInstBefore(Rem, I);
2761 return BinaryOperator::CreateSub(Op0BO, Rem);
2763 return BinaryOperator::CreateSub(Rem, Op0BO);
2767 if (I.getType() == Type::Int1Ty)
2768 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2770 // If one of the operands of the multiply is a cast from a boolean value, then
2771 // we know the bool is either zero or one, so this is a 'masking' multiply.
2772 // See if we can simplify things based on how the boolean was originally
2774 CastInst *BoolCast = 0;
2775 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
2776 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2779 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2780 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2783 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2784 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2785 const Type *SCOpTy = SCIOp0->getType();
2788 // If the icmp is true iff the sign bit of X is set, then convert this
2789 // multiply into a shift/and combination.
2790 if (isa<ConstantInt>(SCIOp1) &&
2791 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2793 // Shift the X value right to turn it into "all signbits".
2794 Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
2795 SCOpTy->getPrimitiveSizeInBits()-1);
2797 InsertNewInstBefore(
2798 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
2799 BoolCast->getOperand(0)->getName()+
2802 // If the multiply type is not the same as the source type, sign extend
2803 // or truncate to the multiply type.
2804 if (I.getType() != V->getType()) {
2805 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2806 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2807 Instruction::CastOps opcode =
2808 (SrcBits == DstBits ? Instruction::BitCast :
2809 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2810 V = InsertCastBefore(opcode, V, I.getType(), I);
2813 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2814 return BinaryOperator::CreateAnd(V, OtherOp);
2819 return Changed ? &I : 0;
2822 Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2823 bool Changed = SimplifyCommutative(I);
2824 Value *Op0 = I.getOperand(0);
2826 // Simplify mul instructions with a constant RHS...
2827 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2828 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2829 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2830 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2831 if (Op1F->isExactlyValue(1.0))
2832 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2833 } else if (isa<VectorType>(Op1->getType())) {
2834 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2835 // As above, vector X*splat(1.0) -> X in all defined cases.
2836 if (Constant *Splat = Op1V->getSplatValue()) {
2837 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2838 if (F->isExactlyValue(1.0))
2839 return ReplaceInstUsesWith(I, Op0);
2844 // Try to fold constant mul into select arguments.
2845 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2846 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2849 if (isa<PHINode>(Op0))
2850 if (Instruction *NV = FoldOpIntoPhi(I))
2854 if (Value *Op0v = dyn_castFNegVal(Op0, Context)) // -X * -Y = X*Y
2855 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
2856 return BinaryOperator::CreateFMul(Op0v, Op1v);
2858 return Changed ? &I : 0;
2861 /// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2863 bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2864 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2866 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2867 int NonNullOperand = -1;
2868 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2869 if (ST->isNullValue())
2871 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2872 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2873 if (ST->isNullValue())
2876 if (NonNullOperand == -1)
2879 Value *SelectCond = SI->getOperand(0);
2881 // Change the div/rem to use 'Y' instead of the select.
2882 I.setOperand(1, SI->getOperand(NonNullOperand));
2884 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2885 // problem. However, the select, or the condition of the select may have
2886 // multiple uses. Based on our knowledge that the operand must be non-zero,
2887 // propagate the known value for the select into other uses of it, and
2888 // propagate a known value of the condition into its other users.
2890 // If the select and condition only have a single use, don't bother with this,
2892 if (SI->use_empty() && SelectCond->hasOneUse())
2895 // Scan the current block backward, looking for other uses of SI.
2896 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2898 while (BBI != BBFront) {
2900 // If we found a call to a function, we can't assume it will return, so
2901 // information from below it cannot be propagated above it.
2902 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2905 // Replace uses of the select or its condition with the known values.
2906 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2909 *I = SI->getOperand(NonNullOperand);
2911 } else if (*I == SelectCond) {
2912 *I = NonNullOperand == 1 ? Context->getConstantIntTrue() :
2913 Context->getConstantIntFalse();
2918 // If we past the instruction, quit looking for it.
2921 if (&*BBI == SelectCond)
2924 // If we ran out of things to eliminate, break out of the loop.
2925 if (SelectCond == 0 && SI == 0)
2933 /// This function implements the transforms on div instructions that work
2934 /// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2935 /// used by the visitors to those instructions.
2936 /// @brief Transforms common to all three div instructions
2937 Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2938 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2940 // undef / X -> 0 for integer.
2941 // undef / X -> undef for FP (the undef could be a snan).
2942 if (isa<UndefValue>(Op0)) {
2943 if (Op0->getType()->isFPOrFPVector())
2944 return ReplaceInstUsesWith(I, Op0);
2945 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2948 // X / undef -> undef
2949 if (isa<UndefValue>(Op1))
2950 return ReplaceInstUsesWith(I, Op1);
2955 /// This function implements the transforms common to both integer division
2956 /// instructions (udiv and sdiv). It is called by the visitors to those integer
2957 /// division instructions.
2958 /// @brief Common integer divide transforms
2959 Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2960 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2962 // (sdiv X, X) --> 1 (udiv X, X) --> 1
2964 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2965 Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
2966 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2967 return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
2970 Constant *CI = Context->getConstantInt(I.getType(), 1);
2971 return ReplaceInstUsesWith(I, CI);
2974 if (Instruction *Common = commonDivTransforms(I))
2977 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2978 // This does not apply for fdiv.
2979 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2982 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2984 if (RHS->equalsInt(1))
2985 return ReplaceInstUsesWith(I, Op0);
2987 // (X / C1) / C2 -> X / (C1*C2)
2988 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2989 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2990 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2991 if (MultiplyOverflows(RHS, LHSRHS,
2992 I.getOpcode()==Instruction::SDiv, Context))
2993 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
2995 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
2996 Context->getConstantExprMul(RHS, LHSRHS));
2999 if (!RHS->isZero()) { // avoid X udiv 0
3000 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3001 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3003 if (isa<PHINode>(Op0))
3004 if (Instruction *NV = FoldOpIntoPhi(I))
3009 // 0 / X == 0, we don't need to preserve faults!
3010 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3011 if (LHS->equalsInt(0))
3012 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3014 // It can't be division by zero, hence it must be division by one.
3015 if (I.getType() == Type::Int1Ty)
3016 return ReplaceInstUsesWith(I, Op0);
3018 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3019 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3022 return ReplaceInstUsesWith(I, Op0);
3028 Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3029 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3031 // Handle the integer div common cases
3032 if (Instruction *Common = commonIDivTransforms(I))
3035 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3036 // X udiv C^2 -> X >> C
3037 // Check to see if this is an unsigned division with an exact power of 2,
3038 // if so, convert to a right shift.
3039 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
3040 return BinaryOperator::CreateLShr(Op0,
3041 Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
3043 // X udiv C, where C >= signbit
3044 if (C->getValue().isNegative()) {
3045 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3046 ICmpInst::ICMP_ULT, Op0, C),
3048 return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3049 Context->getConstantInt(I.getType(), 1));
3053 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3054 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3055 if (RHSI->getOpcode() == Instruction::Shl &&
3056 isa<ConstantInt>(RHSI->getOperand(0))) {
3057 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3058 if (C1.isPowerOf2()) {
3059 Value *N = RHSI->getOperand(1);
3060 const Type *NTy = N->getType();
3061 if (uint32_t C2 = C1.logBase2()) {
3062 Constant *C2V = Context->getConstantInt(NTy, C2);
3063 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
3065 return BinaryOperator::CreateLShr(Op0, N);
3070 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3071 // where C1&C2 are powers of two.
3072 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3073 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3074 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3075 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3076 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3077 // Compute the shift amounts
3078 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3079 // Construct the "on true" case of the select
3080 Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
3081 Instruction *TSI = BinaryOperator::CreateLShr(
3082 Op0, TC, SI->getName()+".t");
3083 TSI = InsertNewInstBefore(TSI, I);
3085 // Construct the "on false" case of the select
3086 Constant *FC = Context->getConstantInt(Op0->getType(), FSA);
3087 Instruction *FSI = BinaryOperator::CreateLShr(
3088 Op0, FC, SI->getName()+".f");
3089 FSI = InsertNewInstBefore(FSI, I);
3091 // construct the select instruction and return it.
3092 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
3098 Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3099 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3101 // Handle the integer div common cases
3102 if (Instruction *Common = commonIDivTransforms(I))
3105 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3107 if (RHS->isAllOnesValue())
3108 return BinaryOperator::CreateNeg(Op0);
3111 // If the sign bits of both operands are zero (i.e. we can prove they are
3112 // unsigned inputs), turn this into a udiv.
3113 if (I.getType()->isInteger()) {
3114 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3115 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3116 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3117 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3124 Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3125 return commonDivTransforms(I);
3128 /// This function implements the transforms on rem instructions that work
3129 /// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3130 /// is used by the visitors to those instructions.
3131 /// @brief Transforms common to all three rem instructions
3132 Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3133 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3135 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3136 if (I.getType()->isFPOrFPVector())
3137 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
3138 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3140 if (isa<UndefValue>(Op1))
3141 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3143 // Handle cases involving: rem X, (select Cond, Y, Z)
3144 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3150 /// This function implements the transforms common to both integer remainder
3151 /// instructions (urem and srem). It is called by the visitors to those integer
3152 /// remainder instructions.
3153 /// @brief Common integer remainder transforms
3154 Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3155 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3157 if (Instruction *common = commonRemTransforms(I))
3160 // 0 % X == 0 for integer, we don't need to preserve faults!
3161 if (Constant *LHS = dyn_cast<Constant>(Op0))
3162 if (LHS->isNullValue())
3163 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3165 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3166 // X % 0 == undef, we don't need to preserve faults!
3167 if (RHS->equalsInt(0))
3168 return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
3170 if (RHS->equalsInt(1)) // X % 1 == 0
3171 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3173 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3174 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3175 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3177 } else if (isa<PHINode>(Op0I)) {
3178 if (Instruction *NV = FoldOpIntoPhi(I))
3182 // See if we can fold away this rem instruction.
3183 if (SimplifyDemandedInstructionBits(I))
3191 Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3192 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3194 if (Instruction *common = commonIRemTransforms(I))
3197 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3198 // X urem C^2 -> X and C
3199 // Check to see if this is an unsigned remainder with an exact power of 2,
3200 // if so, convert to a bitwise and.
3201 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3202 if (C->getValue().isPowerOf2())
3203 return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
3206 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3207 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3208 if (RHSI->getOpcode() == Instruction::Shl &&
3209 isa<ConstantInt>(RHSI->getOperand(0))) {
3210 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3211 Constant *N1 = Context->getConstantIntAllOnesValue(I.getType());
3212 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
3214 return BinaryOperator::CreateAnd(Op0, Add);
3219 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3220 // where C1&C2 are powers of two.
3221 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3222 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3223 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3224 // STO == 0 and SFO == 0 handled above.
3225 if ((STO->getValue().isPowerOf2()) &&
3226 (SFO->getValue().isPowerOf2())) {
3227 Value *TrueAnd = InsertNewInstBefore(
3228 BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3229 SI->getName()+".t"), I);
3230 Value *FalseAnd = InsertNewInstBefore(
3231 BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3232 SI->getName()+".f"), I);
3233 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
3241 Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3242 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3244 // Handle the integer rem common cases
3245 if (Instruction *common = commonIRemTransforms(I))
3248 if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
3249 if (!isa<Constant>(RHSNeg) ||
3250 (isa<ConstantInt>(RHSNeg) &&
3251 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
3253 AddUsesToWorkList(I);
3254 I.setOperand(1, RHSNeg);
3258 // If the sign bits of both operands are zero (i.e. we can prove they are
3259 // unsigned inputs), turn this into a urem.
3260 if (I.getType()->isInteger()) {
3261 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3262 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3263 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
3264 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
3268 // If it's a constant vector, flip any negative values positive.
3269 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3270 unsigned VWidth = RHSV->getNumOperands();
3272 bool hasNegative = false;
3273 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3274 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3275 if (RHS->getValue().isNegative())
3279 std::vector<Constant *> Elts(VWidth);
3280 for (unsigned i = 0; i != VWidth; ++i) {
3281 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3282 if (RHS->getValue().isNegative())
3283 Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
3289 Constant *NewRHSV = Context->getConstantVector(Elts);
3290 if (NewRHSV != RHSV) {
3291 AddUsesToWorkList(I);
3292 I.setOperand(1, NewRHSV);
3301 Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3302 return commonRemTransforms(I);
3305 // isOneBitSet - Return true if there is exactly one bit set in the specified
3307 static bool isOneBitSet(const ConstantInt *CI) {
3308 return CI->getValue().isPowerOf2();
3311 // isHighOnes - Return true if the constant is of the form 1+0+.
3312 // This is the same as lowones(~X).
3313 static bool isHighOnes(const ConstantInt *CI) {
3314 return (~CI->getValue() + 1).isPowerOf2();
3317 /// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3318 /// are carefully arranged to allow folding of expressions such as:
3320 /// (A < B) | (A > B) --> (A != B)
3322 /// Note that this is only valid if the first and second predicates have the
3323 /// same sign. Is illegal to do: (A u< B) | (A s> B)
3325 /// Three bits are used to represent the condition, as follows:
3330 /// <=> Value Definition
3331 /// 000 0 Always false
3338 /// 111 7 Always true
3340 static unsigned getICmpCode(const ICmpInst *ICI) {
3341 switch (ICI->getPredicate()) {
3343 case ICmpInst::ICMP_UGT: return 1; // 001
3344 case ICmpInst::ICMP_SGT: return 1; // 001
3345 case ICmpInst::ICMP_EQ: return 2; // 010
3346 case ICmpInst::ICMP_UGE: return 3; // 011
3347 case ICmpInst::ICMP_SGE: return 3; // 011
3348 case ICmpInst::ICMP_ULT: return 4; // 100
3349 case ICmpInst::ICMP_SLT: return 4; // 100
3350 case ICmpInst::ICMP_NE: return 5; // 101
3351 case ICmpInst::ICMP_ULE: return 6; // 110
3352 case ICmpInst::ICMP_SLE: return 6; // 110
3355 assert(0 && "Invalid ICmp predicate!");
3360 /// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3361 /// predicate into a three bit mask. It also returns whether it is an ordered
3362 /// predicate by reference.
3363 static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3366 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3367 case FCmpInst::FCMP_UNO: return 0; // 000
3368 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3369 case FCmpInst::FCMP_UGT: return 1; // 001
3370 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3371 case FCmpInst::FCMP_UEQ: return 2; // 010
3372 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3373 case FCmpInst::FCMP_UGE: return 3; // 011
3374 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3375 case FCmpInst::FCMP_ULT: return 4; // 100
3376 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3377 case FCmpInst::FCMP_UNE: return 5; // 101
3378 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3379 case FCmpInst::FCMP_ULE: return 6; // 110
3382 // Not expecting FCMP_FALSE and FCMP_TRUE;
3383 assert(0 && "Unexpected FCmp predicate!");
3388 /// getICmpValue - This is the complement of getICmpCode, which turns an
3389 /// opcode and two operands into either a constant true or false, or a brand
3390 /// new ICmp instruction. The sign is passed in to determine which kind
3391 /// of predicate to use in the new icmp instruction.
3392 static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
3393 LLVMContext *Context) {
3395 default: assert(0 && "Illegal ICmp code!");
3396 case 0: return Context->getConstantIntFalse();
3399 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
3401 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3402 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
3405 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
3407 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
3410 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
3412 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3413 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
3416 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
3418 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
3419 case 7: return Context->getConstantIntTrue();
3423 /// getFCmpValue - This is the complement of getFCmpCode, which turns an
3424 /// opcode and two operands into either a FCmp instruction. isordered is passed
3425 /// in to determine which kind of predicate to use in the new fcmp instruction.
3426 static Value *getFCmpValue(bool isordered, unsigned code,
3427 Value *LHS, Value *RHS, LLVMContext *Context) {
3429 default: assert(0 && "Illegal FCmp code!");
3432 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
3434 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
3437 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
3439 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
3442 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
3444 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
3447 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
3449 return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
3452 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
3454 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
3457 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
3459 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
3462 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
3464 return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
3465 case 7: return Context->getConstantIntTrue();
3469 /// PredicatesFoldable - Return true if both predicates match sign or if at
3470 /// least one of them is an equality comparison (which is signless).
3471 static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3472 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3473 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3474 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
3478 // FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3479 struct FoldICmpLogical {
3482 ICmpInst::Predicate pred;
3483 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3484 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3485 pred(ICI->getPredicate()) {}
3486 bool shouldApply(Value *V) const {
3487 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3488 if (PredicatesFoldable(pred, ICI->getPredicate()))
3489 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3490 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
3493 Instruction *apply(Instruction &Log) const {
3494 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3495 if (ICI->getOperand(0) != LHS) {
3496 assert(ICI->getOperand(1) == LHS);
3497 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3500 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3501 unsigned LHSCode = getICmpCode(ICI);
3502 unsigned RHSCode = getICmpCode(RHSICI);
3504 switch (Log.getOpcode()) {
3505 case Instruction::And: Code = LHSCode & RHSCode; break;
3506 case Instruction::Or: Code = LHSCode | RHSCode; break;
3507 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3508 default: assert(0 && "Illegal logical opcode!"); return 0;
3511 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3512 ICmpInst::isSignedPredicate(ICI->getPredicate());
3514 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
3515 if (Instruction *I = dyn_cast<Instruction>(RV))
3517 // Otherwise, it's a constant boolean value...
3518 return IC.ReplaceInstUsesWith(Log, RV);
3521 } // end anonymous namespace
3523 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3524 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3525 // guaranteed to be a binary operator.
3526 Instruction *InstCombiner::OptAndOp(Instruction *Op,
3528 ConstantInt *AndRHS,
3529 BinaryOperator &TheAnd) {
3530 Value *X = Op->getOperand(0);
3531 Constant *Together = 0;
3533 Together = Context->getConstantExprAnd(AndRHS, OpRHS);
3535 switch (Op->getOpcode()) {
3536 case Instruction::Xor:
3537 if (Op->hasOneUse()) {
3538 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3539 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
3540 InsertNewInstBefore(And, TheAnd);
3542 return BinaryOperator::CreateXor(And, Together);
3545 case Instruction::Or:
3546 if (Together == AndRHS) // (X | C) & C --> C
3547 return ReplaceInstUsesWith(TheAnd, AndRHS);
3549 if (Op->hasOneUse() && Together != OpRHS) {
3550 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3551 Instruction *Or = BinaryOperator::CreateOr(X, Together);
3552 InsertNewInstBefore(Or, TheAnd);
3554 return BinaryOperator::CreateAnd(Or, AndRHS);
3557 case Instruction::Add:
3558 if (Op->hasOneUse()) {
3559 // Adding a one to a single bit bit-field should be turned into an XOR
3560 // of the bit. First thing to check is to see if this AND is with a
3561 // single bit constant.
3562 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3564 // If there is only one bit set...
3565 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3566 // Ok, at this point, we know that we are masking the result of the
3567 // ADD down to exactly one bit. If the constant we are adding has
3568 // no bits set below this bit, then we can eliminate the ADD.
3569 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3571 // Check to see if any bits below the one bit set in AndRHSV are set.
3572 if ((AddRHS & (AndRHSV-1)) == 0) {
3573 // If not, the only thing that can effect the output of the AND is
3574 // the bit specified by AndRHSV. If that bit is set, the effect of
3575 // the XOR is to toggle the bit. If it is clear, then the ADD has
3577 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3578 TheAnd.setOperand(0, X);
3581 // Pull the XOR out of the AND.
3582 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
3583 InsertNewInstBefore(NewAnd, TheAnd);
3584 NewAnd->takeName(Op);
3585 return BinaryOperator::CreateXor(NewAnd, AndRHS);
3592 case Instruction::Shl: {
3593 // We know that the AND will not produce any of the bits shifted in, so if
3594 // the anded constant includes them, clear them now!
3596 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3597 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3598 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3599 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
3601 if (CI->getValue() == ShlMask) {
3602 // Masking out bits that the shift already masks
3603 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3604 } else if (CI != AndRHS) { // Reducing bits set in and.
3605 TheAnd.setOperand(1, CI);
3610 case Instruction::LShr:
3612 // We know that the AND will not produce any of the bits shifted in, so if
3613 // the anded constant includes them, clear them now! This only applies to
3614 // unsigned shifts, because a signed shr may bring in set bits!
3616 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3617 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3618 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3619 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3621 if (CI->getValue() == ShrMask) {
3622 // Masking out bits that the shift already masks.
3623 return ReplaceInstUsesWith(TheAnd, Op);
3624 } else if (CI != AndRHS) {
3625 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3630 case Instruction::AShr:
3632 // See if this is shifting in some sign extension, then masking it out
3634 if (Op->hasOneUse()) {
3635 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3636 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3637 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3638 Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
3639 if (C == AndRHS) { // Masking out bits shifted in.
3640 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3641 // Make the argument unsigned.
3642 Value *ShVal = Op->getOperand(0);
3643 ShVal = InsertNewInstBefore(
3644 BinaryOperator::CreateLShr(ShVal, OpRHS,
3645 Op->getName()), TheAnd);
3646 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
3655 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3656 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3657 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3658 /// whether to treat the V, Lo and HI as signed or not. IB is the location to
3659 /// insert new instructions.
3660 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3661 bool isSigned, bool Inside,
3663 assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ?
3664 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3665 "Lo is not <= Hi in range emission code!");
3668 if (Lo == Hi) // Trivially false.
3669 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
3671 // V >= Min && V < Hi --> V < Hi
3672 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3673 ICmpInst::Predicate pred = (isSigned ?
3674 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3675 return new ICmpInst(*Context, pred, V, Hi);
3678 // Emit V-Lo <u Hi-Lo
3679 Constant *NegLo = Context->getConstantExprNeg(Lo);
3680 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3681 InsertNewInstBefore(Add, IB);
3682 Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
3683 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
3686 if (Lo == Hi) // Trivially true.
3687 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
3689 // V < Min || V >= Hi -> V > Hi-1
3690 Hi = SubOne(cast<ConstantInt>(Hi), Context);
3691 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3692 ICmpInst::Predicate pred = (isSigned ?
3693 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3694 return new ICmpInst(*Context, pred, V, Hi);
3697 // Emit V-Lo >u Hi-1-Lo
3698 // Note that Hi has already had one subtracted from it, above.
3699 ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
3700 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
3701 InsertNewInstBefore(Add, IB);
3702 Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
3703 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
3706 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3707 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
3708 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3709 // not, since all 1s are not contiguous.
3710 static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3711 const APInt& V = Val->getValue();
3712 uint32_t BitWidth = Val->getType()->getBitWidth();
3713 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3715 // look for the first zero bit after the run of ones
3716 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3717 // look for the first non-zero bit
3718 ME = V.getActiveBits();
3722 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3723 /// where isSub determines whether the operator is a sub. If we can fold one of
3724 /// the following xforms:
3726 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3727 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3728 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3730 /// return (A +/- B).
3732 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3733 ConstantInt *Mask, bool isSub,
3735 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3736 if (!LHSI || LHSI->getNumOperands() != 2 ||
3737 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3739 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3741 switch (LHSI->getOpcode()) {
3743 case Instruction::And:
3744 if (Context->getConstantExprAnd(N, Mask) == Mask) {
3745 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3746 if ((Mask->getValue().countLeadingZeros() +
3747 Mask->getValue().countPopulation()) ==
3748 Mask->getValue().getBitWidth())
3751 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3752 // part, we don't need any explicit masks to take them out of A. If that
3753 // is all N is, ignore it.
3754 uint32_t MB = 0, ME = 0;
3755 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3756 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3757 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3758 if (MaskedValueIsZero(RHS, Mask))
3763 case Instruction::Or:
3764 case Instruction::Xor:
3765 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3766 if ((Mask->getValue().countLeadingZeros() +
3767 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3768 && Context->getConstantExprAnd(N, Mask)->isNullValue())
3775 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
3777 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
3778 return InsertNewInstBefore(New, I);
3781 /// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3782 Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3783 ICmpInst *LHS, ICmpInst *RHS) {
3785 ConstantInt *LHSCst, *RHSCst;
3786 ICmpInst::Predicate LHSCC, RHSCC;
3788 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
3789 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
3790 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
3793 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3794 // where C is a power of 2
3795 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3796 LHSCst->getValue().isPowerOf2()) {
3797 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3798 InsertNewInstBefore(NewOr, I);
3799 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
3802 // From here on, we only handle:
3803 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3804 if (Val != Val2) return 0;
3806 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3807 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3808 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3809 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3810 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3813 // We can't fold (ugt x, C) & (sgt x, C2).
3814 if (!PredicatesFoldable(LHSCC, RHSCC))
3817 // Ensure that the larger constant is on the RHS.
3819 if (ICmpInst::isSignedPredicate(LHSCC) ||
3820 (ICmpInst::isEquality(LHSCC) &&
3821 ICmpInst::isSignedPredicate(RHSCC)))
3822 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3824 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3827 std::swap(LHS, RHS);
3828 std::swap(LHSCst, RHSCst);
3829 std::swap(LHSCC, RHSCC);
3832 // At this point, we know we have have two icmp instructions
3833 // comparing a value against two constants and and'ing the result
3834 // together. Because of the above check, we know that we only have
3835 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3836 // (from the FoldICmpLogical check above), that the two constants
3837 // are not equal and that the larger constant is on the RHS
3838 assert(LHSCst != RHSCst && "Compares not folded above?");
3841 default: assert(0 && "Unknown integer condition code!");
3842 case ICmpInst::ICMP_EQ:
3844 default: assert(0 && "Unknown integer condition code!");
3845 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3846 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3847 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3848 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3849 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3850 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3851 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3852 return ReplaceInstUsesWith(I, LHS);
3854 case ICmpInst::ICMP_NE:
3856 default: assert(0 && "Unknown integer condition code!");
3857 case ICmpInst::ICMP_ULT:
3858 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
3859 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
3860 break; // (X != 13 & X u< 15) -> no change
3861 case ICmpInst::ICMP_SLT:
3862 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
3863 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
3864 break; // (X != 13 & X s< 15) -> no change
3865 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3866 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3867 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3868 return ReplaceInstUsesWith(I, RHS);
3869 case ICmpInst::ICMP_NE:
3870 if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3871 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
3872 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3873 Val->getName()+".off");
3874 InsertNewInstBefore(Add, I);
3875 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
3876 Context->getConstantInt(Add->getType(), 1));
3878 break; // (X != 13 & X != 15) -> no change
3881 case ICmpInst::ICMP_ULT:
3883 default: assert(0 && "Unknown integer condition code!");
3884 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3885 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3886 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3887 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3889 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3890 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3891 return ReplaceInstUsesWith(I, LHS);
3892 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3896 case ICmpInst::ICMP_SLT:
3898 default: assert(0 && "Unknown integer condition code!");
3899 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3900 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3901 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
3902 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3904 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3905 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3906 return ReplaceInstUsesWith(I, LHS);
3907 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3911 case ICmpInst::ICMP_UGT:
3913 default: assert(0 && "Unknown integer condition code!");
3914 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3915 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3916 return ReplaceInstUsesWith(I, RHS);
3917 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3919 case ICmpInst::ICMP_NE:
3920 if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
3921 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3922 break; // (X u> 13 & X != 15) -> no change
3923 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
3924 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3925 RHSCst, false, true, I);
3926 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3930 case ICmpInst::ICMP_SGT:
3932 default: assert(0 && "Unknown integer condition code!");
3933 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3934 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3935 return ReplaceInstUsesWith(I, RHS);
3936 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3938 case ICmpInst::ICMP_NE:
3939 if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
3940 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
3941 break; // (X s> 13 & X != 15) -> no change
3942 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
3943 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3944 RHSCst, true, true, I);
3945 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3955 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3956 bool Changed = SimplifyCommutative(I);
3957 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3959 if (isa<UndefValue>(Op1)) // X & undef -> 0
3960 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
3964 return ReplaceInstUsesWith(I, Op1);
3966 // See if we can simplify any instructions used by the instruction whose sole
3967 // purpose is to compute bits we don't care about.
3968 if (SimplifyDemandedInstructionBits(I))
3970 if (isa<VectorType>(I.getType())) {
3971 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3972 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3973 return ReplaceInstUsesWith(I, I.getOperand(0));
3974 } else if (isa<ConstantAggregateZero>(Op1)) {
3975 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3979 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3980 const APInt& AndRHSMask = AndRHS->getValue();
3981 APInt NotAndRHS(~AndRHSMask);
3983 // Optimize a variety of ((val OP C1) & C2) combinations...
3984 if (isa<BinaryOperator>(Op0)) {
3985 Instruction *Op0I = cast<Instruction>(Op0);
3986 Value *Op0LHS = Op0I->getOperand(0);
3987 Value *Op0RHS = Op0I->getOperand(1);
3988 switch (Op0I->getOpcode()) {
3989 case Instruction::Xor:
3990 case Instruction::Or:
3991 // If the mask is only needed on one incoming arm, push it up.
3992 if (Op0I->hasOneUse()) {
3993 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3994 // Not masking anything out for the LHS, move to RHS.
3995 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
3996 Op0RHS->getName()+".masked");
3997 InsertNewInstBefore(NewRHS, I);
3998 return BinaryOperator::Create(
3999 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4001 if (!isa<Constant>(Op0RHS) &&
4002 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4003 // Not masking anything out for the RHS, move to LHS.
4004 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
4005 Op0LHS->getName()+".masked");
4006 InsertNewInstBefore(NewLHS, I);
4007 return BinaryOperator::Create(
4008 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4013 case Instruction::Add:
4014 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4015 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4016 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4017 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
4018 return BinaryOperator::CreateAnd(V, AndRHS);
4019 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
4020 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
4023 case Instruction::Sub:
4024 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4025 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4026 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4027 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
4028 return BinaryOperator::CreateAnd(V, AndRHS);
4030 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4031 // has 1's for all bits that the subtraction with A might affect.
4032 if (Op0I->hasOneUse()) {
4033 uint32_t BitWidth = AndRHSMask.getBitWidth();
4034 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4035 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4037 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
4038 if (!(A && A->isZero()) && // avoid infinite recursion.
4039 MaskedValueIsZero(Op0LHS, Mask)) {
4040 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
4041 InsertNewInstBefore(NewNeg, I);
4042 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4047 case Instruction::Shl:
4048 case Instruction::LShr:
4049 // (1 << x) & 1 --> zext(x == 0)
4050 // (1 >> x) & 1 --> zext(x == 0)
4051 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
4052 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4053 Op0RHS, Context->getNullValue(I.getType()));
4054 InsertNewInstBefore(NewICmp, I);
4055 return new ZExtInst(NewICmp, I.getType());
4060 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4061 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4063 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4064 // If this is an integer truncation or change from signed-to-unsigned, and
4065 // if the source is an and/or with immediate, transform it. This
4066 // frequently occurs for bitfield accesses.
4067 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4068 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4069 CastOp->getNumOperands() == 2)
4070 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
4071 if (CastOp->getOpcode() == Instruction::And) {
4072 // Change: and (cast (and X, C1) to T), C2
4073 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4074 // This will fold the two constants together, which may allow
4075 // other simplifications.
4076 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
4077 CastOp->getOperand(0), I.getType(),
4078 CastOp->getName()+".shrunk");
4079 NewCast = InsertNewInstBefore(NewCast, I);
4080 // trunc_or_bitcast(C1)&C2
4082 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4083 C3 = Context->getConstantExprAnd(C3, AndRHS);
4084 return BinaryOperator::CreateAnd(NewCast, C3);
4085 } else if (CastOp->getOpcode() == Instruction::Or) {
4086 // Change: and (cast (or X, C1) to T), C2
4087 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
4089 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4090 if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4092 return ReplaceInstUsesWith(I, AndRHS);
4098 // Try to fold constant and into select arguments.
4099 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4100 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4102 if (isa<PHINode>(Op0))
4103 if (Instruction *NV = FoldOpIntoPhi(I))
4107 Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4108 Value *Op1NotVal = dyn_castNotVal(Op1, Context);
4110 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
4111 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
4113 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4114 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4115 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
4116 I.getName()+".demorgan");
4117 InsertNewInstBefore(Or, I);
4118 return BinaryOperator::CreateNot(Or);
4122 Value *A = 0, *B = 0, *C = 0, *D = 0;
4123 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
4124 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4125 return ReplaceInstUsesWith(I, Op1);
4127 // (A|B) & ~(A&B) -> A^B
4128 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
4129 if ((A == C && B == D) || (A == D && B == C))
4130 return BinaryOperator::CreateXor(A, B);
4134 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
4135 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4136 return ReplaceInstUsesWith(I, Op0);
4138 // ~(A&B) & (A|B) -> A^B
4139 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
4140 if ((A == C && B == D) || (A == D && B == C))
4141 return BinaryOperator::CreateXor(A, B);
4145 if (Op0->hasOneUse() &&
4146 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
4147 if (A == Op1) { // (A^B)&A -> A&(A^B)
4148 I.swapOperands(); // Simplify below
4149 std::swap(Op0, Op1);
4150 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4151 cast<BinaryOperator>(Op0)->swapOperands();
4152 I.swapOperands(); // Simplify below
4153 std::swap(Op0, Op1);
4157 if (Op1->hasOneUse() &&
4158 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
4159 if (B == Op0) { // B&(A^B) -> B&(B^A)
4160 cast<BinaryOperator>(Op1)->swapOperands();
4163 if (A == Op0) { // A&(A^B) -> A & ~B
4164 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
4165 InsertNewInstBefore(NotB, I);
4166 return BinaryOperator::CreateAnd(A, NotB);
4170 // (A&((~A)|B)) -> A&B
4171 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4172 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
4173 return BinaryOperator::CreateAnd(A, Op1);
4174 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4175 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
4176 return BinaryOperator::CreateAnd(A, Op0);
4179 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4180 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4181 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4184 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4185 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4189 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4190 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4191 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4192 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4193 const Type *SrcTy = Op0C->getOperand(0)->getType();
4194 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4195 // Only do this if the casts both really cause code to be generated.
4196 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4198 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4200 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
4201 Op1C->getOperand(0),
4203 InsertNewInstBefore(NewOp, I);
4204 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4208 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4209 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4210 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4211 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4212 SI0->getOperand(1) == SI1->getOperand(1) &&
4213 (SI0->hasOneUse() || SI1->hasOneUse())) {
4214 Instruction *NewOp =
4215 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
4217 SI0->getName()), I);
4218 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4219 SI1->getOperand(1));
4223 // If and'ing two fcmp, try combine them into one.
4224 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4225 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4226 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4227 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4228 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4229 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4230 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4231 // If either of the constants are nans, then the whole thing returns
4233 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4234 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4235 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
4236 LHS->getOperand(0), RHS->getOperand(0));
4239 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4240 FCmpInst::Predicate Op0CC, Op1CC;
4241 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4242 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4243 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4244 // Swap RHS operands to match LHS.
4245 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4246 std::swap(Op1LHS, Op1RHS);
4248 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4249 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4251 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4253 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4254 Op1CC == FCmpInst::FCMP_FALSE)
4255 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4256 else if (Op0CC == FCmpInst::FCMP_TRUE)
4257 return ReplaceInstUsesWith(I, Op1);
4258 else if (Op1CC == FCmpInst::FCMP_TRUE)
4259 return ReplaceInstUsesWith(I, Op0);
4262 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4263 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4265 std::swap(Op0, Op1);
4266 std::swap(Op0Pred, Op1Pred);
4267 std::swap(Op0Ordered, Op1Ordered);
4270 // uno && ueq -> uno && (uno || eq) -> ueq
4271 // ord && olt -> ord && (ord && lt) -> olt
4272 if (Op0Ordered == Op1Ordered)
4273 return ReplaceInstUsesWith(I, Op1);
4274 // uno && oeq -> uno && (ord && eq) -> false
4275 // uno && ord -> false
4277 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
4278 // ord && ueq -> ord && (uno || eq) -> oeq
4279 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4280 Op0LHS, Op0RHS, Context));
4288 return Changed ? &I : 0;
4291 /// CollectBSwapParts - Analyze the specified subexpression and see if it is
4292 /// capable of providing pieces of a bswap. The subexpression provides pieces
4293 /// of a bswap if it is proven that each of the non-zero bytes in the output of
4294 /// the expression came from the corresponding "byte swapped" byte in some other
4295 /// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4296 /// we know that the expression deposits the low byte of %X into the high byte
4297 /// of the bswap result and that all other bytes are zero. This expression is
4298 /// accepted, the high byte of ByteValues is set to X to indicate a correct
4301 /// This function returns true if the match was unsuccessful and false if so.
4302 /// On entry to the function the "OverallLeftShift" is a signed integer value
4303 /// indicating the number of bytes that the subexpression is later shifted. For
4304 /// example, if the expression is later right shifted by 16 bits, the
4305 /// OverallLeftShift value would be -2 on entry. This is used to specify which
4306 /// byte of ByteValues is actually being set.
4308 /// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4309 /// byte is masked to zero by a user. For example, in (X & 255), X will be
4310 /// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4311 /// this function to working on up to 32-byte (256 bit) values. ByteMask is
4312 /// always in the local (OverallLeftShift) coordinate space.
4314 static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4315 SmallVector<Value*, 8> &ByteValues) {
4316 if (Instruction *I = dyn_cast<Instruction>(V)) {
4317 // If this is an or instruction, it may be an inner node of the bswap.
4318 if (I->getOpcode() == Instruction::Or) {
4319 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4321 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4325 // If this is a logical shift by a constant multiple of 8, recurse with
4326 // OverallLeftShift and ByteMask adjusted.
4327 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4329 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4330 // Ensure the shift amount is defined and of a byte value.
4331 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4334 unsigned ByteShift = ShAmt >> 3;
4335 if (I->getOpcode() == Instruction::Shl) {
4336 // X << 2 -> collect(X, +2)
4337 OverallLeftShift += ByteShift;
4338 ByteMask >>= ByteShift;
4340 // X >>u 2 -> collect(X, -2)
4341 OverallLeftShift -= ByteShift;
4342 ByteMask <<= ByteShift;
4343 ByteMask &= (~0U >> (32-ByteValues.size()));
4346 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4347 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4349 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4353 // If this is a logical 'and' with a mask that clears bytes, clear the
4354 // corresponding bytes in ByteMask.
4355 if (I->getOpcode() == Instruction::And &&
4356 isa<ConstantInt>(I->getOperand(1))) {
4357 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4358 unsigned NumBytes = ByteValues.size();
4359 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4360 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4362 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4363 // If this byte is masked out by a later operation, we don't care what
4365 if ((ByteMask & (1 << i)) == 0)
4368 // If the AndMask is all zeros for this byte, clear the bit.
4369 APInt MaskB = AndMask & Byte;
4371 ByteMask &= ~(1U << i);
4375 // If the AndMask is not all ones for this byte, it's not a bytezap.
4379 // Otherwise, this byte is kept.
4382 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4387 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4388 // the input value to the bswap. Some observations: 1) if more than one byte
4389 // is demanded from this input, then it could not be successfully assembled
4390 // into a byteswap. At least one of the two bytes would not be aligned with
4391 // their ultimate destination.
4392 if (!isPowerOf2_32(ByteMask)) return true;
4393 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
4395 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4396 // is demanded, it needs to go into byte 0 of the result. This means that the
4397 // byte needs to be shifted until it lands in the right byte bucket. The
4398 // shift amount depends on the position: if the byte is coming from the high
4399 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4400 // low part, it must be shifted left.
4401 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4402 if (InputByteNo < ByteValues.size()/2) {
4403 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4406 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4410 // If the destination byte value is already defined, the values are or'd
4411 // together, which isn't a bswap (unless it's an or of the same bits).
4412 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
4414 ByteValues[DestByteNo] = V;
4418 /// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4419 /// If so, insert the new bswap intrinsic and return it.
4420 Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4421 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4422 if (!ITy || ITy->getBitWidth() % 16 ||
4423 // ByteMask only allows up to 32-byte values.
4424 ITy->getBitWidth() > 32*8)
4425 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4427 /// ByteValues - For each byte of the result, we keep track of which value
4428 /// defines each byte.
4429 SmallVector<Value*, 8> ByteValues;
4430 ByteValues.resize(ITy->getBitWidth()/8);
4432 // Try to find all the pieces corresponding to the bswap.
4433 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4434 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
4437 // Check to see if all of the bytes come from the same value.
4438 Value *V = ByteValues[0];
4439 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4441 // Check to make sure that all of the bytes come from the same value.
4442 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4443 if (ByteValues[i] != V)
4445 const Type *Tys[] = { ITy };
4446 Module *M = I.getParent()->getParent()->getParent();
4447 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
4448 return CallInst::Create(F, V);
4451 /// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4452 /// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4453 /// we can simplify this expression to "cond ? C : D or B".
4454 static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4455 Value *C, Value *D) {
4456 // If A is not a select of -1/0, this cannot match.
4458 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
4461 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
4462 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
4463 return SelectInst::Create(Cond, C, B);
4464 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4465 return SelectInst::Create(Cond, C, B);
4466 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
4467 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
4468 return SelectInst::Create(Cond, C, D);
4469 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
4470 return SelectInst::Create(Cond, C, D);
4474 /// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4475 Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4476 ICmpInst *LHS, ICmpInst *RHS) {
4478 ConstantInt *LHSCst, *RHSCst;
4479 ICmpInst::Predicate LHSCC, RHSCC;
4481 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4482 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4483 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4486 // From here on, we only handle:
4487 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4488 if (Val != Val2) return 0;
4490 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4491 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4492 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4493 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4494 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4497 // We can't fold (ugt x, C) | (sgt x, C2).
4498 if (!PredicatesFoldable(LHSCC, RHSCC))
4501 // Ensure that the larger constant is on the RHS.
4503 if (ICmpInst::isSignedPredicate(LHSCC) ||
4504 (ICmpInst::isEquality(LHSCC) &&
4505 ICmpInst::isSignedPredicate(RHSCC)))
4506 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4508 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4511 std::swap(LHS, RHS);
4512 std::swap(LHSCst, RHSCst);
4513 std::swap(LHSCC, RHSCC);
4516 // At this point, we know we have have two icmp instructions
4517 // comparing a value against two constants and or'ing the result
4518 // together. Because of the above check, we know that we only have
4519 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4520 // FoldICmpLogical check above), that the two constants are not
4522 assert(LHSCst != RHSCst && "Compares not folded above?");
4525 default: assert(0 && "Unknown integer condition code!");
4526 case ICmpInst::ICMP_EQ:
4528 default: assert(0 && "Unknown integer condition code!");
4529 case ICmpInst::ICMP_EQ:
4530 if (LHSCst == SubOne(RHSCst, Context)) {
4531 // (X == 13 | X == 14) -> X-13 <u 2
4532 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
4533 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4534 Val->getName()+".off");
4535 InsertNewInstBefore(Add, I);
4536 AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
4537 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
4539 break; // (X == 13 | X == 15) -> no change
4540 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4541 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4543 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4544 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4545 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4546 return ReplaceInstUsesWith(I, RHS);
4549 case ICmpInst::ICMP_NE:
4551 default: assert(0 && "Unknown integer condition code!");
4552 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4553 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4554 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4555 return ReplaceInstUsesWith(I, LHS);
4556 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4557 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4558 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4559 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4562 case ICmpInst::ICMP_ULT:
4564 default: assert(0 && "Unknown integer condition code!");
4565 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4567 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4568 // If RHSCst is [us]MAXINT, it is always false. Not handling
4569 // this can cause overflow.
4570 if (RHSCst->isMaxValue(false))
4571 return ReplaceInstUsesWith(I, LHS);
4572 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4574 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4576 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4577 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4578 return ReplaceInstUsesWith(I, RHS);
4579 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4583 case ICmpInst::ICMP_SLT:
4585 default: assert(0 && "Unknown integer condition code!");
4586 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4588 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4589 // If RHSCst is [us]MAXINT, it is always false. Not handling
4590 // this can cause overflow.
4591 if (RHSCst->isMaxValue(true))
4592 return ReplaceInstUsesWith(I, LHS);
4593 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4595 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4597 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4598 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4599 return ReplaceInstUsesWith(I, RHS);
4600 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4604 case ICmpInst::ICMP_UGT:
4606 default: assert(0 && "Unknown integer condition code!");
4607 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4608 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4609 return ReplaceInstUsesWith(I, LHS);
4610 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4612 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4613 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4614 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4615 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4619 case ICmpInst::ICMP_SGT:
4621 default: assert(0 && "Unknown integer condition code!");
4622 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4623 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4624 return ReplaceInstUsesWith(I, LHS);
4625 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4627 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4628 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4629 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4630 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4638 /// FoldOrWithConstants - This helper function folds:
4640 /// ((A | B) & C1) | (B & C2)
4646 /// when the XOR of the two constants is "all ones" (-1).
4647 Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
4648 Value *A, Value *B, Value *C) {
4649 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4653 ConstantInt *CI2 = 0;
4654 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
4656 APInt Xor = CI1->getValue() ^ CI2->getValue();
4657 if (!Xor.isAllOnesValue()) return 0;
4659 if (V1 == A || V1 == B) {
4660 Instruction *NewOp =
4661 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4662 return BinaryOperator::CreateOr(NewOp, V1);
4668 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4669 bool Changed = SimplifyCommutative(I);
4670 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4672 if (isa<UndefValue>(Op1)) // X | undef -> -1
4673 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4677 return ReplaceInstUsesWith(I, Op0);
4679 // See if we can simplify any instructions used by the instruction whose sole
4680 // purpose is to compute bits we don't care about.
4681 if (SimplifyDemandedInstructionBits(I))
4683 if (isa<VectorType>(I.getType())) {
4684 if (isa<ConstantAggregateZero>(Op1)) {
4685 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4686 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4687 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4688 return ReplaceInstUsesWith(I, I.getOperand(1));
4693 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4694 ConstantInt *C1 = 0; Value *X = 0;
4695 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4696 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4697 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4698 InsertNewInstBefore(Or, I);
4700 return BinaryOperator::CreateAnd(Or,
4701 Context->getConstantInt(RHS->getValue() | C1->getValue()));
4704 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4705 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
4706 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
4707 InsertNewInstBefore(Or, I);
4709 return BinaryOperator::CreateXor(Or,
4710 Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
4713 // Try to fold constant and into select arguments.
4714 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4715 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4717 if (isa<PHINode>(Op0))
4718 if (Instruction *NV = FoldOpIntoPhi(I))
4722 Value *A = 0, *B = 0;
4723 ConstantInt *C1 = 0, *C2 = 0;
4725 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4726 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4727 return ReplaceInstUsesWith(I, Op1);
4728 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4729 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4730 return ReplaceInstUsesWith(I, Op0);
4732 // (A | B) | C and A | (B | C) -> bswap if possible.
4733 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4734 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4735 match(Op1, m_Or(m_Value(), m_Value())) ||
4736 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4737 match(Op1, m_Shift(m_Value(), m_Value())))) {
4738 if (Instruction *BSwap = MatchBSwap(I))
4742 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4743 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4744 MaskedValueIsZero(Op1, C1->getValue())) {
4745 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
4746 InsertNewInstBefore(NOr, I);
4748 return BinaryOperator::CreateXor(NOr, C1);
4751 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4752 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4753 MaskedValueIsZero(Op0, C1->getValue())) {
4754 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
4755 InsertNewInstBefore(NOr, I);
4757 return BinaryOperator::CreateXor(NOr, C1);
4761 Value *C = 0, *D = 0;
4762 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4763 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4764 Value *V1 = 0, *V2 = 0, *V3 = 0;
4765 C1 = dyn_cast<ConstantInt>(C);
4766 C2 = dyn_cast<ConstantInt>(D);
4767 if (C1 && C2) { // (A & C1)|(B & C2)
4768 // If we have: ((V + N) & C1) | (V & C2)
4769 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4770 // replace with V+N.
4771 if (C1->getValue() == ~C2->getValue()) {
4772 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4773 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4774 // Add commutes, try both ways.
4775 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4776 return ReplaceInstUsesWith(I, A);
4777 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4778 return ReplaceInstUsesWith(I, A);
4780 // Or commutes, try both ways.
4781 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4782 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4783 // Add commutes, try both ways.
4784 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4785 return ReplaceInstUsesWith(I, B);
4786 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4787 return ReplaceInstUsesWith(I, B);
4790 V1 = 0; V2 = 0; V3 = 0;
4793 // Check to see if we have any common things being and'ed. If so, find the
4794 // terms for V1 & (V2|V3).
4795 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4796 if (A == B) // (A & C)|(A & D) == A & (C|D)
4797 V1 = A, V2 = C, V3 = D;
4798 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4799 V1 = A, V2 = B, V3 = C;
4800 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4801 V1 = C, V2 = A, V3 = D;
4802 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4803 V1 = C, V2 = A, V3 = B;
4807 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4808 return BinaryOperator::CreateAnd(V1, Or);
4812 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
4813 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4815 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4817 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4819 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4822 // ((A&~B)|(~A&B)) -> A^B
4823 if ((match(C, m_Not(m_Specific(D))) &&
4824 match(B, m_Not(m_Specific(A)))))
4825 return BinaryOperator::CreateXor(A, D);
4826 // ((~B&A)|(~A&B)) -> A^B
4827 if ((match(A, m_Not(m_Specific(D))) &&
4828 match(B, m_Not(m_Specific(C)))))
4829 return BinaryOperator::CreateXor(C, D);
4830 // ((A&~B)|(B&~A)) -> A^B
4831 if ((match(C, m_Not(m_Specific(B))) &&
4832 match(D, m_Not(m_Specific(A)))))
4833 return BinaryOperator::CreateXor(A, B);
4834 // ((~B&A)|(B&~A)) -> A^B
4835 if ((match(A, m_Not(m_Specific(B))) &&
4836 match(D, m_Not(m_Specific(C)))))
4837 return BinaryOperator::CreateXor(C, B);
4840 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4841 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4842 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4843 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4844 SI0->getOperand(1) == SI1->getOperand(1) &&
4845 (SI0->hasOneUse() || SI1->hasOneUse())) {
4846 Instruction *NewOp =
4847 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
4849 SI0->getName()), I);
4850 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
4851 SI1->getOperand(1));
4855 // ((A|B)&1)|(B&-2) -> (A&1) | B
4856 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4857 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4858 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
4859 if (Ret) return Ret;
4861 // (B&-2)|((A|B)&1) -> (A&1) | B
4862 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4863 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
4864 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
4865 if (Ret) return Ret;
4868 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4869 if (A == Op1) // ~A | A == -1
4870 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4874 // Note, A is still live here!
4875 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4877 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
4879 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4880 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4881 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
4882 I.getName()+".demorgan"), I);
4883 return BinaryOperator::CreateNot(And);
4887 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4888 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4889 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
4892 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4893 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4897 // fold (or (cast A), (cast B)) -> (cast (or A, B))
4898 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4899 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4900 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4901 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4902 !isa<ICmpInst>(Op1C->getOperand(0))) {
4903 const Type *SrcTy = Op0C->getOperand(0)->getType();
4904 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4905 // Only do this if the casts both really cause code to be
4907 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4909 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4911 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
4912 Op1C->getOperand(0),
4914 InsertNewInstBefore(NewOp, I);
4915 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
4922 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4923 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4924 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4925 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4926 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4927 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4928 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4929 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4930 // If either of the constants are nans, then the whole thing returns
4932 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
4933 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4935 // Otherwise, no need to compare the two constants, compare the
4937 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4938 LHS->getOperand(0), RHS->getOperand(0));
4941 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4942 FCmpInst::Predicate Op0CC, Op1CC;
4943 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4944 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4945 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4946 // Swap RHS operands to match LHS.
4947 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4948 std::swap(Op1LHS, Op1RHS);
4950 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4951 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4953 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4955 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4956 Op1CC == FCmpInst::FCMP_TRUE)
4957 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
4958 else if (Op0CC == FCmpInst::FCMP_FALSE)
4959 return ReplaceInstUsesWith(I, Op1);
4960 else if (Op1CC == FCmpInst::FCMP_FALSE)
4961 return ReplaceInstUsesWith(I, Op0);
4964 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4965 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4966 if (Op0Ordered == Op1Ordered) {
4967 // If both are ordered or unordered, return a new fcmp with
4968 // or'ed predicates.
4969 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4970 Op0LHS, Op0RHS, Context);
4971 if (Instruction *I = dyn_cast<Instruction>(RV))
4973 // Otherwise, it's a constant boolean value...
4974 return ReplaceInstUsesWith(I, RV);
4982 return Changed ? &I : 0;
4987 // XorSelf - Implements: X ^ X --> 0
4990 XorSelf(Value *rhs) : RHS(rhs) {}
4991 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4992 Instruction *apply(BinaryOperator &Xor) const {
4999 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5000 bool Changed = SimplifyCommutative(I);
5001 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5003 if (isa<UndefValue>(Op1)) {
5004 if (isa<UndefValue>(Op0))
5005 // Handle undef ^ undef -> 0 special case. This is a common
5007 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5008 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
5011 // xor X, X = 0, even if X is nested in a sequence of Xor's.
5012 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
5013 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
5014 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
5017 // See if we can simplify any instructions used by the instruction whose sole
5018 // purpose is to compute bits we don't care about.
5019 if (SimplifyDemandedInstructionBits(I))
5021 if (isa<VectorType>(I.getType()))
5022 if (isa<ConstantAggregateZero>(Op1))
5023 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
5025 // Is this a ~ operation?
5026 if (Value *NotOp = dyn_castNotVal(&I, Context)) {
5027 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5028 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5029 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5030 if (Op0I->getOpcode() == Instruction::And ||
5031 Op0I->getOpcode() == Instruction::Or) {
5032 if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5033 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
5035 BinaryOperator::CreateNot(Op0I->getOperand(1),
5036 Op0I->getOperand(1)->getName()+".not");
5037 InsertNewInstBefore(NotY, I);
5038 if (Op0I->getOpcode() == Instruction::And)
5039 return BinaryOperator::CreateOr(Op0NotVal, NotY);
5041 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
5048 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
5049 if (RHS == Context->getConstantIntTrue() && Op0->hasOneUse()) {
5050 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
5051 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
5052 return new ICmpInst(*Context, ICI->getInversePredicate(),
5053 ICI->getOperand(0), ICI->getOperand(1));
5055 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
5056 return new FCmpInst(*Context, FCI->getInversePredicate(),
5057 FCI->getOperand(0), FCI->getOperand(1));
5060 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5061 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5062 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5063 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5064 Instruction::CastOps Opcode = Op0C->getOpcode();
5065 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
5066 if (RHS == Context->getConstantExprCast(Opcode,
5067 Context->getConstantIntTrue(),
5068 Op0C->getDestTy())) {
5069 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
5071 CI->getOpcode(), CI->getInversePredicate(),
5072 CI->getOperand(0), CI->getOperand(1)), I);
5073 NewCI->takeName(CI);
5074 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5081 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5082 // ~(c-X) == X-c-1 == X+(-c-1)
5083 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5084 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
5085 Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5086 Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5087 Context->getConstantInt(I.getType(), 1));
5088 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
5091 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
5092 if (Op0I->getOpcode() == Instruction::Add) {
5093 // ~(X-c) --> (-c-1)-X
5094 if (RHS->isAllOnesValue()) {
5095 Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
5096 return BinaryOperator::CreateSub(
5097 Context->getConstantExprSub(NegOp0CI,
5098 Context->getConstantInt(I.getType(), 1)),
5099 Op0I->getOperand(0));
5100 } else if (RHS->getValue().isSignBit()) {
5101 // (X + C) ^ signbit -> (X + C + signbit)
5103 Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
5104 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
5107 } else if (Op0I->getOpcode() == Instruction::Or) {
5108 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5109 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
5110 Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
5111 // Anything in both C1 and C2 is known to be zero, remove it from
5113 Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5114 NewRHS = Context->getConstantExprAnd(NewRHS,
5115 Context->getConstantExprNot(CommonBits));
5116 AddToWorkList(Op0I);
5117 I.setOperand(0, Op0I->getOperand(0));
5118 I.setOperand(1, NewRHS);
5125 // Try to fold constant and into select arguments.
5126 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5127 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5129 if (isa<PHINode>(Op0))
5130 if (Instruction *NV = FoldOpIntoPhi(I))
5134 if (Value *X = dyn_castNotVal(Op0, Context)) // ~A ^ A == -1
5136 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5138 if (Value *X = dyn_castNotVal(Op1, Context)) // A ^ ~A == -1
5140 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
5143 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5146 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
5147 if (A == Op0) { // B^(B|A) == (A|B)^B
5148 Op1I->swapOperands();
5150 std::swap(Op0, Op1);
5151 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5152 I.swapOperands(); // Simplified below.
5153 std::swap(Op0, Op1);
5155 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
5156 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
5157 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
5158 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
5159 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
5160 if (A == Op0) { // A^(A&B) -> A^(B&A)
5161 Op1I->swapOperands();
5164 if (B == Op0) { // A^(B&A) -> (B&A)^A
5165 I.swapOperands(); // Simplified below.
5166 std::swap(Op0, Op1);
5171 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5174 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
5175 if (A == Op1) // (B|A)^B == (A|B)^B
5177 if (B == Op1) { // (A|B)^B == A & ~B
5179 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5180 return BinaryOperator::CreateAnd(A, NotB);
5182 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5183 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5184 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5185 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
5186 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5187 if (A == Op1) // (A&B)^A -> (B&A)^A
5189 if (B == Op1 && // (B&A)^A == ~B & A
5190 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5192 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5193 return BinaryOperator::CreateAnd(N, Op1);
5198 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5199 if (Op0I && Op1I && Op0I->isShift() &&
5200 Op0I->getOpcode() == Op1I->getOpcode() &&
5201 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5202 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5203 Instruction *NewOp =
5204 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
5205 Op1I->getOperand(0),
5206 Op0I->getName()), I);
5207 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
5208 Op1I->getOperand(1));
5212 Value *A, *B, *C, *D;
5213 // (A & B)^(A | B) -> A ^ B
5214 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5215 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5216 if ((A == C && B == D) || (A == D && B == C))
5217 return BinaryOperator::CreateXor(A, B);
5219 // (A | B)^(A & B) -> A ^ B
5220 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5221 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5222 if ((A == C && B == D) || (A == D && B == C))
5223 return BinaryOperator::CreateXor(A, B);
5227 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5228 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5229 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5230 // (X & Y)^(X & Y) -> (Y^Z) & X
5231 Value *X = 0, *Y = 0, *Z = 0;
5233 X = A, Y = B, Z = D;
5235 X = A, Y = B, Z = C;
5237 X = B, Y = A, Z = D;
5239 X = B, Y = A, Z = C;
5242 Instruction *NewOp =
5243 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5244 return BinaryOperator::CreateAnd(NewOp, X);
5249 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5250 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5251 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
5254 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
5255 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5256 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5257 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5258 const Type *SrcTy = Op0C->getOperand(0)->getType();
5259 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5260 // Only do this if the casts both really cause code to be generated.
5261 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5263 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5265 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
5266 Op1C->getOperand(0),
5268 InsertNewInstBefore(NewOp, I);
5269 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
5274 return Changed ? &I : 0;
5277 static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
5278 LLVMContext *Context) {
5279 return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
5282 static bool HasAddOverflow(ConstantInt *Result,
5283 ConstantInt *In1, ConstantInt *In2,
5286 if (In2->getValue().isNegative())
5287 return Result->getValue().sgt(In1->getValue());
5289 return Result->getValue().slt(In1->getValue());
5291 return Result->getValue().ult(In1->getValue());
5294 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5295 /// overflowed for this type.
5296 static bool AddWithOverflow(Constant *&Result, Constant *In1,
5297 Constant *In2, LLVMContext *Context,
5298 bool IsSigned = false) {
5299 Result = Context->getConstantExprAdd(In1, In2);
5301 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5302 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5303 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5304 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5305 ExtractElement(In1, Idx, Context),
5306 ExtractElement(In2, Idx, Context),
5313 return HasAddOverflow(cast<ConstantInt>(Result),
5314 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5318 static bool HasSubOverflow(ConstantInt *Result,
5319 ConstantInt *In1, ConstantInt *In2,
5322 if (In2->getValue().isNegative())
5323 return Result->getValue().slt(In1->getValue());
5325 return Result->getValue().sgt(In1->getValue());
5327 return Result->getValue().ugt(In1->getValue());
5330 /// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5331 /// overflowed for this type.
5332 static bool SubWithOverflow(Constant *&Result, Constant *In1,
5333 Constant *In2, LLVMContext *Context,
5334 bool IsSigned = false) {
5335 Result = Context->getConstantExprSub(In1, In2);
5337 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5338 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
5339 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5340 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5341 ExtractElement(In1, Idx, Context),
5342 ExtractElement(In2, Idx, Context),
5349 return HasSubOverflow(cast<ConstantInt>(Result),
5350 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5354 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5355 /// code necessary to compute the offset from the base pointer (without adding
5356 /// in the base pointer). Return the result as a signed integer of intptr size.
5357 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5358 TargetData &TD = IC.getTargetData();
5359 gep_type_iterator GTI = gep_type_begin(GEP);
5360 const Type *IntPtrTy = TD.getIntPtrType();
5361 LLVMContext *Context = IC.getContext();
5362 Value *Result = Context->getNullValue(IntPtrTy);
5364 // Build a mask for high order bits.
5365 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5366 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5368 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5371 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
5372 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5373 if (OpC->isZero()) continue;
5375 // Handle a struct index, which adds its field offset to the pointer.
5376 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5377 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5379 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5381 Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
5383 Result = IC.InsertNewInstBefore(
5384 BinaryOperator::CreateAdd(Result,
5385 Context->getConstantInt(IntPtrTy, Size),
5386 GEP->getName()+".offs"), I);
5390 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5392 Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5393 Scale = Context->getConstantExprMul(OC, Scale);
5394 if (Constant *RC = dyn_cast<Constant>(Result))
5395 Result = Context->getConstantExprAdd(RC, Scale);
5397 // Emit an add instruction.
5398 Result = IC.InsertNewInstBefore(
5399 BinaryOperator::CreateAdd(Result, Scale,
5400 GEP->getName()+".offs"), I);
5404 // Convert to correct type.
5405 if (Op->getType() != IntPtrTy) {
5406 if (Constant *OpC = dyn_cast<Constant>(Op))
5407 Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
5409 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5411 Op->getName()+".c"), I);
5414 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5415 if (Constant *OpC = dyn_cast<Constant>(Op))
5416 Op = Context->getConstantExprMul(OpC, Scale);
5417 else // We'll let instcombine(mul) convert this to a shl if possible.
5418 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
5419 GEP->getName()+".idx"), I);
5422 // Emit an add instruction.
5423 if (isa<Constant>(Op) && isa<Constant>(Result))
5424 Result = Context->getConstantExprAdd(cast<Constant>(Op),
5425 cast<Constant>(Result));
5427 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
5428 GEP->getName()+".offs"), I);
5434 /// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5435 /// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5436 /// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5437 /// complex, and scales are involved. The above expression would also be legal
5438 /// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5439 /// later form is less amenable to optimization though, and we are allowed to
5440 /// generate the first by knowing that pointer arithmetic doesn't overflow.
5442 /// If we can't emit an optimized form for this expression, this returns null.
5444 static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5446 TargetData &TD = IC.getTargetData();
5447 gep_type_iterator GTI = gep_type_begin(GEP);
5449 // Check to see if this gep only has a single variable index. If so, and if
5450 // any constant indices are a multiple of its scale, then we can compute this
5451 // in terms of the scale of the variable index. For example, if the GEP
5452 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5453 // because the expression will cross zero at the same point.
5454 unsigned i, e = GEP->getNumOperands();
5456 for (i = 1; i != e; ++i, ++GTI) {
5457 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5458 // Compute the aggregate offset of constant indices.
5459 if (CI->isZero()) continue;
5461 // Handle a struct index, which adds its field offset to the pointer.
5462 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5463 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5465 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5466 Offset += Size*CI->getSExtValue();
5469 // Found our variable index.
5474 // If there are no variable indices, we must have a constant offset, just
5475 // evaluate it the general way.
5476 if (i == e) return 0;
5478 Value *VariableIdx = GEP->getOperand(i);
5479 // Determine the scale factor of the variable element. For example, this is
5480 // 4 if the variable index is into an array of i32.
5481 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
5483 // Verify that there are no other variable indices. If so, emit the hard way.
5484 for (++i, ++GTI; i != e; ++i, ++GTI) {
5485 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5488 // Compute the aggregate offset of constant indices.
5489 if (CI->isZero()) continue;
5491 // Handle a struct index, which adds its field offset to the pointer.
5492 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5493 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5495 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
5496 Offset += Size*CI->getSExtValue();
5500 // Okay, we know we have a single variable index, which must be a
5501 // pointer/array/vector index. If there is no offset, life is simple, return
5503 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5505 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5506 // we don't need to bother extending: the extension won't affect where the
5507 // computation crosses zero.
5508 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5509 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5510 VariableIdx->getNameStart(), &I);
5514 // Otherwise, there is an index. The computation we will do will be modulo
5515 // the pointer size, so get it.
5516 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5518 Offset &= PtrSizeMask;
5519 VariableScale &= PtrSizeMask;
5521 // To do this transformation, any constant index must be a multiple of the
5522 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5523 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5524 // multiple of the variable scale.
5525 int64_t NewOffs = Offset / (int64_t)VariableScale;
5526 if (Offset != NewOffs*(int64_t)VariableScale)
5529 // Okay, we can do this evaluation. Start by converting the index to intptr.
5530 const Type *IntPtrTy = TD.getIntPtrType();
5531 if (VariableIdx->getType() != IntPtrTy)
5532 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
5534 VariableIdx->getNameStart(), &I);
5535 Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
5536 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
5540 /// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5541 /// else. At this point we know that the GEP is on the LHS of the comparison.
5542 Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5543 ICmpInst::Predicate Cond,
5545 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5547 // Look through bitcasts.
5548 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5549 RHS = BCI->getOperand(0);
5551 Value *PtrBase = GEPLHS->getOperand(0);
5552 if (PtrBase == RHS) {
5553 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
5554 // This transformation (ignoring the base and scales) is valid because we
5555 // know pointers can't overflow. See if we can output an optimized form.
5556 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5558 // If not, synthesize the offset the hard way.
5560 Offset = EmitGEPOffset(GEPLHS, I, *this);
5561 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
5562 Context->getNullValue(Offset->getType()));
5563 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5564 // If the base pointers are different, but the indices are the same, just
5565 // compare the base pointer.
5566 if (PtrBase != GEPRHS->getOperand(0)) {
5567 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5568 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5569 GEPRHS->getOperand(0)->getType();
5571 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5572 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5573 IndicesTheSame = false;
5577 // If all indices are the same, just compare the base pointers.
5579 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
5580 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5582 // Otherwise, the base pointers are different and the indices are
5583 // different, bail out.
5587 // If one of the GEPs has all zero indices, recurse.
5588 bool AllZeros = true;
5589 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5590 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5591 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5596 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5597 ICmpInst::getSwappedPredicate(Cond), I);
5599 // If the other GEP has all zero indices, recurse.
5601 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5602 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5603 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5608 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5610 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5611 // If the GEPs only differ by one index, compare it.
5612 unsigned NumDifferences = 0; // Keep track of # differences.
5613 unsigned DiffOperand = 0; // The operand that differs.
5614 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5615 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5616 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5617 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5618 // Irreconcilable differences.
5622 if (NumDifferences++) break;
5627 if (NumDifferences == 0) // SAME GEP?
5628 return ReplaceInstUsesWith(I, // No comparison is needed here.
5629 Context->getConstantInt(Type::Int1Ty,
5630 ICmpInst::isTrueWhenEqual(Cond)));
5632 else if (NumDifferences == 1) {
5633 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5634 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5635 // Make sure we do a signed comparison here.
5636 return new ICmpInst(*Context,
5637 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5641 // Only lower this if the icmp is the only user of the GEP or if we expect
5642 // the result to fold to a constant!
5643 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5644 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5645 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5646 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5647 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5648 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
5654 /// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5656 Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5659 if (!isa<ConstantFP>(RHSC)) return 0;
5660 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5662 // Get the width of the mantissa. We don't want to hack on conversions that
5663 // might lose information from the integer, e.g. "i64 -> float"
5664 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
5665 if (MantissaWidth == -1) return 0; // Unknown.
5667 // Check to see that the input is converted from an integer type that is small
5668 // enough that preserves all bits. TODO: check here for "known" sign bits.
5669 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5670 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
5672 // If this is a uitofp instruction, we need an extra bit to hold the sign.
5673 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5677 // If the conversion would lose info, don't hack on this.
5678 if ((int)InputSize > MantissaWidth)
5681 // Otherwise, we can potentially simplify the comparison. We know that it
5682 // will always come through as an integer value and we know the constant is
5683 // not a NAN (it would have been previously simplified).
5684 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5686 ICmpInst::Predicate Pred;
5687 switch (I.getPredicate()) {
5688 default: assert(0 && "Unexpected predicate!");
5689 case FCmpInst::FCMP_UEQ:
5690 case FCmpInst::FCMP_OEQ:
5691 Pred = ICmpInst::ICMP_EQ;
5693 case FCmpInst::FCMP_UGT:
5694 case FCmpInst::FCMP_OGT:
5695 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5697 case FCmpInst::FCMP_UGE:
5698 case FCmpInst::FCMP_OGE:
5699 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5701 case FCmpInst::FCMP_ULT:
5702 case FCmpInst::FCMP_OLT:
5703 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5705 case FCmpInst::FCMP_ULE:
5706 case FCmpInst::FCMP_OLE:
5707 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5709 case FCmpInst::FCMP_UNE:
5710 case FCmpInst::FCMP_ONE:
5711 Pred = ICmpInst::ICMP_NE;
5713 case FCmpInst::FCMP_ORD:
5714 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5715 case FCmpInst::FCMP_UNO:
5716 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5719 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5721 // Now we know that the APFloat is a normal number, zero or inf.
5723 // See if the FP constant is too large for the integer. For example,
5724 // comparing an i8 to 300.0.
5725 unsigned IntWidth = IntTy->getScalarSizeInBits();
5728 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5729 // and large values.
5730 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5731 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5732 APFloat::rmNearestTiesToEven);
5733 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5734 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5735 Pred == ICmpInst::ICMP_SLE)
5736 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5737 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5740 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5741 // +INF and large values.
5742 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5743 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5744 APFloat::rmNearestTiesToEven);
5745 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5746 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5747 Pred == ICmpInst::ICMP_ULE)
5748 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5749 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5754 // See if the RHS value is < SignedMin.
5755 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5756 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5757 APFloat::rmNearestTiesToEven);
5758 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5759 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5760 Pred == ICmpInst::ICMP_SGE)
5761 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5762 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5766 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5767 // [0, UMAX], but it may still be fractional. See if it is fractional by
5768 // casting the FP value to the integer value and back, checking for equality.
5769 // Don't do this for zero, because -0.0 is not fractional.
5770 Constant *RHSInt = LHSUnsigned
5771 ? Context->getConstantExprFPToUI(RHSC, IntTy)
5772 : Context->getConstantExprFPToSI(RHSC, IntTy);
5773 if (!RHS.isZero()) {
5774 bool Equal = LHSUnsigned
5775 ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5776 : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
5778 // If we had a comparison against a fractional value, we have to adjust
5779 // the compare predicate and sometimes the value. RHSC is rounded towards
5780 // zero at this point.
5782 default: assert(0 && "Unexpected integer comparison!");
5783 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
5784 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5785 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
5786 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5787 case ICmpInst::ICMP_ULE:
5788 // (float)int <= 4.4 --> int <= 4
5789 // (float)int <= -4.4 --> false
5790 if (RHS.isNegative())
5791 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5793 case ICmpInst::ICMP_SLE:
5794 // (float)int <= 4.4 --> int <= 4
5795 // (float)int <= -4.4 --> int < -4
5796 if (RHS.isNegative())
5797 Pred = ICmpInst::ICMP_SLT;
5799 case ICmpInst::ICMP_ULT:
5800 // (float)int < -4.4 --> false
5801 // (float)int < 4.4 --> int <= 4
5802 if (RHS.isNegative())
5803 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5804 Pred = ICmpInst::ICMP_ULE;
5806 case ICmpInst::ICMP_SLT:
5807 // (float)int < -4.4 --> int < -4
5808 // (float)int < 4.4 --> int <= 4
5809 if (!RHS.isNegative())
5810 Pred = ICmpInst::ICMP_SLE;
5812 case ICmpInst::ICMP_UGT:
5813 // (float)int > 4.4 --> int > 4
5814 // (float)int > -4.4 --> true
5815 if (RHS.isNegative())
5816 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5818 case ICmpInst::ICMP_SGT:
5819 // (float)int > 4.4 --> int > 4
5820 // (float)int > -4.4 --> int >= -4
5821 if (RHS.isNegative())
5822 Pred = ICmpInst::ICMP_SGE;
5824 case ICmpInst::ICMP_UGE:
5825 // (float)int >= -4.4 --> true
5826 // (float)int >= 4.4 --> int > 4
5827 if (!RHS.isNegative())
5828 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5829 Pred = ICmpInst::ICMP_UGT;
5831 case ICmpInst::ICMP_SGE:
5832 // (float)int >= -4.4 --> int >= -4
5833 // (float)int >= 4.4 --> int > 4
5834 if (!RHS.isNegative())
5835 Pred = ICmpInst::ICMP_SGT;
5841 // Lower this FP comparison into an appropriate integer version of the
5843 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
5846 Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5847 bool Changed = SimplifyCompare(I);
5848 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5850 // Fold trivial predicates.
5851 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5852 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5853 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5854 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5856 // Simplify 'fcmp pred X, X'
5858 switch (I.getPredicate()) {
5859 default: assert(0 && "Unknown predicate!");
5860 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5861 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5862 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5863 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5864 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5865 case FCmpInst::FCMP_OLT: // True if ordered and less than
5866 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5867 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5869 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5870 case FCmpInst::FCMP_ULT: // True if unordered or less than
5871 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5872 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5873 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5874 I.setPredicate(FCmpInst::FCMP_UNO);
5875 I.setOperand(1, Context->getNullValue(Op0->getType()));
5878 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5879 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5880 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5881 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5882 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5883 I.setPredicate(FCmpInst::FCMP_ORD);
5884 I.setOperand(1, Context->getNullValue(Op0->getType()));
5889 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5890 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5892 // Handle fcmp with constant RHS
5893 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5894 // If the constant is a nan, see if we can fold the comparison based on it.
5895 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5896 if (CFP->getValueAPF().isNaN()) {
5897 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
5898 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
5899 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5900 "Comparison must be either ordered or unordered!");
5901 // True if unordered.
5902 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5906 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5907 switch (LHSI->getOpcode()) {
5908 case Instruction::PHI:
5909 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5910 // block. If in the same block, we're encouraging jump threading. If
5911 // not, we are just pessimizing the code by making an i1 phi.
5912 if (LHSI->getParent() == I.getParent())
5913 if (Instruction *NV = FoldOpIntoPhi(I))
5916 case Instruction::SIToFP:
5917 case Instruction::UIToFP:
5918 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5921 case Instruction::Select:
5922 // If either operand of the select is a constant, we can fold the
5923 // comparison into the select arms, which will cause one to be
5924 // constant folded and the select turned into a bitwise or.
5925 Value *Op1 = 0, *Op2 = 0;
5926 if (LHSI->hasOneUse()) {
5927 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5928 // Fold the known value into the constant operand.
5929 Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5930 // Insert a new FCmp of the other select operand.
5931 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5932 LHSI->getOperand(2), RHSC,
5934 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5935 // Fold the known value into the constant operand.
5936 Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
5937 // Insert a new FCmp of the other select operand.
5938 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
5939 LHSI->getOperand(1), RHSC,
5945 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
5950 return Changed ? &I : 0;
5953 Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5954 bool Changed = SimplifyCompare(I);
5955 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5956 const Type *Ty = Op0->getType();
5960 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
5961 I.isTrueWhenEqual()));
5963 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5964 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
5966 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5967 // addresses never equal each other! We already know that Op0 != Op1.
5968 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5969 isa<ConstantPointerNull>(Op0)) &&
5970 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5971 isa<ConstantPointerNull>(Op1)))
5972 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
5973 !I.isTrueWhenEqual()));
5975 // icmp's with boolean values can always be turned into bitwise operations
5976 if (Ty == Type::Int1Ty) {
5977 switch (I.getPredicate()) {
5978 default: assert(0 && "Invalid icmp instruction!");
5979 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
5980 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
5981 InsertNewInstBefore(Xor, I);
5982 return BinaryOperator::CreateNot(Xor);
5984 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
5985 return BinaryOperator::CreateXor(Op0, Op1);
5987 case ICmpInst::ICMP_UGT:
5988 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
5990 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
5991 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
5992 InsertNewInstBefore(Not, I);
5993 return BinaryOperator::CreateAnd(Not, Op1);
5995 case ICmpInst::ICMP_SGT:
5996 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
5998 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5999 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6000 InsertNewInstBefore(Not, I);
6001 return BinaryOperator::CreateAnd(Not, Op0);
6003 case ICmpInst::ICMP_UGE:
6004 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6006 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
6007 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
6008 InsertNewInstBefore(Not, I);
6009 return BinaryOperator::CreateOr(Not, Op1);
6011 case ICmpInst::ICMP_SGE:
6012 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6014 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
6015 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6016 InsertNewInstBefore(Not, I);
6017 return BinaryOperator::CreateOr(Not, Op0);
6022 unsigned BitWidth = 0;
6024 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6025 else if (Ty->isIntOrIntVector())
6026 BitWidth = Ty->getScalarSizeInBits();
6028 bool isSignBit = false;
6030 // See if we are doing a comparison with a constant.
6031 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6032 Value *A = 0, *B = 0;
6034 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6035 if (I.isEquality() && CI->isNullValue() &&
6036 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
6037 // (icmp cond A B) if cond is equality
6038 return new ICmpInst(*Context, I.getPredicate(), A, B);
6041 // If we have an icmp le or icmp ge instruction, turn it into the
6042 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6043 // them being folded in the code below.
6044 switch (I.getPredicate()) {
6046 case ICmpInst::ICMP_ULE:
6047 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
6048 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6049 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6050 AddOne(CI, Context));
6051 case ICmpInst::ICMP_SLE:
6052 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
6053 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6054 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6055 AddOne(CI, Context));
6056 case ICmpInst::ICMP_UGE:
6057 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
6058 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6059 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6060 SubOne(CI, Context));
6061 case ICmpInst::ICMP_SGE:
6062 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
6063 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6064 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6065 SubOne(CI, Context));
6068 // If this comparison is a normal comparison, it demands all
6069 // bits, if it is a sign bit comparison, it only demands the sign bit.
6071 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6074 // See if we can fold the comparison based on range information we can get
6075 // by checking whether bits are known to be zero or one in the input.
6076 if (BitWidth != 0) {
6077 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6078 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6080 if (SimplifyDemandedBits(I.getOperandUse(0),
6081 isSignBit ? APInt::getSignBit(BitWidth)
6082 : APInt::getAllOnesValue(BitWidth),
6083 Op0KnownZero, Op0KnownOne, 0))
6085 if (SimplifyDemandedBits(I.getOperandUse(1),
6086 APInt::getAllOnesValue(BitWidth),
6087 Op1KnownZero, Op1KnownOne, 0))
6090 // Given the known and unknown bits, compute a range that the LHS could be
6091 // in. Compute the Min, Max and RHS values based on the known bits. For the
6092 // EQ and NE we use unsigned values.
6093 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6094 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6095 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6096 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6098 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6101 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6103 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6107 // If Min and Max are known to be the same, then SimplifyDemandedBits
6108 // figured out that the LHS is a constant. Just constant fold this now so
6109 // that code below can assume that Min != Max.
6110 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
6111 return new ICmpInst(*Context, I.getPredicate(),
6112 Context->getConstantInt(Op0Min), Op1);
6113 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
6114 return new ICmpInst(*Context, I.getPredicate(), Op0,
6115 Context->getConstantInt(Op1Min));
6117 // Based on the range information we know about the LHS, see if we can
6118 // simplify this comparison. For example, (x&4) < 8 is always true.
6119 switch (I.getPredicate()) {
6120 default: assert(0 && "Unknown icmp opcode!");
6121 case ICmpInst::ICMP_EQ:
6122 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6123 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6125 case ICmpInst::ICMP_NE:
6126 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
6127 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6129 case ICmpInst::ICMP_ULT:
6130 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
6131 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6132 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
6133 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6134 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
6135 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6136 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6137 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
6138 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6139 SubOne(CI, Context));
6141 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6142 if (CI->isMinValue(true))
6143 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6144 Context->getConstantIntAllOnesValue(Op0->getType()));
6147 case ICmpInst::ICMP_UGT:
6148 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
6149 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6150 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
6151 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6153 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
6154 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6155 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6156 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
6157 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6158 AddOne(CI, Context));
6160 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6161 if (CI->isMaxValue(true))
6162 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6163 Context->getNullValue(Op0->getType()));
6166 case ICmpInst::ICMP_SLT:
6167 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
6168 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6169 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
6170 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6171 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
6172 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6173 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6174 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
6175 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6176 SubOne(CI, Context));
6179 case ICmpInst::ICMP_SGT:
6180 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
6181 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6182 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
6183 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6185 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
6186 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
6187 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6188 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
6189 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6190 AddOne(CI, Context));
6193 case ICmpInst::ICMP_SGE:
6194 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6195 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
6196 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6197 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
6198 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6200 case ICmpInst::ICMP_SLE:
6201 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6202 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
6203 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6204 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
6205 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6207 case ICmpInst::ICMP_UGE:
6208 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6209 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
6210 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6211 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
6212 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6214 case ICmpInst::ICMP_ULE:
6215 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6216 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
6217 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
6218 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
6219 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
6223 // Turn a signed comparison into an unsigned one if both operands
6224 // are known to have the same sign.
6225 if (I.isSignedPredicate() &&
6226 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6227 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
6228 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
6231 // Test if the ICmpInst instruction is used exclusively by a select as
6232 // part of a minimum or maximum operation. If so, refrain from doing
6233 // any other folding. This helps out other analyses which understand
6234 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6235 // and CodeGen. And in this case, at least one of the comparison
6236 // operands has at least one user besides the compare (the select),
6237 // which would often largely negate the benefit of folding anyway.
6239 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6240 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6241 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6244 // See if we are doing a comparison between a constant and an instruction that
6245 // can be folded into the comparison.
6246 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6247 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6248 // instruction, see if that instruction also has constants so that the
6249 // instruction can be folded into the icmp
6250 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6251 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6255 // Handle icmp with constant (but not simple integer constant) RHS
6256 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6257 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6258 switch (LHSI->getOpcode()) {
6259 case Instruction::GetElementPtr:
6260 if (RHSC->isNullValue()) {
6261 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6262 bool isAllZeros = true;
6263 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6264 if (!isa<Constant>(LHSI->getOperand(i)) ||
6265 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6270 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
6271 Context->getNullValue(LHSI->getOperand(0)->getType()));
6275 case Instruction::PHI:
6276 // Only fold icmp into the PHI if the phi and fcmp are in the same
6277 // block. If in the same block, we're encouraging jump threading. If
6278 // not, we are just pessimizing the code by making an i1 phi.
6279 if (LHSI->getParent() == I.getParent())
6280 if (Instruction *NV = FoldOpIntoPhi(I))
6283 case Instruction::Select: {
6284 // If either operand of the select is a constant, we can fold the
6285 // comparison into the select arms, which will cause one to be
6286 // constant folded and the select turned into a bitwise or.
6287 Value *Op1 = 0, *Op2 = 0;
6288 if (LHSI->hasOneUse()) {
6289 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6290 // Fold the known value into the constant operand.
6291 Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6292 // Insert a new ICmp of the other select operand.
6293 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6294 LHSI->getOperand(2), RHSC,
6296 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6297 // Fold the known value into the constant operand.
6298 Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
6299 // Insert a new ICmp of the other select operand.
6300 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
6301 LHSI->getOperand(1), RHSC,
6307 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
6310 case Instruction::Malloc:
6311 // If we have (malloc != null), and if the malloc has a single use, we
6312 // can assume it is successful and remove the malloc.
6313 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6314 AddToWorkList(LHSI);
6315 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
6316 !I.isTrueWhenEqual()));
6322 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6323 if (User *GEP = dyn_castGetElementPtr(Op0))
6324 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6326 if (User *GEP = dyn_castGetElementPtr(Op1))
6327 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6328 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6331 // Test to see if the operands of the icmp are casted versions of other
6332 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6334 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6335 if (isa<PointerType>(Op0->getType()) &&
6336 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6337 // We keep moving the cast from the left operand over to the right
6338 // operand, where it can often be eliminated completely.
6339 Op0 = CI->getOperand(0);
6341 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6342 // so eliminate it as well.
6343 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6344 Op1 = CI2->getOperand(0);
6346 // If Op1 is a constant, we can fold the cast into the constant.
6347 if (Op0->getType() != Op1->getType()) {
6348 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6349 Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
6351 // Otherwise, cast the RHS right before the icmp
6352 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
6355 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
6359 if (isa<CastInst>(Op0)) {
6360 // Handle the special case of: icmp (cast bool to X), <cst>
6361 // This comes up when you have code like
6364 // For generality, we handle any zero-extension of any operand comparison
6365 // with a constant or another cast from the same type.
6366 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6367 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6371 // See if it's the same type of instruction on the left and right.
6372 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6373 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
6374 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6375 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
6376 switch (Op0I->getOpcode()) {
6378 case Instruction::Add:
6379 case Instruction::Sub:
6380 case Instruction::Xor:
6381 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
6382 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
6383 Op1I->getOperand(0));
6384 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6385 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6386 if (CI->getValue().isSignBit()) {
6387 ICmpInst::Predicate Pred = I.isSignedPredicate()
6388 ? I.getUnsignedPredicate()
6389 : I.getSignedPredicate();
6390 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6391 Op1I->getOperand(0));
6394 if (CI->getValue().isMaxSignedValue()) {
6395 ICmpInst::Predicate Pred = I.isSignedPredicate()
6396 ? I.getUnsignedPredicate()
6397 : I.getSignedPredicate();
6398 Pred = I.getSwappedPredicate(Pred);
6399 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
6400 Op1I->getOperand(0));
6404 case Instruction::Mul:
6405 if (!I.isEquality())
6408 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6409 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6410 // Mask = -1 >> count-trailing-zeros(Cst).
6411 if (!CI->isZero() && !CI->isOne()) {
6412 const APInt &AP = CI->getValue();
6413 ConstantInt *Mask = Context->getConstantInt(
6414 APInt::getLowBitsSet(AP.getBitWidth(),
6416 AP.countTrailingZeros()));
6417 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6419 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6421 InsertNewInstBefore(And1, I);
6422 InsertNewInstBefore(And2, I);
6423 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
6432 // ~x < ~y --> y < x
6434 if (match(Op0, m_Not(m_Value(A))) &&
6435 match(Op1, m_Not(m_Value(B))))
6436 return new ICmpInst(*Context, I.getPredicate(), B, A);
6439 if (I.isEquality()) {
6440 Value *A, *B, *C, *D;
6442 // -x == -y --> x == y
6443 if (match(Op0, m_Neg(m_Value(A))) &&
6444 match(Op1, m_Neg(m_Value(B))))
6445 return new ICmpInst(*Context, I.getPredicate(), A, B);
6447 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6448 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6449 Value *OtherVal = A == Op1 ? B : A;
6450 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6451 Context->getNullValue(A->getType()));
6454 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6455 // A^c1 == C^c2 --> A == C^(c1^c2)
6456 ConstantInt *C1, *C2;
6457 if (match(B, m_ConstantInt(C1)) &&
6458 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6460 Context->getConstantInt(C1->getValue() ^ C2->getValue());
6461 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6462 return new ICmpInst(*Context, I.getPredicate(), A,
6463 InsertNewInstBefore(Xor, I));
6466 // A^B == A^D -> B == D
6467 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6468 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6469 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6470 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
6474 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6475 (A == Op0 || B == Op0)) {
6476 // A == (A^B) -> B == 0
6477 Value *OtherVal = A == Op0 ? B : A;
6478 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
6479 Context->getNullValue(A->getType()));
6482 // (A-B) == A -> B == 0
6483 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6484 return new ICmpInst(*Context, I.getPredicate(), B,
6485 Context->getNullValue(B->getType()));
6487 // A == (A-B) -> B == 0
6488 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
6489 return new ICmpInst(*Context, I.getPredicate(), B,
6490 Context->getNullValue(B->getType()));
6492 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6493 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6494 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6495 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6496 Value *X = 0, *Y = 0, *Z = 0;
6499 X = B; Y = D; Z = A;
6500 } else if (A == D) {
6501 X = B; Y = C; Z = A;
6502 } else if (B == C) {
6503 X = A; Y = D; Z = B;
6504 } else if (B == D) {
6505 X = A; Y = C; Z = B;
6508 if (X) { // Build (X^Y) & Z
6509 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6510 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
6511 I.setOperand(0, Op1);
6512 I.setOperand(1, Context->getNullValue(Op1->getType()));
6517 return Changed ? &I : 0;
6521 /// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6522 /// and CmpRHS are both known to be integer constants.
6523 Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6524 ConstantInt *DivRHS) {
6525 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6526 const APInt &CmpRHSV = CmpRHS->getValue();
6528 // FIXME: If the operand types don't match the type of the divide
6529 // then don't attempt this transform. The code below doesn't have the
6530 // logic to deal with a signed divide and an unsigned compare (and
6531 // vice versa). This is because (x /s C1) <s C2 produces different
6532 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6533 // (x /u C1) <u C2. Simply casting the operands and result won't
6534 // work. :( The if statement below tests that condition and bails
6536 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6537 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6539 if (DivRHS->isZero())
6540 return 0; // The ProdOV computation fails on divide by zero.
6541 if (DivIsSigned && DivRHS->isAllOnesValue())
6542 return 0; // The overflow computation also screws up here
6543 if (DivRHS->isOne())
6544 return 0; // Not worth bothering, and eliminates some funny cases
6547 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6548 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6549 // C2 (CI). By solving for X we can turn this into a range check
6550 // instead of computing a divide.
6551 Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
6553 // Determine if the product overflows by seeing if the product is
6554 // not equal to the divide. Make sure we do the same kind of divide
6555 // as in the LHS instruction that we're folding.
6556 bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6557 Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
6559 // Get the ICmp opcode
6560 ICmpInst::Predicate Pred = ICI.getPredicate();
6562 // Figure out the interval that is being checked. For example, a comparison
6563 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6564 // Compute this interval based on the constants involved and the signedness of
6565 // the compare/divide. This computes a half-open interval, keeping track of
6566 // whether either value in the interval overflows. After analysis each
6567 // overflow variable is set to 0 if it's corresponding bound variable is valid
6568 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6569 int LoOverflow = 0, HiOverflow = 0;
6570 Constant *LoBound = 0, *HiBound = 0;
6572 if (!DivIsSigned) { // udiv
6573 // e.g. X/5 op 3 --> [15, 20)
6575 HiOverflow = LoOverflow = ProdOV;
6577 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
6578 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
6579 if (CmpRHSV == 0) { // (X / pos) op 0
6580 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
6581 LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS,
6584 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
6585 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6586 HiOverflow = LoOverflow = ProdOV;
6588 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
6589 } else { // (X / pos) op neg
6590 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
6591 HiBound = AddOne(Prod, Context);
6592 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6594 ConstantInt* DivNeg =
6595 cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6596 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
6600 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
6601 if (CmpRHSV == 0) { // (X / neg) op 0
6602 // e.g. X/-5 op 0 --> [-4, 5)
6603 LoBound = AddOne(DivRHS, Context);
6604 HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6605 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6606 HiOverflow = 1; // [INTMIN+1, overflow)
6607 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6609 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
6610 // e.g. X/-5 op 3 --> [-19, -14)
6611 HiBound = AddOne(Prod, Context);
6612 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6614 LoOverflow = AddWithOverflow(LoBound, HiBound,
6615 DivRHS, Context, true) ? -1 : 0;
6616 } else { // (X / neg) op neg
6617 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6618 LoOverflow = HiOverflow = ProdOV;
6620 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
6623 // Dividing by a negative swaps the condition. LT <-> GT
6624 Pred = ICmpInst::getSwappedPredicate(Pred);
6627 Value *X = DivI->getOperand(0);
6629 default: assert(0 && "Unhandled icmp opcode!");
6630 case ICmpInst::ICMP_EQ:
6631 if (LoOverflow && HiOverflow)
6632 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6633 else if (HiOverflow)
6634 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
6635 ICmpInst::ICMP_UGE, X, LoBound);
6636 else if (LoOverflow)
6637 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
6638 ICmpInst::ICMP_ULT, X, HiBound);
6640 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6641 case ICmpInst::ICMP_NE:
6642 if (LoOverflow && HiOverflow)
6643 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6644 else if (HiOverflow)
6645 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
6646 ICmpInst::ICMP_ULT, X, LoBound);
6647 else if (LoOverflow)
6648 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
6649 ICmpInst::ICMP_UGE, X, HiBound);
6651 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6652 case ICmpInst::ICMP_ULT:
6653 case ICmpInst::ICMP_SLT:
6654 if (LoOverflow == +1) // Low bound is greater than input range.
6655 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6656 if (LoOverflow == -1) // Low bound is less than input range.
6657 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6658 return new ICmpInst(*Context, Pred, X, LoBound);
6659 case ICmpInst::ICMP_UGT:
6660 case ICmpInst::ICMP_SGT:
6661 if (HiOverflow == +1) // High bound greater than input range.
6662 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6663 else if (HiOverflow == -1) // High bound less than input range.
6664 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6665 if (Pred == ICmpInst::ICMP_UGT)
6666 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
6668 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
6673 /// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6675 Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6678 const APInt &RHSV = RHS->getValue();
6680 switch (LHSI->getOpcode()) {
6681 case Instruction::Trunc:
6682 if (ICI.isEquality() && LHSI->hasOneUse()) {
6683 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6684 // of the high bits truncated out of x are known.
6685 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6686 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6687 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6688 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6689 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6691 // If all the high bits are known, we can do this xform.
6692 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6693 // Pull in the high bits from known-ones set.
6694 APInt NewRHS(RHS->getValue());
6695 NewRHS.zext(SrcBits);
6697 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6698 Context->getConstantInt(NewRHS));
6703 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6704 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6705 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6707 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6708 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
6709 Value *CompareVal = LHSI->getOperand(0);
6711 // If the sign bit of the XorCST is not set, there is no change to
6712 // the operation, just stop using the Xor.
6713 if (!XorCST->getValue().isNegative()) {
6714 ICI.setOperand(0, CompareVal);
6715 AddToWorkList(LHSI);
6719 // Was the old condition true if the operand is positive?
6720 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6722 // If so, the new one isn't.
6723 isTrueIfPositive ^= true;
6725 if (isTrueIfPositive)
6726 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
6727 SubOne(RHS, Context));
6729 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
6730 AddOne(RHS, Context));
6733 if (LHSI->hasOneUse()) {
6734 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6735 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6736 const APInt &SignBit = XorCST->getValue();
6737 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6738 ? ICI.getUnsignedPredicate()
6739 : ICI.getSignedPredicate();
6740 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6741 Context->getConstantInt(RHSV ^ SignBit));
6744 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
6745 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
6746 const APInt &NotSignBit = XorCST->getValue();
6747 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6748 ? ICI.getUnsignedPredicate()
6749 : ICI.getSignedPredicate();
6750 Pred = ICI.getSwappedPredicate(Pred);
6751 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
6752 Context->getConstantInt(RHSV ^ NotSignBit));
6757 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6758 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6759 LHSI->getOperand(0)->hasOneUse()) {
6760 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6762 // If the LHS is an AND of a truncating cast, we can widen the
6763 // and/compare to be the input width without changing the value
6764 // produced, eliminating a cast.
6765 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6766 // We can do this transformation if either the AND constant does not
6767 // have its sign bit set or if it is an equality comparison.
6768 // Extending a relational comparison when we're checking the sign
6769 // bit would not work.
6770 if (Cast->hasOneUse() &&
6771 (ICI.isEquality() ||
6772 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
6774 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6775 APInt NewCST = AndCST->getValue();
6776 NewCST.zext(BitWidth);
6778 NewCI.zext(BitWidth);
6779 Instruction *NewAnd =
6780 BinaryOperator::CreateAnd(Cast->getOperand(0),
6781 Context->getConstantInt(NewCST),LHSI->getName());
6782 InsertNewInstBefore(NewAnd, ICI);
6783 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
6784 Context->getConstantInt(NewCI));
6788 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6789 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6790 // happens a LOT in code produced by the C front-end, for bitfield
6792 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6793 if (Shift && !Shift->isShift())
6797 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6798 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6799 const Type *AndTy = AndCST->getType(); // Type of the and.
6801 // We can fold this as long as we can't shift unknown bits
6802 // into the mask. This can only happen with signed shift
6803 // rights, as they sign-extend.
6805 bool CanFold = Shift->isLogicalShift();
6807 // To test for the bad case of the signed shr, see if any
6808 // of the bits shifted in could be tested after the mask.
6809 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6810 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6812 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6813 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6814 AndCST->getValue()) == 0)
6820 if (Shift->getOpcode() == Instruction::Shl)
6821 NewCst = Context->getConstantExprLShr(RHS, ShAmt);
6823 NewCst = Context->getConstantExprShl(RHS, ShAmt);
6825 // Check to see if we are shifting out any of the bits being
6827 if (Context->getConstantExpr(Shift->getOpcode(),
6828 NewCst, ShAmt) != RHS) {
6829 // If we shifted bits out, the fold is not going to work out.
6830 // As a special case, check to see if this means that the
6831 // result is always true or false now.
6832 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6833 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
6834 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6835 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
6837 ICI.setOperand(1, NewCst);
6838 Constant *NewAndCST;
6839 if (Shift->getOpcode() == Instruction::Shl)
6840 NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
6842 NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
6843 LHSI->setOperand(1, NewAndCST);
6844 LHSI->setOperand(0, Shift->getOperand(0));
6845 AddToWorkList(Shift); // Shift is dead.
6846 AddUsesToWorkList(ICI);
6852 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6853 // preferable because it allows the C<<Y expression to be hoisted out
6854 // of a loop if Y is invariant and X is not.
6855 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6856 ICI.isEquality() && !Shift->isArithmeticShift() &&
6857 !isa<Constant>(Shift->getOperand(0))) {
6860 if (Shift->getOpcode() == Instruction::LShr) {
6861 NS = BinaryOperator::CreateShl(AndCST,
6862 Shift->getOperand(1), "tmp");
6864 // Insert a logical shift.
6865 NS = BinaryOperator::CreateLShr(AndCST,
6866 Shift->getOperand(1), "tmp");
6868 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6870 // Compute X & (C << Y).
6871 Instruction *NewAnd =
6872 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
6873 InsertNewInstBefore(NewAnd, ICI);
6875 ICI.setOperand(0, NewAnd);
6881 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6882 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6885 uint32_t TypeBits = RHSV.getBitWidth();
6887 // Check that the shift amount is in range. If not, don't perform
6888 // undefined shifts. When the shift is visited it will be
6890 if (ShAmt->uge(TypeBits))
6893 if (ICI.isEquality()) {
6894 // If we are comparing against bits always shifted out, the
6895 // comparison cannot succeed.
6897 Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6899 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6900 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6901 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6902 return ReplaceInstUsesWith(ICI, Cst);
6905 if (LHSI->hasOneUse()) {
6906 // Otherwise strength reduce the shift into an and.
6907 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6909 Context->getConstantInt(APInt::getLowBitsSet(TypeBits,
6910 TypeBits-ShAmtVal));
6913 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6914 Mask, LHSI->getName()+".mask");
6915 Value *And = InsertNewInstBefore(AndI, ICI);
6916 return new ICmpInst(*Context, ICI.getPredicate(), And,
6917 Context->getConstantInt(RHSV.lshr(ShAmtVal)));
6921 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6922 bool TrueIfSigned = false;
6923 if (LHSI->hasOneUse() &&
6924 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6925 // (X << 31) <s 0 --> (X&1) != 0
6926 Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
6927 (TypeBits-ShAmt->getZExtValue()-1));
6929 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6930 Mask, LHSI->getName()+".mask");
6931 Value *And = InsertNewInstBefore(AndI, ICI);
6933 return new ICmpInst(*Context,
6934 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6935 And, Context->getNullValue(And->getType()));
6940 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6941 case Instruction::AShr: {
6942 // Only handle equality comparisons of shift-by-constant.
6943 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6944 if (!ShAmt || !ICI.isEquality()) break;
6946 // Check that the shift amount is in range. If not, don't perform
6947 // undefined shifts. When the shift is visited it will be
6949 uint32_t TypeBits = RHSV.getBitWidth();
6950 if (ShAmt->uge(TypeBits))
6953 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6955 // If we are comparing against bits always shifted out, the
6956 // comparison cannot succeed.
6957 APInt Comp = RHSV << ShAmtVal;
6958 if (LHSI->getOpcode() == Instruction::LShr)
6959 Comp = Comp.lshr(ShAmtVal);
6961 Comp = Comp.ashr(ShAmtVal);
6963 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6964 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6965 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
6966 return ReplaceInstUsesWith(ICI, Cst);
6969 // Otherwise, check to see if the bits shifted out are known to be zero.
6970 // If so, we can compare against the unshifted value:
6971 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
6972 if (LHSI->hasOneUse() &&
6973 MaskedValueIsZero(LHSI->getOperand(0),
6974 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6975 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
6976 Context->getConstantExprShl(RHS, ShAmt));
6979 if (LHSI->hasOneUse()) {
6980 // Otherwise strength reduce the shift into an and.
6981 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6982 Constant *Mask = Context->getConstantInt(Val);
6985 BinaryOperator::CreateAnd(LHSI->getOperand(0),
6986 Mask, LHSI->getName()+".mask");
6987 Value *And = InsertNewInstBefore(AndI, ICI);
6988 return new ICmpInst(*Context, ICI.getPredicate(), And,
6989 Context->getConstantExprShl(RHS, ShAmt));
6994 case Instruction::SDiv:
6995 case Instruction::UDiv:
6996 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6997 // Fold this div into the comparison, producing a range check.
6998 // Determine, based on the divide type, what the range is being
6999 // checked. If there is an overflow on the low or high side, remember
7000 // it, otherwise compute the range [low, hi) bounding the new value.
7001 // See: InsertRangeTest above for the kinds of replacements possible.
7002 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7003 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7008 case Instruction::Add:
7009 // Fold: icmp pred (add, X, C1), C2
7011 if (!ICI.isEquality()) {
7012 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7014 const APInt &LHSV = LHSC->getValue();
7016 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7019 if (ICI.isSignedPredicate()) {
7020 if (CR.getLower().isSignBit()) {
7021 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
7022 Context->getConstantInt(CR.getUpper()));
7023 } else if (CR.getUpper().isSignBit()) {
7024 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
7025 Context->getConstantInt(CR.getLower()));
7028 if (CR.getLower().isMinValue()) {
7029 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
7030 Context->getConstantInt(CR.getUpper()));
7031 } else if (CR.getUpper().isMinValue()) {
7032 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
7033 Context->getConstantInt(CR.getLower()));
7040 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7041 if (ICI.isEquality()) {
7042 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7044 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7045 // the second operand is a constant, simplify a bit.
7046 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7047 switch (BO->getOpcode()) {
7048 case Instruction::SRem:
7049 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7050 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7051 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7052 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7053 Instruction *NewRem =
7054 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
7056 InsertNewInstBefore(NewRem, ICI);
7057 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
7058 Context->getNullValue(BO->getType()));
7062 case Instruction::Add:
7063 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7064 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7065 if (BO->hasOneUse())
7066 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7067 Context->getConstantExprSub(RHS, BOp1C));
7068 } else if (RHSV == 0) {
7069 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7070 // efficiently invertible, or if the add has just this one use.
7071 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7073 if (Value *NegVal = dyn_castNegVal(BOp1, Context))
7074 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
7075 else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
7076 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
7077 else if (BO->hasOneUse()) {
7078 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
7079 InsertNewInstBefore(Neg, ICI);
7081 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
7085 case Instruction::Xor:
7086 // For the xor case, we can xor two constants together, eliminating
7087 // the explicit xor.
7088 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
7089 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7090 Context->getConstantExprXor(RHS, BOC));
7093 case Instruction::Sub:
7094 // Replace (([sub|xor] A, B) != 0) with (A != B)
7096 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
7100 case Instruction::Or:
7101 // If bits are being or'd in that are not present in the constant we
7102 // are comparing against, then the comparison could never succeed!
7103 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
7104 Constant *NotCI = Context->getConstantExprNot(RHS);
7105 if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7106 return ReplaceInstUsesWith(ICI,
7107 Context->getConstantInt(Type::Int1Ty,
7112 case Instruction::And:
7113 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7114 // If bits are being compared against that are and'd out, then the
7115 // comparison can never succeed!
7116 if ((RHSV & ~BOC->getValue()) != 0)
7117 return ReplaceInstUsesWith(ICI,
7118 Context->getConstantInt(Type::Int1Ty,
7121 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7122 if (RHS == BOC && RHSV.isPowerOf2())
7123 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
7124 ICmpInst::ICMP_NE, LHSI,
7125 Context->getNullValue(RHS->getType()));
7127 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
7128 if (BOC->getValue().isSignBit()) {
7129 Value *X = BO->getOperand(0);
7130 Constant *Zero = Context->getNullValue(X->getType());
7131 ICmpInst::Predicate pred = isICMP_NE ?
7132 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
7133 return new ICmpInst(*Context, pred, X, Zero);
7136 // ((X & ~7) == 0) --> X < 8
7137 if (RHSV == 0 && isHighOnes(BOC)) {
7138 Value *X = BO->getOperand(0);
7139 Constant *NegX = Context->getConstantExprNeg(BOC);
7140 ICmpInst::Predicate pred = isICMP_NE ?
7141 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
7142 return new ICmpInst(*Context, pred, X, NegX);
7147 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7148 // Handle icmp {eq|ne} <intrinsic>, intcst.
7149 if (II->getIntrinsicID() == Intrinsic::bswap) {
7151 ICI.setOperand(0, II->getOperand(1));
7152 ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
7160 /// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7161 /// We only handle extending casts so far.
7163 Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7164 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7165 Value *LHSCIOp = LHSCI->getOperand(0);
7166 const Type *SrcTy = LHSCIOp->getType();
7167 const Type *DestTy = LHSCI->getType();
7170 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7171 // integer type is the same size as the pointer type.
7172 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7173 getTargetData().getPointerSizeInBits() ==
7174 cast<IntegerType>(DestTy)->getBitWidth()) {
7176 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
7177 RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
7178 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7179 RHSOp = RHSC->getOperand(0);
7180 // If the pointer types don't match, insert a bitcast.
7181 if (LHSCIOp->getType() != RHSOp->getType())
7182 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
7186 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
7189 // The code below only handles extension cast instructions, so far.
7191 if (LHSCI->getOpcode() != Instruction::ZExt &&
7192 LHSCI->getOpcode() != Instruction::SExt)
7195 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7196 bool isSignedCmp = ICI.isSignedPredicate();
7198 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7199 // Not an extension from the same type?
7200 RHSCIOp = CI->getOperand(0);
7201 if (RHSCIOp->getType() != LHSCIOp->getType())
7204 // If the signedness of the two casts doesn't agree (i.e. one is a sext
7205 // and the other is a zext), then we can't handle this.
7206 if (CI->getOpcode() != LHSCI->getOpcode())
7209 // Deal with equality cases early.
7210 if (ICI.isEquality())
7211 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7213 // A signed comparison of sign extended values simplifies into a
7214 // signed comparison.
7215 if (isSignedCmp && isSignedExt)
7216 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
7218 // The other three cases all fold into an unsigned comparison.
7219 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
7222 // If we aren't dealing with a constant on the RHS, exit early
7223 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7227 // Compute the constant that would happen if we truncated to SrcTy then
7228 // reextended to DestTy.
7229 Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7230 Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7233 // If the re-extended constant didn't change...
7235 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7236 // For example, we might have:
7237 // %A = sext i16 %X to i32
7238 // %B = icmp ugt i32 %A, 1330
7239 // It is incorrect to transform this into
7240 // %B = icmp ugt i16 %X, 1330
7241 // because %A may have negative value.
7243 // However, we allow this when the compare is EQ/NE, because they are
7245 if (isSignedExt == isSignedCmp || ICI.isEquality())
7246 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
7250 // The re-extended constant changed so the constant cannot be represented
7251 // in the shorter type. Consequently, we cannot emit a simple comparison.
7253 // First, handle some easy cases. We know the result cannot be equal at this
7254 // point so handle the ICI.isEquality() cases
7255 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
7256 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
7257 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
7258 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
7260 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7261 // should have been folded away previously and not enter in here.
7264 // We're performing a signed comparison.
7265 if (cast<ConstantInt>(CI)->getValue().isNegative())
7266 Result = Context->getConstantIntFalse(); // X < (small) --> false
7268 Result = Context->getConstantIntTrue(); // X < (large) --> true
7270 // We're performing an unsigned comparison.
7272 // We're performing an unsigned comp with a sign extended value.
7273 // This is true if the input is >= 0. [aka >s -1]
7274 Constant *NegOne = Context->getConstantIntAllOnesValue(SrcTy);
7275 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7276 LHSCIOp, NegOne, ICI.getName()), ICI);
7278 // Unsigned extend & unsigned compare -> always true.
7279 Result = Context->getConstantIntTrue();
7283 // Finally, return the value computed.
7284 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
7285 ICI.getPredicate() == ICmpInst::ICMP_SLT)
7286 return ReplaceInstUsesWith(ICI, Result);
7288 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7289 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7290 "ICmp should be folded!");
7291 if (Constant *CI = dyn_cast<Constant>(Result))
7292 return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
7293 return BinaryOperator::CreateNot(Result);
7296 Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7297 return commonShiftTransforms(I);
7300 Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7301 return commonShiftTransforms(I);
7304 Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
7305 if (Instruction *R = commonShiftTransforms(I))
7308 Value *Op0 = I.getOperand(0);
7310 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7311 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7312 if (CSI->isAllOnesValue())
7313 return ReplaceInstUsesWith(I, CSI);
7315 // See if we can turn a signed shr into an unsigned shr.
7316 if (MaskedValueIsZero(Op0,
7317 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7318 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7320 // Arithmetic shifting an all-sign-bit value is a no-op.
7321 unsigned NumSignBits = ComputeNumSignBits(Op0);
7322 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7323 return ReplaceInstUsesWith(I, Op0);
7328 Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7329 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7330 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7332 // shl X, 0 == X and shr X, 0 == X
7333 // shl 0, X == 0 and shr 0, X == 0
7334 if (Op1 == Context->getNullValue(Op1->getType()) ||
7335 Op0 == Context->getNullValue(Op0->getType()))
7336 return ReplaceInstUsesWith(I, Op0);
7338 if (isa<UndefValue>(Op0)) {
7339 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7340 return ReplaceInstUsesWith(I, Op0);
7341 else // undef << X -> 0, undef >>u X -> 0
7342 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7344 if (isa<UndefValue>(Op1)) {
7345 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7346 return ReplaceInstUsesWith(I, Op0);
7347 else // X << undef, X >>u undef -> 0
7348 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7351 // See if we can fold away this shift.
7352 if (SimplifyDemandedInstructionBits(I))
7355 // Try to fold constant and into select arguments.
7356 if (isa<Constant>(Op0))
7357 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7358 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7361 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7362 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7367 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7368 BinaryOperator &I) {
7369 bool isLeftShift = I.getOpcode() == Instruction::Shl;
7371 // See if we can simplify any instructions used by the instruction whose sole
7372 // purpose is to compute bits we don't care about.
7373 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
7375 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7378 if (Op1->uge(TypeBits)) {
7379 if (I.getOpcode() != Instruction::AShr)
7380 return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
7382 I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
7387 // ((X*C1) << C2) == (X * (C1 << C2))
7388 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7389 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7390 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
7391 return BinaryOperator::CreateMul(BO->getOperand(0),
7392 Context->getConstantExprShl(BOOp, Op1));
7394 // Try to fold constant and into select arguments.
7395 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7396 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7398 if (isa<PHINode>(Op0))
7399 if (Instruction *NV = FoldOpIntoPhi(I))
7402 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7403 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7404 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7405 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7406 // place. Don't try to do this transformation in this case. Also, we
7407 // require that the input operand is a shift-by-constant so that we have
7408 // confidence that the shifts will get folded together. We could do this
7409 // xform in more cases, but it is unlikely to be profitable.
7410 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7411 isa<ConstantInt>(TrOp->getOperand(1))) {
7412 // Okay, we'll do this xform. Make the shift of shift.
7413 Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
7414 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
7416 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7418 // For logical shifts, the truncation has the effect of making the high
7419 // part of the register be zeros. Emulate this by inserting an AND to
7420 // clear the top bits as needed. This 'and' will usually be zapped by
7421 // other xforms later if dead.
7422 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7423 unsigned DstSize = TI->getType()->getScalarSizeInBits();
7424 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7426 // The mask we constructed says what the trunc would do if occurring
7427 // between the shifts. We want to know the effect *after* the second
7428 // shift. We know that it is a logical shift by a constant, so adjust the
7429 // mask as appropriate.
7430 if (I.getOpcode() == Instruction::Shl)
7431 MaskV <<= Op1->getZExtValue();
7433 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7434 MaskV = MaskV.lshr(Op1->getZExtValue());
7438 BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV),
7440 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7442 // Return the value truncated to the interesting size.
7443 return new TruncInst(And, I.getType());
7447 if (Op0->hasOneUse()) {
7448 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7449 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7452 switch (Op0BO->getOpcode()) {
7454 case Instruction::Add:
7455 case Instruction::And:
7456 case Instruction::Or:
7457 case Instruction::Xor: {
7458 // These operators commute.
7459 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7460 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
7461 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
7462 Instruction *YS = BinaryOperator::CreateShl(
7463 Op0BO->getOperand(0), Op1,
7465 InsertNewInstBefore(YS, I); // (Y << C)
7467 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
7468 Op0BO->getOperand(1)->getName());
7469 InsertNewInstBefore(X, I); // (X + (Y << C))
7470 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7471 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7472 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7475 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7476 Value *Op0BOOp1 = Op0BO->getOperand(1);
7477 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7479 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7480 m_ConstantInt(CC))) &&
7481 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
7482 Instruction *YS = BinaryOperator::CreateShl(
7483 Op0BO->getOperand(0), Op1,
7485 InsertNewInstBefore(YS, I); // (Y << C)
7487 BinaryOperator::CreateAnd(V1,
7488 Context->getConstantExprShl(CC, Op1),
7489 V1->getName()+".mask");
7490 InsertNewInstBefore(XM, I); // X & (CC << C)
7492 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
7497 case Instruction::Sub: {
7498 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7499 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7500 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
7501 Instruction *YS = BinaryOperator::CreateShl(
7502 Op0BO->getOperand(1), Op1,
7504 InsertNewInstBefore(YS, I); // (Y << C)
7506 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
7507 Op0BO->getOperand(0)->getName());
7508 InsertNewInstBefore(X, I); // (X + (Y << C))
7509 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
7510 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
7511 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7514 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7515 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7516 match(Op0BO->getOperand(0),
7517 m_And(m_Shr(m_Value(V1), m_Value(V2)),
7518 m_ConstantInt(CC))) && V2 == Op1 &&
7519 cast<BinaryOperator>(Op0BO->getOperand(0))
7520 ->getOperand(0)->hasOneUse()) {
7521 Instruction *YS = BinaryOperator::CreateShl(
7522 Op0BO->getOperand(1), Op1,
7524 InsertNewInstBefore(YS, I); // (Y << C)
7526 BinaryOperator::CreateAnd(V1,
7527 Context->getConstantExprShl(CC, Op1),
7528 V1->getName()+".mask");
7529 InsertNewInstBefore(XM, I); // X & (CC << C)
7531 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
7539 // If the operand is an bitwise operator with a constant RHS, and the
7540 // shift is the only use, we can pull it out of the shift.
7541 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7542 bool isValid = true; // Valid only for And, Or, Xor
7543 bool highBitSet = false; // Transform if high bit of constant set?
7545 switch (Op0BO->getOpcode()) {
7546 default: isValid = false; break; // Do not perform transform!
7547 case Instruction::Add:
7548 isValid = isLeftShift;
7550 case Instruction::Or:
7551 case Instruction::Xor:
7554 case Instruction::And:
7559 // If this is a signed shift right, and the high bit is modified
7560 // by the logical operation, do not perform the transformation.
7561 // The highBitSet boolean indicates the value of the high bit of
7562 // the constant which would cause it to be modified for this
7565 if (isValid && I.getOpcode() == Instruction::AShr)
7566 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
7569 Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
7571 Instruction *NewShift =
7572 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
7573 InsertNewInstBefore(NewShift, I);
7574 NewShift->takeName(Op0BO);
7576 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
7583 // Find out if this is a shift of a shift by a constant.
7584 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7585 if (ShiftOp && !ShiftOp->isShift())
7588 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7589 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7590 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7591 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7592 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7593 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7594 Value *X = ShiftOp->getOperand(0);
7596 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
7598 const IntegerType *Ty = cast<IntegerType>(I.getType());
7600 // Check for (X << c1) << c2 and (X >> c1) >> c2
7601 if (I.getOpcode() == ShiftOp->getOpcode()) {
7602 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7604 if (AmtSum >= TypeBits) {
7605 if (I.getOpcode() != Instruction::AShr)
7606 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7607 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7610 return BinaryOperator::Create(I.getOpcode(), X,
7611 Context->getConstantInt(Ty, AmtSum));
7612 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7613 I.getOpcode() == Instruction::AShr) {
7614 if (AmtSum >= TypeBits)
7615 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
7617 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
7618 return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
7619 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7620 I.getOpcode() == Instruction::LShr) {
7621 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7622 if (AmtSum >= TypeBits)
7623 AmtSum = TypeBits-1;
7625 Instruction *Shift =
7626 BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
7627 InsertNewInstBefore(Shift, I);
7629 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7630 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7633 // Okay, if we get here, one shift must be left, and the other shift must be
7634 // right. See if the amounts are equal.
7635 if (ShiftAmt1 == ShiftAmt2) {
7636 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7637 if (I.getOpcode() == Instruction::Shl) {
7638 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
7639 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7641 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7642 if (I.getOpcode() == Instruction::LShr) {
7643 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
7644 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
7646 // We can simplify ((X << C) >>s C) into a trunc + sext.
7647 // NOTE: we could do this for any C, but that would make 'unusual' integer
7648 // types. For now, just stick to ones well-supported by the code
7650 const Type *SExtType = 0;
7651 switch (Ty->getBitWidth() - ShiftAmt1) {
7658 SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
7663 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7664 InsertNewInstBefore(NewTrunc, I);
7665 return new SExtInst(NewTrunc, Ty);
7667 // Otherwise, we can't handle it yet.
7668 } else if (ShiftAmt1 < ShiftAmt2) {
7669 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7671 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7672 if (I.getOpcode() == Instruction::Shl) {
7673 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7674 ShiftOp->getOpcode() == Instruction::AShr);
7675 Instruction *Shift =
7676 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7677 InsertNewInstBefore(Shift, I);
7679 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7680 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7683 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7684 if (I.getOpcode() == Instruction::LShr) {
7685 assert(ShiftOp->getOpcode() == Instruction::Shl);
7686 Instruction *Shift =
7687 BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
7688 InsertNewInstBefore(Shift, I);
7690 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7691 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7694 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7696 assert(ShiftAmt2 < ShiftAmt1);
7697 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7699 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7700 if (I.getOpcode() == Instruction::Shl) {
7701 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7702 ShiftOp->getOpcode() == Instruction::AShr);
7703 Instruction *Shift =
7704 BinaryOperator::Create(ShiftOp->getOpcode(), X,
7705 Context->getConstantInt(Ty, ShiftDiff));
7706 InsertNewInstBefore(Shift, I);
7708 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
7709 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7712 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7713 if (I.getOpcode() == Instruction::LShr) {
7714 assert(ShiftOp->getOpcode() == Instruction::Shl);
7715 Instruction *Shift =
7716 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
7717 InsertNewInstBefore(Shift, I);
7719 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
7720 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
7723 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7730 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7731 /// expression. If so, decompose it, returning some value X, such that Val is
7734 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7735 int &Offset, LLVMContext *Context) {
7736 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7737 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7738 Offset = CI->getZExtValue();
7740 return Context->getConstantInt(Type::Int32Ty, 0);
7741 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7742 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7743 if (I->getOpcode() == Instruction::Shl) {
7744 // This is a value scaled by '1 << the shift amt'.
7745 Scale = 1U << RHS->getZExtValue();
7747 return I->getOperand(0);
7748 } else if (I->getOpcode() == Instruction::Mul) {
7749 // This value is scaled by 'RHS'.
7750 Scale = RHS->getZExtValue();
7752 return I->getOperand(0);
7753 } else if (I->getOpcode() == Instruction::Add) {
7754 // We have X+C. Check to see if we really have (X*C2)+C1,
7755 // where C1 is divisible by C2.
7758 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7760 Offset += RHS->getZExtValue();
7767 // Otherwise, we can't look past this.
7774 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7775 /// try to eliminate the cast by moving the type information into the alloc.
7776 Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7777 AllocationInst &AI) {
7778 const PointerType *PTy = cast<PointerType>(CI.getType());
7780 // Remove any uses of AI that are dead.
7781 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7783 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7784 Instruction *User = cast<Instruction>(*UI++);
7785 if (isInstructionTriviallyDead(User)) {
7786 while (UI != E && *UI == User)
7787 ++UI; // If this instruction uses AI more than once, don't break UI.
7790 DOUT << "IC: DCE: " << *User;
7791 EraseInstFromFunction(*User);
7795 // Get the type really allocated and the type casted to.
7796 const Type *AllocElTy = AI.getAllocatedType();
7797 const Type *CastElTy = PTy->getElementType();
7798 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7800 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7801 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7802 if (CastElTyAlign < AllocElTyAlign) return 0;
7804 // If the allocation has multiple uses, only promote it if we are strictly
7805 // increasing the alignment of the resultant allocation. If we keep it the
7806 // same, we open the door to infinite loops of various kinds. (A reference
7807 // from a dbg.declare doesn't count as a use for this purpose.)
7808 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7809 CastElTyAlign == AllocElTyAlign) return 0;
7811 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7812 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
7813 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7815 // See if we can satisfy the modulus by pulling a scale out of the array
7817 unsigned ArraySizeScale;
7819 Value *NumElements = // See if the array size is a decomposable linear expr.
7820 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7821 ArrayOffset, Context);
7823 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7825 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7826 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7828 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7833 // If the allocation size is constant, form a constant mul expression
7834 Amt = Context->getConstantInt(Type::Int32Ty, Scale);
7835 if (isa<ConstantInt>(NumElements))
7836 Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
7837 cast<ConstantInt>(Amt));
7838 // otherwise multiply the amount and the number of elements
7840 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
7841 Amt = InsertNewInstBefore(Tmp, AI);
7845 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7846 Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
7847 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
7848 Amt = InsertNewInstBefore(Tmp, AI);
7851 AllocationInst *New;
7852 if (isa<MallocInst>(AI))
7853 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7855 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7856 InsertNewInstBefore(New, AI);
7859 // If the allocation has one real use plus a dbg.declare, just remove the
7861 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7862 EraseInstFromFunction(*DI);
7864 // If the allocation has multiple real uses, insert a cast and change all
7865 // things that used it to use the new cast. This will also hack on CI, but it
7867 else if (!AI.hasOneUse()) {
7868 AddUsesToWorkList(AI);
7869 // New is the allocation instruction, pointer typed. AI is the original
7870 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7871 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7872 InsertNewInstBefore(NewCast, AI);
7873 AI.replaceAllUsesWith(NewCast);
7875 return ReplaceInstUsesWith(CI, New);
7878 /// CanEvaluateInDifferentType - Return true if we can take the specified value
7879 /// and return it as type Ty without inserting any new casts and without
7880 /// changing the computed value. This is used by code that tries to decide
7881 /// whether promoting or shrinking integer operations to wider or smaller types
7882 /// will allow us to eliminate a truncate or extend.
7884 /// This is a truncation operation if Ty is smaller than V->getType(), or an
7885 /// extension operation if Ty is larger.
7887 /// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7888 /// should return true if trunc(V) can be computed by computing V in the smaller
7889 /// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7890 /// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7891 /// efficiently truncated.
7893 /// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7894 /// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7895 /// the final result.
7896 bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
7898 int &NumCastsRemoved){
7899 // We can always evaluate constants in another type.
7900 if (isa<Constant>(V))
7903 Instruction *I = dyn_cast<Instruction>(V);
7904 if (!I) return false;
7906 const Type *OrigTy = V->getType();
7908 // If this is an extension or truncate, we can often eliminate it.
7909 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7910 // If this is a cast from the destination type, we can trivially eliminate
7911 // it, and this will remove a cast overall.
7912 if (I->getOperand(0)->getType() == Ty) {
7913 // If the first operand is itself a cast, and is eliminable, do not count
7914 // this as an eliminable cast. We would prefer to eliminate those two
7916 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
7922 // We can't extend or shrink something that has multiple uses: doing so would
7923 // require duplicating the instruction in general, which isn't profitable.
7924 if (!I->hasOneUse()) return false;
7926 unsigned Opc = I->getOpcode();
7928 case Instruction::Add:
7929 case Instruction::Sub:
7930 case Instruction::Mul:
7931 case Instruction::And:
7932 case Instruction::Or:
7933 case Instruction::Xor:
7934 // These operators can all arbitrarily be extended or truncated.
7935 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7937 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7940 case Instruction::Shl:
7941 // If we are truncating the result of this SHL, and if it's a shift of a
7942 // constant amount, we can always perform a SHL in a smaller type.
7943 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7944 uint32_t BitWidth = Ty->getScalarSizeInBits();
7945 if (BitWidth < OrigTy->getScalarSizeInBits() &&
7946 CI->getLimitedValue(BitWidth) < BitWidth)
7947 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7951 case Instruction::LShr:
7952 // If this is a truncate of a logical shr, we can truncate it to a smaller
7953 // lshr iff we know that the bits we would otherwise be shifting in are
7955 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7956 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7957 uint32_t BitWidth = Ty->getScalarSizeInBits();
7958 if (BitWidth < OrigBitWidth &&
7959 MaskedValueIsZero(I->getOperand(0),
7960 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7961 CI->getLimitedValue(BitWidth) < BitWidth) {
7962 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7967 case Instruction::ZExt:
7968 case Instruction::SExt:
7969 case Instruction::Trunc:
7970 // If this is the same kind of case as our original (e.g. zext+zext), we
7971 // can safely replace it. Note that replacing it does not reduce the number
7972 // of casts in the input.
7976 // sext (zext ty1), ty2 -> zext ty2
7977 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
7980 case Instruction::Select: {
7981 SelectInst *SI = cast<SelectInst>(I);
7982 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
7984 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
7987 case Instruction::PHI: {
7988 // We can change a phi if we can change all operands.
7989 PHINode *PN = cast<PHINode>(I);
7990 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7991 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
7997 // TODO: Can handle more cases here.
8004 /// EvaluateInDifferentType - Given an expression that
8005 /// CanEvaluateInDifferentType returns true for, actually insert the code to
8006 /// evaluate the expression.
8007 Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
8009 if (Constant *C = dyn_cast<Constant>(V))
8010 return Context->getConstantExprIntegerCast(C, Ty,
8011 isSigned /*Sext or ZExt*/);
8013 // Otherwise, it must be an instruction.
8014 Instruction *I = cast<Instruction>(V);
8015 Instruction *Res = 0;
8016 unsigned Opc = I->getOpcode();
8018 case Instruction::Add:
8019 case Instruction::Sub:
8020 case Instruction::Mul:
8021 case Instruction::And:
8022 case Instruction::Or:
8023 case Instruction::Xor:
8024 case Instruction::AShr:
8025 case Instruction::LShr:
8026 case Instruction::Shl: {
8027 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8028 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8029 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
8032 case Instruction::Trunc:
8033 case Instruction::ZExt:
8034 case Instruction::SExt:
8035 // If the source type of the cast is the type we're trying for then we can
8036 // just return the source. There's no need to insert it because it is not
8038 if (I->getOperand(0)->getType() == Ty)
8039 return I->getOperand(0);
8041 // Otherwise, must be the same type of cast, so just reinsert a new one.
8042 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
8045 case Instruction::Select: {
8046 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8047 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8048 Res = SelectInst::Create(I->getOperand(0), True, False);
8051 case Instruction::PHI: {
8052 PHINode *OPN = cast<PHINode>(I);
8053 PHINode *NPN = PHINode::Create(Ty);
8054 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8055 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8056 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8062 // TODO: Can handle more cases here.
8063 assert(0 && "Unreachable!");
8068 return InsertNewInstBefore(Res, *I);
8071 /// @brief Implement the transforms common to all CastInst visitors.
8072 Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8073 Value *Src = CI.getOperand(0);
8075 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8076 // eliminate it now.
8077 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8078 if (Instruction::CastOps opc =
8079 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8080 // The first cast (CSrc) is eliminable so we need to fix up or replace
8081 // the second cast (CI). CSrc will then have a good chance of being dead.
8082 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
8086 // If we are casting a select then fold the cast into the select
8087 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8088 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8091 // If we are casting a PHI then fold the cast into the PHI
8092 if (isa<PHINode>(Src))
8093 if (Instruction *NV = FoldOpIntoPhi(CI))
8099 /// FindElementAtOffset - Given a type and a constant offset, determine whether
8100 /// or not there is a sequence of GEP indices into the type that will land us at
8101 /// the specified offset. If so, fill them into NewIndices and return the
8102 /// resultant element type, otherwise return null.
8103 static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8104 SmallVectorImpl<Value*> &NewIndices,
8105 const TargetData *TD,
8106 LLVMContext *Context) {
8107 if (!Ty->isSized()) return 0;
8109 // Start with the index over the outer type. Note that the type size
8110 // might be zero (even if the offset isn't zero) if the indexed type
8111 // is something like [0 x {int, int}]
8112 const Type *IntPtrTy = TD->getIntPtrType();
8113 int64_t FirstIdx = 0;
8114 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
8115 FirstIdx = Offset/TySize;
8116 Offset -= FirstIdx*TySize;
8118 // Handle hosts where % returns negative instead of values [0..TySize).
8122 assert(Offset >= 0);
8124 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8127 NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
8129 // Index into the types. If we fail, set OrigBase to null.
8131 // Indexing into tail padding between struct/array elements.
8132 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
8135 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8136 const StructLayout *SL = TD->getStructLayout(STy);
8137 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8138 "Offset must stay within the indexed type");
8140 unsigned Elt = SL->getElementContainingOffset(Offset);
8141 NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
8143 Offset -= SL->getElementOffset(Elt);
8144 Ty = STy->getElementType(Elt);
8145 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
8146 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
8147 assert(EltSize && "Cannot index into a zero-sized array");
8148 NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
8150 Ty = AT->getElementType();
8152 // Otherwise, we can't index into the middle of this atomic type, bail.
8160 /// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8161 Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8162 Value *Src = CI.getOperand(0);
8164 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8165 // If casting the result of a getelementptr instruction with no offset, turn
8166 // this into a cast of the original pointer!
8167 if (GEP->hasAllZeroIndices()) {
8168 // Changing the cast operand is usually not a good idea but it is safe
8169 // here because the pointer operand is being replaced with another
8170 // pointer operand so the opcode doesn't need to change.
8172 CI.setOperand(0, GEP->getOperand(0));
8176 // If the GEP has a single use, and the base pointer is a bitcast, and the
8177 // GEP computes a constant offset, see if we can convert these three
8178 // instructions into fewer. This typically happens with unions and other
8179 // non-type-safe code.
8180 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8181 if (GEP->hasAllConstantIndices()) {
8182 // We are guaranteed to get a constant from EmitGEPOffset.
8183 ConstantInt *OffsetV =
8184 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
8185 int64_t Offset = OffsetV->getSExtValue();
8187 // Get the base pointer input of the bitcast, and the type it points to.
8188 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8189 const Type *GEPIdxTy =
8190 cast<PointerType>(OrigBase->getType())->getElementType();
8191 SmallVector<Value*, 8> NewIndices;
8192 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
8193 // If we were able to index down into an element, create the GEP
8194 // and bitcast the result. This eliminates one bitcast, potentially
8196 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8198 NewIndices.end(), "");
8199 InsertNewInstBefore(NGEP, CI);
8200 NGEP->takeName(GEP);
8202 if (isa<BitCastInst>(CI))
8203 return new BitCastInst(NGEP, CI.getType());
8204 assert(isa<PtrToIntInst>(CI));
8205 return new PtrToIntInst(NGEP, CI.getType());
8211 return commonCastTransforms(CI);
8214 /// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8215 /// type like i42. We don't want to introduce operations on random non-legal
8216 /// integer types where they don't already exist in the code. In the future,
8217 /// we should consider making this based off target-data, so that 32-bit targets
8218 /// won't get i64 operations etc.
8219 static bool isSafeIntegerType(const Type *Ty) {
8220 switch (Ty->getPrimitiveSizeInBits()) {
8231 /// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
8232 /// integer types. This function implements the common transforms for all those
8234 /// @brief Implement the transforms common to CastInst with integer operands
8235 Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8236 if (Instruction *Result = commonCastTransforms(CI))
8239 Value *Src = CI.getOperand(0);
8240 const Type *SrcTy = Src->getType();
8241 const Type *DestTy = CI.getType();
8242 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8243 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
8245 // See if we can simplify any instructions used by the LHS whose sole
8246 // purpose is to compute bits we don't care about.
8247 if (SimplifyDemandedInstructionBits(CI))
8250 // If the source isn't an instruction or has more than one use then we
8251 // can't do anything more.
8252 Instruction *SrcI = dyn_cast<Instruction>(Src);
8253 if (!SrcI || !Src->hasOneUse())
8256 // Attempt to propagate the cast into the instruction for int->int casts.
8257 int NumCastsRemoved = 0;
8258 if (!isa<BitCastInst>(CI) &&
8259 // Only do this if the dest type is a simple type, don't convert the
8260 // expression tree to something weird like i93 unless the source is also
8262 (isSafeIntegerType(DestTy->getScalarType()) ||
8263 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8264 CanEvaluateInDifferentType(SrcI, DestTy,
8265 CI.getOpcode(), NumCastsRemoved)) {
8266 // If this cast is a truncate, evaluting in a different type always
8267 // eliminates the cast, so it is always a win. If this is a zero-extension,
8268 // we need to do an AND to maintain the clear top-part of the computation,
8269 // so we require that the input have eliminated at least one cast. If this
8270 // is a sign extension, we insert two new casts (to do the extension) so we
8271 // require that two casts have been eliminated.
8272 bool DoXForm = false;
8273 bool JustReplace = false;
8274 switch (CI.getOpcode()) {
8276 // All the others use floating point so we shouldn't actually
8277 // get here because of the check above.
8278 assert(0 && "Unknown cast type");
8279 case Instruction::Trunc:
8282 case Instruction::ZExt: {
8283 DoXForm = NumCastsRemoved >= 1;
8284 if (!DoXForm && 0) {
8285 // If it's unnecessary to issue an AND to clear the high bits, it's
8286 // always profitable to do this xform.
8287 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
8288 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8289 if (MaskedValueIsZero(TryRes, Mask))
8290 return ReplaceInstUsesWith(CI, TryRes);
8292 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8293 if (TryI->use_empty())
8294 EraseInstFromFunction(*TryI);
8298 case Instruction::SExt: {
8299 DoXForm = NumCastsRemoved >= 2;
8300 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
8301 // If we do not have to emit the truncate + sext pair, then it's always
8302 // profitable to do this xform.
8304 // It's not safe to eliminate the trunc + sext pair if one of the
8305 // eliminated cast is a truncate. e.g.
8306 // t2 = trunc i32 t1 to i16
8307 // t3 = sext i16 t2 to i32
8310 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
8311 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8312 if (NumSignBits > (DestBitSize - SrcBitSize))
8313 return ReplaceInstUsesWith(CI, TryRes);
8315 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
8316 if (TryI->use_empty())
8317 EraseInstFromFunction(*TryI);
8324 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8326 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8327 CI.getOpcode() == Instruction::SExt);
8329 // Just replace this cast with the result.
8330 return ReplaceInstUsesWith(CI, Res);
8332 assert(Res->getType() == DestTy);
8333 switch (CI.getOpcode()) {
8334 default: assert(0 && "Unknown cast type!");
8335 case Instruction::Trunc:
8336 case Instruction::BitCast:
8337 // Just replace this cast with the result.
8338 return ReplaceInstUsesWith(CI, Res);
8339 case Instruction::ZExt: {
8340 assert(SrcBitSize < DestBitSize && "Not a zext?");
8342 // If the high bits are already zero, just replace this cast with the
8344 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8345 if (MaskedValueIsZero(Res, Mask))
8346 return ReplaceInstUsesWith(CI, Res);
8348 // We need to emit an AND to clear the high bits.
8349 Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
8351 return BinaryOperator::CreateAnd(Res, C);
8353 case Instruction::SExt: {
8354 // If the high bits are already filled with sign bit, just replace this
8355 // cast with the result.
8356 unsigned NumSignBits = ComputeNumSignBits(Res);
8357 if (NumSignBits > (DestBitSize - SrcBitSize))
8358 return ReplaceInstUsesWith(CI, Res);
8360 // We need to emit a cast to truncate, then a cast to sext.
8361 return CastInst::Create(Instruction::SExt,
8362 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8369 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8370 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8372 switch (SrcI->getOpcode()) {
8373 case Instruction::Add:
8374 case Instruction::Mul:
8375 case Instruction::And:
8376 case Instruction::Or:
8377 case Instruction::Xor:
8378 // If we are discarding information, rewrite.
8379 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8380 // Don't insert two casts if they cannot be eliminated. We allow
8381 // two casts to be inserted if the sizes are the same. This could
8382 // only be converting signedness, which is a noop.
8383 if (DestBitSize == SrcBitSize ||
8384 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8385 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8386 Instruction::CastOps opcode = CI.getOpcode();
8387 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8388 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8389 return BinaryOperator::Create(
8390 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8394 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8395 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8396 SrcI->getOpcode() == Instruction::Xor &&
8397 Op1 == Context->getConstantIntTrue() &&
8398 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
8399 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
8400 return BinaryOperator::CreateXor(New,
8401 Context->getConstantInt(CI.getType(), 1));
8404 case Instruction::SDiv:
8405 case Instruction::UDiv:
8406 case Instruction::SRem:
8407 case Instruction::URem:
8408 // If we are just changing the sign, rewrite.
8409 if (DestBitSize == SrcBitSize) {
8410 // Don't insert two casts if they cannot be eliminated. We allow
8411 // two casts to be inserted if the sizes are the same. This could
8412 // only be converting signedness, which is a noop.
8413 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8414 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8415 Value *Op0c = InsertCastBefore(Instruction::BitCast,
8416 Op0, DestTy, *SrcI);
8417 Value *Op1c = InsertCastBefore(Instruction::BitCast,
8418 Op1, DestTy, *SrcI);
8419 return BinaryOperator::Create(
8420 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8425 case Instruction::Shl:
8426 // Allow changing the sign of the source operand. Do not allow
8427 // changing the size of the shift, UNLESS the shift amount is a
8428 // constant. We must not change variable sized shifts to a smaller
8429 // size, because it is undefined to shift more bits out than exist
8431 if (DestBitSize == SrcBitSize ||
8432 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
8433 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8434 Instruction::BitCast : Instruction::Trunc);
8435 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8436 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
8437 return BinaryOperator::CreateShl(Op0c, Op1c);
8440 case Instruction::AShr:
8441 // If this is a signed shr, and if all bits shifted in are about to be
8442 // truncated off, turn it into an unsigned shr to allow greater
8444 if (DestBitSize < SrcBitSize &&
8445 isa<ConstantInt>(Op1)) {
8446 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
8447 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8448 // Insert the new logical shift right.
8449 return BinaryOperator::CreateLShr(Op0, Op1);
8457 Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8458 if (Instruction *Result = commonIntCastTransforms(CI))
8461 Value *Src = CI.getOperand(0);
8462 const Type *Ty = CI.getType();
8463 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8464 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
8466 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
8467 if (DestBitWidth == 1 &&
8468 isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
8469 Constant *One = Context->getConstantInt(Src->getType(), 1);
8470 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
8471 Value *Zero = Context->getNullValue(Src->getType());
8472 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
8475 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8476 ConstantInt *ShAmtV = 0;
8478 if (Src->hasOneUse() &&
8479 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
8480 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8482 // Get a mask for the bits shifting in.
8483 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8484 if (MaskedValueIsZero(ShiftOp, Mask)) {
8485 if (ShAmt >= DestBitWidth) // All zeros.
8486 return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
8488 // Okay, we can shrink this. Truncate the input, then return a new
8490 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
8491 Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
8492 return BinaryOperator::CreateLShr(V1, V2);
8499 /// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8500 /// in order to eliminate the icmp.
8501 Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8503 // If we are just checking for a icmp eq of a single bit and zext'ing it
8504 // to an integer, then shift the bit to the appropriate place and then
8505 // cast to integer to avoid the comparison.
8506 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8507 const APInt &Op1CV = Op1C->getValue();
8509 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8510 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8511 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8512 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8513 if (!DoXform) return ICI;
8515 Value *In = ICI->getOperand(0);
8516 Value *Sh = Context->getConstantInt(In->getType(),
8517 In->getType()->getScalarSizeInBits()-1);
8518 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
8519 In->getName()+".lobit"),
8521 if (In->getType() != CI.getType())
8522 In = CastInst::CreateIntegerCast(In, CI.getType(),
8523 false/*ZExt*/, "tmp", &CI);
8525 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8526 Constant *One = Context->getConstantInt(In->getType(), 1);
8527 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
8528 In->getName()+".not"),
8532 return ReplaceInstUsesWith(CI, In);
8537 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8538 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8539 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8540 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8541 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8542 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8543 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8544 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8545 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8546 // This only works for EQ and NE
8547 ICI->isEquality()) {
8548 // If Op1C some other power of two, convert:
8549 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8550 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8551 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8552 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8554 APInt KnownZeroMask(~KnownZero);
8555 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8556 if (!DoXform) return ICI;
8558 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8559 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8560 // (X&4) == 2 --> false
8561 // (X&4) != 2 --> true
8562 Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8563 Res = Context->getConstantExprZExt(Res, CI.getType());
8564 return ReplaceInstUsesWith(CI, Res);
8567 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8568 Value *In = ICI->getOperand(0);
8570 // Perform a logical shr by shiftamt.
8571 // Insert the shift to put the result in the low bit.
8572 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
8573 Context->getConstantInt(In->getType(), ShiftAmt),
8574 In->getName()+".lobit"), CI);
8577 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8578 Constant *One = Context->getConstantInt(In->getType(), 1);
8579 In = BinaryOperator::CreateXor(In, One, "tmp");
8580 InsertNewInstBefore(cast<Instruction>(In), CI);
8583 if (CI.getType() == In->getType())
8584 return ReplaceInstUsesWith(CI, In);
8586 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
8594 Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8595 // If one of the common conversion will work ..
8596 if (Instruction *Result = commonIntCastTransforms(CI))
8599 Value *Src = CI.getOperand(0);
8601 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8602 // types and if the sizes are just right we can convert this into a logical
8603 // 'and' which will be much cheaper than the pair of casts.
8604 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8605 // Get the sizes of the types involved. We know that the intermediate type
8606 // will be smaller than A or C, but don't know the relation between A and C.
8607 Value *A = CSrc->getOperand(0);
8608 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8609 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8610 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8611 // If we're actually extending zero bits, then if
8612 // SrcSize < DstSize: zext(a & mask)
8613 // SrcSize == DstSize: a & mask
8614 // SrcSize > DstSize: trunc(a) & mask
8615 if (SrcSize < DstSize) {
8616 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8617 Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
8619 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8620 InsertNewInstBefore(And, CI);
8621 return new ZExtInst(And, CI.getType());
8622 } else if (SrcSize == DstSize) {
8623 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8624 return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
8626 } else if (SrcSize > DstSize) {
8627 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8628 InsertNewInstBefore(Trunc, CI);
8629 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
8630 return BinaryOperator::CreateAnd(Trunc,
8631 Context->getConstantInt(Trunc->getType(),
8636 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8637 return transformZExtICmp(ICI, CI);
8639 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8640 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8641 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8642 // of the (zext icmp) will be transformed.
8643 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8644 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8645 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8646 (transformZExtICmp(LHS, CI, false) ||
8647 transformZExtICmp(RHS, CI, false))) {
8648 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8649 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
8650 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
8654 // zext(trunc(t) & C) -> (t & zext(C)).
8655 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8656 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8657 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8658 Value *TI0 = TI->getOperand(0);
8659 if (TI0->getType() == CI.getType())
8661 BinaryOperator::CreateAnd(TI0,
8662 Context->getConstantExprZExt(C, CI.getType()));
8665 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8666 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8667 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8668 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8669 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8670 And->getOperand(1) == C)
8671 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8672 Value *TI0 = TI->getOperand(0);
8673 if (TI0->getType() == CI.getType()) {
8674 Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
8675 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8676 InsertNewInstBefore(NewAnd, *And);
8677 return BinaryOperator::CreateXor(NewAnd, ZC);
8684 Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8685 if (Instruction *I = commonIntCastTransforms(CI))
8688 Value *Src = CI.getOperand(0);
8690 // Canonicalize sign-extend from i1 to a select.
8691 if (Src->getType() == Type::Int1Ty)
8692 return SelectInst::Create(Src,
8693 Context->getConstantIntAllOnesValue(CI.getType()),
8694 Context->getNullValue(CI.getType()));
8696 // See if the value being truncated is already sign extended. If so, just
8697 // eliminate the trunc/sext pair.
8698 if (getOpcode(Src) == Instruction::Trunc) {
8699 Value *Op = cast<User>(Src)->getOperand(0);
8700 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8701 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8702 unsigned DestBits = CI.getType()->getScalarSizeInBits();
8703 unsigned NumSignBits = ComputeNumSignBits(Op);
8705 if (OpBits == DestBits) {
8706 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8707 // bits, it is already ready.
8708 if (NumSignBits > DestBits-MidBits)
8709 return ReplaceInstUsesWith(CI, Op);
8710 } else if (OpBits < DestBits) {
8711 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8712 // bits, just sext from i32.
8713 if (NumSignBits > OpBits-MidBits)
8714 return new SExtInst(Op, CI.getType(), "tmp");
8716 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8717 // bits, just truncate to i32.
8718 if (NumSignBits > OpBits-MidBits)
8719 return new TruncInst(Op, CI.getType(), "tmp");
8723 // If the input is a shl/ashr pair of a same constant, then this is a sign
8724 // extension from a smaller value. If we could trust arbitrary bitwidth
8725 // integers, we could turn this into a truncate to the smaller bit and then
8726 // use a sext for the whole extension. Since we don't, look deeper and check
8727 // for a truncate. If the source and dest are the same type, eliminate the
8728 // trunc and extend and just do shifts. For example, turn:
8729 // %a = trunc i32 %i to i8
8730 // %b = shl i8 %a, 6
8731 // %c = ashr i8 %b, 6
8732 // %d = sext i8 %c to i32
8734 // %a = shl i32 %i, 30
8735 // %d = ashr i32 %a, 30
8737 ConstantInt *BA = 0, *CA = 0;
8738 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8739 m_ConstantInt(CA))) &&
8740 BA == CA && isa<TruncInst>(A)) {
8741 Value *I = cast<TruncInst>(A)->getOperand(0);
8742 if (I->getType() == CI.getType()) {
8743 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8744 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
8745 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8746 Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
8747 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8749 return BinaryOperator::CreateAShr(I, ShAmtV);
8756 /// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8757 /// in the specified FP type without changing its value.
8758 static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
8759 LLVMContext *Context) {
8761 APFloat F = CFP->getValueAPF();
8762 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8764 return Context->getConstantFP(F);
8768 /// LookThroughFPExtensions - If this is an fp extension instruction, look
8769 /// through it until we get the source value.
8770 static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
8771 if (Instruction *I = dyn_cast<Instruction>(V))
8772 if (I->getOpcode() == Instruction::FPExt)
8773 return LookThroughFPExtensions(I->getOperand(0), Context);
8775 // If this value is a constant, return the constant in the smallest FP type
8776 // that can accurately represent it. This allows us to turn
8777 // (float)((double)X+2.0) into x+2.0f.
8778 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8779 if (CFP->getType() == Type::PPC_FP128Ty)
8780 return V; // No constant folding of this.
8781 // See if the value can be truncated to float and then reextended.
8782 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
8784 if (CFP->getType() == Type::DoubleTy)
8785 return V; // Won't shrink.
8786 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
8788 // Don't try to shrink to various long double types.
8794 Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8795 if (Instruction *I = commonCastTransforms(CI))
8798 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
8799 // smaller than the destination type, we can eliminate the truncate by doing
8800 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
8801 // many builtins (sqrt, etc).
8802 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8803 if (OpI && OpI->hasOneUse()) {
8804 switch (OpI->getOpcode()) {
8806 case Instruction::FAdd:
8807 case Instruction::FSub:
8808 case Instruction::FMul:
8809 case Instruction::FDiv:
8810 case Instruction::FRem:
8811 const Type *SrcTy = OpI->getType();
8812 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8813 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
8814 if (LHSTrunc->getType() != SrcTy &&
8815 RHSTrunc->getType() != SrcTy) {
8816 unsigned DstSize = CI.getType()->getScalarSizeInBits();
8817 // If the source types were both smaller than the destination type of
8818 // the cast, do this xform.
8819 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8820 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
8821 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8823 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8825 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
8834 Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8835 return commonCastTransforms(CI);
8838 Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
8839 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8841 return commonCastTransforms(FI);
8843 // fptoui(uitofp(X)) --> X
8844 // fptoui(sitofp(X)) --> X
8845 // This is safe if the intermediate type has enough bits in its mantissa to
8846 // accurately represent all values of X. For example, do not do this with
8847 // i64->float->i64. This is also safe for sitofp case, because any negative
8848 // 'X' value would cause an undefined result for the fptoui.
8849 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8850 OpI->getOperand(0)->getType() == FI.getType() &&
8851 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
8852 OpI->getType()->getFPMantissaWidth())
8853 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8855 return commonCastTransforms(FI);
8858 Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
8859 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8861 return commonCastTransforms(FI);
8863 // fptosi(sitofp(X)) --> X
8864 // fptosi(uitofp(X)) --> X
8865 // This is safe if the intermediate type has enough bits in its mantissa to
8866 // accurately represent all values of X. For example, do not do this with
8867 // i64->float->i64. This is also safe for sitofp case, because any negative
8868 // 'X' value would cause an undefined result for the fptoui.
8869 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8870 OpI->getOperand(0)->getType() == FI.getType() &&
8871 (int)FI.getType()->getScalarSizeInBits() <=
8872 OpI->getType()->getFPMantissaWidth())
8873 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
8875 return commonCastTransforms(FI);
8878 Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8879 return commonCastTransforms(CI);
8882 Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8883 return commonCastTransforms(CI);
8886 Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8887 // If the destination integer type is smaller than the intptr_t type for
8888 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8889 // trunc to be exposed to other transforms. Don't do this for extending
8890 // ptrtoint's, because we don't know if the target sign or zero extends its
8892 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
8893 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8894 TD->getIntPtrType(),
8896 return new TruncInst(P, CI.getType());
8899 return commonPointerCastTransforms(CI);
8902 Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8903 // If the source integer type is larger than the intptr_t type for
8904 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8905 // allows the trunc to be exposed to other transforms. Don't do this for
8906 // extending inttoptr's, because we don't know if the target sign or zero
8907 // extends to pointers.
8908 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
8909 TD->getPointerSizeInBits()) {
8910 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8911 TD->getIntPtrType(),
8913 return new IntToPtrInst(P, CI.getType());
8916 if (Instruction *I = commonCastTransforms(CI))
8919 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8920 if (!DestPointee->isSized()) return 0;
8922 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8925 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8926 m_ConstantInt(Cst)))) {
8927 // If the source and destination operands have the same type, see if this
8928 // is a single-index GEP.
8929 if (X->getType() == CI.getType()) {
8930 // Get the size of the pointee type.
8931 uint64_t Size = TD->getTypeAllocSize(DestPointee);
8933 // Convert the constant to intptr type.
8934 APInt Offset = Cst->getValue();
8935 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8937 // If Offset is evenly divisible by Size, we can do this xform.
8938 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8939 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8940 return GetElementPtrInst::Create(X, Context->getConstantInt(Offset));
8943 // TODO: Could handle other cases, e.g. where add is indexing into field of
8945 } else if (CI.getOperand(0)->hasOneUse() &&
8946 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8947 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8948 // "inttoptr+GEP" instead of "add+intptr".
8950 // Get the size of the pointee type.
8951 uint64_t Size = TD->getTypeAllocSize(DestPointee);
8953 // Convert the constant to intptr type.
8954 APInt Offset = Cst->getValue();
8955 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8957 // If Offset is evenly divisible by Size, we can do this xform.
8958 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8959 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8961 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8963 return GetElementPtrInst::Create(P,
8964 Context->getConstantInt(Offset), "tmp");
8970 Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8971 // If the operands are integer typed then apply the integer transforms,
8972 // otherwise just apply the common ones.
8973 Value *Src = CI.getOperand(0);
8974 const Type *SrcTy = Src->getType();
8975 const Type *DestTy = CI.getType();
8977 if (SrcTy->isInteger() && DestTy->isInteger()) {
8978 if (Instruction *Result = commonIntCastTransforms(CI))
8980 } else if (isa<PointerType>(SrcTy)) {
8981 if (Instruction *I = commonPointerCastTransforms(CI))
8984 if (Instruction *Result = commonCastTransforms(CI))
8989 // Get rid of casts from one type to the same type. These are useless and can
8990 // be replaced by the operand.
8991 if (DestTy == Src->getType())
8992 return ReplaceInstUsesWith(CI, Src);
8994 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8995 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8996 const Type *DstElTy = DstPTy->getElementType();
8997 const Type *SrcElTy = SrcPTy->getElementType();
8999 // If the address spaces don't match, don't eliminate the bitcast, which is
9000 // required for changing types.
9001 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9004 // If we are casting a malloc or alloca to a pointer to a type of the same
9005 // size, rewrite the allocation instruction to allocate the "right" type.
9006 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
9007 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9010 // If the source and destination are pointers, and this cast is equivalent
9011 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
9012 // This can enhance SROA and other transforms that want type-safe pointers.
9013 Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
9014 unsigned NumZeros = 0;
9015 while (SrcElTy != DstElTy &&
9016 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9017 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9018 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9022 // If we found a path from the src to dest, create the getelementptr now.
9023 if (SrcElTy == DstElTy) {
9024 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
9025 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
9026 ((Instruction*) NULL));
9030 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9031 if (SVI->hasOneUse()) {
9032 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9033 // a bitconvert to a vector with the same # elts.
9034 if (isa<VectorType>(DestTy) &&
9035 cast<VectorType>(DestTy)->getNumElements() ==
9036 SVI->getType()->getNumElements() &&
9037 SVI->getType()->getNumElements() ==
9038 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
9040 // If either of the operands is a cast from CI.getType(), then
9041 // evaluating the shuffle in the casted destination's type will allow
9042 // us to eliminate at least one cast.
9043 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9044 Tmp->getOperand(0)->getType() == DestTy) ||
9045 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9046 Tmp->getOperand(0)->getType() == DestTy)) {
9047 Value *LHS = InsertCastBefore(Instruction::BitCast,
9048 SVI->getOperand(0), DestTy, CI);
9049 Value *RHS = InsertCastBefore(Instruction::BitCast,
9050 SVI->getOperand(1), DestTy, CI);
9051 // Return a new shuffle vector. Use the same element ID's, as we
9052 // know the vector types match #elts.
9053 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9061 /// GetSelectFoldableOperands - We want to turn code that looks like this:
9063 /// %D = select %cond, %C, %A
9065 /// %C = select %cond, %B, 0
9068 /// Assuming that the specified instruction is an operand to the select, return
9069 /// a bitmask indicating which operands of this instruction are foldable if they
9070 /// equal the other incoming value of the select.
9072 static unsigned GetSelectFoldableOperands(Instruction *I) {
9073 switch (I->getOpcode()) {
9074 case Instruction::Add:
9075 case Instruction::Mul:
9076 case Instruction::And:
9077 case Instruction::Or:
9078 case Instruction::Xor:
9079 return 3; // Can fold through either operand.
9080 case Instruction::Sub: // Can only fold on the amount subtracted.
9081 case Instruction::Shl: // Can only fold on the shift amount.
9082 case Instruction::LShr:
9083 case Instruction::AShr:
9086 return 0; // Cannot fold
9090 /// GetSelectFoldableConstant - For the same transformation as the previous
9091 /// function, return the identity constant that goes into the select.
9092 static Constant *GetSelectFoldableConstant(Instruction *I,
9093 LLVMContext *Context) {
9094 switch (I->getOpcode()) {
9095 default: assert(0 && "This cannot happen!"); abort();
9096 case Instruction::Add:
9097 case Instruction::Sub:
9098 case Instruction::Or:
9099 case Instruction::Xor:
9100 case Instruction::Shl:
9101 case Instruction::LShr:
9102 case Instruction::AShr:
9103 return Context->getNullValue(I->getType());
9104 case Instruction::And:
9105 return Context->getAllOnesValue(I->getType());
9106 case Instruction::Mul:
9107 return Context->getConstantInt(I->getType(), 1);
9111 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9112 /// have the same opcode and only one use each. Try to simplify this.
9113 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9115 if (TI->getNumOperands() == 1) {
9116 // If this is a non-volatile load or a cast from the same type,
9119 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9122 return 0; // unknown unary op.
9125 // Fold this by inserting a select from the input values.
9126 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9127 FI->getOperand(0), SI.getName()+".v");
9128 InsertNewInstBefore(NewSI, SI);
9129 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
9133 // Only handle binary operators here.
9134 if (!isa<BinaryOperator>(TI))
9137 // Figure out if the operations have any operands in common.
9138 Value *MatchOp, *OtherOpT, *OtherOpF;
9140 if (TI->getOperand(0) == FI->getOperand(0)) {
9141 MatchOp = TI->getOperand(0);
9142 OtherOpT = TI->getOperand(1);
9143 OtherOpF = FI->getOperand(1);
9144 MatchIsOpZero = true;
9145 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9146 MatchOp = TI->getOperand(1);
9147 OtherOpT = TI->getOperand(0);
9148 OtherOpF = FI->getOperand(0);
9149 MatchIsOpZero = false;
9150 } else if (!TI->isCommutative()) {
9152 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9153 MatchOp = TI->getOperand(0);
9154 OtherOpT = TI->getOperand(1);
9155 OtherOpF = FI->getOperand(0);
9156 MatchIsOpZero = true;
9157 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9158 MatchOp = TI->getOperand(1);
9159 OtherOpT = TI->getOperand(0);
9160 OtherOpF = FI->getOperand(1);
9161 MatchIsOpZero = true;
9166 // If we reach here, they do have operations in common.
9167 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9168 OtherOpF, SI.getName()+".v");
9169 InsertNewInstBefore(NewSI, SI);
9171 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9173 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
9175 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
9177 assert(0 && "Shouldn't get here");
9181 static bool isSelect01(Constant *C1, Constant *C2) {
9182 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9185 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9188 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9191 /// FoldSelectIntoOp - Try fold the select into one of the operands to
9192 /// facilitate further optimization.
9193 Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9195 // See the comment above GetSelectFoldableOperands for a description of the
9196 // transformation we are doing here.
9197 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9198 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9199 !isa<Constant>(FalseVal)) {
9200 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9201 unsigned OpToFold = 0;
9202 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9204 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9209 Constant *C = GetSelectFoldableConstant(TVI, Context);
9210 Value *OOp = TVI->getOperand(2-OpToFold);
9211 // Avoid creating select between 2 constants unless it's selecting
9213 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9214 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9215 InsertNewInstBefore(NewSel, SI);
9216 NewSel->takeName(TVI);
9217 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9218 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9219 assert(0 && "Unknown instruction!!");
9226 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9227 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9228 !isa<Constant>(TrueVal)) {
9229 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9230 unsigned OpToFold = 0;
9231 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9233 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9238 Constant *C = GetSelectFoldableConstant(FVI, Context);
9239 Value *OOp = FVI->getOperand(2-OpToFold);
9240 // Avoid creating select between 2 constants unless it's selecting
9242 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9243 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9244 InsertNewInstBefore(NewSel, SI);
9245 NewSel->takeName(FVI);
9246 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9247 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9248 assert(0 && "Unknown instruction!!");
9258 /// visitSelectInstWithICmp - Visit a SelectInst that has an
9259 /// ICmpInst as its first operand.
9261 Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9263 bool Changed = false;
9264 ICmpInst::Predicate Pred = ICI->getPredicate();
9265 Value *CmpLHS = ICI->getOperand(0);
9266 Value *CmpRHS = ICI->getOperand(1);
9267 Value *TrueVal = SI.getTrueValue();
9268 Value *FalseVal = SI.getFalseValue();
9270 // Check cases where the comparison is with a constant that
9271 // can be adjusted to fit the min/max idiom. We may edit ICI in
9272 // place here, so make sure the select is the only user.
9273 if (ICI->hasOneUse())
9274 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
9277 case ICmpInst::ICMP_ULT:
9278 case ICmpInst::ICMP_SLT: {
9279 // X < MIN ? T : F --> F
9280 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9281 return ReplaceInstUsesWith(SI, FalseVal);
9282 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
9283 Constant *AdjustedRHS = SubOne(CI, Context);
9284 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9285 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9286 Pred = ICmpInst::getSwappedPredicate(Pred);
9287 CmpRHS = AdjustedRHS;
9288 std::swap(FalseVal, TrueVal);
9289 ICI->setPredicate(Pred);
9290 ICI->setOperand(1, CmpRHS);
9291 SI.setOperand(1, TrueVal);
9292 SI.setOperand(2, FalseVal);
9297 case ICmpInst::ICMP_UGT:
9298 case ICmpInst::ICMP_SGT: {
9299 // X > MAX ? T : F --> F
9300 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9301 return ReplaceInstUsesWith(SI, FalseVal);
9302 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
9303 Constant *AdjustedRHS = AddOne(CI, Context);
9304 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9305 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9306 Pred = ICmpInst::getSwappedPredicate(Pred);
9307 CmpRHS = AdjustedRHS;
9308 std::swap(FalseVal, TrueVal);
9309 ICI->setPredicate(Pred);
9310 ICI->setOperand(1, CmpRHS);
9311 SI.setOperand(1, TrueVal);
9312 SI.setOperand(2, FalseVal);
9319 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9320 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
9321 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
9322 if (match(TrueVal, m_ConstantInt<-1>()) &&
9323 match(FalseVal, m_ConstantInt<0>()))
9324 Pred = ICI->getPredicate();
9325 else if (match(TrueVal, m_ConstantInt<0>()) &&
9326 match(FalseVal, m_ConstantInt<-1>()))
9327 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9329 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9330 // If we are just checking for a icmp eq of a single bit and zext'ing it
9331 // to an integer, then shift the bit to the appropriate place and then
9332 // cast to integer to avoid the comparison.
9333 const APInt &Op1CV = CI->getValue();
9335 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9336 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9337 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
9338 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
9339 Value *In = ICI->getOperand(0);
9340 Value *Sh = Context->getConstantInt(In->getType(),
9341 In->getType()->getScalarSizeInBits()-1);
9342 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9343 In->getName()+".lobit"),
9345 if (In->getType() != SI.getType())
9346 In = CastInst::CreateIntegerCast(In, SI.getType(),
9347 true/*SExt*/, "tmp", ICI);
9349 if (Pred == ICmpInst::ICMP_SGT)
9350 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9351 In->getName()+".not"), *ICI);
9353 return ReplaceInstUsesWith(SI, In);
9358 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9359 // Transform (X == Y) ? X : Y -> Y
9360 if (Pred == ICmpInst::ICMP_EQ)
9361 return ReplaceInstUsesWith(SI, FalseVal);
9362 // Transform (X != Y) ? X : Y -> X
9363 if (Pred == ICmpInst::ICMP_NE)
9364 return ReplaceInstUsesWith(SI, TrueVal);
9365 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9367 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9368 // Transform (X == Y) ? Y : X -> X
9369 if (Pred == ICmpInst::ICMP_EQ)
9370 return ReplaceInstUsesWith(SI, FalseVal);
9371 // Transform (X != Y) ? Y : X -> Y
9372 if (Pred == ICmpInst::ICMP_NE)
9373 return ReplaceInstUsesWith(SI, TrueVal);
9374 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9377 /// NOTE: if we wanted to, this is where to detect integer ABS
9379 return Changed ? &SI : 0;
9382 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9383 Value *CondVal = SI.getCondition();
9384 Value *TrueVal = SI.getTrueValue();
9385 Value *FalseVal = SI.getFalseValue();
9387 // select true, X, Y -> X
9388 // select false, X, Y -> Y
9389 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9390 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9392 // select C, X, X -> X
9393 if (TrueVal == FalseVal)
9394 return ReplaceInstUsesWith(SI, TrueVal);
9396 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9397 return ReplaceInstUsesWith(SI, FalseVal);
9398 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9399 return ReplaceInstUsesWith(SI, TrueVal);
9400 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9401 if (isa<Constant>(TrueVal))
9402 return ReplaceInstUsesWith(SI, TrueVal);
9404 return ReplaceInstUsesWith(SI, FalseVal);
9407 if (SI.getType() == Type::Int1Ty) {
9408 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9409 if (C->getZExtValue()) {
9410 // Change: A = select B, true, C --> A = or B, C
9411 return BinaryOperator::CreateOr(CondVal, FalseVal);
9413 // Change: A = select B, false, C --> A = and !B, C
9415 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9416 "not."+CondVal->getName()), SI);
9417 return BinaryOperator::CreateAnd(NotCond, FalseVal);
9419 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9420 if (C->getZExtValue() == false) {
9421 // Change: A = select B, C, false --> A = and B, C
9422 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9424 // Change: A = select B, C, true --> A = or !B, C
9426 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9427 "not."+CondVal->getName()), SI);
9428 return BinaryOperator::CreateOr(NotCond, TrueVal);
9432 // select a, b, a -> a&b
9433 // select a, a, b -> a|b
9434 if (CondVal == TrueVal)
9435 return BinaryOperator::CreateOr(CondVal, FalseVal);
9436 else if (CondVal == FalseVal)
9437 return BinaryOperator::CreateAnd(CondVal, TrueVal);
9440 // Selecting between two integer constants?
9441 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9442 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9443 // select C, 1, 0 -> zext C to int
9444 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
9445 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
9446 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9447 // select C, 0, 1 -> zext !C to int
9449 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
9450 "not."+CondVal->getName()), SI);
9451 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
9454 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9456 // (x <s 0) ? -1 : 0 -> ashr x, 31
9457 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
9458 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
9459 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
9460 // The comparison constant and the result are not neccessarily the
9461 // same width. Make an all-ones value by inserting a AShr.
9462 Value *X = IC->getOperand(0);
9463 uint32_t Bits = X->getType()->getScalarSizeInBits();
9464 Constant *ShAmt = Context->getConstantInt(X->getType(), Bits-1);
9465 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
9467 InsertNewInstBefore(SRA, SI);
9469 // Then cast to the appropriate width.
9470 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
9475 // If one of the constants is zero (we know they can't both be) and we
9476 // have an icmp instruction with zero, and we have an 'and' with the
9477 // non-constant value, eliminate this whole mess. This corresponds to
9478 // cases like this: ((X & 27) ? 27 : 0)
9479 if (TrueValC->isZero() || FalseValC->isZero())
9480 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9481 cast<Constant>(IC->getOperand(1))->isNullValue())
9482 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9483 if (ICA->getOpcode() == Instruction::And &&
9484 isa<ConstantInt>(ICA->getOperand(1)) &&
9485 (ICA->getOperand(1) == TrueValC ||
9486 ICA->getOperand(1) == FalseValC) &&
9487 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9488 // Okay, now we know that everything is set up, we just don't
9489 // know whether we have a icmp_ne or icmp_eq and whether the
9490 // true or false val is the zero.
9491 bool ShouldNotVal = !TrueValC->isZero();
9492 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9495 V = InsertNewInstBefore(BinaryOperator::Create(
9496 Instruction::Xor, V, ICA->getOperand(1)), SI);
9497 return ReplaceInstUsesWith(SI, V);
9502 // See if we are selecting two values based on a comparison of the two values.
9503 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9504 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9505 // Transform (X == Y) ? X : Y -> Y
9506 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9507 // This is not safe in general for floating point:
9508 // consider X== -0, Y== +0.
9509 // It becomes safe if either operand is a nonzero constant.
9510 ConstantFP *CFPt, *CFPf;
9511 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9512 !CFPt->getValueAPF().isZero()) ||
9513 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9514 !CFPf->getValueAPF().isZero()))
9515 return ReplaceInstUsesWith(SI, FalseVal);
9517 // Transform (X != Y) ? X : Y -> X
9518 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9519 return ReplaceInstUsesWith(SI, TrueVal);
9520 // NOTE: if we wanted to, this is where to detect MIN/MAX
9522 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9523 // Transform (X == Y) ? Y : X -> X
9524 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9525 // This is not safe in general for floating point:
9526 // consider X== -0, Y== +0.
9527 // It becomes safe if either operand is a nonzero constant.
9528 ConstantFP *CFPt, *CFPf;
9529 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9530 !CFPt->getValueAPF().isZero()) ||
9531 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9532 !CFPf->getValueAPF().isZero()))
9533 return ReplaceInstUsesWith(SI, FalseVal);
9535 // Transform (X != Y) ? Y : X -> Y
9536 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9537 return ReplaceInstUsesWith(SI, TrueVal);
9538 // NOTE: if we wanted to, this is where to detect MIN/MAX
9540 // NOTE: if we wanted to, this is where to detect ABS
9543 // See if we are selecting two values based on a comparison of the two values.
9544 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9545 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9548 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9549 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9550 if (TI->hasOneUse() && FI->hasOneUse()) {
9551 Instruction *AddOp = 0, *SubOp = 0;
9553 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9554 if (TI->getOpcode() == FI->getOpcode())
9555 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9558 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9559 // even legal for FP.
9560 if ((TI->getOpcode() == Instruction::Sub &&
9561 FI->getOpcode() == Instruction::Add) ||
9562 (TI->getOpcode() == Instruction::FSub &&
9563 FI->getOpcode() == Instruction::FAdd)) {
9564 AddOp = FI; SubOp = TI;
9565 } else if ((FI->getOpcode() == Instruction::Sub &&
9566 TI->getOpcode() == Instruction::Add) ||
9567 (FI->getOpcode() == Instruction::FSub &&
9568 TI->getOpcode() == Instruction::FAdd)) {
9569 AddOp = TI; SubOp = FI;
9573 Value *OtherAddOp = 0;
9574 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9575 OtherAddOp = AddOp->getOperand(1);
9576 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9577 OtherAddOp = AddOp->getOperand(0);
9581 // So at this point we know we have (Y -> OtherAddOp):
9582 // select C, (add X, Y), (sub X, Z)
9583 Value *NegVal; // Compute -Z
9584 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9585 NegVal = Context->getConstantExprNeg(C);
9587 NegVal = InsertNewInstBefore(
9588 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
9591 Value *NewTrueOp = OtherAddOp;
9592 Value *NewFalseOp = NegVal;
9594 std::swap(NewTrueOp, NewFalseOp);
9595 Instruction *NewSel =
9596 SelectInst::Create(CondVal, NewTrueOp,
9597 NewFalseOp, SI.getName() + ".p");
9599 NewSel = InsertNewInstBefore(NewSel, SI);
9600 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
9605 // See if we can fold the select into one of our operands.
9606 if (SI.getType()->isInteger()) {
9607 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9612 if (BinaryOperator::isNot(CondVal)) {
9613 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9614 SI.setOperand(1, FalseVal);
9615 SI.setOperand(2, TrueVal);
9622 /// EnforceKnownAlignment - If the specified pointer points to an object that
9623 /// we control, modify the object's alignment to PrefAlign. This isn't
9624 /// often possible though. If alignment is important, a more reliable approach
9625 /// is to simply align all global variables and allocation instructions to
9626 /// their preferred alignment from the beginning.
9628 static unsigned EnforceKnownAlignment(Value *V,
9629 unsigned Align, unsigned PrefAlign) {
9631 User *U = dyn_cast<User>(V);
9632 if (!U) return Align;
9634 switch (getOpcode(U)) {
9636 case Instruction::BitCast:
9637 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9638 case Instruction::GetElementPtr: {
9639 // If all indexes are zero, it is just the alignment of the base pointer.
9640 bool AllZeroOperands = true;
9641 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
9642 if (!isa<Constant>(*i) ||
9643 !cast<Constant>(*i)->isNullValue()) {
9644 AllZeroOperands = false;
9648 if (AllZeroOperands) {
9649 // Treat this like a bitcast.
9650 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9656 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9657 // If there is a large requested alignment and we can, bump up the alignment
9659 if (!GV->isDeclaration()) {
9660 if (GV->getAlignment() >= PrefAlign)
9661 Align = GV->getAlignment();
9663 GV->setAlignment(PrefAlign);
9667 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9668 // If there is a requested alignment and if this is an alloca, round up. We
9669 // don't do this for malloc, because some systems can't respect the request.
9670 if (isa<AllocaInst>(AI)) {
9671 if (AI->getAlignment() >= PrefAlign)
9672 Align = AI->getAlignment();
9674 AI->setAlignment(PrefAlign);
9683 /// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9684 /// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9685 /// and it is more than the alignment of the ultimate object, see if we can
9686 /// increase the alignment of the ultimate object, making this check succeed.
9687 unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9688 unsigned PrefAlign) {
9689 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9690 sizeof(PrefAlign) * CHAR_BIT;
9691 APInt Mask = APInt::getAllOnesValue(BitWidth);
9692 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9693 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9694 unsigned TrailZ = KnownZero.countTrailingOnes();
9695 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9697 if (PrefAlign > Align)
9698 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9700 // We don't need to make any adjustment.
9704 Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
9705 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9706 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
9707 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9708 unsigned CopyAlign = MI->getAlignment();
9710 if (CopyAlign < MinAlign) {
9711 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9716 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9718 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9719 if (MemOpLength == 0) return 0;
9721 // Source and destination pointer types are always "i8*" for intrinsic. See
9722 // if the size is something we can handle with a single primitive load/store.
9723 // A single load+store correctly handles overlapping memory in the memmove
9725 unsigned Size = MemOpLength->getZExtValue();
9726 if (Size == 0) return MI; // Delete this mem transfer.
9728 if (Size > 8 || (Size&(Size-1)))
9729 return 0; // If not 1/2/4/8 bytes, exit.
9731 // Use an integer load+store unless we can find something better.
9733 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
9735 // Memcpy forces the use of i8* for the source and destination. That means
9736 // that if you're using memcpy to move one double around, you'll get a cast
9737 // from double* to i8*. We'd much rather use a double load+store rather than
9738 // an i64 load+store, here because this improves the odds that the source or
9739 // dest address will be promotable. See if we can find a better type than the
9740 // integer datatype.
9741 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9742 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9743 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9744 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9745 // down through these levels if so.
9746 while (!SrcETy->isSingleValueType()) {
9747 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9748 if (STy->getNumElements() == 1)
9749 SrcETy = STy->getElementType(0);
9752 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9753 if (ATy->getNumElements() == 1)
9754 SrcETy = ATy->getElementType();
9761 if (SrcETy->isSingleValueType())
9762 NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
9767 // If the memcpy/memmove provides better alignment info than we can
9769 SrcAlign = std::max(SrcAlign, CopyAlign);
9770 DstAlign = std::max(DstAlign, CopyAlign);
9772 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9773 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
9774 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9775 InsertNewInstBefore(L, *MI);
9776 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9778 // Set the size of the copy to 0, it will be deleted on the next iteration.
9779 MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
9783 Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9784 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9785 if (MI->getAlignment() < Alignment) {
9786 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9791 // Extract the length and alignment and fill if they are constant.
9792 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9793 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9794 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9796 uint64_t Len = LenC->getZExtValue();
9797 Alignment = MI->getAlignment();
9799 // If the length is zero, this is a no-op
9800 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9802 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9803 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9804 const Type *ITy = Context->getIntegerType(Len*8); // n=1 -> i8.
9806 Value *Dest = MI->getDest();
9807 Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
9809 // Alignment 0 is identity for alignment 1 for memset, but not store.
9810 if (Alignment == 0) Alignment = 1;
9812 // Extract the fill value and store.
9813 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9814 InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9815 Dest, false, Alignment), *MI);
9817 // Set the size of the copy to 0, it will be deleted on the next iteration.
9818 MI->setLength(Context->getNullValue(LenC->getType()));
9826 /// visitCallInst - CallInst simplification. This mostly only handles folding
9827 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9828 /// the heavy lifting.
9830 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9831 // If the caller function is nounwind, mark the call as nounwind, even if the
9833 if (CI.getParent()->getParent()->doesNotThrow() &&
9834 !CI.doesNotThrow()) {
9835 CI.setDoesNotThrow();
9841 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9842 if (!II) return visitCallSite(&CI);
9844 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9846 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9847 bool Changed = false;
9849 // memmove/cpy/set of zero bytes is a noop.
9850 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9851 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9853 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9854 if (CI->getZExtValue() == 1) {
9855 // Replace the instruction with just byte operations. We would
9856 // transform other cases to loads/stores, but we don't know if
9857 // alignment is sufficient.
9861 // If we have a memmove and the source operation is a constant global,
9862 // then the source and dest pointers can't alias, so we can change this
9863 // into a call to memcpy.
9864 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
9865 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9866 if (GVSrc->isConstant()) {
9867 Module *M = CI.getParent()->getParent()->getParent();
9868 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9870 Tys[0] = CI.getOperand(3)->getType();
9872 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
9876 // memmove(x,x,size) -> noop.
9877 if (MMI->getSource() == MMI->getDest())
9878 return EraseInstFromFunction(CI);
9881 // If we can determine a pointer alignment that is bigger than currently
9882 // set, update the alignment.
9883 if (isa<MemTransferInst>(MI)) {
9884 if (Instruction *I = SimplifyMemTransfer(MI))
9886 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9887 if (Instruction *I = SimplifyMemSet(MSI))
9891 if (Changed) return II;
9894 switch (II->getIntrinsicID()) {
9896 case Intrinsic::bswap:
9897 // bswap(bswap(x)) -> x
9898 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9899 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9900 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9902 case Intrinsic::ppc_altivec_lvx:
9903 case Intrinsic::ppc_altivec_lvxl:
9904 case Intrinsic::x86_sse_loadu_ps:
9905 case Intrinsic::x86_sse2_loadu_pd:
9906 case Intrinsic::x86_sse2_loadu_dq:
9907 // Turn PPC lvx -> load if the pointer is known aligned.
9908 // Turn X86 loadups -> load if the pointer is known aligned.
9909 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9910 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9911 Context->getPointerTypeUnqual(II->getType()),
9913 return new LoadInst(Ptr);
9916 case Intrinsic::ppc_altivec_stvx:
9917 case Intrinsic::ppc_altivec_stvxl:
9918 // Turn stvx -> store if the pointer is known aligned.
9919 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9920 const Type *OpPtrTy =
9921 Context->getPointerTypeUnqual(II->getOperand(1)->getType());
9922 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9923 return new StoreInst(II->getOperand(1), Ptr);
9926 case Intrinsic::x86_sse_storeu_ps:
9927 case Intrinsic::x86_sse2_storeu_pd:
9928 case Intrinsic::x86_sse2_storeu_dq:
9929 // Turn X86 storeu -> store if the pointer is known aligned.
9930 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9931 const Type *OpPtrTy =
9932 Context->getPointerTypeUnqual(II->getOperand(2)->getType());
9933 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9934 return new StoreInst(II->getOperand(2), Ptr);
9938 case Intrinsic::x86_sse_cvttss2si: {
9939 // These intrinsics only demands the 0th element of its input vector. If
9940 // we can simplify the input based on that, do so now.
9942 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9943 APInt DemandedElts(VWidth, 1);
9944 APInt UndefElts(VWidth, 0);
9945 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
9947 II->setOperand(1, V);
9953 case Intrinsic::ppc_altivec_vperm:
9954 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9955 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9956 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
9958 // Check that all of the elements are integer constants or undefs.
9959 bool AllEltsOk = true;
9960 for (unsigned i = 0; i != 16; ++i) {
9961 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9962 !isa<UndefValue>(Mask->getOperand(i))) {
9969 // Cast the input vectors to byte vectors.
9970 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9971 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9972 Value *Result = Context->getUndef(Op0->getType());
9974 // Only extract each element once.
9975 Value *ExtractedElts[32];
9976 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9978 for (unsigned i = 0; i != 16; ++i) {
9979 if (isa<UndefValue>(Mask->getOperand(i)))
9981 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9982 Idx &= 31; // Match the hardware behavior.
9984 if (ExtractedElts[Idx] == 0) {
9986 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9987 InsertNewInstBefore(Elt, CI);
9988 ExtractedElts[Idx] = Elt;
9991 // Insert this value into the result vector.
9992 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9994 InsertNewInstBefore(cast<Instruction>(Result), CI);
9996 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
10001 case Intrinsic::stackrestore: {
10002 // If the save is right next to the restore, remove the restore. This can
10003 // happen when variable allocas are DCE'd.
10004 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10005 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10006 BasicBlock::iterator BI = SS;
10008 return EraseInstFromFunction(CI);
10012 // Scan down this block to see if there is another stack restore in the
10013 // same block without an intervening call/alloca.
10014 BasicBlock::iterator BI = II;
10015 TerminatorInst *TI = II->getParent()->getTerminator();
10016 bool CannotRemove = false;
10017 for (++BI; &*BI != TI; ++BI) {
10018 if (isa<AllocaInst>(BI)) {
10019 CannotRemove = true;
10022 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10023 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10024 // If there is a stackrestore below this one, remove this one.
10025 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10026 return EraseInstFromFunction(CI);
10027 // Otherwise, ignore the intrinsic.
10029 // If we found a non-intrinsic call, we can't remove the stack
10031 CannotRemove = true;
10037 // If the stack restore is in a return/unwind block and if there are no
10038 // allocas or calls between the restore and the return, nuke the restore.
10039 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10040 return EraseInstFromFunction(CI);
10045 return visitCallSite(II);
10048 // InvokeInst simplification
10050 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10051 return visitCallSite(&II);
10054 /// isSafeToEliminateVarargsCast - If this cast does not affect the value
10055 /// passed through the varargs area, we can eliminate the use of the cast.
10056 static bool isSafeToEliminateVarargsCast(const CallSite CS,
10057 const CastInst * const CI,
10058 const TargetData * const TD,
10060 if (!CI->isLosslessCast())
10063 // The size of ByVal arguments is derived from the type, so we
10064 // can't change to a type with a different size. If the size were
10065 // passed explicitly we could avoid this check.
10066 if (!CS.paramHasAttr(ix, Attribute::ByVal))
10069 const Type* SrcTy =
10070 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10071 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10072 if (!SrcTy->isSized() || !DstTy->isSized())
10074 if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
10079 // visitCallSite - Improvements for call and invoke instructions.
10081 Instruction *InstCombiner::visitCallSite(CallSite CS) {
10082 bool Changed = false;
10084 // If the callee is a constexpr cast of a function, attempt to move the cast
10085 // to the arguments of the call/invoke.
10086 if (transformConstExprCastCall(CS)) return 0;
10088 Value *Callee = CS.getCalledValue();
10090 if (Function *CalleeF = dyn_cast<Function>(Callee))
10091 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10092 Instruction *OldCall = CS.getInstruction();
10093 // If the call and callee calling conventions don't match, this call must
10094 // be unreachable, as the call is undefined.
10095 new StoreInst(Context->getConstantIntTrue(),
10096 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10098 if (!OldCall->use_empty())
10099 OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
10100 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10101 return EraseInstFromFunction(*OldCall);
10105 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10106 // This instruction is not reachable, just remove it. We insert a store to
10107 // undef so that we know that this code is not reachable, despite the fact
10108 // that we can't modify the CFG here.
10109 new StoreInst(Context->getConstantIntTrue(),
10110 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10111 CS.getInstruction());
10113 if (!CS.getInstruction()->use_empty())
10114 CS.getInstruction()->
10115 replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
10117 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10118 // Don't break the CFG, insert a dummy cond branch.
10119 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
10120 Context->getConstantIntTrue(), II);
10122 return EraseInstFromFunction(*CS.getInstruction());
10125 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10126 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10127 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10128 return transformCallThroughTrampoline(CS);
10130 const PointerType *PTy = cast<PointerType>(Callee->getType());
10131 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10132 if (FTy->isVarArg()) {
10133 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
10134 // See if we can optimize any arguments passed through the varargs area of
10136 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
10137 E = CS.arg_end(); I != E; ++I, ++ix) {
10138 CastInst *CI = dyn_cast<CastInst>(*I);
10139 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10140 *I = CI->getOperand(0);
10146 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
10147 // Inline asm calls cannot throw - mark them 'nounwind'.
10148 CS.setDoesNotThrow();
10152 return Changed ? CS.getInstruction() : 0;
10155 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
10156 // attempt to move the cast to the arguments of the call/invoke.
10158 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10159 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10160 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10161 if (CE->getOpcode() != Instruction::BitCast ||
10162 !isa<Function>(CE->getOperand(0)))
10164 Function *Callee = cast<Function>(CE->getOperand(0));
10165 Instruction *Caller = CS.getInstruction();
10166 const AttrListPtr &CallerPAL = CS.getAttributes();
10168 // Okay, this is a cast from a function to a different type. Unless doing so
10169 // would cause a type conversion of one of our arguments, change this call to
10170 // be a direct call with arguments casted to the appropriate types.
10172 const FunctionType *FT = Callee->getFunctionType();
10173 const Type *OldRetTy = Caller->getType();
10174 const Type *NewRetTy = FT->getReturnType();
10176 if (isa<StructType>(NewRetTy))
10177 return false; // TODO: Handle multiple return values.
10179 // Check to see if we are changing the return type...
10180 if (OldRetTy != NewRetTy) {
10181 if (Callee->isDeclaration() &&
10182 // Conversion is ok if changing from one pointer type to another or from
10183 // a pointer to an integer of the same size.
10184 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
10185 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
10186 return false; // Cannot transform this return value.
10188 if (!Caller->use_empty() &&
10189 // void -> non-void is handled specially
10190 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
10191 return false; // Cannot transform this return value.
10193 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
10194 Attributes RAttrs = CallerPAL.getRetAttributes();
10195 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
10196 return false; // Attribute not compatible with transformed value.
10199 // If the callsite is an invoke instruction, and the return value is used by
10200 // a PHI node in a successor, we cannot change the return type of the call
10201 // because there is no place to put the cast instruction (without breaking
10202 // the critical edge). Bail out in this case.
10203 if (!Caller->use_empty())
10204 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10205 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10207 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10208 if (PN->getParent() == II->getNormalDest() ||
10209 PN->getParent() == II->getUnwindDest())
10213 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10214 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10216 CallSite::arg_iterator AI = CS.arg_begin();
10217 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10218 const Type *ParamTy = FT->getParamType(i);
10219 const Type *ActTy = (*AI)->getType();
10221 if (!CastInst::isCastable(ActTy, ParamTy))
10222 return false; // Cannot transform this parameter value.
10224 if (CallerPAL.getParamAttributes(i + 1)
10225 & Attribute::typeIncompatible(ParamTy))
10226 return false; // Attribute not compatible with transformed value.
10228 // Converting from one pointer type to another or between a pointer and an
10229 // integer of the same size is safe even if we do not have a body.
10230 bool isConvertible = ActTy == ParamTy ||
10231 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10232 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
10233 if (Callee->isDeclaration() && !isConvertible) return false;
10236 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10237 Callee->isDeclaration())
10238 return false; // Do not delete arguments unless we have a function body.
10240 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10241 !CallerPAL.isEmpty())
10242 // In this case we have more arguments than the new function type, but we
10243 // won't be dropping them. Check that these extra arguments have attributes
10244 // that are compatible with being a vararg call argument.
10245 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10246 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
10248 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
10249 if (PAttrs & Attribute::VarArgsIncompatible)
10253 // Okay, we decided that this is a safe thing to do: go ahead and start
10254 // inserting cast instructions as necessary...
10255 std::vector<Value*> Args;
10256 Args.reserve(NumActualArgs);
10257 SmallVector<AttributeWithIndex, 8> attrVec;
10258 attrVec.reserve(NumCommonArgs);
10260 // Get any return attributes.
10261 Attributes RAttrs = CallerPAL.getRetAttributes();
10263 // If the return value is not being used, the type may not be compatible
10264 // with the existing attributes. Wipe out any problematic attributes.
10265 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
10267 // Add the new return attributes.
10269 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
10271 AI = CS.arg_begin();
10272 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10273 const Type *ParamTy = FT->getParamType(i);
10274 if ((*AI)->getType() == ParamTy) {
10275 Args.push_back(*AI);
10277 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10278 false, ParamTy, false);
10279 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
10280 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10283 // Add any parameter attributes.
10284 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10285 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10288 // If the function takes more arguments than the call was taking, add them
10290 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
10291 Args.push_back(Context->getNullValue(FT->getParamType(i)));
10293 // If we are removing arguments to the function, emit an obnoxious warning...
10294 if (FT->getNumParams() < NumActualArgs) {
10295 if (!FT->isVarArg()) {
10296 cerr << "WARNING: While resolving call to function '"
10297 << Callee->getName() << "' arguments were dropped!\n";
10299 // Add all of the arguments in their promoted form to the arg list...
10300 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10301 const Type *PTy = getPromotedType((*AI)->getType());
10302 if (PTy != (*AI)->getType()) {
10303 // Must promote to pass through va_arg area!
10304 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10306 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
10307 InsertNewInstBefore(Cast, *Caller);
10308 Args.push_back(Cast);
10310 Args.push_back(*AI);
10313 // Add any parameter attributes.
10314 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
10315 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
10320 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10321 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10323 if (NewRetTy == Type::VoidTy)
10324 Caller->setName(""); // Void type should not have a name.
10326 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
10329 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10330 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
10331 Args.begin(), Args.end(),
10332 Caller->getName(), Caller);
10333 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
10334 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
10336 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10337 Caller->getName(), Caller);
10338 CallInst *CI = cast<CallInst>(Caller);
10339 if (CI->isTailCall())
10340 cast<CallInst>(NC)->setTailCall();
10341 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
10342 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
10345 // Insert a cast of the return type as necessary.
10347 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
10348 if (NV->getType() != Type::VoidTy) {
10349 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
10351 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
10353 // If this is an invoke instruction, we should insert it after the first
10354 // non-phi, instruction in the normal successor block.
10355 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10356 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
10357 InsertNewInstBefore(NC, *I);
10359 // Otherwise, it's a call, just insert cast right after the call instr
10360 InsertNewInstBefore(NC, *Caller);
10362 AddUsersToWorkList(*Caller);
10364 NV = Context->getUndef(Caller->getType());
10368 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10369 Caller->replaceAllUsesWith(NV);
10370 Caller->eraseFromParent();
10371 RemoveFromWorkList(Caller);
10375 // transformCallThroughTrampoline - Turn a call to a function created by the
10376 // init_trampoline intrinsic into a direct call to the underlying function.
10378 Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10379 Value *Callee = CS.getCalledValue();
10380 const PointerType *PTy = cast<PointerType>(Callee->getType());
10381 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10382 const AttrListPtr &Attrs = CS.getAttributes();
10384 // If the call already has the 'nest' attribute somewhere then give up -
10385 // otherwise 'nest' would occur twice after splicing in the chain.
10386 if (Attrs.hasAttrSomewhere(Attribute::Nest))
10389 IntrinsicInst *Tramp =
10390 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10392 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
10393 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10394 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10396 const AttrListPtr &NestAttrs = NestF->getAttributes();
10397 if (!NestAttrs.isEmpty()) {
10398 unsigned NestIdx = 1;
10399 const Type *NestTy = 0;
10400 Attributes NestAttr = Attribute::None;
10402 // Look for a parameter marked with the 'nest' attribute.
10403 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10404 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
10405 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
10406 // Record the parameter type and any other attributes.
10408 NestAttr = NestAttrs.getParamAttributes(NestIdx);
10413 Instruction *Caller = CS.getInstruction();
10414 std::vector<Value*> NewArgs;
10415 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10417 SmallVector<AttributeWithIndex, 8> NewAttrs;
10418 NewAttrs.reserve(Attrs.getNumSlots() + 1);
10420 // Insert the nest argument into the call argument list, which may
10421 // mean appending it. Likewise for attributes.
10423 // Add any result attributes.
10424 if (Attributes Attr = Attrs.getRetAttributes())
10425 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
10429 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10431 if (Idx == NestIdx) {
10432 // Add the chain argument and attributes.
10433 Value *NestVal = Tramp->getOperand(3);
10434 if (NestVal->getType() != NestTy)
10435 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10436 NewArgs.push_back(NestVal);
10437 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
10443 // Add the original argument and attributes.
10444 NewArgs.push_back(*I);
10445 if (Attributes Attr = Attrs.getParamAttributes(Idx))
10447 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
10453 // Add any function attributes.
10454 if (Attributes Attr = Attrs.getFnAttributes())
10455 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10457 // The trampoline may have been bitcast to a bogus type (FTy).
10458 // Handle this by synthesizing a new function type, equal to FTy
10459 // with the chain parameter inserted.
10461 std::vector<const Type*> NewTypes;
10462 NewTypes.reserve(FTy->getNumParams()+1);
10464 // Insert the chain's type into the list of parameter types, which may
10465 // mean appending it.
10468 FunctionType::param_iterator I = FTy->param_begin(),
10469 E = FTy->param_end();
10472 if (Idx == NestIdx)
10473 // Add the chain's type.
10474 NewTypes.push_back(NestTy);
10479 // Add the original type.
10480 NewTypes.push_back(*I);
10486 // Replace the trampoline call with a direct call. Let the generic
10487 // code sort out any function type mismatches.
10488 FunctionType *NewFTy =
10489 Context->getFunctionType(FTy->getReturnType(), NewTypes,
10491 Constant *NewCallee =
10492 NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10493 NestF : Context->getConstantExprBitCast(NestF,
10494 Context->getPointerTypeUnqual(NewFTy));
10495 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
10497 Instruction *NewCaller;
10498 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
10499 NewCaller = InvokeInst::Create(NewCallee,
10500 II->getNormalDest(), II->getUnwindDest(),
10501 NewArgs.begin(), NewArgs.end(),
10502 Caller->getName(), Caller);
10503 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
10504 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
10506 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10507 Caller->getName(), Caller);
10508 if (cast<CallInst>(Caller)->isTailCall())
10509 cast<CallInst>(NewCaller)->setTailCall();
10510 cast<CallInst>(NewCaller)->
10511 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
10512 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
10514 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10515 Caller->replaceAllUsesWith(NewCaller);
10516 Caller->eraseFromParent();
10517 RemoveFromWorkList(Caller);
10522 // Replace the trampoline call with a direct call. Since there is no 'nest'
10523 // parameter, there is no need to adjust the argument list. Let the generic
10524 // code sort out any function type mismatches.
10525 Constant *NewCallee =
10526 NestF->getType() == PTy ? NestF :
10527 Context->getConstantExprBitCast(NestF, PTy);
10528 CS.setCalledFunction(NewCallee);
10529 return CS.getInstruction();
10532 /// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10533 /// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10534 /// and a single binop.
10535 Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10536 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10537 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
10538 unsigned Opc = FirstInst->getOpcode();
10539 Value *LHSVal = FirstInst->getOperand(0);
10540 Value *RHSVal = FirstInst->getOperand(1);
10542 const Type *LHSType = LHSVal->getType();
10543 const Type *RHSType = RHSVal->getType();
10545 // Scan to see if all operands are the same opcode, all have one use, and all
10546 // kill their operands (i.e. the operands have one use).
10547 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10548 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10549 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10550 // Verify type of the LHS matches so we don't fold cmp's of different
10551 // types or GEP's with different index types.
10552 I->getOperand(0)->getType() != LHSType ||
10553 I->getOperand(1)->getType() != RHSType)
10556 // If they are CmpInst instructions, check their predicates
10557 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10558 if (cast<CmpInst>(I)->getPredicate() !=
10559 cast<CmpInst>(FirstInst)->getPredicate())
10562 // Keep track of which operand needs a phi node.
10563 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10564 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10567 // Otherwise, this is safe to transform!
10569 Value *InLHS = FirstInst->getOperand(0);
10570 Value *InRHS = FirstInst->getOperand(1);
10571 PHINode *NewLHS = 0, *NewRHS = 0;
10573 NewLHS = PHINode::Create(LHSType,
10574 FirstInst->getOperand(0)->getName() + ".pn");
10575 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10576 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10577 InsertNewInstBefore(NewLHS, PN);
10582 NewRHS = PHINode::Create(RHSType,
10583 FirstInst->getOperand(1)->getName() + ".pn");
10584 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10585 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10586 InsertNewInstBefore(NewRHS, PN);
10590 // Add all operands to the new PHIs.
10591 if (NewLHS || NewRHS) {
10592 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10593 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10595 Value *NewInLHS = InInst->getOperand(0);
10596 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10599 Value *NewInRHS = InInst->getOperand(1);
10600 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10605 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10606 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
10607 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10608 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10612 Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10613 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10615 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10616 FirstInst->op_end());
10617 // This is true if all GEP bases are allocas and if all indices into them are
10619 bool AllBasePointersAreAllocas = true;
10621 // Scan to see if all operands are the same opcode, all have one use, and all
10622 // kill their operands (i.e. the operands have one use).
10623 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10624 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10625 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10626 GEP->getNumOperands() != FirstInst->getNumOperands())
10629 // Keep track of whether or not all GEPs are of alloca pointers.
10630 if (AllBasePointersAreAllocas &&
10631 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10632 !GEP->hasAllConstantIndices()))
10633 AllBasePointersAreAllocas = false;
10635 // Compare the operand lists.
10636 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10637 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10640 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10641 // if one of the PHIs has a constant for the index. The index may be
10642 // substantially cheaper to compute for the constants, so making it a
10643 // variable index could pessimize the path. This also handles the case
10644 // for struct indices, which must always be constant.
10645 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10646 isa<ConstantInt>(GEP->getOperand(op)))
10649 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10651 FixedOperands[op] = 0; // Needs a PHI.
10655 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
10656 // bother doing this transformation. At best, this will just save a bit of
10657 // offset calculation, but all the predecessors will have to materialize the
10658 // stack address into a register anyway. We'd actually rather *clone* the
10659 // load up into the predecessors so that we have a load of a gep of an alloca,
10660 // which can usually all be folded into the load.
10661 if (AllBasePointersAreAllocas)
10664 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10665 // that is variable.
10666 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10668 bool HasAnyPHIs = false;
10669 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10670 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10671 Value *FirstOp = FirstInst->getOperand(i);
10672 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10673 FirstOp->getName()+".pn");
10674 InsertNewInstBefore(NewPN, PN);
10676 NewPN->reserveOperandSpace(e);
10677 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10678 OperandPhis[i] = NewPN;
10679 FixedOperands[i] = NewPN;
10684 // Add all operands to the new PHIs.
10686 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10687 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10688 BasicBlock *InBB = PN.getIncomingBlock(i);
10690 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10691 if (PHINode *OpPhi = OperandPhis[op])
10692 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10696 Value *Base = FixedOperands[0];
10697 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10698 FixedOperands.end());
10702 /// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10703 /// sink the load out of the block that defines it. This means that it must be
10704 /// obvious the value of the load is not changed from the point of the load to
10705 /// the end of the block it is in.
10707 /// Finally, it is safe, but not profitable, to sink a load targetting a
10708 /// non-address-taken alloca. Doing so will cause us to not promote the alloca
10710 static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
10711 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10713 for (++BBI; BBI != E; ++BBI)
10714 if (BBI->mayWriteToMemory())
10717 // Check for non-address taken alloca. If not address-taken already, it isn't
10718 // profitable to do this xform.
10719 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10720 bool isAddressTaken = false;
10721 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10723 if (isa<LoadInst>(UI)) continue;
10724 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10725 // If storing TO the alloca, then the address isn't taken.
10726 if (SI->getOperand(1) == AI) continue;
10728 isAddressTaken = true;
10732 if (!isAddressTaken && AI->isStaticAlloca())
10736 // If this load is a load from a GEP with a constant offset from an alloca,
10737 // then we don't want to sink it. In its present form, it will be
10738 // load [constant stack offset]. Sinking it will cause us to have to
10739 // materialize the stack addresses in each predecessor in a register only to
10740 // do a shared load from register in the successor.
10741 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10742 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10743 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10750 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10751 // operator and they all are only used by the PHI, PHI together their
10752 // inputs, and do the operation once, to the result of the PHI.
10753 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10754 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10756 // Scan the instruction, looking for input operations that can be folded away.
10757 // If all input operands to the phi are the same instruction (e.g. a cast from
10758 // the same type or "+42") we can pull the operation through the PHI, reducing
10759 // code size and simplifying code.
10760 Constant *ConstantOp = 0;
10761 const Type *CastSrcTy = 0;
10762 bool isVolatile = false;
10763 if (isa<CastInst>(FirstInst)) {
10764 CastSrcTy = FirstInst->getOperand(0)->getType();
10765 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10766 // Can fold binop, compare or shift here if the RHS is a constant,
10767 // otherwise call FoldPHIArgBinOpIntoPHI.
10768 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10769 if (ConstantOp == 0)
10770 return FoldPHIArgBinOpIntoPHI(PN);
10771 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10772 isVolatile = LI->isVolatile();
10773 // We can't sink the load if the loaded value could be modified between the
10774 // load and the PHI.
10775 if (LI->getParent() != PN.getIncomingBlock(0) ||
10776 !isSafeAndProfitableToSinkLoad(LI))
10779 // If the PHI is of volatile loads and the load block has multiple
10780 // successors, sinking it would remove a load of the volatile value from
10781 // the path through the other successor.
10783 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10786 } else if (isa<GetElementPtrInst>(FirstInst)) {
10787 return FoldPHIArgGEPIntoPHI(PN);
10789 return 0; // Cannot fold this operation.
10792 // Check to see if all arguments are the same operation.
10793 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10794 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10795 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10796 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10799 if (I->getOperand(0)->getType() != CastSrcTy)
10800 return 0; // Cast operation must match.
10801 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10802 // We can't sink the load if the loaded value could be modified between
10803 // the load and the PHI.
10804 if (LI->isVolatile() != isVolatile ||
10805 LI->getParent() != PN.getIncomingBlock(i) ||
10806 !isSafeAndProfitableToSinkLoad(LI))
10809 // If the PHI is of volatile loads and the load block has multiple
10810 // successors, sinking it would remove a load of the volatile value from
10811 // the path through the other successor.
10813 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10816 } else if (I->getOperand(1) != ConstantOp) {
10821 // Okay, they are all the same operation. Create a new PHI node of the
10822 // correct type, and PHI together all of the LHS's of the instructions.
10823 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10824 PN.getName()+".in");
10825 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10827 Value *InVal = FirstInst->getOperand(0);
10828 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10830 // Add all operands to the new PHI.
10831 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10832 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10833 if (NewInVal != InVal)
10835 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10840 // The new PHI unions all of the same values together. This is really
10841 // common, so we handle it intelligently here for compile-time speed.
10845 InsertNewInstBefore(NewPN, PN);
10849 // Insert and return the new operation.
10850 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
10851 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
10852 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
10853 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
10854 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
10855 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10856 PhiVal, ConstantOp);
10857 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10859 // If this was a volatile load that we are merging, make sure to loop through
10860 // and mark all the input loads as non-volatile. If we don't do this, we will
10861 // insert a new volatile load and the old ones will not be deletable.
10863 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10864 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10866 return new LoadInst(PhiVal, "", isVolatile);
10869 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10871 static bool DeadPHICycle(PHINode *PN,
10872 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10873 if (PN->use_empty()) return true;
10874 if (!PN->hasOneUse()) return false;
10876 // Remember this node, and if we find the cycle, return.
10877 if (!PotentiallyDeadPHIs.insert(PN))
10880 // Don't scan crazily complex things.
10881 if (PotentiallyDeadPHIs.size() == 16)
10884 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10885 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10890 /// PHIsEqualValue - Return true if this phi node is always equal to
10891 /// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10892 /// z = some value; x = phi (y, z); y = phi (x, z)
10893 static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10894 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10895 // See if we already saw this PHI node.
10896 if (!ValueEqualPHIs.insert(PN))
10899 // Don't scan crazily complex things.
10900 if (ValueEqualPHIs.size() == 16)
10903 // Scan the operands to see if they are either phi nodes or are equal to
10905 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10906 Value *Op = PN->getIncomingValue(i);
10907 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10908 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10910 } else if (Op != NonPhiInVal)
10918 // PHINode simplification
10920 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10921 // If LCSSA is around, don't mess with Phi nodes
10922 if (MustPreserveLCSSA) return 0;
10924 if (Value *V = PN.hasConstantValue())
10925 return ReplaceInstUsesWith(PN, V);
10927 // If all PHI operands are the same operation, pull them through the PHI,
10928 // reducing code size.
10929 if (isa<Instruction>(PN.getIncomingValue(0)) &&
10930 isa<Instruction>(PN.getIncomingValue(1)) &&
10931 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10932 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10933 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10934 // than themselves more than once.
10935 PN.getIncomingValue(0)->hasOneUse())
10936 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10939 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10940 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10941 // PHI)... break the cycle.
10942 if (PN.hasOneUse()) {
10943 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10944 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10945 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10946 PotentiallyDeadPHIs.insert(&PN);
10947 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10948 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10951 // If this phi has a single use, and if that use just computes a value for
10952 // the next iteration of a loop, delete the phi. This occurs with unused
10953 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10954 // common case here is good because the only other things that catch this
10955 // are induction variable analysis (sometimes) and ADCE, which is only run
10957 if (PHIUser->hasOneUse() &&
10958 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10959 PHIUser->use_back() == &PN) {
10960 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
10964 // We sometimes end up with phi cycles that non-obviously end up being the
10965 // same value, for example:
10966 // z = some value; x = phi (y, z); y = phi (x, z)
10967 // where the phi nodes don't necessarily need to be in the same block. Do a
10968 // quick check to see if the PHI node only contains a single non-phi value, if
10969 // so, scan to see if the phi cycle is actually equal to that value.
10971 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10972 // Scan for the first non-phi operand.
10973 while (InValNo != NumOperandVals &&
10974 isa<PHINode>(PN.getIncomingValue(InValNo)))
10977 if (InValNo != NumOperandVals) {
10978 Value *NonPhiInVal = PN.getOperand(InValNo);
10980 // Scan the rest of the operands to see if there are any conflicts, if so
10981 // there is no need to recursively scan other phis.
10982 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10983 Value *OpVal = PN.getIncomingValue(InValNo);
10984 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10988 // If we scanned over all operands, then we have one unique value plus
10989 // phi values. Scan PHI nodes to see if they all merge in each other or
10991 if (InValNo == NumOperandVals) {
10992 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10993 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10994 return ReplaceInstUsesWith(PN, NonPhiInVal);
11001 static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
11002 Instruction *InsertPoint,
11003 InstCombiner *IC) {
11004 unsigned PtrSize = DTy->getScalarSizeInBits();
11005 unsigned VTySize = V->getType()->getScalarSizeInBits();
11006 // We must cast correctly to the pointer type. Ensure that we
11007 // sign extend the integer value if it is smaller as this is
11008 // used for address computation.
11009 Instruction::CastOps opcode =
11010 (VTySize < PtrSize ? Instruction::SExt :
11011 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
11012 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
11016 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11017 Value *PtrOp = GEP.getOperand(0);
11018 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
11019 // If so, eliminate the noop.
11020 if (GEP.getNumOperands() == 1)
11021 return ReplaceInstUsesWith(GEP, PtrOp);
11023 if (isa<UndefValue>(GEP.getOperand(0)))
11024 return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
11026 bool HasZeroPointerIndex = false;
11027 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11028 HasZeroPointerIndex = C->isNullValue();
11030 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11031 return ReplaceInstUsesWith(GEP, PtrOp);
11033 // Eliminate unneeded casts for indices.
11034 bool MadeChange = false;
11036 gep_type_iterator GTI = gep_type_begin(GEP);
11037 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11038 i != e; ++i, ++GTI) {
11039 if (isa<SequentialType>(*GTI)) {
11040 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
11041 if (CI->getOpcode() == Instruction::ZExt ||
11042 CI->getOpcode() == Instruction::SExt) {
11043 const Type *SrcTy = CI->getOperand(0)->getType();
11044 // We can eliminate a cast from i32 to i64 iff the target
11045 // is a 32-bit pointer target.
11046 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
11048 *i = CI->getOperand(0);
11052 // If we are using a wider index than needed for this platform, shrink it
11053 // to what we need. If narrower, sign-extend it to what we need.
11054 // If the incoming value needs a cast instruction,
11055 // insert it. This explicit cast can make subsequent optimizations more
11058 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
11059 if (Constant *C = dyn_cast<Constant>(Op)) {
11060 *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
11063 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11068 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11069 if (Constant *C = dyn_cast<Constant>(Op)) {
11070 *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
11073 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11081 if (MadeChange) return &GEP;
11083 // Combine Indices - If the source pointer to this getelementptr instruction
11084 // is a getelementptr instruction, combine the indices of the two
11085 // getelementptr instructions into a single instruction.
11087 SmallVector<Value*, 8> SrcGEPOperands;
11088 if (User *Src = dyn_castGetElementPtr(PtrOp))
11089 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11091 if (!SrcGEPOperands.empty()) {
11092 // Note that if our source is a gep chain itself that we wait for that
11093 // chain to be resolved before we perform this transformation. This
11094 // avoids us creating a TON of code in some cases.
11096 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11097 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11098 return 0; // Wait until our source is folded to completion.
11100 SmallVector<Value*, 8> Indices;
11102 // Find out whether the last index in the source GEP is a sequential idx.
11103 bool EndsWithSequential = false;
11104 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11105 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11106 EndsWithSequential = !isa<StructType>(*I);
11108 // Can we combine the two pointer arithmetics offsets?
11109 if (EndsWithSequential) {
11110 // Replace: gep (gep %P, long B), long A, ...
11111 // With: T = long A+B; gep %P, T, ...
11113 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
11114 if (SO1 == Context->getNullValue(SO1->getType())) {
11116 } else if (GO1 == Context->getNullValue(GO1->getType())) {
11119 // If they aren't the same type, convert both to an integer of the
11120 // target's pointer size.
11121 if (SO1->getType() != GO1->getType()) {
11122 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
11124 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
11125 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
11127 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
11129 unsigned PS = TD->getPointerSizeInBits();
11130 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
11131 // Convert GO1 to SO1's type.
11132 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11134 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
11135 // Convert SO1 to GO1's type.
11136 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11138 const Type *PT = TD->getIntPtrType();
11139 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11140 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11144 if (isa<Constant>(SO1) && isa<Constant>(GO1))
11145 Sum = Context->getConstantExprAdd(cast<Constant>(SO1),
11146 cast<Constant>(GO1));
11148 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
11149 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11153 // Recycle the GEP we already have if possible.
11154 if (SrcGEPOperands.size() == 2) {
11155 GEP.setOperand(0, SrcGEPOperands[0]);
11156 GEP.setOperand(1, Sum);
11159 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11160 SrcGEPOperands.end()-1);
11161 Indices.push_back(Sum);
11162 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11164 } else if (isa<Constant>(*GEP.idx_begin()) &&
11165 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11166 SrcGEPOperands.size() != 1) {
11167 // Otherwise we can do the fold if the first index of the GEP is a zero
11168 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11169 SrcGEPOperands.end());
11170 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11173 if (!Indices.empty())
11174 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11175 Indices.end(), GEP.getName());
11177 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11178 // GEP of global variable. If all of the indices for this GEP are
11179 // constants, we can promote this to a constexpr instead of an instruction.
11181 // Scan for nonconstants...
11182 SmallVector<Constant*, 8> Indices;
11183 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11184 for (; I != E && isa<Constant>(*I); ++I)
11185 Indices.push_back(cast<Constant>(*I));
11187 if (I == E) { // If they are all constants...
11188 Constant *CE = Context->getConstantExprGetElementPtr(GV,
11189 &Indices[0],Indices.size());
11191 // Replace all uses of the GEP with the new constexpr...
11192 return ReplaceInstUsesWith(GEP, CE);
11194 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
11195 if (!isa<PointerType>(X->getType())) {
11196 // Not interesting. Source pointer must be a cast from pointer.
11197 } else if (HasZeroPointerIndex) {
11198 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11199 // into : GEP [10 x i8]* X, i32 0, ...
11201 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11202 // into : GEP i8* X, ...
11204 // This occurs when the program declares an array extern like "int X[];"
11205 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11206 const PointerType *XTy = cast<PointerType>(X->getType());
11207 if (const ArrayType *CATy =
11208 dyn_cast<ArrayType>(CPTy->getElementType())) {
11209 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11210 if (CATy->getElementType() == XTy->getElementType()) {
11211 // -> GEP i8* X, ...
11212 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11213 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11215 } else if (const ArrayType *XATy =
11216 dyn_cast<ArrayType>(XTy->getElementType())) {
11217 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
11218 if (CATy->getElementType() == XATy->getElementType()) {
11219 // -> GEP [10 x i8]* X, i32 0, ...
11220 // At this point, we know that the cast source type is a pointer
11221 // to an array of the same type as the destination pointer
11222 // array. Because the array type is never stepped over (there
11223 // is a leading zero) we can fold the cast into this GEP.
11224 GEP.setOperand(0, X);
11229 } else if (GEP.getNumOperands() == 2) {
11230 // Transform things like:
11231 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11232 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
11233 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11234 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11235 if (isa<ArrayType>(SrcElTy) &&
11236 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11237 TD->getTypeAllocSize(ResElTy)) {
11239 Idx[0] = Context->getNullValue(Type::Int32Ty);
11240 Idx[1] = GEP.getOperand(1);
11241 Value *V = InsertNewInstBefore(
11242 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
11243 // V and GEP are both pointer types --> BitCast
11244 return new BitCastInst(V, GEP.getType());
11247 // Transform things like:
11248 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
11249 // (where tmp = 8*tmp2) into:
11250 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
11252 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
11253 uint64_t ArrayEltSize =
11254 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
11256 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11257 // allow either a mul, shift, or constant here.
11259 ConstantInt *Scale = 0;
11260 if (ArrayEltSize == 1) {
11261 NewIdx = GEP.getOperand(1);
11263 Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
11264 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
11265 NewIdx = Context->getConstantInt(CI->getType(), 1);
11267 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11268 if (Inst->getOpcode() == Instruction::Shl &&
11269 isa<ConstantInt>(Inst->getOperand(1))) {
11270 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11271 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
11272 Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
11274 NewIdx = Inst->getOperand(0);
11275 } else if (Inst->getOpcode() == Instruction::Mul &&
11276 isa<ConstantInt>(Inst->getOperand(1))) {
11277 Scale = cast<ConstantInt>(Inst->getOperand(1));
11278 NewIdx = Inst->getOperand(0);
11282 // If the index will be to exactly the right offset with the scale taken
11283 // out, perform the transformation. Note, we don't know whether Scale is
11284 // signed or not. We'll use unsigned version of division/modulo
11285 // operation after making sure Scale doesn't have the sign bit set.
11286 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
11287 Scale->getZExtValue() % ArrayEltSize == 0) {
11288 Scale = Context->getConstantInt(Scale->getType(),
11289 Scale->getZExtValue() / ArrayEltSize);
11290 if (Scale->getZExtValue() != 1) {
11292 Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
11294 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
11295 NewIdx = InsertNewInstBefore(Sc, GEP);
11298 // Insert the new GEP instruction.
11300 Idx[0] = Context->getNullValue(Type::Int32Ty);
11302 Instruction *NewGEP =
11303 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
11304 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11305 // The NewGEP must be pointer typed, so must the old one -> BitCast
11306 return new BitCastInst(NewGEP, GEP.getType());
11312 /// See if we can simplify:
11313 /// X = bitcast A to B*
11314 /// Y = gep X, <...constant indices...>
11315 /// into a gep of the original struct. This is important for SROA and alias
11316 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
11317 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
11318 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11319 // Determine how much the GEP moves the pointer. We are guaranteed to get
11320 // a constant back from EmitGEPOffset.
11321 ConstantInt *OffsetV =
11322 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
11323 int64_t Offset = OffsetV->getSExtValue();
11325 // If this GEP instruction doesn't move the pointer, just replace the GEP
11326 // with a bitcast of the real input to the dest type.
11328 // If the bitcast is of an allocation, and the allocation will be
11329 // converted to match the type of the cast, don't touch this.
11330 if (isa<AllocationInst>(BCI->getOperand(0))) {
11331 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11332 if (Instruction *I = visitBitCast(*BCI)) {
11335 BCI->getParent()->getInstList().insert(BCI, I);
11336 ReplaceInstUsesWith(*BCI, I);
11341 return new BitCastInst(BCI->getOperand(0), GEP.getType());
11344 // Otherwise, if the offset is non-zero, we need to find out if there is a
11345 // field at Offset in 'A's type. If so, we can pull the cast through the
11347 SmallVector<Value*, 8> NewIndices;
11349 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
11350 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
11351 Instruction *NGEP =
11352 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11354 if (NGEP->getType() == GEP.getType()) return NGEP;
11355 InsertNewInstBefore(NGEP, GEP);
11356 NGEP->takeName(&GEP);
11357 return new BitCastInst(NGEP, GEP.getType());
11365 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11366 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
11367 if (AI.isArrayAllocation()) { // Check C != 1
11368 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11369 const Type *NewTy =
11370 Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
11371 AllocationInst *New = 0;
11373 // Create and insert the replacement instruction...
11374 if (isa<MallocInst>(AI))
11375 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11377 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11378 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11381 InsertNewInstBefore(New, AI);
11383 // Scan to the end of the allocation instructions, to skip over a block of
11384 // allocas if possible...also skip interleaved debug info
11386 BasicBlock::iterator It = New;
11387 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
11389 // Now that I is pointing to the first non-allocation-inst in the block,
11390 // insert our getelementptr instruction...
11392 Value *NullIdx = Context->getNullValue(Type::Int32Ty);
11396 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11397 New->getName()+".sub", It);
11399 // Now make everything use the getelementptr instead of the original
11401 return ReplaceInstUsesWith(AI, V);
11402 } else if (isa<UndefValue>(AI.getArraySize())) {
11403 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11407 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11408 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
11409 // Note that we only do this for alloca's, because malloc should allocate
11410 // and return a unique pointer, even for a zero byte allocation.
11411 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
11412 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
11414 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11415 if (AI.getAlignment() == 0)
11416 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11422 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11423 Value *Op = FI.getOperand(0);
11425 // free undef -> unreachable.
11426 if (isa<UndefValue>(Op)) {
11427 // Insert a new store to null because we cannot modify the CFG here.
11428 new StoreInst(Context->getConstantIntTrue(),
11429 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
11430 return EraseInstFromFunction(FI);
11433 // If we have 'free null' delete the instruction. This can happen in stl code
11434 // when lots of inlining happens.
11435 if (isa<ConstantPointerNull>(Op))
11436 return EraseInstFromFunction(FI);
11438 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11439 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11440 FI.setOperand(0, CI->getOperand(0));
11444 // Change free (gep X, 0,0,0,0) into free(X)
11445 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11446 if (GEPI->hasAllZeroIndices()) {
11447 AddToWorkList(GEPI);
11448 FI.setOperand(0, GEPI->getOperand(0));
11453 // Change free(malloc) into nothing, if the malloc has a single use.
11454 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11455 if (MI->hasOneUse()) {
11456 EraseInstFromFunction(FI);
11457 return EraseInstFromFunction(*MI);
11464 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
11465 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
11466 const TargetData *TD) {
11467 User *CI = cast<User>(LI.getOperand(0));
11468 Value *CastOp = CI->getOperand(0);
11469 LLVMContext *Context = IC.getContext();
11472 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11473 // Instead of loading constant c string, use corresponding integer value
11474 // directly if string length is small enough.
11476 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11477 unsigned len = Str.length();
11478 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11479 unsigned numBits = Ty->getPrimitiveSizeInBits();
11480 // Replace LI with immediate integer store.
11481 if ((numBits >> 3) == len + 1) {
11482 APInt StrVal(numBits, 0);
11483 APInt SingleChar(numBits, 0);
11484 if (TD->isLittleEndian()) {
11485 for (signed i = len-1; i >= 0; i--) {
11486 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11487 StrVal = (StrVal << 8) | SingleChar;
11490 for (unsigned i = 0; i < len; i++) {
11491 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11492 StrVal = (StrVal << 8) | SingleChar;
11494 // Append NULL at the end.
11496 StrVal = (StrVal << 8) | SingleChar;
11498 Value *NL = Context->getConstantInt(StrVal);
11499 return IC.ReplaceInstUsesWith(LI, NL);
11505 const PointerType *DestTy = cast<PointerType>(CI->getType());
11506 const Type *DestPTy = DestTy->getElementType();
11507 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11509 // If the address spaces don't match, don't eliminate the cast.
11510 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11513 const Type *SrcPTy = SrcTy->getElementType();
11515 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11516 isa<VectorType>(DestPTy)) {
11517 // If the source is an array, the code below will not succeed. Check to
11518 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11520 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11521 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11522 if (ASrcTy->getNumElements() != 0) {
11524 Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11525 CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
11526 SrcTy = cast<PointerType>(CastOp->getType());
11527 SrcPTy = SrcTy->getElementType();
11530 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
11531 isa<VectorType>(SrcPTy)) &&
11532 // Do not allow turning this into a load of an integer, which is then
11533 // casted to a pointer, this pessimizes pointer analysis a lot.
11534 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11535 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11536 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11538 // Okay, we are casting from one integer or pointer type to another of
11539 // the same size. Instead of casting the pointer before the load, cast
11540 // the result of the loaded value.
11541 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11543 LI.isVolatile()),LI);
11544 // Now cast the result of the load.
11545 return new BitCastInst(NewLoad, LI.getType());
11552 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11553 Value *Op = LI.getOperand(0);
11555 // Attempt to improve the alignment.
11556 unsigned KnownAlign =
11557 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
11559 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11560 LI.getAlignment()))
11561 LI.setAlignment(KnownAlign);
11563 // load (cast X) --> cast (load X) iff safe
11564 if (isa<CastInst>(Op))
11565 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11568 // None of the following transforms are legal for volatile loads.
11569 if (LI.isVolatile()) return 0;
11571 // Do really simple store-to-load forwarding and load CSE, to catch cases
11572 // where there are several consequtive memory accesses to the same location,
11573 // separated by a few arithmetic operations.
11574 BasicBlock::iterator BBI = &LI;
11575 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11576 return ReplaceInstUsesWith(LI, AvailableVal);
11578 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11579 const Value *GEPI0 = GEPI->getOperand(0);
11580 // TODO: Consider a target hook for valid address spaces for this xform.
11581 if (isa<ConstantPointerNull>(GEPI0) &&
11582 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
11583 // Insert a new store to null instruction before the load to indicate
11584 // that this code is not reachable. We do this instead of inserting
11585 // an unreachable instruction directly because we cannot modify the
11587 new StoreInst(Context->getUndef(LI.getType()),
11588 Context->getNullValue(Op->getType()), &LI);
11589 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11593 if (Constant *C = dyn_cast<Constant>(Op)) {
11594 // load null/undef -> undef
11595 // TODO: Consider a target hook for valid address spaces for this xform.
11596 if (isa<UndefValue>(C) || (C->isNullValue() &&
11597 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
11598 // Insert a new store to null instruction before the load to indicate that
11599 // this code is not reachable. We do this instead of inserting an
11600 // unreachable instruction directly because we cannot modify the CFG.
11601 new StoreInst(Context->getUndef(LI.getType()),
11602 Context->getNullValue(Op->getType()), &LI);
11603 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11606 // Instcombine load (constant global) into the value loaded.
11607 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11608 if (GV->isConstant() && GV->hasDefinitiveInitializer())
11609 return ReplaceInstUsesWith(LI, GV->getInitializer());
11611 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
11612 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
11613 if (CE->getOpcode() == Instruction::GetElementPtr) {
11614 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11615 if (GV->isConstant() && GV->hasDefinitiveInitializer())
11617 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
11619 return ReplaceInstUsesWith(LI, V);
11620 if (CE->getOperand(0)->isNullValue()) {
11621 // Insert a new store to null instruction before the load to indicate
11622 // that this code is not reachable. We do this instead of inserting
11623 // an unreachable instruction directly because we cannot modify the
11625 new StoreInst(Context->getUndef(LI.getType()),
11626 Context->getNullValue(Op->getType()), &LI);
11627 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11630 } else if (CE->isCast()) {
11631 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
11637 // If this load comes from anywhere in a constant global, and if the global
11638 // is all undef or zero, we know what it loads.
11639 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
11640 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
11641 if (GV->getInitializer()->isNullValue())
11642 return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
11643 else if (isa<UndefValue>(GV->getInitializer()))
11644 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
11648 if (Op->hasOneUse()) {
11649 // Change select and PHI nodes to select values instead of addresses: this
11650 // helps alias analysis out a lot, allows many others simplifications, and
11651 // exposes redundancy in the code.
11653 // Note that we cannot do the transformation unless we know that the
11654 // introduced loads cannot trap! Something like this is valid as long as
11655 // the condition is always false: load (select bool %C, int* null, int* %G),
11656 // but it would not be valid if we transformed it to load from null
11657 // unconditionally.
11659 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11660 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11661 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11662 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11663 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11664 SI->getOperand(1)->getName()+".val"), LI);
11665 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11666 SI->getOperand(2)->getName()+".val"), LI);
11667 return SelectInst::Create(SI->getCondition(), V1, V2);
11670 // load (select (cond, null, P)) -> load P
11671 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11672 if (C->isNullValue()) {
11673 LI.setOperand(0, SI->getOperand(2));
11677 // load (select (cond, P, null)) -> load P
11678 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11679 if (C->isNullValue()) {
11680 LI.setOperand(0, SI->getOperand(1));
11688 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11689 /// when possible. This makes it generally easy to do alias analysis and/or
11690 /// SROA/mem2reg of the memory object.
11691 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11692 User *CI = cast<User>(SI.getOperand(1));
11693 Value *CastOp = CI->getOperand(0);
11694 LLVMContext *Context = IC.getContext();
11696 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11697 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11698 if (SrcTy == 0) return 0;
11700 const Type *SrcPTy = SrcTy->getElementType();
11702 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11705 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11706 /// to its first element. This allows us to handle things like:
11707 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11708 /// on 32-bit hosts.
11709 SmallVector<Value*, 4> NewGEPIndices;
11711 // If the source is an array, the code below will not succeed. Check to
11712 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11714 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11715 // Index through pointer.
11716 Constant *Zero = Context->getNullValue(Type::Int32Ty);
11717 NewGEPIndices.push_back(Zero);
11720 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
11721 if (!STy->getNumElements()) /* Struct can be empty {} */
11723 NewGEPIndices.push_back(Zero);
11724 SrcPTy = STy->getElementType(0);
11725 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11726 NewGEPIndices.push_back(Zero);
11727 SrcPTy = ATy->getElementType();
11733 SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
11736 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11739 // If the pointers point into different address spaces or if they point to
11740 // values with different sizes, we can't do the transformation.
11741 if (SrcTy->getAddressSpace() !=
11742 cast<PointerType>(CI->getType())->getAddressSpace() ||
11743 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
11744 IC.getTargetData().getTypeSizeInBits(DestPTy))
11747 // Okay, we are casting from one integer or pointer type to another of
11748 // the same size. Instead of casting the pointer before
11749 // the store, cast the value to be stored.
11751 Value *SIOp0 = SI.getOperand(0);
11752 Instruction::CastOps opcode = Instruction::BitCast;
11753 const Type* CastSrcTy = SIOp0->getType();
11754 const Type* CastDstTy = SrcPTy;
11755 if (isa<PointerType>(CastDstTy)) {
11756 if (CastSrcTy->isInteger())
11757 opcode = Instruction::IntToPtr;
11758 } else if (isa<IntegerType>(CastDstTy)) {
11759 if (isa<PointerType>(SIOp0->getType()))
11760 opcode = Instruction::PtrToInt;
11763 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11764 // emit a GEP to index into its first field.
11765 if (!NewGEPIndices.empty()) {
11766 if (Constant *C = dyn_cast<Constant>(CastOp))
11767 CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0],
11768 NewGEPIndices.size());
11770 CastOp = IC.InsertNewInstBefore(
11771 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11772 NewGEPIndices.end()), SI);
11775 if (Constant *C = dyn_cast<Constant>(SIOp0))
11776 NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
11778 NewCast = IC.InsertNewInstBefore(
11779 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11781 return new StoreInst(NewCast, CastOp);
11784 /// equivalentAddressValues - Test if A and B will obviously have the same
11785 /// value. This includes recognizing that %t0 and %t1 will have the same
11786 /// value in code like this:
11787 /// %t0 = getelementptr \@a, 0, 3
11788 /// store i32 0, i32* %t0
11789 /// %t1 = getelementptr \@a, 0, 3
11790 /// %t2 = load i32* %t1
11792 static bool equivalentAddressValues(Value *A, Value *B) {
11793 // Test if the values are trivially equivalent.
11794 if (A == B) return true;
11796 // Test if the values come form identical arithmetic instructions.
11797 if (isa<BinaryOperator>(A) ||
11798 isa<CastInst>(A) ||
11800 isa<GetElementPtrInst>(A))
11801 if (Instruction *BI = dyn_cast<Instruction>(B))
11802 if (cast<Instruction>(A)->isIdenticalTo(BI))
11805 // Otherwise they may not be equivalent.
11809 // If this instruction has two uses, one of which is a llvm.dbg.declare,
11810 // return the llvm.dbg.declare.
11811 DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11812 if (!V->hasNUses(2))
11814 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11816 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11818 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11819 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11826 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11827 Value *Val = SI.getOperand(0);
11828 Value *Ptr = SI.getOperand(1);
11830 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11831 EraseInstFromFunction(SI);
11836 // If the RHS is an alloca with a single use, zapify the store, making the
11838 // If the RHS is an alloca with a two uses, the other one being a
11839 // llvm.dbg.declare, zapify the store and the declare, making the
11840 // alloca dead. We must do this to prevent declare's from affecting
11842 if (!SI.isVolatile()) {
11843 if (Ptr->hasOneUse()) {
11844 if (isa<AllocaInst>(Ptr)) {
11845 EraseInstFromFunction(SI);
11849 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11850 if (isa<AllocaInst>(GEP->getOperand(0))) {
11851 if (GEP->getOperand(0)->hasOneUse()) {
11852 EraseInstFromFunction(SI);
11856 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11857 EraseInstFromFunction(*DI);
11858 EraseInstFromFunction(SI);
11865 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11866 EraseInstFromFunction(*DI);
11867 EraseInstFromFunction(SI);
11873 // Attempt to improve the alignment.
11874 unsigned KnownAlign =
11875 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
11877 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11878 SI.getAlignment()))
11879 SI.setAlignment(KnownAlign);
11881 // Do really simple DSE, to catch cases where there are several consecutive
11882 // stores to the same location, separated by a few arithmetic operations. This
11883 // situation often occurs with bitfield accesses.
11884 BasicBlock::iterator BBI = &SI;
11885 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11888 // Don't count debug info directives, lest they affect codegen,
11889 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11890 // It is necessary for correctness to skip those that feed into a
11891 // llvm.dbg.declare, as these are not present when debugging is off.
11892 if (isa<DbgInfoIntrinsic>(BBI) ||
11893 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
11898 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11899 // Prev store isn't volatile, and stores to the same location?
11900 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11901 SI.getOperand(1))) {
11904 EraseInstFromFunction(*PrevSI);
11910 // If this is a load, we have to stop. However, if the loaded value is from
11911 // the pointer we're loading and is producing the pointer we're storing,
11912 // then *this* store is dead (X = load P; store X -> P).
11913 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
11914 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11915 !SI.isVolatile()) {
11916 EraseInstFromFunction(SI);
11920 // Otherwise, this is a load from some other location. Stores before it
11921 // may not be dead.
11925 // Don't skip over loads or things that can modify memory.
11926 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
11931 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11933 // store X, null -> turns into 'unreachable' in SimplifyCFG
11934 if (isa<ConstantPointerNull>(Ptr) &&
11935 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
11936 if (!isa<UndefValue>(Val)) {
11937 SI.setOperand(0, Context->getUndef(Val->getType()));
11938 if (Instruction *U = dyn_cast<Instruction>(Val))
11939 AddToWorkList(U); // Dropped a use.
11942 return 0; // Do not modify these!
11945 // store undef, Ptr -> noop
11946 if (isa<UndefValue>(Val)) {
11947 EraseInstFromFunction(SI);
11952 // If the pointer destination is a cast, see if we can fold the cast into the
11954 if (isa<CastInst>(Ptr))
11955 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11957 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11959 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11963 // If this store is the last instruction in the basic block (possibly
11964 // excepting debug info instructions and the pointer bitcasts that feed
11965 // into them), and if the block ends with an unconditional branch, try
11966 // to move it to the successor block.
11970 } while (isa<DbgInfoIntrinsic>(BBI) ||
11971 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
11972 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11973 if (BI->isUnconditional())
11974 if (SimplifyStoreAtEndOfBlock(SI))
11975 return 0; // xform done!
11980 /// SimplifyStoreAtEndOfBlock - Turn things like:
11981 /// if () { *P = v1; } else { *P = v2 }
11982 /// into a phi node with a store in the successor.
11984 /// Simplify things like:
11985 /// *P = v1; if () { *P = v2; }
11986 /// into a phi node with a store in the successor.
11988 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11989 BasicBlock *StoreBB = SI.getParent();
11991 // Check to see if the successor block has exactly two incoming edges. If
11992 // so, see if the other predecessor contains a store to the same location.
11993 // if so, insert a PHI node (if needed) and move the stores down.
11994 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11996 // Determine whether Dest has exactly two predecessors and, if so, compute
11997 // the other predecessor.
11998 pred_iterator PI = pred_begin(DestBB);
11999 BasicBlock *OtherBB = 0;
12000 if (*PI != StoreBB)
12003 if (PI == pred_end(DestBB))
12006 if (*PI != StoreBB) {
12011 if (++PI != pred_end(DestBB))
12014 // Bail out if all the relevant blocks aren't distinct (this can happen,
12015 // for example, if SI is in an infinite loop)
12016 if (StoreBB == DestBB || OtherBB == DestBB)
12019 // Verify that the other block ends in a branch and is not otherwise empty.
12020 BasicBlock::iterator BBI = OtherBB->getTerminator();
12021 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12022 if (!OtherBr || BBI == OtherBB->begin())
12025 // If the other block ends in an unconditional branch, check for the 'if then
12026 // else' case. there is an instruction before the branch.
12027 StoreInst *OtherStore = 0;
12028 if (OtherBr->isUnconditional()) {
12030 // Skip over debugging info.
12031 while (isa<DbgInfoIntrinsic>(BBI) ||
12032 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12033 if (BBI==OtherBB->begin())
12037 // If this isn't a store, or isn't a store to the same location, bail out.
12038 OtherStore = dyn_cast<StoreInst>(BBI);
12039 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12042 // Otherwise, the other block ended with a conditional branch. If one of the
12043 // destinations is StoreBB, then we have the if/then case.
12044 if (OtherBr->getSuccessor(0) != StoreBB &&
12045 OtherBr->getSuccessor(1) != StoreBB)
12048 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12049 // if/then triangle. See if there is a store to the same ptr as SI that
12050 // lives in OtherBB.
12052 // Check to see if we find the matching store.
12053 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12054 if (OtherStore->getOperand(1) != SI.getOperand(1))
12058 // If we find something that may be using or overwriting the stored
12059 // value, or if we run out of instructions, we can't do the xform.
12060 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
12061 BBI == OtherBB->begin())
12065 // In order to eliminate the store in OtherBr, we have to
12066 // make sure nothing reads or overwrites the stored value in
12068 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12069 // FIXME: This should really be AA driven.
12070 if (I->mayReadFromMemory() || I->mayWriteToMemory())
12075 // Insert a PHI node now if we need it.
12076 Value *MergedVal = OtherStore->getOperand(0);
12077 if (MergedVal != SI.getOperand(0)) {
12078 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
12079 PN->reserveOperandSpace(2);
12080 PN->addIncoming(SI.getOperand(0), SI.getParent());
12081 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12082 MergedVal = InsertNewInstBefore(PN, DestBB->front());
12085 // Advance to a place where it is safe to insert the new store and
12087 BBI = DestBB->getFirstNonPHI();
12088 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12089 OtherStore->isVolatile()), *BBI);
12091 // Nuke the old stores.
12092 EraseInstFromFunction(SI);
12093 EraseInstFromFunction(*OtherStore);
12099 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12100 // Change br (not X), label True, label False to: br X, label False, True
12102 BasicBlock *TrueDest;
12103 BasicBlock *FalseDest;
12104 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
12105 !isa<Constant>(X)) {
12106 // Swap Destinations and condition...
12107 BI.setCondition(X);
12108 BI.setSuccessor(0, FalseDest);
12109 BI.setSuccessor(1, TrueDest);
12113 // Cannonicalize fcmp_one -> fcmp_oeq
12114 FCmpInst::Predicate FPred; Value *Y;
12115 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
12116 TrueDest, FalseDest)))
12117 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12118 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12119 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12120 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
12121 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
12122 NewSCC->takeName(I);
12123 // Swap Destinations and condition...
12124 BI.setCondition(NewSCC);
12125 BI.setSuccessor(0, FalseDest);
12126 BI.setSuccessor(1, TrueDest);
12127 RemoveFromWorkList(I);
12128 I->eraseFromParent();
12129 AddToWorkList(NewSCC);
12133 // Cannonicalize icmp_ne -> icmp_eq
12134 ICmpInst::Predicate IPred;
12135 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
12136 TrueDest, FalseDest)))
12137 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12138 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12139 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12140 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12141 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
12142 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
12143 NewSCC->takeName(I);
12144 // Swap Destinations and condition...
12145 BI.setCondition(NewSCC);
12146 BI.setSuccessor(0, FalseDest);
12147 BI.setSuccessor(1, TrueDest);
12148 RemoveFromWorkList(I);
12149 I->eraseFromParent();;
12150 AddToWorkList(NewSCC);
12157 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12158 Value *Cond = SI.getCondition();
12159 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12160 if (I->getOpcode() == Instruction::Add)
12161 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12162 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12163 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
12165 Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
12167 SI.setOperand(0, I->getOperand(0));
12175 Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
12176 Value *Agg = EV.getAggregateOperand();
12178 if (!EV.hasIndices())
12179 return ReplaceInstUsesWith(EV, Agg);
12181 if (Constant *C = dyn_cast<Constant>(Agg)) {
12182 if (isa<UndefValue>(C))
12183 return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
12185 if (isa<ConstantAggregateZero>(C))
12186 return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
12188 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12189 // Extract the element indexed by the first index out of the constant
12190 Value *V = C->getOperand(*EV.idx_begin());
12191 if (EV.getNumIndices() > 1)
12192 // Extract the remaining indices out of the constant indexed by the
12194 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12196 return ReplaceInstUsesWith(EV, V);
12198 return 0; // Can't handle other constants
12200 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12201 // We're extracting from an insertvalue instruction, compare the indices
12202 const unsigned *exti, *exte, *insi, *inse;
12203 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12204 exte = EV.idx_end(), inse = IV->idx_end();
12205 exti != exte && insi != inse;
12207 if (*insi != *exti)
12208 // The insert and extract both reference distinctly different elements.
12209 // This means the extract is not influenced by the insert, and we can
12210 // replace the aggregate operand of the extract with the aggregate
12211 // operand of the insert. i.e., replace
12212 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12213 // %E = extractvalue { i32, { i32 } } %I, 0
12215 // %E = extractvalue { i32, { i32 } } %A, 0
12216 return ExtractValueInst::Create(IV->getAggregateOperand(),
12217 EV.idx_begin(), EV.idx_end());
12219 if (exti == exte && insi == inse)
12220 // Both iterators are at the end: Index lists are identical. Replace
12221 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12222 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12224 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12225 if (exti == exte) {
12226 // The extract list is a prefix of the insert list. i.e. replace
12227 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12228 // %E = extractvalue { i32, { i32 } } %I, 1
12230 // %X = extractvalue { i32, { i32 } } %A, 1
12231 // %E = insertvalue { i32 } %X, i32 42, 0
12232 // by switching the order of the insert and extract (though the
12233 // insertvalue should be left in, since it may have other uses).
12234 Value *NewEV = InsertNewInstBefore(
12235 ExtractValueInst::Create(IV->getAggregateOperand(),
12236 EV.idx_begin(), EV.idx_end()),
12238 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12242 // The insert list is a prefix of the extract list
12243 // We can simply remove the common indices from the extract and make it
12244 // operate on the inserted value instead of the insertvalue result.
12246 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12247 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12249 // %E extractvalue { i32 } { i32 42 }, 0
12250 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12253 // Can't simplify extracts from other values. Note that nested extracts are
12254 // already simplified implicitely by the above (extract ( extract (insert) )
12255 // will be translated into extract ( insert ( extract ) ) first and then just
12256 // the value inserted, if appropriate).
12260 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12261 /// is to leave as a vector operation.
12262 static bool CheapToScalarize(Value *V, bool isConstant) {
12263 if (isa<ConstantAggregateZero>(V))
12265 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12266 if (isConstant) return true;
12267 // If all elts are the same, we can extract.
12268 Constant *Op0 = C->getOperand(0);
12269 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12270 if (C->getOperand(i) != Op0)
12274 Instruction *I = dyn_cast<Instruction>(V);
12275 if (!I) return false;
12277 // Insert element gets simplified to the inserted element or is deleted if
12278 // this is constant idx extract element and its a constant idx insertelt.
12279 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12280 isa<ConstantInt>(I->getOperand(2)))
12282 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12284 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12285 if (BO->hasOneUse() &&
12286 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12287 CheapToScalarize(BO->getOperand(1), isConstant)))
12289 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12290 if (CI->hasOneUse() &&
12291 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12292 CheapToScalarize(CI->getOperand(1), isConstant)))
12298 /// Read and decode a shufflevector mask.
12300 /// It turns undef elements into values that are larger than the number of
12301 /// elements in the input.
12302 static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12303 unsigned NElts = SVI->getType()->getNumElements();
12304 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12305 return std::vector<unsigned>(NElts, 0);
12306 if (isa<UndefValue>(SVI->getOperand(2)))
12307 return std::vector<unsigned>(NElts, 2*NElts);
12309 std::vector<unsigned> Result;
12310 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
12311 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12312 if (isa<UndefValue>(*i))
12313 Result.push_back(NElts*2); // undef -> 8
12315 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
12319 /// FindScalarElement - Given a vector and an element number, see if the scalar
12320 /// value is already around as a register, for example if it were inserted then
12321 /// extracted from the vector.
12322 static Value *FindScalarElement(Value *V, unsigned EltNo,
12323 LLVMContext *Context) {
12324 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12325 const VectorType *PTy = cast<VectorType>(V->getType());
12326 unsigned Width = PTy->getNumElements();
12327 if (EltNo >= Width) // Out of range access.
12328 return Context->getUndef(PTy->getElementType());
12330 if (isa<UndefValue>(V))
12331 return Context->getUndef(PTy->getElementType());
12332 else if (isa<ConstantAggregateZero>(V))
12333 return Context->getNullValue(PTy->getElementType());
12334 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12335 return CP->getOperand(EltNo);
12336 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12337 // If this is an insert to a variable element, we don't know what it is.
12338 if (!isa<ConstantInt>(III->getOperand(2)))
12340 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12342 // If this is an insert to the element we are looking for, return the
12344 if (EltNo == IIElt)
12345 return III->getOperand(1);
12347 // Otherwise, the insertelement doesn't modify the value, recurse on its
12349 return FindScalarElement(III->getOperand(0), EltNo, Context);
12350 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
12351 unsigned LHSWidth =
12352 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12353 unsigned InEl = getShuffleMask(SVI)[EltNo];
12354 if (InEl < LHSWidth)
12355 return FindScalarElement(SVI->getOperand(0), InEl, Context);
12356 else if (InEl < LHSWidth*2)
12357 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
12359 return Context->getUndef(PTy->getElementType());
12362 // Otherwise, we don't know.
12366 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
12367 // If vector val is undef, replace extract with scalar undef.
12368 if (isa<UndefValue>(EI.getOperand(0)))
12369 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12371 // If vector val is constant 0, replace extract with scalar 0.
12372 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
12373 return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
12375 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
12376 // If vector val is constant with all elements the same, replace EI with
12377 // that element. When the elements are not identical, we cannot replace yet
12378 // (we do that below, but only when the index is constant).
12379 Constant *op0 = C->getOperand(0);
12380 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12381 if (C->getOperand(i) != op0) {
12386 return ReplaceInstUsesWith(EI, op0);
12389 // If extracting a specified index from the vector, see if we can recursively
12390 // find a previously computed scalar that was inserted into the vector.
12391 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12392 unsigned IndexVal = IdxC->getZExtValue();
12393 unsigned VectorWidth =
12394 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12396 // If this is extracting an invalid index, turn this into undef, to avoid
12397 // crashing the code below.
12398 if (IndexVal >= VectorWidth)
12399 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12401 // This instruction only demands the single element from the input vector.
12402 // If the input vector has a single use, simplify it based on this use
12404 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
12405 APInt UndefElts(VectorWidth, 0);
12406 APInt DemandedMask(VectorWidth, 1 << IndexVal);
12407 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
12408 DemandedMask, UndefElts)) {
12409 EI.setOperand(0, V);
12414 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
12415 return ReplaceInstUsesWith(EI, Elt);
12417 // If the this extractelement is directly using a bitcast from a vector of
12418 // the same number of elements, see if we can find the source element from
12419 // it. In this case, we will end up needing to bitcast the scalars.
12420 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12421 if (const VectorType *VT =
12422 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12423 if (VT->getNumElements() == VectorWidth)
12424 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12425 IndexVal, Context))
12426 return new BitCastInst(Elt, EI.getType());
12430 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12431 if (I->hasOneUse()) {
12432 // Push extractelement into predecessor operation if legal and
12433 // profitable to do so
12434 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12435 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12436 if (CheapToScalarize(BO, isConstantElt)) {
12437 ExtractElementInst *newEI0 =
12438 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12439 EI.getName()+".lhs");
12440 ExtractElementInst *newEI1 =
12441 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12442 EI.getName()+".rhs");
12443 InsertNewInstBefore(newEI0, EI);
12444 InsertNewInstBefore(newEI1, EI);
12445 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
12447 } else if (isa<LoadInst>(I)) {
12449 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
12450 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
12451 Context->getPointerType(EI.getType(), AS),EI);
12452 GetElementPtrInst *GEP =
12453 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
12454 InsertNewInstBefore(GEP, EI);
12455 return new LoadInst(GEP);
12458 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12459 // Extracting the inserted element?
12460 if (IE->getOperand(2) == EI.getOperand(1))
12461 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12462 // If the inserted and extracted elements are constants, they must not
12463 // be the same value, extract from the pre-inserted value instead.
12464 if (isa<Constant>(IE->getOperand(2)) &&
12465 isa<Constant>(EI.getOperand(1))) {
12466 AddUsesToWorkList(EI);
12467 EI.setOperand(0, IE->getOperand(0));
12470 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12471 // If this is extracting an element from a shufflevector, figure out where
12472 // it came from and extract from the appropriate input element instead.
12473 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12474 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12476 unsigned LHSWidth =
12477 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12479 if (SrcIdx < LHSWidth)
12480 Src = SVI->getOperand(0);
12481 else if (SrcIdx < LHSWidth*2) {
12482 SrcIdx -= LHSWidth;
12483 Src = SVI->getOperand(1);
12485 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
12487 return new ExtractElementInst(Src, SrcIdx);
12494 /// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12495 /// elements from either LHS or RHS, return the shuffle mask and true.
12496 /// Otherwise, return false.
12497 static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
12498 std::vector<Constant*> &Mask,
12499 LLVMContext *Context) {
12500 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12501 "Invalid CollectSingleShuffleElements");
12502 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12504 if (isa<UndefValue>(V)) {
12505 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12507 } else if (V == LHS) {
12508 for (unsigned i = 0; i != NumElts; ++i)
12509 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12511 } else if (V == RHS) {
12512 for (unsigned i = 0; i != NumElts; ++i)
12513 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
12515 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12516 // If this is an insert of an extract from some other vector, include it.
12517 Value *VecOp = IEI->getOperand(0);
12518 Value *ScalarOp = IEI->getOperand(1);
12519 Value *IdxOp = IEI->getOperand(2);
12521 if (!isa<ConstantInt>(IdxOp))
12523 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12525 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12526 // Okay, we can handle this if the vector we are insertinting into is
12527 // transitively ok.
12528 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12529 // If so, update the mask to reflect the inserted undef.
12530 Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
12533 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12534 if (isa<ConstantInt>(EI->getOperand(1)) &&
12535 EI->getOperand(0)->getType() == V->getType()) {
12536 unsigned ExtractedIdx =
12537 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12539 // This must be extracting from either LHS or RHS.
12540 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12541 // Okay, we can handle this if the vector we are insertinting into is
12542 // transitively ok.
12543 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
12544 // If so, update the mask to reflect the inserted value.
12545 if (EI->getOperand(0) == LHS) {
12546 Mask[InsertedIdx % NumElts] =
12547 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12549 assert(EI->getOperand(0) == RHS);
12550 Mask[InsertedIdx % NumElts] =
12551 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
12560 // TODO: Handle shufflevector here!
12565 /// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12566 /// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12567 /// that computes V and the LHS value of the shuffle.
12568 static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
12569 Value *&RHS, LLVMContext *Context) {
12570 assert(isa<VectorType>(V->getType()) &&
12571 (RHS == 0 || V->getType() == RHS->getType()) &&
12572 "Invalid shuffle!");
12573 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12575 if (isa<UndefValue>(V)) {
12576 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
12578 } else if (isa<ConstantAggregateZero>(V)) {
12579 Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
12581 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12582 // If this is an insert of an extract from some other vector, include it.
12583 Value *VecOp = IEI->getOperand(0);
12584 Value *ScalarOp = IEI->getOperand(1);
12585 Value *IdxOp = IEI->getOperand(2);
12587 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12588 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12589 EI->getOperand(0)->getType() == V->getType()) {
12590 unsigned ExtractedIdx =
12591 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12592 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12594 // Either the extracted from or inserted into vector must be RHSVec,
12595 // otherwise we'd end up with a shuffle of three inputs.
12596 if (EI->getOperand(0) == RHS || RHS == 0) {
12597 RHS = EI->getOperand(0);
12598 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
12599 Mask[InsertedIdx % NumElts] =
12600 Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
12604 if (VecOp == RHS) {
12605 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12607 // Everything but the extracted element is replaced with the RHS.
12608 for (unsigned i = 0; i != NumElts; ++i) {
12609 if (i != InsertedIdx)
12610 Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
12615 // If this insertelement is a chain that comes from exactly these two
12616 // vectors, return the vector and the effective shuffle.
12617 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12619 return EI->getOperand(0);
12624 // TODO: Handle shufflevector here!
12626 // Otherwise, can't do anything fancy. Return an identity vector.
12627 for (unsigned i = 0; i != NumElts; ++i)
12628 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
12632 Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12633 Value *VecOp = IE.getOperand(0);
12634 Value *ScalarOp = IE.getOperand(1);
12635 Value *IdxOp = IE.getOperand(2);
12637 // Inserting an undef or into an undefined place, remove this.
12638 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12639 ReplaceInstUsesWith(IE, VecOp);
12641 // If the inserted element was extracted from some other vector, and if the
12642 // indexes are constant, try to turn this into a shufflevector operation.
12643 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12644 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12645 EI->getOperand(0)->getType() == IE.getType()) {
12646 unsigned NumVectorElts = IE.getType()->getNumElements();
12647 unsigned ExtractedIdx =
12648 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12649 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12651 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12652 return ReplaceInstUsesWith(IE, VecOp);
12654 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12655 return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
12657 // If we are extracting a value from a vector, then inserting it right
12658 // back into the same place, just use the input vector.
12659 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12660 return ReplaceInstUsesWith(IE, VecOp);
12662 // We could theoretically do this for ANY input. However, doing so could
12663 // turn chains of insertelement instructions into a chain of shufflevector
12664 // instructions, and right now we do not merge shufflevectors. As such,
12665 // only do this in a situation where it is clear that there is benefit.
12666 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12667 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12668 // the values of VecOp, except then one read from EIOp0.
12669 // Build a new shuffle mask.
12670 std::vector<Constant*> Mask;
12671 if (isa<UndefValue>(VecOp))
12672 Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
12674 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12675 Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
12678 Mask[InsertedIdx] =
12679 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
12680 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12681 Context->getConstantVector(Mask));
12684 // If this insertelement isn't used by some other insertelement, turn it
12685 // (and any insertelements it points to), into one big shuffle.
12686 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12687 std::vector<Constant*> Mask;
12689 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12690 if (RHS == 0) RHS = Context->getUndef(LHS->getType());
12691 // We now have a shuffle of LHS, RHS, Mask.
12692 return new ShuffleVectorInst(LHS, RHS,
12693 Context->getConstantVector(Mask));
12698 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12699 APInt UndefElts(VWidth, 0);
12700 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12701 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12708 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12709 Value *LHS = SVI.getOperand(0);
12710 Value *RHS = SVI.getOperand(1);
12711 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12713 bool MadeChange = false;
12715 // Undefined shuffle mask -> undefined value.
12716 if (isa<UndefValue>(SVI.getOperand(2)))
12717 return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
12719 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
12721 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12724 APInt UndefElts(VWidth, 0);
12725 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12726 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12727 LHS = SVI.getOperand(0);
12728 RHS = SVI.getOperand(1);
12732 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12733 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12734 if (LHS == RHS || isa<UndefValue>(LHS)) {
12735 if (isa<UndefValue>(LHS) && LHS == RHS) {
12736 // shuffle(undef,undef,mask) -> undef.
12737 return ReplaceInstUsesWith(SVI, LHS);
12740 // Remap any references to RHS to use LHS.
12741 std::vector<Constant*> Elts;
12742 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12743 if (Mask[i] >= 2*e)
12744 Elts.push_back(Context->getUndef(Type::Int32Ty));
12746 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
12747 (Mask[i] < e && isa<UndefValue>(LHS))) {
12748 Mask[i] = 2*e; // Turn into undef.
12749 Elts.push_back(Context->getUndef(Type::Int32Ty));
12751 Mask[i] = Mask[i] % e; // Force to LHS.
12752 Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
12756 SVI.setOperand(0, SVI.getOperand(1));
12757 SVI.setOperand(1, Context->getUndef(RHS->getType()));
12758 SVI.setOperand(2, Context->getConstantVector(Elts));
12759 LHS = SVI.getOperand(0);
12760 RHS = SVI.getOperand(1);
12764 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12765 bool isLHSID = true, isRHSID = true;
12767 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12768 if (Mask[i] >= e*2) continue; // Ignore undef values.
12769 // Is this an identity shuffle of the LHS value?
12770 isLHSID &= (Mask[i] == i);
12772 // Is this an identity shuffle of the RHS value?
12773 isRHSID &= (Mask[i]-e == i);
12776 // Eliminate identity shuffles.
12777 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12778 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12780 // If the LHS is a shufflevector itself, see if we can combine it with this
12781 // one without producing an unusual shuffle. Here we are really conservative:
12782 // we are absolutely afraid of producing a shuffle mask not in the input
12783 // program, because the code gen may not be smart enough to turn a merged
12784 // shuffle into two specific shuffles: it may produce worse code. As such,
12785 // we only merge two shuffles if the result is one of the two input shuffle
12786 // masks. In this case, merging the shuffles just removes one instruction,
12787 // which we know is safe. This is good for things like turning:
12788 // (splat(splat)) -> splat.
12789 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12790 if (isa<UndefValue>(RHS)) {
12791 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12793 std::vector<unsigned> NewMask;
12794 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12795 if (Mask[i] >= 2*e)
12796 NewMask.push_back(2*e);
12798 NewMask.push_back(LHSMask[Mask[i]]);
12800 // If the result mask is equal to the src shuffle or this shuffle mask, do
12801 // the replacement.
12802 if (NewMask == LHSMask || NewMask == Mask) {
12803 unsigned LHSInNElts =
12804 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
12805 std::vector<Constant*> Elts;
12806 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12807 if (NewMask[i] >= LHSInNElts*2) {
12808 Elts.push_back(Context->getUndef(Type::Int32Ty));
12810 Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
12813 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12814 LHSSVI->getOperand(1),
12815 Context->getConstantVector(Elts));
12820 return MadeChange ? &SVI : 0;
12826 /// TryToSinkInstruction - Try to move the specified instruction from its
12827 /// current block into the beginning of DestBlock, which can only happen if it's
12828 /// safe to move the instruction past all of the instructions between it and the
12829 /// end of its block.
12830 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12831 assert(I->hasOneUse() && "Invariants didn't hold!");
12833 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
12834 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
12837 // Do not sink alloca instructions out of the entry block.
12838 if (isa<AllocaInst>(I) && I->getParent() ==
12839 &DestBlock->getParent()->getEntryBlock())
12842 // We can only sink load instructions if there is nothing between the load and
12843 // the end of block that could change the value.
12844 if (I->mayReadFromMemory()) {
12845 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
12847 if (Scan->mayWriteToMemory())
12851 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
12853 CopyPrecedingStopPoint(I, InsertPos);
12854 I->moveBefore(InsertPos);
12860 /// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12861 /// all reachable code to the worklist.
12863 /// This has a couple of tricks to make the code faster and more powerful. In
12864 /// particular, we constant fold and DCE instructions as we go, to avoid adding
12865 /// them to the worklist (this significantly speeds up instcombine on code where
12866 /// many instructions are dead or constant). Additionally, if we find a branch
12867 /// whose condition is a known constant, we only visit the reachable successors.
12869 static void AddReachableCodeToWorklist(BasicBlock *BB,
12870 SmallPtrSet<BasicBlock*, 64> &Visited,
12872 const TargetData *TD) {
12873 SmallVector<BasicBlock*, 256> Worklist;
12874 Worklist.push_back(BB);
12876 while (!Worklist.empty()) {
12877 BB = Worklist.back();
12878 Worklist.pop_back();
12880 // We have now visited this block! If we've already been here, ignore it.
12881 if (!Visited.insert(BB)) continue;
12883 DbgInfoIntrinsic *DBI_Prev = NULL;
12884 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12885 Instruction *Inst = BBI++;
12887 // DCE instruction if trivially dead.
12888 if (isInstructionTriviallyDead(Inst)) {
12890 DOUT << "IC: DCE: " << *Inst;
12891 Inst->eraseFromParent();
12895 // ConstantProp instruction if trivially constant.
12896 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
12897 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12898 Inst->replaceAllUsesWith(C);
12900 Inst->eraseFromParent();
12904 // If there are two consecutive llvm.dbg.stoppoint calls then
12905 // it is likely that the optimizer deleted code in between these
12907 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12910 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12911 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12912 IC.RemoveFromWorkList(DBI_Prev);
12913 DBI_Prev->eraseFromParent();
12915 DBI_Prev = DBI_Next;
12920 IC.AddToWorkList(Inst);
12923 // Recursively visit successors. If this is a branch or switch on a
12924 // constant, only visit the reachable successor.
12925 TerminatorInst *TI = BB->getTerminator();
12926 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12927 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12928 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
12929 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
12930 Worklist.push_back(ReachableBB);
12933 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12934 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12935 // See if this is an explicit destination.
12936 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12937 if (SI->getCaseValue(i) == Cond) {
12938 BasicBlock *ReachableBB = SI->getSuccessor(i);
12939 Worklist.push_back(ReachableBB);
12943 // Otherwise it is the default destination.
12944 Worklist.push_back(SI->getSuccessor(0));
12949 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12950 Worklist.push_back(TI->getSuccessor(i));
12954 bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12955 bool Changed = false;
12956 TD = &getAnalysis<TargetData>();
12958 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12959 << F.getNameStr() << "\n");
12962 // Do a depth-first traversal of the function, populate the worklist with
12963 // the reachable instructions. Ignore blocks that are not reachable. Keep
12964 // track of which blocks we visit.
12965 SmallPtrSet<BasicBlock*, 64> Visited;
12966 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12968 // Do a quick scan over the function. If we find any blocks that are
12969 // unreachable, remove any instructions inside of them. This prevents
12970 // the instcombine code from having to deal with some bad special cases.
12971 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12972 if (!Visited.count(BB)) {
12973 Instruction *Term = BB->getTerminator();
12974 while (Term != BB->begin()) { // Remove instrs bottom-up
12975 BasicBlock::iterator I = Term; --I;
12977 DOUT << "IC: DCE: " << *I;
12978 // A debug intrinsic shouldn't force another iteration if we weren't
12979 // going to do one without it.
12980 if (!isa<DbgInfoIntrinsic>(I)) {
12984 if (!I->use_empty())
12985 I->replaceAllUsesWith(Context->getUndef(I->getType()));
12986 I->eraseFromParent();
12991 while (!Worklist.empty()) {
12992 Instruction *I = RemoveOneFromWorkList();
12993 if (I == 0) continue; // skip null values.
12995 // Check to see if we can DCE the instruction.
12996 if (isInstructionTriviallyDead(I)) {
12997 // Add operands to the worklist.
12998 if (I->getNumOperands() < 4)
12999 AddUsesToWorkList(*I);
13002 DOUT << "IC: DCE: " << *I;
13004 I->eraseFromParent();
13005 RemoveFromWorkList(I);
13010 // Instruction isn't dead, see if we can constant propagate it.
13011 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
13012 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
13014 // Add operands to the worklist.
13015 AddUsesToWorkList(*I);
13016 ReplaceInstUsesWith(*I, C);
13019 I->eraseFromParent();
13020 RemoveFromWorkList(I);
13026 (I->getType()->getTypeID() == Type::VoidTyID ||
13027 I->isTrapping())) {
13028 // See if we can constant fold its operands.
13029 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13030 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
13031 if (Constant *NewC = ConstantFoldConstantExpression(CE,
13032 F.getContext(), TD))
13039 // See if we can trivially sink this instruction to a successor basic block.
13040 if (I->hasOneUse()) {
13041 BasicBlock *BB = I->getParent();
13042 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13043 if (UserParent != BB) {
13044 bool UserIsSuccessor = false;
13045 // See if the user is one of our successors.
13046 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13047 if (*SI == UserParent) {
13048 UserIsSuccessor = true;
13052 // If the user is one of our immediate successors, and if that successor
13053 // only has us as a predecessors (we'd have to split the critical edge
13054 // otherwise), we can keep going.
13055 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13056 next(pred_begin(UserParent)) == pred_end(UserParent))
13057 // Okay, the CFG is simple enough, try to sink this instruction.
13058 Changed |= TryToSinkInstruction(I, UserParent);
13062 // Now that we have an instruction, try combining it to simplify it...
13066 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13067 if (Instruction *Result = visit(*I)) {
13069 // Should we replace the old instruction with a new one?
13071 DOUT << "IC: Old = " << *I
13072 << " New = " << *Result;
13074 // Everything uses the new instruction now.
13075 I->replaceAllUsesWith(Result);
13077 // Push the new instruction and any users onto the worklist.
13078 AddToWorkList(Result);
13079 AddUsersToWorkList(*Result);
13081 // Move the name to the new instruction first.
13082 Result->takeName(I);
13084 // Insert the new instruction into the basic block...
13085 BasicBlock *InstParent = I->getParent();
13086 BasicBlock::iterator InsertPos = I;
13088 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13089 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13092 InstParent->getInstList().insert(InsertPos, Result);
13094 // Make sure that we reprocess all operands now that we reduced their
13096 AddUsesToWorkList(*I);
13098 // Instructions can end up on the worklist more than once. Make sure
13099 // we do not process an instruction that has been deleted.
13100 RemoveFromWorkList(I);
13102 // Erase the old instruction.
13103 InstParent->getInstList().erase(I);
13106 DOUT << "IC: Mod = " << OrigI
13107 << " New = " << *I;
13110 // If the instruction was modified, it's possible that it is now dead.
13111 // if so, remove it.
13112 if (isInstructionTriviallyDead(I)) {
13113 // Make sure we process all operands now that we are reducing their
13115 AddUsesToWorkList(*I);
13117 // Instructions may end up in the worklist more than once. Erase all
13118 // occurrences of this instruction.
13119 RemoveFromWorkList(I);
13120 I->eraseFromParent();
13123 AddUsersToWorkList(*I);
13130 assert(WorklistMap.empty() && "Worklist empty, but map not?");
13132 // Do an explicit clear, this shrinks the map if needed.
13133 WorklistMap.clear();
13138 bool InstCombiner::runOnFunction(Function &F) {
13139 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13141 bool EverMadeChange = false;
13143 // Iterate while there is work to do.
13144 unsigned Iteration = 0;
13145 while (DoOneIteration(F, Iteration++))
13146 EverMadeChange = true;
13147 return EverMadeChange;
13150 FunctionPass *llvm::createInstructionCombiningPass() {
13151 return new InstCombiner();